ngram
listlengths
0
82k
[ "= await response.json() assert response_json['error_code'] == 'not_found' assert response_json['error_message'] ==", "with client.get(partner_search_with_str_coordinates_url) as response: # noqa assert response.status == 400", "partner_bar_legal() async def test_should_return_not_found_when_no_partner_covers_coordinate( self, client, partner_search_coordinates_url ): async with", "with client.get(partner_search_coordinates_url) as response: # noqa assert response.status == 200", "response: # noqa assert response.status == 200 response_json = await", "partner_search_with_str_coordinates_url ): async with client.get(partner_search_with_str_coordinates_url) as response: # noqa assert", "client, partner_search_coordinates_url, save_partners ): async with client.get(partner_search_coordinates_url) as response: #", "assert response.status == 200 response_json = await response.json() assert response_json", "from drink_partners.contrib.samples import partner_bar_legal class TestSearchPartner: async def test_should_return_bad_request_for_str_coordinates( self,", "self, client, partner_search_coordinates_url, save_partners ): async with client.get(partner_search_coordinates_url) as response:", "self, client, partner_search_coordinates_url ): async with client.get(partner_search_coordinates_url) as response: #", "# noqa assert response.status == 400 response_json = await response.json()", "response_json = await response.json() assert response_json == partner_bar_legal() async def", "404 response_json = await response.json() assert response_json['error_code'] == 'not_found' assert", "latitude:a' ) async def test_should_return_nearest_partner_for_coordinate( self, client, partner_search_coordinates_url, save_partners ):", "async def test_should_return_bad_request_for_str_coordinates( self, client, partner_search_with_str_coordinates_url ): async with client.get(partner_search_with_str_coordinates_url)", "response.status == 400 response_json = await response.json() assert response_json['error_code'] ==", "noqa assert response.status == 404 response_json = await response.json() assert", "client.get(partner_search_coordinates_url) as response: # noqa assert response.status == 404 response_json", "as response: # noqa assert response.status == 200 response_json =", "test_should_return_not_found_when_no_partner_covers_coordinate( self, client, partner_search_coordinates_url ): async with client.get(partner_search_coordinates_url) as response:", "response.status == 200 response_json = await response.json() assert response_json ==", "response_json['error_message'] == ( 'Partners not found covering area for '", "test_should_return_nearest_partner_for_coordinate( self, client, partner_search_coordinates_url, save_partners ): async with client.get(partner_search_coordinates_url) as", "== 404 response_json = await response.json() assert response_json['error_code'] == 'not_found'", "assert response.status == 400 response_json = await response.json() assert response_json['error_code']", "await response.json() assert response_json['error_code'] == 'not_found' assert response_json['error_message'] == (", "async with client.get(partner_search_with_str_coordinates_url) as response: # noqa assert response.status ==", "response.status == 404 response_json = await response.json() assert response_json['error_code'] ==", "TestSearchPartner: async def test_should_return_bad_request_for_str_coordinates( self, client, partner_search_with_str_coordinates_url ): async with", "client.get(partner_search_coordinates_url) as response: # noqa assert response.status == 200 response_json", "partner_bar_legal class TestSearchPartner: async def test_should_return_bad_request_for_str_coordinates( self, client, partner_search_with_str_coordinates_url ):", "def test_should_return_nearest_partner_for_coordinate( self, client, partner_search_coordinates_url, save_partners ): async with client.get(partner_search_coordinates_url)", "partner_search_coordinates_url, save_partners ): async with client.get(partner_search_coordinates_url) as response: # noqa", "response_json = await response.json() assert response_json['error_code'] == 'not_found' assert response_json['error_message']", "( 'Invalid coordinate longitude:a latitude:a' ) async def test_should_return_nearest_partner_for_coordinate( self,", "response: # noqa assert response.status == 400 response_json = await", "class TestSearchPartner: async def test_should_return_bad_request_for_str_coordinates( self, client, partner_search_with_str_coordinates_url ): async", "response_json == partner_bar_legal() async def test_should_return_not_found_when_no_partner_covers_coordinate( self, client, partner_search_coordinates_url ):", "async def test_should_return_nearest_partner_for_coordinate( self, client, partner_search_coordinates_url, save_partners ): async with", "async with client.get(partner_search_coordinates_url) as response: # noqa assert response.status ==", "def test_should_return_not_found_when_no_partner_covers_coordinate( self, client, partner_search_coordinates_url ): async with client.get(partner_search_coordinates_url) as", "assert response.status == 404 response_json = await response.json() assert response_json['error_code']", "): async with client.get(partner_search_with_str_coordinates_url) as response: # noqa assert response.status", "response.json() assert response_json['error_code'] == 'bad_request' assert response_json['error_message'] == ( 'Invalid", "== partner_bar_legal() async def test_should_return_not_found_when_no_partner_covers_coordinate( self, client, partner_search_coordinates_url ): async", "as response: # noqa assert response.status == 404 response_json =", "response: # noqa assert response.status == 404 response_json = await", "response_json = await response.json() assert response_json['error_code'] == 'bad_request' assert response_json['error_message']", "== ( 'Partners not found covering area for ' 'latitude:-43.36556", "# noqa assert response.status == 404 response_json = await response.json()", "self, client, partner_search_with_str_coordinates_url ): async with client.get(partner_search_with_str_coordinates_url) as response: #", "response.json() assert response_json == partner_bar_legal() async def test_should_return_not_found_when_no_partner_covers_coordinate( self, client,", "client, partner_search_coordinates_url ): async with client.get(partner_search_coordinates_url) as response: # noqa", "400 response_json = await response.json() assert response_json['error_code'] == 'bad_request' assert", "client.get(partner_search_with_str_coordinates_url) as response: # noqa assert response.status == 400 response_json", "noqa assert response.status == 400 response_json = await response.json() assert", "save_partners ): async with client.get(partner_search_coordinates_url) as response: # noqa assert", "== ( 'Invalid coordinate longitude:a latitude:a' ) async def test_should_return_nearest_partner_for_coordinate(", "import partner_bar_legal class TestSearchPartner: async def test_should_return_bad_request_for_str_coordinates( self, client, partner_search_with_str_coordinates_url", "assert response_json['error_message'] == ( 'Partners not found covering area for", "( 'Partners not found covering area for ' 'latitude:-43.36556 longitude:-22.99669'", "'Invalid coordinate longitude:a latitude:a' ) async def test_should_return_nearest_partner_for_coordinate( self, client,", "response_json['error_code'] == 'not_found' assert response_json['error_message'] == ( 'Partners not found", "client, partner_search_with_str_coordinates_url ): async with client.get(partner_search_with_str_coordinates_url) as response: # noqa", "'bad_request' assert response_json['error_message'] == ( 'Invalid coordinate longitude:a latitude:a' )", "'Partners not found covering area for ' 'latitude:-43.36556 longitude:-22.99669' )", "longitude:a latitude:a' ) async def test_should_return_nearest_partner_for_coordinate( self, client, partner_search_coordinates_url, save_partners", "def test_should_return_bad_request_for_str_coordinates( self, client, partner_search_with_str_coordinates_url ): async with client.get(partner_search_with_str_coordinates_url) as", "async def test_should_return_not_found_when_no_partner_covers_coordinate( self, client, partner_search_coordinates_url ): async with client.get(partner_search_coordinates_url)", "assert response_json['error_message'] == ( 'Invalid coordinate longitude:a latitude:a' ) async", "): async with client.get(partner_search_coordinates_url) as response: # noqa assert response.status", "= await response.json() assert response_json['error_code'] == 'bad_request' assert response_json['error_message'] ==", "200 response_json = await response.json() assert response_json == partner_bar_legal() async", ") async def test_should_return_nearest_partner_for_coordinate( self, client, partner_search_coordinates_url, save_partners ): async", "partner_search_coordinates_url ): async with client.get(partner_search_coordinates_url) as response: # noqa assert", "test_should_return_bad_request_for_str_coordinates( self, client, partner_search_with_str_coordinates_url ): async with client.get(partner_search_with_str_coordinates_url) as response:", "response_json['error_code'] == 'bad_request' assert response_json['error_message'] == ( 'Invalid coordinate longitude:a", "assert response_json['error_code'] == 'bad_request' assert response_json['error_message'] == ( 'Invalid coordinate", "assert response_json['error_code'] == 'not_found' assert response_json['error_message'] == ( 'Partners not", "drink_partners.contrib.samples import partner_bar_legal class TestSearchPartner: async def test_should_return_bad_request_for_str_coordinates( self, client,", "== 400 response_json = await response.json() assert response_json['error_code'] == 'bad_request'", "await response.json() assert response_json == partner_bar_legal() async def test_should_return_not_found_when_no_partner_covers_coordinate( self,", "response.json() assert response_json['error_code'] == 'not_found' assert response_json['error_message'] == ( 'Partners", "'not_found' assert response_json['error_message'] == ( 'Partners not found covering area", "with client.get(partner_search_coordinates_url) as response: # noqa assert response.status == 404", "response_json['error_message'] == ( 'Invalid coordinate longitude:a latitude:a' ) async def", "= await response.json() assert response_json == partner_bar_legal() async def test_should_return_not_found_when_no_partner_covers_coordinate(", "# noqa assert response.status == 200 response_json = await response.json()", "as response: # noqa assert response.status == 400 response_json =", "assert response_json == partner_bar_legal() async def test_should_return_not_found_when_no_partner_covers_coordinate( self, client, partner_search_coordinates_url", "== 'not_found' assert response_json['error_message'] == ( 'Partners not found covering", "== 200 response_json = await response.json() assert response_json == partner_bar_legal()", "== 'bad_request' assert response_json['error_message'] == ( 'Invalid coordinate longitude:a latitude:a'", "coordinate longitude:a latitude:a' ) async def test_should_return_nearest_partner_for_coordinate( self, client, partner_search_coordinates_url,", "noqa assert response.status == 200 response_json = await response.json() assert", "await response.json() assert response_json['error_code'] == 'bad_request' assert response_json['error_message'] == (" ]
[ "file result_csv_writer.writerow([\"PassengerId\", \"Survived\"]) for list_idx in xrange(len(predict_label_list)): PassengerId = start_id", "in quiting MySQL.\") logging.error(\"MySQL Error {error_num}: {error_info}.\".format(error_num = e.args[0], error_info", "train_data) logging.info(\"len(train_data):{0}\".format(len(train_data))) logging.info(\"train_data[0]:{0}\".format(train_data[0])) logging.info(\"type(train_data[0]):{0}\".format(type(train_data[0]))) test_data = map(lambda (PassengerId, Survived, Pclass,", "solution if cur_iter == 0: optimal_solution['cur_iter'] = cur_iter optimal_solution['cost'] =", "train_label_matrix - hypothesis error_list.append(error) logging.info(\"cur_iter:{0}, cost:{1}, sum(error):{2}\".format(cur_iter+1, cost, sum(error))) #", "SibSp, Parch, Fare),\\ test_feature_tuple_list) logging.info(\"len(train_feature_intercept_term_added_tuple_list):{0}\".format(len(train_feature_intercept_term_added_tuple_list))) logging.info(\"train_feature_intercept_term_added_tuple_list[0]:{0}\".format(train_feature_intercept_term_added_tuple_list[0])) logging.info(\"len(test_feature_intercept_term_added_tuple_list):{0}\".format(len(test_feature_intercept_term_added_tuple_list))) logging.info(\"test_feature_intercept_term_added_tuple_list[0]:{0}\".format(test_feature_intercept_term_added_tuple_list[0])) return train_feature_intercept_term_added_tuple_list,\\", "(2*train_sample_num) * (array(weight_matrix[1:]) * array(weight_matrix[1:])).sum() cost_list.append(cost) # [891, 1] error", "[891, 1] <- [891, 7]*[7, 1] hypothesis = self.sigmoid_function(train_input_matrix *", "time.clock() logging.basicConfig(level = logging.INFO, format = '%(asctime)s %(levelname)5s %(filename)19s[line:%(lineno)3d] %(funcName)s", "= predict_label_list) logging.info(\"precision:{0}\".format(precision)) logging.info(\"recall:{0}\".format(recall)) logging.info(\"F1:{0}\".format(F1)) return accuracy, precision, recall, F1", "logging.info(\"test_data[0]:{0}\".format(test_data[0])) logging.info(\"type(test_data[0]):{0}\".format(type(test_data[0]))) except MySQLdb.Error, e: self.con.rollback() logging.error(\"Fail in fetch data", "Age, SibSp, Parch, Fare):\\ (InterceptTerm, Sex, Fare),\\ train_feature_tuple_list) train_input_matrix =", "def __del__(self): try: self.con.close() logging.info(\"Success in quiting MySQL.\") except MySQLdb.Error,", "logging.info(\"len(train_data):{0}\".format(len(train_data))) logging.info(\"train_data[0]:{0}\".format(train_data[0])) logging.info(\"type(train_data[0]):{0}\".format(type(train_data[0]))) elif sql_idx == 1: test_data = cursor.fetchall()", "+ learning_rate * \\ ( (float(1)/train_sample_num) * train_input_matrix[:, 1::].transpose() *", "cost optimal_solution['abs(error.sum())'] = abs(error.sum()) optimal_solution['weight_matrix'] = weight_matrix elif cur_iter !=", "recall, F1 right_predict_num, accuracy = compute_accuracy(train_label_list = train_label_list,\\ predict_label_list =", "filename = 'main.log', filemode = 'a') console = logging.StreamHandler() console.setLevel(logging.INFO)", "logging.info(\"Success in connecting MySQL.\") except MySQLdb.Error, e: logging.error(\"Fail in connecting", "= e.args[1])) @Decorator.log_of_function def __del__(self): try: self.con.close() logging.info(\"Success in quiting", "\\ # ( 1 / 1 * [891, 6].T *", "== 0: optimal_solution['cur_iter'] = cur_iter optimal_solution['cost'] = cost optimal_solution['abs(error.sum())'] =", "int(Survived),\\ int(Pclass),\\ Sex,\\ int(Age),\\ int(SibSp),\\ int(Parch)\\ ),\\ test_data) logging.info(\"len(test_data):{0}\".format(len(test_data))) logging.info(\"test_data[0]:{0}\".format(test_data[0]))", "file(result_csv_dir, 'wb') logging.info(\"Success in attaining file handle of {0}.\".format(result_csv_dir)) except", "Exception as e: logging.error(\"Fail in closing file handle of {0}.\".format(result_csv_dir))", "e.args[1])) train_data = map(lambda (PassengerId, Survived, Pclass, Sex, Age, SibSp,", "cursor.fetchall() logging.info(\"len(train_data):{0}\".format(len(train_data))) logging.info(\"train_data[0]:{0}\".format(train_data[0])) logging.info(\"type(train_data[0]):{0}\".format(type(train_data[0]))) elif sql_idx == 1: test_data =", "handle of {0}.\".format(result_csv_dir)) logging.error(e) return -1 # create csv writer", "exp import csv import decorator_of_function ################################### PART2 CLASS && FUNCTION", "result_csv_writer.writerow([\"PassengerId\", \"Survived\"]) for list_idx in xrange(len(predict_label_list)): PassengerId = start_id +", "= abs(error.sum()) optimal_solution['weight_matrix'] = weight_matrix logging.info(\"optimal_solution['cur_iter']:{0}\".format(optimal_solution['cur_iter'])) logging.info(\"optimal_solution['cost':{0}\".format(optimal_solution['cost'])) logging.info(\"optimal_solution['abs(error.sum())']:{0}\".format(optimal_solution['abs(error.sum())'])) logging.info(\"optimal_solution['weight_matrix'].tolist():{0}\".format(optimal_solution['weight_matrix'].tolist())) #\"\"\"", "true_negative_num = 10E-10 predicted_positive_num = predict_label_list.count(1) predicted_negative_num = predict_label_list.count(0) for", "cur_iter in xrange(max_iteration_time): # [891, 1] <- [891, 7]*[7, 1]", "e.args[0], error_info = e.args[1])) @Decorator.log_of_function def __del__(self): try: self.con.close() logging.info(\"Success", "return weight_matrix #return optimal_solution['weight_matrix'] @Decorator.log_of_function def predict(self, train_feature_tuple_list, weight_matrix): '''", "csv file try: result_csv_handle = file(result_csv_dir, 'wb') logging.info(\"Success in attaining", "################################### PART2 CLASS && FUNCTION ########################### class CreateLogisticRegressionModel(object): Decorator =", "1 * [891, 1].T *[891, 1] weight_matrix[0] = weight_matrix[0] +", "%(funcName)s %(message)s') console.setFormatter(formatter) logging.getLogger('').addHandler(console) logging.info(\"START CLASS {class_name}.\".format(class_name = CreateLogisticRegressionModel.__name__)) try:", "self.start)) @Decorator.log_of_function def get_data_from_database(self, database_name, passenger_table_name): cursor = self.con.cursor() sql_list", "i in xrange(row): print i+1, predict_label_matrix[i][0] ''' predict_prob_list = predict_prob_matrix.transpose().tolist()[0]", "# test set sql_list.append(\"\"\"SELECT PassengerId, Survived, Pclass, Sex, Age, SibSp,", "start_id, predict_label_list, result_csv_dir): # open csv file try: result_csv_handle =", "error_info = e.args[1])) @Decorator.log_of_function def __del__(self): try: self.con.close() logging.info(\"Success in", "predict_label_matrix[i][0] ''' predict_prob_list = predict_prob_matrix.transpose().tolist()[0] predict_label_list = [] for prob_idx", "cur_iter != 0 and optimal_solution['abs(error.sum())'] > abs(error.sum()): optimal_solution['cur_iter'] = cur_iter", "return accuracy, precision, recall, F1 @Decorator.log_of_function def write_csv_file(self, start_id, predict_label_list,", "predict_prob > 0.5: predict_label_list.append(1) else: predict_label_list.append(0) return predict_label_list @Decorator.log_of_function def", "{error_num}: {error_info}.\".format(error_num = e.args[0], error_info = e.args[1])) train_data = map(lambda", "@Decorator.log_of_function def accuracy(self, train_label_list, predict_label_list): logging.info(\"len(train_label_list):{0}\".format(len(train_label_list))) logging.info(\"len(predict_label_list):{0}\".format(len(predict_label_list))) # compute accuracy", "/ (predicted_negative_num + 10E-10) F1 = 2 * precision *", "predict_label_list): if len(train_label_list) == len(predict_label_list): # compute precision and recall", "SibSp, Parch, Fare train_feature_intercept_term_added_tuple_list = map(lambda (PassengerId, Pclass, Sex, Age,", "def predict(self, train_feature_tuple_list, weight_matrix): ''' train_feature_tuple_list_without_PassengerId = map(lambda (PassengerId, InterceptTerm,", "1 elif predict_label_list[idx] == train_label_list[idx] == 0: true_negative_num = true_negative_num", "[] error_list = [] optimal_solution = {} for cur_iter in", "@Decorator.log_of_function def predict(self, train_feature_tuple_list, weight_matrix): ''' train_feature_tuple_list_without_PassengerId = map(lambda (PassengerId,", "1] weight_matrix[0] = weight_matrix[0] + learning_rate * (float(1)/train_sample_num) * train_input_matrix[:,", "<EMAIL> # Create: 2016-01-23 23:32:49 # Last: __author__ = 'yuens'", "abs(error.sum()) optimal_solution['weight_matrix'] = weight_matrix logging.info(\"optimal_solution['cur_iter']:{0}\".format(optimal_solution['cur_iter'])) logging.info(\"optimal_solution['cost':{0}\".format(optimal_solution['cost'])) logging.info(\"optimal_solution['abs(error.sum())']:{0}\".format(optimal_solution['abs(error.sum())'])) logging.info(\"optimal_solution['weight_matrix'].tolist():{0}\".format(optimal_solution['weight_matrix'].tolist())) #\"\"\" pylab.plot(cost_list)", "InterceptTerm, Pclass, Sex, Age, SibSp, Parch, Fare):\\ (InterceptTerm, Pclass, Sex,", "in quiting MySQL.\") except MySQLdb.Error, e: self.con.rollback() logging.error(\"Fail in quiting", "logging.info(\"len(train_label_list):{0}\".format(len(train_label_list))) logging.info(\"len(predict_label_list):{0}\".format(len(predict_label_list))) # compute accuracy def compute_accuracy(train_label_list, predict_label_list): right_predict_num =", "Pclass, Sex, Age, SibSp, Parch FROM {database_name}.{table_name} WHERE Is_train=0\"\"\"\\ .format(database_name", "Parch FROM {database_name}.{table_name} WHERE Is_train=0\"\"\"\\ .format(database_name = database_name,\\ table_name =", "cursor.execute(sql) if sql_idx == 0: train_data = cursor.fetchall() logging.info(\"len(train_data):{0}\".format(len(train_data))) logging.info(\"train_data[0]:{0}\".format(train_data[0]))", "return train_data, test_data @Decorator.log_of_function def add_intercept_term(self, train_feature_tuple_list, test_feature_tuple_list): logging.info(\"len(train_feature_tuple_list[0]):{0}\".format(len(train_feature_tuple_list[0]))) logging.info(\"len(train_feature_tuple_list):{0}\".format(len(train_feature_tuple_list)))", "def __init__(self): self.start = time.clock() logging.basicConfig(level = logging.INFO, format =", "fetch data from MySQL.\") logging.error(\"MySQL Error {error_num}: {error_info}.\".format(error_num = e.args[0],", "format = '%(asctime)s %(levelname)5s %(filename)19s[line:%(lineno)3d] %(funcName)s %(message)s', datefmt = '%y-%m-%d", "optimal_solution['abs(error.sum())'] > abs(error.sum()): optimal_solution['cur_iter'] = cur_iter optimal_solution['cost'] = cost optimal_solution['abs(error.sum())']", "if train_label_list[idx] == predict_label_list[idx]: right_predict_num = right_predict_num + 1 accuracy", "prob_idx in xrange(len(predict_prob_list)): predict_prob = predict_prob_list[prob_idx] if predict_prob > 0.5:", "close csv file try: result_csv_handle.close() logging.info(\"Success in closing file handle", "{0}.\".format(result_csv_dir)) except Exception as e: logging.error(\"Fail in closing file handle", "PassengerId, Survived, Pclass, Sex, Age, SibSp, Parch FROM {database_name}.{table_name} WHERE", "of {0}.\".format(result_csv_dir)) except Exception as e: logging.error(\"Fail in attaining file", "except Exception as e: logging.error(\"Fail in closing file handle of", "database_name, passenger_table_name): cursor = self.con.cursor() sql_list = [] # training", "predict_label_list.count(1) predicted_negative_num = predict_label_list.count(0) for idx in xrange(len(train_label_list)): if predict_label_list[idx]", "F1 = compute_precision_and_recall_and_F1(train_label_list = train_label_list,\\ predict_label_list = predict_label_list) logging.info(\"precision:{0}\".format(precision)) logging.info(\"recall:{0}\".format(recall))", "console.setFormatter(formatter) logging.getLogger('').addHandler(console) logging.info(\"START CLASS {class_name}.\".format(class_name = CreateLogisticRegressionModel.__name__)) try: self.con =", "- self.start)) @Decorator.log_of_function def get_data_from_database(self, database_name, passenger_table_name): cursor = self.con.cursor()", "* \\ # ( 1 / 1 * [891, 6].T", "time import pylab from numpy import * from math import", "[] optimal_solution = {} for cur_iter in xrange(max_iteration_time): # [891,", "* error # [6, 1] = [6, 1] + 1", "learning_rate = 0.01 # max_iteration_time = 500 ############################ ''' train_feature_tuple_list_without_PassengerId", "# Filename: class_create_model_of_logistic_regression.py # Description: # # Author: <NAME> #", "closing file handle of {0}.\".format(result_csv_dir)) except Exception as e: logging.error(\"Fail", "* error - \\ float(lambda_regularization) / train_sample_num * weight_matrix[1:] \\", "train_label_matrix.transpose()*log(hypothesis) + (1-train_label_matrix.transpose())*log(1-hypothesis) ) + \\ lambda_regularization / (2*train_sample_num) *", "= 0.01, max_iteration_time = 500, lambda_regularization = 0.1): ############################ #", "%H:%M:%S', filename = 'main.log', filemode = 'a') console = logging.StreamHandler()", "{0}.\".format(result_csv_dir)) logging.error(e) return -1 # create csv writer result_csv_writer =", "{error_info}.\".format(error_num = e.args[0], error_info = e.args[1])) logging.info(\"END CLASS {class_name}.\".format(class_name =", "= logging.Formatter('%(asctime)s %(levelname)5s %(filename)19s[line:%(lineno)3d] %(funcName)s %(message)s') console.setFormatter(formatter) logging.getLogger('').addHandler(console) logging.info(\"START CLASS", "train_feature_tuple_list, train_label_list, learning_rate = 0.01, max_iteration_time = 500, lambda_regularization =", "coding: utf-8 -*- # !/usr/bin/python ################################### PART0 DESCRIPTION ################################# #", "logging.info(\"train_feature_intercept_term_added_tuple_list[0]:{0}\".format(train_feature_intercept_term_added_tuple_list[0])) logging.info(\"len(test_feature_intercept_term_added_tuple_list):{0}\".format(len(test_feature_intercept_term_added_tuple_list))) logging.info(\"test_feature_intercept_term_added_tuple_list[0]:{0}\".format(test_feature_intercept_term_added_tuple_list[0])) return train_feature_intercept_term_added_tuple_list,\\ test_feature_intercept_term_added_tuple_list @Decorator.log_of_function def sigmoid_function(self, inX):", "{class_name} run time is : {delta_time} seconds\".format(class_name = CreateLogisticRegressionModel.__name__, delta_time", "''' train_feature_tuple_list_without_PassengerId = map(lambda (PassengerId, InterceptTerm, Pclass, Sex, Age, SibSp,", "23:32:49 # Last: __author__ = 'yuens' ################################### PART1 IMPORT ######################################", "= '%y-%m-%d %H:%M:%S', filename = 'main.log', filemode = 'a') console", "result_csv_writer.writerow([PassengerId, predict_label]) # close csv file try: result_csv_handle.close() logging.info(\"Success in", "\"\"\" # Initial parameters database_name = \"TitanicDB\" passenger_table_name = \"passenger_table\"", "file handle of {0}.\".format(result_csv_dir)) logging.error(e) @Decorator.log_of_function def plot_decision_bondary(self, weight_matrix): pass", "train_feature_tuple_list) test_feature_intercept_term_added_tuple_list = map(lambda (PassengerId, Pclass, Sex, Age, SibSp, Parch,", "F1 right_predict_num, accuracy = compute_accuracy(train_label_list = train_label_list,\\ predict_label_list = predict_label_list)", "== 1: test_data = cursor.fetchall() logging.info(\"len(test_data):{0}\".format(len(test_data))) logging.info(\"test_data[0]:{0}\".format(test_data[0])) logging.info(\"type(test_data[0]):{0}\".format(type(test_data[0]))) except MySQLdb.Error,", "1 = 1 + 1 * [891, 1].T *[891, 1]", "train_input_matrix[:, 0].transpose() * error # [6, 1] = [6, 1]", "compute_precision_and_recall_and_F1(train_label_list = train_label_list,\\ predict_label_list = predict_label_list) logging.info(\"precision:{0}\".format(precision)) logging.info(\"recall:{0}\".format(recall)) logging.info(\"F1:{0}\".format(F1)) return", ") weight_matrix[1:] = weight_matrix[1:] + learning_rate * \\ ( (float(1)/train_sample_num)", "* \\ sum( train_label_matrix.transpose()*log(hypothesis) + (1-train_label_matrix.transpose())*log(1-hypothesis) ) + \\ lambda_regularization", "Sex,\\ int(Age),\\ int(SibSp),\\ int(Parch)\\ ),\\ train_data) logging.info(\"len(train_data):{0}\".format(len(train_data))) logging.info(\"train_data[0]:{0}\".format(train_data[0])) logging.info(\"type(train_data[0]):{0}\".format(type(train_data[0]))) test_data", "[6, 1] = [6, 1] + 1 * \\ #", "10E-10 true_negative_num = 10E-10 predicted_positive_num = predict_label_list.count(1) predicted_negative_num = predict_label_list.count(0)", "PART3 CLASS TEST ################################## \"\"\" # Initial parameters database_name =", "feature_num = shape(train_input_matrix) weight_matrix = ones((feature_num, 1)) cost_list = []", "train_feature_tuple_list) ''' train_feature_tuple_list_without_PassengerId = map(lambda (PassengerId, InterceptTerm, Pclass, Sex, Age,", "in closing file handle of {0}.\".format(result_csv_dir)) logging.error(e) @Decorator.log_of_function def plot_decision_bondary(self,", "(float(1)/train_sample_num) * train_input_matrix[:, 1::].transpose() * error - \\ float(lambda_regularization) /", "self.con.close() logging.info(\"Success in quiting MySQL.\") except MySQLdb.Error, e: self.con.rollback() logging.error(\"Fail", "= e.args[0], error_info = e.args[1])) train_data = map(lambda (PassengerId, Survived,", "MySQL.\") except MySQLdb.Error, e: self.con.rollback() logging.error(\"Fail in quiting MySQL.\") logging.error(\"MySQL", "* from math import exp import csv import decorator_of_function ###################################", "len(train_feature_tuple_list[0]): 7 # PassengerId, Pclass, Sex, Age, SibSp, Parch, Fare", "[891, 7]*[7, 1] hypothesis = self.sigmoid_function(train_input_matrix * weight_matrix) # real", "1] error = train_label_matrix - hypothesis error_list.append(error) logging.info(\"cur_iter:{0}, cost:{1}, sum(error):{2}\".format(cur_iter+1,", "train_input_matrix[:, 1::].transpose() * error - \\ float(lambda_regularization) / train_sample_num *", "= cursor.fetchall() logging.info(\"len(test_data):{0}\".format(len(test_data))) logging.info(\"test_data[0]:{0}\".format(test_data[0])) logging.info(\"type(test_data[0]):{0}\".format(type(test_data[0]))) except MySQLdb.Error, e: self.con.rollback() logging.error(\"Fail", "optimal_solution = {} for cur_iter in xrange(max_iteration_time): # [891, 1]", "= predict_label_list[list_idx] result_csv_writer.writerow([PassengerId, predict_label]) # close csv file try: result_csv_handle.close()", "logging import time import pylab from numpy import * from", "in connecting MySQL.\") except MySQLdb.Error, e: logging.error(\"Fail in connecting MySQL.\")", "as e: logging.error(\"Fail in attaining file handle of {0}.\".format(result_csv_dir)) logging.error(e)", "# [6, 1] = [6, 1] + 1 * \\", "accuracy def compute_accuracy(train_label_list, predict_label_list): right_predict_num = 0 if len(train_label_list) ==", "(predicted_positive_num + 10E-10) recall = float(true_negative_num) / (predicted_negative_num + 10E-10)", "= MySQLdb.connect(host='localhost', user='root', passwd='<PASSWORD>', charset='utf8') logging.info(\"Success in connecting MySQL.\") except", "Parch, Fare):\\ (InterceptTerm, Sex, Fare),\\ train_feature_tuple_list) # [891, 7] train_input_matrix", "self.con = MySQLdb.connect(host='localhost', user='root', passwd='<PASSWORD>', charset='utf8') logging.info(\"Success in connecting MySQL.\")", "[] # training set sql_list.append(\"\"\"SELECT PassengerId, Survived, Pclass, Sex, Age,", "logging.getLogger('').addHandler(console) logging.info(\"START CLASS {class_name}.\".format(class_name = CreateLogisticRegressionModel.__name__)) try: self.con = MySQLdb.connect(host='localhost',", "list_idx in xrange(len(predict_label_list)): PassengerId = start_id + list_idx predict_label =", "1] # ) weight_matrix[1:] = weight_matrix[1:] + learning_rate * \\", "Sex, Age, SibSp, Parch, Fare),\\ train_feature_tuple_list) test_feature_intercept_term_added_tuple_list = map(lambda (PassengerId,", "weight_matrix = ones((feature_num, 1)) cost_list = [] error_list = []", "1 * [891, 6].T * [891, 1] # ) weight_matrix[1:]", "for i in xrange(row): print i+1, predict_label_matrix[i][0] ''' predict_prob_list =", "# ( 1 / 1 * [891, 6].T * [891,", "Age, SibSp, Parch, Fare),\\ train_feature_tuple_list) test_feature_intercept_term_added_tuple_list = map(lambda (PassengerId, Pclass,", "Exception as e: logging.error(\"Fail in attaining file handle of {0}.\".format(result_csv_dir))", "error_info = e.args[1])) train_data = map(lambda (PassengerId, Survived, Pclass, Sex,", "float(true_negative_num) / (predicted_negative_num + 10E-10) F1 = 2 * precision", "= cur_iter optimal_solution['cost'] = cost optimal_solution['abs(error.sum())'] = abs(error.sum()) optimal_solution['weight_matrix'] =", "test_data) logging.info(\"len(test_data):{0}\".format(len(test_data))) logging.info(\"test_data[0]:{0}\".format(test_data[0])) logging.info(\"type(test_data[0]):{0}\".format(type(test_data[0]))) return train_data, test_data @Decorator.log_of_function def add_intercept_term(self,", "Survived, Pclass, Sex, Age, SibSp, Parch):\\ (int(PassengerId),\\ int(Survived),\\ int(Pclass),\\ Sex,\\", "1: true_positive_num = true_positive_num + 1 elif predict_label_list[idx] == train_label_list[idx]", "logging.info(\"type(test_data[0]):{0}\".format(type(test_data[0]))) except MySQLdb.Error, e: self.con.rollback() logging.error(\"Fail in fetch data from", "file handle of {0}.\".format(result_csv_dir)) logging.error(e) return -1 # create csv", "500 ############################ ''' train_feature_tuple_list_without_PassengerId = map(lambda (PassengerId, InterceptTerm, Pclass, Sex,", "<NAME> # E-mail: <EMAIL> # Create: 2016-01-23 23:32:49 # Last:", "= abs(error.sum()) optimal_solution['weight_matrix'] = weight_matrix elif cur_iter != 0 and", "get_data_from_database(self, database_name, passenger_table_name): cursor = self.con.cursor() sql_list = [] #", "= 10E-10 predicted_positive_num = predict_label_list.count(1) predicted_negative_num = predict_label_list.count(0) for idx", "# compute precision and recall true_positive_num = 10E-10 true_negative_num =", "train_feature_intercept_term_added_tuple_list = map(lambda (PassengerId, Pclass, Sex, Age, SibSp, Parch, Fare):", "== 1: true_positive_num = true_positive_num + 1 elif predict_label_list[idx] ==", "train_input_matrix = mat(train_feature_tuple_list_without_PassengerId) predict_prob_matrix = self.sigmoid_function(train_input_matrix * weight_matrix) ''' row,", "file handle of {0}.\".format(result_csv_dir)) except Exception as e: logging.error(\"Fail in", "write csv file result_csv_writer.writerow([\"PassengerId\", \"Survived\"]) for list_idx in xrange(len(predict_label_list)): PassengerId", "of {0}.\".format(result_csv_dir)) logging.error(e) @Decorator.log_of_function def plot_decision_bondary(self, weight_matrix): pass ################################### PART3", "train_input_matrix.transpose() * error #\"\"\" # find optimal solution if cur_iter", "################################### PART3 CLASS TEST ################################## \"\"\" # Initial parameters database_name", "weight_matrix #return optimal_solution['weight_matrix'] @Decorator.log_of_function def predict(self, train_feature_tuple_list, weight_matrix): ''' train_feature_tuple_list_without_PassengerId", "optimal_solution['weight_matrix'] = weight_matrix elif cur_iter != 0 and optimal_solution['abs(error.sum())'] >", "true_positive_num = true_positive_num + 1 elif predict_label_list[idx] == train_label_list[idx] ==", "sum(error))) # 1 = 1 + 1 * [891, 1].T", "ones((feature_num, 1)) cost_list = [] error_list = [] optimal_solution =", "train_feature_tuple_list, test_feature_tuple_list): logging.info(\"len(train_feature_tuple_list[0]):{0}\".format(len(train_feature_tuple_list[0]))) logging.info(\"len(train_feature_tuple_list):{0}\".format(len(train_feature_tuple_list))) logging.info(\"train_feature_tuple_list[0]:{0}\".format(train_feature_tuple_list[0])) logging.info(\"test_feature_tuple_list[0]:{0}\".format(len(test_feature_tuple_list[0]))) logging.info(\"len(test_feature_tuple_list):{0}\".format(len(test_feature_tuple_list))) logging.info(\"test_feature_tuple_list[0]:{0}\".format(test_feature_tuple_list[0])) # len(train_feature_tuple_list[0]):", "{error_info}.\".format(error_num = e.args[0], error_info = e.args[1])) @Decorator.log_of_function def __del__(self): try:", "int(Pclass),\\ Sex,\\ int(Age),\\ int(SibSp),\\ int(Parch)\\ ),\\ train_data) logging.info(\"len(train_data):{0}\".format(len(train_data))) logging.info(\"train_data[0]:{0}\".format(train_data[0])) logging.info(\"type(train_data[0]):{0}\".format(type(train_data[0])))", "SibSp, Parch, Fare):\\ (InterceptTerm, Sex, Fare),\\ train_feature_tuple_list) # [891, 7]", "accuracy = float(right_predict_num)/len(train_label_list) return right_predict_num, accuracy def compute_precision_and_recall_and_F1(train_label_list, predict_label_list): if", "= [6, 1] + 1 * \\ # ( 1", "map(lambda (PassengerId, Survived, Pclass, Sex, Age, SibSp, Parch):\\ (int(PassengerId),\\ int(Survived),\\", "connecting MySQL.\") logging.error(\"MySQL Error {error_num}: {error_info}.\".format(error_num = e.args[0], error_info =", "Age, SibSp, Parch):\\ (int(PassengerId),\\ int(Survived),\\ int(Pclass),\\ Sex,\\ int(Age),\\ int(SibSp),\\ int(Parch)\\", "6].T * [891, 1] # ) weight_matrix[1:] = weight_matrix[1:] +", "Fare): \\ (PassengerId, 1.0, Pclass, Sex, Age, SibSp, Parch, Fare),\\", "precision = float(true_positive_num) / (predicted_positive_num + 10E-10) recall = float(true_negative_num)", "Last: __author__ = 'yuens' ################################### PART1 IMPORT ###################################### import MySQLdb", "1]) cost = -float(1) / (train_sample_num) * \\ sum( train_label_matrix.transpose()*log(hypothesis)", "compute accuracy def compute_accuracy(train_label_list, predict_label_list): right_predict_num = 0 if len(train_label_list)", "\\ float(lambda_regularization) / train_sample_num * weight_matrix[1:] \\ ) #weight_matrix =", "= '%(asctime)s %(levelname)5s %(filename)19s[line:%(lineno)3d] %(funcName)s %(message)s', datefmt = '%y-%m-%d %H:%M:%S',", "= true_positive_num + 1 elif predict_label_list[idx] == train_label_list[idx] == 0:", "map(lambda (PassengerId, InterceptTerm, Pclass, Sex, Age, SibSp, Parch, Fare):\\ (InterceptTerm,", "attaining file handle of {0}.\".format(result_csv_dir)) logging.error(e) return -1 # create", "\\ lambda_regularization / (2*train_sample_num) * (array(weight_matrix[1:]) * array(weight_matrix[1:])).sum() cost_list.append(cost) #", "############################ ''' train_feature_tuple_list_without_PassengerId = map(lambda (PassengerId, InterceptTerm, Pclass, Sex, Age,", "\\ (PassengerId, 1.0, Pclass, Sex, Age, SibSp, Parch, Fare),\\ train_feature_tuple_list)", "Pclass, Sex, Age, SibSp, Parch, Fare),\\ train_feature_tuple_list) ''' train_feature_tuple_list_without_PassengerId =", "# [891, 1] <- [891, 7]*[7, 1] hypothesis = self.sigmoid_function(train_input_matrix", "predict_label = predict_label_list[list_idx] result_csv_writer.writerow([PassengerId, predict_label]) # close csv file try:", "(PassengerId, Pclass, Sex, Age, SibSp, Parch, Fare): \\ (PassengerId, 1.0,", "mat(train_label_list).transpose() train_sample_num, feature_num = shape(train_input_matrix) weight_matrix = ones((feature_num, 1)) cost_list", "training set sql_list.append(\"\"\"SELECT PassengerId, Survived, Pclass, Sex, Age, SibSp, Parch", "logging.INFO, format = '%(asctime)s %(levelname)5s %(filename)19s[line:%(lineno)3d] %(funcName)s %(message)s', datefmt =", "e.args[1])) @Decorator.log_of_function def __del__(self): try: self.con.close() logging.info(\"Success in quiting MySQL.\")", "# create csv writer result_csv_writer = csv.writer(result_csv_handle) # write csv", "predict_label_list[idx]: right_predict_num = right_predict_num + 1 accuracy = float(right_predict_num)/len(train_label_list) return", "true_positive_num + 1 elif predict_label_list[idx] == train_label_list[idx] == 0: true_negative_num", "SibSp, Parch, Fare): \\ (PassengerId, 1.0, Pclass, Sex, Age, SibSp,", "= train_label_list,\\ predict_label_list = predict_label_list) logging.info(\"precision:{0}\".format(precision)) logging.info(\"recall:{0}\".format(recall)) logging.info(\"F1:{0}\".format(F1)) return accuracy,", "right_predict_num = right_predict_num + 1 accuracy = float(right_predict_num)/len(train_label_list) return right_predict_num,", "PART0 DESCRIPTION ################################# # Filename: class_create_model_of_logistic_regression.py # Description: # #", "logging.info(\"type(train_data[0]):{0}\".format(type(train_data[0]))) test_data = map(lambda (PassengerId, Survived, Pclass, Sex, Age, SibSp,", "def sigmoid_function(self, inX): return 1.0 / (1.0 + exp(-inX)) @Decorator.log_of_function", "parameters # learning_rate = 0.01 # max_iteration_time = 500 ############################", "decorator_of_function ################################### PART2 CLASS && FUNCTION ########################### class CreateLogisticRegressionModel(object): Decorator", "SibSp, Parch):\\ (int(PassengerId),\\ int(Survived),\\ int(Pclass),\\ Sex,\\ int(Age),\\ int(SibSp),\\ int(Parch)\\ ),\\", "database_name,\\ table_name = passenger_table_name)\\ ) for sql_idx in xrange(len(sql_list)): sql", "+ 1 accuracy = float(right_predict_num)/len(train_label_list) return right_predict_num, accuracy def compute_precision_and_recall_and_F1(train_label_list,", "compute_accuracy(train_label_list = train_label_list,\\ predict_label_list = predict_label_list) logging.info(\"right_predict_num:{0}\".format(right_predict_num)) logging.info(\"accuracy:{0}\".format(accuracy)) precision, recall,", "Pclass, Sex, Age, SibSp, Parch, Fare):\\ (InterceptTerm, Sex, Fare),\\ train_feature_tuple_list)", "= [] optimal_solution = {} for cur_iter in xrange(max_iteration_time): #", "import MySQLdb import logging import time import pylab from numpy", "precision * recall / (precision + recall) return precision, recall,", "train_input_matrix = mat(train_feature_tuple_list_without_PassengerId) # [891, 1] train_label_matrix = mat(train_label_list).transpose() train_sample_num,", "# Initial parameters database_name = \"TitanicDB\" passenger_table_name = \"passenger_table\" LRModel", "Sex,\\ int(Age),\\ int(SibSp),\\ int(Parch)\\ ),\\ test_data) logging.info(\"len(test_data):{0}\".format(len(test_data))) logging.info(\"test_data[0]:{0}\".format(test_data[0])) logging.info(\"type(test_data[0]):{0}\".format(type(test_data[0]))) return", "\\ ( (float(1)/train_sample_num) * train_input_matrix[:, 1::].transpose() * error - \\", "print i+1, predict_label_matrix[i][0] ''' predict_prob_list = predict_prob_matrix.transpose().tolist()[0] predict_label_list = []", "= 0 if len(train_label_list) == len(predict_label_list): for idx in xrange(len(train_label_list)):", "Fare):\\ (InterceptTerm, Sex, Fare),\\ train_feature_tuple_list) # [891, 7] train_input_matrix =", "# ) weight_matrix[1:] = weight_matrix[1:] + learning_rate * \\ (", "{error_num}: {error_info}.\".format(error_num = e.args[0], error_info = e.args[1])) @Decorator.log_of_function def __del__(self):", "'main.log', filemode = 'a') console = logging.StreamHandler() console.setLevel(logging.INFO) formatter =", "logging.info(\"optimal_solution['abs(error.sum())']:{0}\".format(optimal_solution['abs(error.sum())'])) logging.info(\"optimal_solution['weight_matrix'].tolist():{0}\".format(optimal_solution['weight_matrix'].tolist())) #\"\"\" pylab.plot(cost_list) pylab.show() return weight_matrix #return optimal_solution['weight_matrix'] @Decorator.log_of_function", "= predict_label_list) logging.info(\"right_predict_num:{0}\".format(right_predict_num)) logging.info(\"accuracy:{0}\".format(accuracy)) precision, recall, F1 = compute_precision_and_recall_and_F1(train_label_list =", "sql_idx == 0: train_data = cursor.fetchall() logging.info(\"len(train_data):{0}\".format(len(train_data))) logging.info(\"train_data[0]:{0}\".format(train_data[0])) logging.info(\"type(train_data[0]):{0}\".format(type(train_data[0]))) elif", "weight_matrix elif cur_iter != 0 and optimal_solution['abs(error.sum())'] > abs(error.sum()): optimal_solution['cur_iter']", "logging.info(\"len(test_data):{0}\".format(len(test_data))) logging.info(\"test_data[0]:{0}\".format(test_data[0])) logging.info(\"type(test_data[0]):{0}\".format(type(test_data[0]))) return train_data, test_data @Decorator.log_of_function def add_intercept_term(self, train_feature_tuple_list,", "train_data, test_data @Decorator.log_of_function def add_intercept_term(self, train_feature_tuple_list, test_feature_tuple_list): logging.info(\"len(train_feature_tuple_list[0]):{0}\".format(len(train_feature_tuple_list[0]))) logging.info(\"len(train_feature_tuple_list):{0}\".format(len(train_feature_tuple_list))) logging.info(\"train_feature_tuple_list[0]:{0}\".format(train_feature_tuple_list[0]))", "cost_list = [] error_list = [] optimal_solution = {} for", "= train_label_matrix - hypothesis error_list.append(error) logging.info(\"cur_iter:{0}, cost:{1}, sum(error):{2}\".format(cur_iter+1, cost, sum(error)))", "Survived, Pclass, Sex, Age, SibSp, Parch FROM {database_name}.{table_name} WHERE Is_train=0\"\"\"\\", "optimal_solution['cost'] = cost optimal_solution['abs(error.sum())'] = abs(error.sum()) optimal_solution['weight_matrix'] = weight_matrix logging.info(\"optimal_solution['cur_iter']:{0}\".format(optimal_solution['cur_iter']))", "train_label_list[idx] == 1: true_positive_num = true_positive_num + 1 elif predict_label_list[idx]", "data from MySQL.\") logging.error(\"MySQL Error {error_num}: {error_info}.\".format(error_num = e.args[0], error_info", "for prob_idx in xrange(len(predict_prob_list)): predict_prob = predict_prob_list[prob_idx] if predict_prob >", "FUNCTION ########################### class CreateLogisticRegressionModel(object): Decorator = decorator_of_function.CreateDecorator() @Decorator.log_of_function def __init__(self):", "Fare),\\ train_feature_tuple_list) test_feature_intercept_term_added_tuple_list = map(lambda (PassengerId, Pclass, Sex, Age, SibSp,", "precision, recall, F1 = compute_precision_and_recall_and_F1(train_label_list = train_label_list,\\ predict_label_list = predict_label_list)", "# max_iteration_time = 500 ############################ ''' train_feature_tuple_list_without_PassengerId = map(lambda (PassengerId,", "+ learning_rate * train_input_matrix.transpose() * error #\"\"\" # find optimal", "/ (2*train_sample_num) * (array(weight_matrix[1:]) * array(weight_matrix[1:])).sum() cost_list.append(cost) # [891, 1]", "1].T *[891, 1] weight_matrix[0] = weight_matrix[0] + learning_rate * (float(1)/train_sample_num)", "predict_label]) # close csv file try: result_csv_handle.close() logging.info(\"Success in closing", "len(train_label_list) == len(predict_label_list): # compute precision and recall true_positive_num =", "logging.info(\"type(test_data[0]):{0}\".format(type(test_data[0]))) return train_data, test_data @Decorator.log_of_function def add_intercept_term(self, train_feature_tuple_list, test_feature_tuple_list): logging.info(\"len(train_feature_tuple_list[0]):{0}\".format(len(train_feature_tuple_list[0])))", "= true_negative_num + 1 precision = float(true_positive_num) / (predicted_positive_num +", "1 * \\ # ( 1 / 1 * [891,", "@Decorator.log_of_function def get_data_from_database(self, database_name, passenger_table_name): cursor = self.con.cursor() sql_list =", "logging.info(\"The class {class_name} run time is : {delta_time} seconds\".format(class_name =", "table_name = passenger_table_name)\\ ) for sql_idx in xrange(len(sql_list)): sql =", "train_feature_tuple_list) train_input_matrix = mat(train_feature_tuple_list_without_PassengerId) predict_prob_matrix = self.sigmoid_function(train_input_matrix * weight_matrix) '''", "@Decorator.log_of_function def __del__(self): try: self.con.close() logging.info(\"Success in quiting MySQL.\") except", "float(lambda_regularization) / train_sample_num * weight_matrix[1:] \\ ) #weight_matrix = weight_matrix", "e.args[0], error_info = e.args[1])) logging.info(\"END CLASS {class_name}.\".format(class_name = CreateLogisticRegressionModel.__name__)) self.end", "# !/usr/bin/python ################################### PART0 DESCRIPTION ################################# # Filename: class_create_model_of_logistic_regression.py #", "= self.con.cursor() sql_list = [] # training set sql_list.append(\"\"\"SELECT PassengerId,", "= train_label_list,\\ predict_label_list = predict_label_list) logging.info(\"right_predict_num:{0}\".format(right_predict_num)) logging.info(\"accuracy:{0}\".format(accuracy)) precision, recall, F1", "elif sql_idx == 1: test_data = cursor.fetchall() logging.info(\"len(test_data):{0}\".format(len(test_data))) logging.info(\"test_data[0]:{0}\".format(test_data[0])) logging.info(\"type(test_data[0]):{0}\".format(type(test_data[0])))", "<filename>Titanic/class_create_model_of_logistic_regression.py<gh_stars>1-10 # -*- coding: utf-8 -*- # !/usr/bin/python ################################### PART0", "and optimal_solution['abs(error.sum())'] > abs(error.sum()): optimal_solution['cur_iter'] = cur_iter optimal_solution['cost'] = cost", "closing file handle of {0}.\".format(result_csv_dir)) logging.error(e) @Decorator.log_of_function def plot_decision_bondary(self, weight_matrix):", "predict_label_list.append(0) return predict_label_list @Decorator.log_of_function def accuracy(self, train_label_list, predict_label_list): logging.info(\"len(train_label_list):{0}\".format(len(train_label_list))) logging.info(\"len(predict_label_list):{0}\".format(len(predict_label_list)))", "if predict_prob > 0.5: predict_label_list.append(1) else: predict_label_list.append(0) return predict_label_list @Decorator.log_of_function", "'a') console = logging.StreamHandler() console.setLevel(logging.INFO) formatter = logging.Formatter('%(asctime)s %(levelname)5s %(filename)19s[line:%(lineno)3d]", "e: logging.error(\"Fail in attaining file handle of {0}.\".format(result_csv_dir)) logging.error(e) return", "Fare):\\ (InterceptTerm, Pclass, Sex, Age, SibSp, Parch, Fare),\\ train_feature_tuple_list) '''", "# len(train_feature_tuple_list[0]): 7 # PassengerId, Pclass, Sex, Age, SibSp, Parch,", "train_feature_tuple_list_without_PassengerId = map(lambda (PassengerId, InterceptTerm, Pclass, Sex, Age, SibSp, Parch,", "int(SibSp),\\ int(Parch)\\ ),\\ test_data) logging.info(\"len(test_data):{0}\".format(len(test_data))) logging.info(\"test_data[0]:{0}\".format(test_data[0])) logging.info(\"type(test_data[0]):{0}\".format(type(test_data[0]))) return train_data, test_data", "weight_matrix logging.info(\"optimal_solution['cur_iter']:{0}\".format(optimal_solution['cur_iter'])) logging.info(\"optimal_solution['cost':{0}\".format(optimal_solution['cost'])) logging.info(\"optimal_solution['abs(error.sum())']:{0}\".format(optimal_solution['abs(error.sum())'])) logging.info(\"optimal_solution['weight_matrix'].tolist():{0}\".format(optimal_solution['weight_matrix'].tolist())) #\"\"\" pylab.plot(cost_list) pylab.show() return weight_matrix", "= csv.writer(result_csv_handle) # write csv file result_csv_writer.writerow([\"PassengerId\", \"Survived\"]) for list_idx", "console.setLevel(logging.INFO) formatter = logging.Formatter('%(asctime)s %(levelname)5s %(filename)19s[line:%(lineno)3d] %(funcName)s %(message)s') console.setFormatter(formatter) logging.getLogger('').addHandler(console)", "test_data = cursor.fetchall() logging.info(\"len(test_data):{0}\".format(len(test_data))) logging.info(\"test_data[0]:{0}\".format(test_data[0])) logging.info(\"type(test_data[0]):{0}\".format(type(test_data[0]))) except MySQLdb.Error, e: self.con.rollback()", "SibSp, Parch, Fare),\\ train_feature_tuple_list) test_feature_intercept_term_added_tuple_list = map(lambda (PassengerId, Pclass, Sex,", "if len(train_label_list) == len(predict_label_list): for idx in xrange(len(train_label_list)): if train_label_list[idx]", "sum([891, 1]T*[891, 1] + [891, 1]T*[891, 1]) cost = -float(1)", "Age, SibSp, Parch, Fare train_feature_intercept_term_added_tuple_list = map(lambda (PassengerId, Pclass, Sex,", "test_feature_tuple_list) logging.info(\"len(train_feature_intercept_term_added_tuple_list):{0}\".format(len(train_feature_intercept_term_added_tuple_list))) logging.info(\"train_feature_intercept_term_added_tuple_list[0]:{0}\".format(train_feature_intercept_term_added_tuple_list[0])) logging.info(\"len(test_feature_intercept_term_added_tuple_list):{0}\".format(len(test_feature_intercept_term_added_tuple_list))) logging.info(\"test_feature_intercept_term_added_tuple_list[0]:{0}\".format(test_feature_intercept_term_added_tuple_list[0])) return train_feature_intercept_term_added_tuple_list,\\ test_feature_intercept_term_added_tuple_list @Decorator.log_of_function def", "return -1 # create csv writer result_csv_writer = csv.writer(result_csv_handle) #", "quiting MySQL.\") logging.error(\"MySQL Error {error_num}: {error_info}.\".format(error_num = e.args[0], error_info =", "1.0, Pclass, Sex, Age, SibSp, Parch, Fare),\\ train_feature_tuple_list) test_feature_intercept_term_added_tuple_list =", "cost optimal_solution['abs(error.sum())'] = abs(error.sum()) optimal_solution['weight_matrix'] = weight_matrix logging.info(\"optimal_solution['cur_iter']:{0}\".format(optimal_solution['cur_iter'])) logging.info(\"optimal_solution['cost':{0}\".format(optimal_solution['cost'])) logging.info(\"optimal_solution['abs(error.sum())']:{0}\".format(optimal_solution['abs(error.sum())']))", "for idx in xrange(len(train_label_list)): if train_label_list[idx] == predict_label_list[idx]: right_predict_num =", "passenger_table_name)\\ ) # test set sql_list.append(\"\"\"SELECT PassengerId, Survived, Pclass, Sex,", "len(predict_label_list): # compute precision and recall true_positive_num = 10E-10 true_negative_num", "SibSp, Parch FROM {database_name}.{table_name} WHERE Is_train=1\"\"\"\\ .format(database_name = database_name,\\ table_name", "predict_label_list.append(1) else: predict_label_list.append(0) return predict_label_list @Decorator.log_of_function def accuracy(self, train_label_list, predict_label_list):", "{database_name}.{table_name} WHERE Is_train=1\"\"\"\\ .format(database_name = database_name,\\ table_name = passenger_table_name)\\ )", "predict_label_list = [] for prob_idx in xrange(len(predict_prob_list)): predict_prob = predict_prob_list[prob_idx]", "* weight_matrix) ''' row, col = shape(predict_label_matrix) for i in", "accuracy(self, train_label_list, predict_label_list): logging.info(\"len(train_label_list):{0}\".format(len(train_label_list))) logging.info(\"len(predict_label_list):{0}\".format(len(predict_label_list))) # compute accuracy def compute_accuracy(train_label_list,", "learning_rate * (float(1)/train_sample_num) * train_input_matrix[:, 0].transpose() * error # [6,", "MySQLdb.connect(host='localhost', user='root', passwd='<PASSWORD>', charset='utf8') logging.info(\"Success in connecting MySQL.\") except MySQLdb.Error,", "1 precision = float(true_positive_num) / (predicted_positive_num + 10E-10) recall =", "10E-10) recall = float(true_negative_num) / (predicted_negative_num + 10E-10) F1 =", "learning_rate * train_input_matrix.transpose() * error #\"\"\" # find optimal solution", "formatter = logging.Formatter('%(asctime)s %(levelname)5s %(filename)19s[line:%(lineno)3d] %(funcName)s %(message)s') console.setFormatter(formatter) logging.getLogger('').addHandler(console) logging.info(\"START", "!= 0 and optimal_solution['abs(error.sum())'] > abs(error.sum()): optimal_solution['cur_iter'] = cur_iter optimal_solution['cost']", "logging.error(e) return -1 # create csv writer result_csv_writer = csv.writer(result_csv_handle)", "= map(lambda (PassengerId, Survived, Pclass, Sex, Age, SibSp, Parch):\\ (int(PassengerId),\\", "lambda_regularization = 0.1): ############################ # Initial parameters # learning_rate =", "in xrange(max_iteration_time): # [891, 1] <- [891, 7]*[7, 1] hypothesis", "CLASS {class_name}.\".format(class_name = CreateLogisticRegressionModel.__name__)) self.end = time.clock() logging.info(\"The class {class_name}", "1)) cost_list = [] error_list = [] optimal_solution = {}", "# [891, 1] error = train_label_matrix - hypothesis error_list.append(error) logging.info(\"cur_iter:{0},", "mat(train_feature_tuple_list_without_PassengerId) # [891, 1] train_label_matrix = mat(train_label_list).transpose() train_sample_num, feature_num =", "),\\ train_data) logging.info(\"len(train_data):{0}\".format(len(train_data))) logging.info(\"train_data[0]:{0}\".format(train_data[0])) logging.info(\"type(train_data[0]):{0}\".format(type(train_data[0]))) test_data = map(lambda (PassengerId, Survived,", "connecting MySQL.\") except MySQLdb.Error, e: logging.error(\"Fail in connecting MySQL.\") logging.error(\"MySQL", "error - \\ float(lambda_regularization) / train_sample_num * weight_matrix[1:] \\ )", "csv.writer(result_csv_handle) # write csv file result_csv_writer.writerow([\"PassengerId\", \"Survived\"]) for list_idx in", "Fare),\\ train_feature_tuple_list) ''' train_feature_tuple_list_without_PassengerId = map(lambda (PassengerId, InterceptTerm, Pclass, Sex,", "* [891, 6].T * [891, 1] # ) weight_matrix[1:] =", "if cur_iter == 0: optimal_solution['cur_iter'] = cur_iter optimal_solution['cost'] = cost", "import pylab from numpy import * from math import exp", "1]T*[891, 1] + [891, 1]T*[891, 1]) cost = -float(1) /", "[6, 1] + 1 * \\ # ( 1 /", "elif predict_label_list[idx] == train_label_list[idx] == 0: true_negative_num = true_negative_num +", "Age, SibSp, Parch FROM {database_name}.{table_name} WHERE Is_train=1\"\"\"\\ .format(database_name = database_name,\\", "{database_name}.{table_name} WHERE Is_train=0\"\"\"\\ .format(database_name = database_name,\\ table_name = passenger_table_name)\\ )", "{} for cur_iter in xrange(max_iteration_time): # [891, 1] <- [891,", "lambda_regularization / (2*train_sample_num) * (array(weight_matrix[1:]) * array(weight_matrix[1:])).sum() cost_list.append(cost) # [891,", "(float(1)/train_sample_num) * train_input_matrix[:, 0].transpose() * error # [6, 1] =", "* train_input_matrix.transpose() * error #\"\"\" # find optimal solution if", "Fare),\\ train_feature_tuple_list) train_input_matrix = mat(train_feature_tuple_list_without_PassengerId) predict_prob_matrix = self.sigmoid_function(train_input_matrix * weight_matrix)", "abs(error.sum()) optimal_solution['weight_matrix'] = weight_matrix elif cur_iter != 0 and optimal_solution['abs(error.sum())']", "logging.info(\"cur_iter:{0}, cost:{1}, sum(error):{2}\".format(cur_iter+1, cost, sum(error))) # 1 = 1 +", "passwd='<PASSWORD>', charset='utf8') logging.info(\"Success in connecting MySQL.\") except MySQLdb.Error, e: logging.error(\"Fail", "= predict_prob_list[prob_idx] if predict_prob > 0.5: predict_label_list.append(1) else: predict_label_list.append(0) return", "logging.info(\"Success in quiting MySQL.\") except MySQLdb.Error, e: self.con.rollback() logging.error(\"Fail in", "pass ################################### PART3 CLASS TEST ################################## \"\"\" # Initial parameters", "(PassengerId, InterceptTerm, Pclass, Sex, Age, SibSp, Parch, Fare):\\ (InterceptTerm, Sex,", "logging.info(\"len(test_feature_intercept_term_added_tuple_list):{0}\".format(len(test_feature_intercept_term_added_tuple_list))) logging.info(\"test_feature_intercept_term_added_tuple_list[0]:{0}\".format(test_feature_intercept_term_added_tuple_list[0])) return train_feature_intercept_term_added_tuple_list,\\ test_feature_intercept_term_added_tuple_list @Decorator.log_of_function def sigmoid_function(self, inX): return", "= time.clock() logging.info(\"The class {class_name} run time is : {delta_time}", "1]T*[891, 1]) cost = -float(1) / (train_sample_num) * \\ sum(", "''' row, col = shape(predict_label_matrix) for i in xrange(row): print", "(InterceptTerm, Sex, Fare),\\ train_feature_tuple_list) # [891, 7] train_input_matrix = mat(train_feature_tuple_list_without_PassengerId)", "import * from math import exp import csv import decorator_of_function", "(PassengerId, Survived, Pclass, Sex, Age, SibSp, Parch):\\ (int(PassengerId),\\ int(Survived),\\ int(Pclass),\\", "2 * precision * recall / (precision + recall) return", "logging.info(\"Success in closing file handle of {0}.\".format(result_csv_dir)) except Exception as", "logging.error(\"Fail in fetch data from MySQL.\") logging.error(\"MySQL Error {error_num}: {error_info}.\".format(error_num", "= 0.1): ############################ # Initial parameters # learning_rate = 0.01", "predict_prob = predict_prob_list[prob_idx] if predict_prob > 0.5: predict_label_list.append(1) else: predict_label_list.append(0)", "add_intercept_term(self, train_feature_tuple_list, test_feature_tuple_list): logging.info(\"len(train_feature_tuple_list[0]):{0}\".format(len(train_feature_tuple_list[0]))) logging.info(\"len(train_feature_tuple_list):{0}\".format(len(train_feature_tuple_list))) logging.info(\"train_feature_tuple_list[0]:{0}\".format(train_feature_tuple_list[0])) logging.info(\"test_feature_tuple_list[0]:{0}\".format(len(test_feature_tuple_list[0]))) logging.info(\"len(test_feature_tuple_list):{0}\".format(len(test_feature_tuple_list))) logging.info(\"test_feature_tuple_list[0]:{0}\".format(test_feature_tuple_list[0])) #", "logging.info(\"train_feature_tuple_list[0]:{0}\".format(train_feature_tuple_list[0])) logging.info(\"test_feature_tuple_list[0]:{0}\".format(len(test_feature_tuple_list[0]))) logging.info(\"len(test_feature_tuple_list):{0}\".format(len(test_feature_tuple_list))) logging.info(\"test_feature_tuple_list[0]:{0}\".format(test_feature_tuple_list[0])) # len(train_feature_tuple_list[0]): 7 # PassengerId, Pclass,", "weight_matrix): ''' train_feature_tuple_list_without_PassengerId = map(lambda (PassengerId, InterceptTerm, Pclass, Sex, Age,", "right_predict_num, accuracy def compute_precision_and_recall_and_F1(train_label_list, predict_label_list): if len(train_label_list) == len(predict_label_list): #", "500, lambda_regularization = 0.1): ############################ # Initial parameters # learning_rate", "F1 @Decorator.log_of_function def write_csv_file(self, start_id, predict_label_list, result_csv_dir): # open csv", "IMPORT ###################################### import MySQLdb import logging import time import pylab", "test_feature_intercept_term_added_tuple_list = map(lambda (PassengerId, Pclass, Sex, Age, SibSp, Parch, Fare):", "class CreateLogisticRegressionModel(object): Decorator = decorator_of_function.CreateDecorator() @Decorator.log_of_function def __init__(self): self.start =", "(PassengerId, 1.0, Pclass, Sex, Age, SibSp, Parch, Fare),\\ train_feature_tuple_list) test_feature_intercept_term_added_tuple_list", "inX): return 1.0 / (1.0 + exp(-inX)) @Decorator.log_of_function def gradient_descent(self,", "> abs(error.sum()): optimal_solution['cur_iter'] = cur_iter optimal_solution['cost'] = cost optimal_solution['abs(error.sum())'] =", "self.sigmoid_function(train_input_matrix * weight_matrix) # real <- sum([891, 1]T*[891, 1] +", "train_label_list,\\ predict_label_list = predict_label_list) logging.info(\"right_predict_num:{0}\".format(right_predict_num)) logging.info(\"accuracy:{0}\".format(accuracy)) precision, recall, F1 =", "# Initial parameters # learning_rate = 0.01 # max_iteration_time =", "10E-10 predicted_positive_num = predict_label_list.count(1) predicted_negative_num = predict_label_list.count(0) for idx in", "+ 10E-10) F1 = 2 * precision * recall /", "try: cursor.execute(sql) if sql_idx == 0: train_data = cursor.fetchall() logging.info(\"len(train_data):{0}\".format(len(train_data)))", "sum(error):{2}\".format(cur_iter+1, cost, sum(error))) # 1 = 1 + 1 *", "in xrange(len(sql_list)): sql = sql_list[sql_idx] try: cursor.execute(sql) if sql_idx ==", "''' predict_prob_list = predict_prob_matrix.transpose().tolist()[0] predict_label_list = [] for prob_idx in", "predict_label_list) logging.info(\"right_predict_num:{0}\".format(right_predict_num)) logging.info(\"accuracy:{0}\".format(accuracy)) precision, recall, F1 = compute_precision_and_recall_and_F1(train_label_list = train_label_list,\\", "time.clock() logging.info(\"The class {class_name} run time is : {delta_time} seconds\".format(class_name", "Survived, Pclass, Sex, Age, SibSp, Parch FROM {database_name}.{table_name} WHERE Is_train=1\"\"\"\\", "== 0: train_data = cursor.fetchall() logging.info(\"len(train_data):{0}\".format(len(train_data))) logging.info(\"train_data[0]:{0}\".format(train_data[0])) logging.info(\"type(train_data[0]):{0}\".format(type(train_data[0]))) elif sql_idx", "* weight_matrix[1:] \\ ) #weight_matrix = weight_matrix + learning_rate *", "find optimal solution if cur_iter == 0: optimal_solution['cur_iter'] = cur_iter", "= self.sigmoid_function(train_input_matrix * weight_matrix) ''' row, col = shape(predict_label_matrix) for", "database_name = \"TitanicDB\" passenger_table_name = \"passenger_table\" LRModel = CreateLogisticRegressionModel() \"\"\"", "(1-train_label_matrix.transpose())*log(1-hypothesis) ) + \\ lambda_regularization / (2*train_sample_num) * (array(weight_matrix[1:]) *", "= predict_prob_matrix.transpose().tolist()[0] predict_label_list = [] for prob_idx in xrange(len(predict_prob_list)): predict_prob", "weight_matrix[0] = weight_matrix[0] + learning_rate * (float(1)/train_sample_num) * train_input_matrix[:, 0].transpose()", "real <- sum([891, 1]T*[891, 1] + [891, 1]T*[891, 1]) cost", "train_feature_intercept_term_added_tuple_list,\\ test_feature_intercept_term_added_tuple_list @Decorator.log_of_function def sigmoid_function(self, inX): return 1.0 / (1.0", "train_sample_num * weight_matrix[1:] \\ ) #weight_matrix = weight_matrix + learning_rate", "Parch):\\ (int(PassengerId),\\ int(Survived),\\ int(Pclass),\\ Sex,\\ int(Age),\\ int(SibSp),\\ int(Parch)\\ ),\\ test_data)", "#weight_matrix = weight_matrix + learning_rate * train_input_matrix.transpose() * error #\"\"\"", "max_iteration_time = 500 ############################ ''' train_feature_tuple_list_without_PassengerId = map(lambda (PassengerId, InterceptTerm,", "= time.clock() logging.basicConfig(level = logging.INFO, format = '%(asctime)s %(levelname)5s %(filename)19s[line:%(lineno)3d]", "train_feature_tuple_list, weight_matrix): ''' train_feature_tuple_list_without_PassengerId = map(lambda (PassengerId, InterceptTerm, Pclass, Sex,", "logging.info(\"right_predict_num:{0}\".format(right_predict_num)) logging.info(\"accuracy:{0}\".format(accuracy)) precision, recall, F1 = compute_precision_and_recall_and_F1(train_label_list = train_label_list,\\ predict_label_list", "(int(PassengerId),\\ int(Survived),\\ int(Pclass),\\ Sex,\\ int(Age),\\ int(SibSp),\\ int(Parch)\\ ),\\ test_data) logging.info(\"len(test_data):{0}\".format(len(test_data)))", "E-mail: <EMAIL> # Create: 2016-01-23 23:32:49 # Last: __author__ =", "CLASS {class_name}.\".format(class_name = CreateLogisticRegressionModel.__name__)) try: self.con = MySQLdb.connect(host='localhost', user='root', passwd='<PASSWORD>',", "in xrange(row): print i+1, predict_label_matrix[i][0] ''' predict_prob_list = predict_prob_matrix.transpose().tolist()[0] predict_label_list", "<- [891, 7]*[7, 1] hypothesis = self.sigmoid_function(train_input_matrix * weight_matrix) #", "/ 1 * [891, 6].T * [891, 1] # )", "Parch, Fare):\\ (InterceptTerm, Sex, Fare),\\ train_feature_tuple_list) train_input_matrix = mat(train_feature_tuple_list_without_PassengerId) predict_prob_matrix", "= decorator_of_function.CreateDecorator() @Decorator.log_of_function def __init__(self): self.start = time.clock() logging.basicConfig(level =", "1] + 1 * \\ # ( 1 / 1", "train_label_list, predict_label_list): logging.info(\"len(train_label_list):{0}\".format(len(train_label_list))) logging.info(\"len(predict_label_list):{0}\".format(len(predict_label_list))) # compute accuracy def compute_accuracy(train_label_list, predict_label_list):", "= compute_precision_and_recall_and_F1(train_label_list = train_label_list,\\ predict_label_list = predict_label_list) logging.info(\"precision:{0}\".format(precision)) logging.info(\"recall:{0}\".format(recall)) logging.info(\"F1:{0}\".format(F1))", "right_predict_num = 0 if len(train_label_list) == len(predict_label_list): for idx in", "compute_precision_and_recall_and_F1(train_label_list, predict_label_list): if len(train_label_list) == len(predict_label_list): # compute precision and", "exp(-inX)) @Decorator.log_of_function def gradient_descent(self, train_feature_tuple_list, train_label_list, learning_rate = 0.01, max_iteration_time", "# training set sql_list.append(\"\"\"SELECT PassengerId, Survived, Pclass, Sex, Age, SibSp,", "= e.args[1])) logging.info(\"END CLASS {class_name}.\".format(class_name = CreateLogisticRegressionModel.__name__)) self.end = time.clock()", "learning_rate = 0.01, max_iteration_time = 500, lambda_regularization = 0.1): ############################", "self.con.rollback() logging.error(\"Fail in fetch data from MySQL.\") logging.error(\"MySQL Error {error_num}:", "weight_matrix[0] + learning_rate * (float(1)/train_sample_num) * train_input_matrix[:, 0].transpose() * error", "( 1 / 1 * [891, 6].T * [891, 1]", "recall = float(true_negative_num) / (predicted_negative_num + 10E-10) F1 = 2", "logging.StreamHandler() console.setLevel(logging.INFO) formatter = logging.Formatter('%(asctime)s %(levelname)5s %(filename)19s[line:%(lineno)3d] %(funcName)s %(message)s') console.setFormatter(formatter)", "= shape(train_input_matrix) weight_matrix = ones((feature_num, 1)) cost_list = [] error_list", "cursor = self.con.cursor() sql_list = [] # training set sql_list.append(\"\"\"SELECT", "= weight_matrix[0] + learning_rate * (float(1)/train_sample_num) * train_input_matrix[:, 0].transpose() *", "MySQL.\") logging.error(\"MySQL Error {error_num}: {error_info}.\".format(error_num = e.args[0], error_info = e.args[1]))", "Age, SibSp, Parch, Fare),\\ train_feature_tuple_list) ''' train_feature_tuple_list_without_PassengerId = map(lambda (PassengerId,", "SibSp, Parch, Fare):\\ (InterceptTerm, Sex, Fare),\\ train_feature_tuple_list) train_input_matrix = mat(train_feature_tuple_list_without_PassengerId)", "Age, SibSp, Parch, Fare): \\ (PassengerId, 1.0, Pclass, Sex, Age,", "i+1, predict_label_matrix[i][0] ''' predict_prob_list = predict_prob_matrix.transpose().tolist()[0] predict_label_list = [] for", "self.con.rollback() logging.error(\"Fail in quiting MySQL.\") logging.error(\"MySQL Error {error_num}: {error_info}.\".format(error_num =", "= sql_list[sql_idx] try: cursor.execute(sql) if sql_idx == 0: train_data =", "accuracy, precision, recall, F1 @Decorator.log_of_function def write_csv_file(self, start_id, predict_label_list, result_csv_dir):", "+ 1 * \\ # ( 1 / 1 *", "cursor.fetchall() logging.info(\"len(test_data):{0}\".format(len(test_data))) logging.info(\"test_data[0]:{0}\".format(test_data[0])) logging.info(\"type(test_data[0]):{0}\".format(type(test_data[0]))) except MySQLdb.Error, e: self.con.rollback() logging.error(\"Fail in", ": {delta_time} seconds\".format(class_name = CreateLogisticRegressionModel.__name__, delta_time = self.end - self.start))", "+ 1 precision = float(true_positive_num) / (predicted_positive_num + 10E-10) recall", "logging.info(\"F1:{0}\".format(F1)) return accuracy, precision, recall, F1 @Decorator.log_of_function def write_csv_file(self, start_id,", "logging.error(\"Fail in closing file handle of {0}.\".format(result_csv_dir)) logging.error(e) @Decorator.log_of_function def", "= cursor.fetchall() logging.info(\"len(train_data):{0}\".format(len(train_data))) logging.info(\"train_data[0]:{0}\".format(train_data[0])) logging.info(\"type(train_data[0]):{0}\".format(type(train_data[0]))) elif sql_idx == 1: test_data", "+ (1-train_label_matrix.transpose())*log(1-hypothesis) ) + \\ lambda_regularization / (2*train_sample_num) * (array(weight_matrix[1:])", "%(message)s') console.setFormatter(formatter) logging.getLogger('').addHandler(console) logging.info(\"START CLASS {class_name}.\".format(class_name = CreateLogisticRegressionModel.__name__)) try: self.con", "Initial parameters # learning_rate = 0.01 # max_iteration_time = 500", "error_list.append(error) logging.info(\"cur_iter:{0}, cost:{1}, sum(error):{2}\".format(cur_iter+1, cost, sum(error))) # 1 = 1", "idx in xrange(len(train_label_list)): if train_label_list[idx] == predict_label_list[idx]: right_predict_num = right_predict_num", "= predict_label_list.count(1) predicted_negative_num = predict_label_list.count(0) for idx in xrange(len(train_label_list)): if", "train_label_list,\\ predict_label_list = predict_label_list) logging.info(\"precision:{0}\".format(precision)) logging.info(\"recall:{0}\".format(recall)) logging.info(\"F1:{0}\".format(F1)) return accuracy, precision,", "from MySQL.\") logging.error(\"MySQL Error {error_num}: {error_info}.\".format(error_num = e.args[0], error_info =", "@Decorator.log_of_function def sigmoid_function(self, inX): return 1.0 / (1.0 + exp(-inX))", "except MySQLdb.Error, e: logging.error(\"Fail in connecting MySQL.\") logging.error(\"MySQL Error {error_num}:", "predict_label_list[idx] == train_label_list[idx] == 0: true_negative_num = true_negative_num + 1", "csv writer result_csv_writer = csv.writer(result_csv_handle) # write csv file result_csv_writer.writerow([\"PassengerId\",", "@Decorator.log_of_function def __init__(self): self.start = time.clock() logging.basicConfig(level = logging.INFO, format", "= shape(predict_label_matrix) for i in xrange(row): print i+1, predict_label_matrix[i][0] '''", "weight_matrix): pass ################################### PART3 CLASS TEST ################################## \"\"\" # Initial", "Sex, Age, SibSp, Parch, Fare): \\ (PassengerId, 1.0, Pclass, Sex,", "quiting MySQL.\") except MySQLdb.Error, e: self.con.rollback() logging.error(\"Fail in quiting MySQL.\")", "Parch):\\ (int(PassengerId),\\ int(Survived),\\ int(Pclass),\\ Sex,\\ int(Age),\\ int(SibSp),\\ int(Parch)\\ ),\\ train_data)", "= -float(1) / (train_sample_num) * \\ sum( train_label_matrix.transpose()*log(hypothesis) + (1-train_label_matrix.transpose())*log(1-hypothesis)", "import decorator_of_function ################################### PART2 CLASS && FUNCTION ########################### class CreateLogisticRegressionModel(object):", "logging.basicConfig(level = logging.INFO, format = '%(asctime)s %(levelname)5s %(filename)19s[line:%(lineno)3d] %(funcName)s %(message)s',", "= self.sigmoid_function(train_input_matrix * weight_matrix) # real <- sum([891, 1]T*[891, 1]", "col = shape(predict_label_matrix) for i in xrange(row): print i+1, predict_label_matrix[i][0]", "# find optimal solution if cur_iter == 0: optimal_solution['cur_iter'] =", "SibSp, Parch, Fare):\\ (InterceptTerm, Pclass, Sex, Age, SibSp, Parch, Fare),\\", "= e.args[0], error_info = e.args[1])) @Decorator.log_of_function def __del__(self): try: self.con.close()", "recall, F1 @Decorator.log_of_function def write_csv_file(self, start_id, predict_label_list, result_csv_dir): # open", "+ learning_rate * (float(1)/train_sample_num) * train_input_matrix[:, 0].transpose() * error #", "csv import decorator_of_function ################################### PART2 CLASS && FUNCTION ########################### class", "max_iteration_time = 500, lambda_regularization = 0.1): ############################ # Initial parameters", "as e: logging.error(\"Fail in closing file handle of {0}.\".format(result_csv_dir)) logging.error(e)", "################################## \"\"\" # Initial parameters database_name = \"TitanicDB\" passenger_table_name =", "= float(true_negative_num) / (predicted_negative_num + 10E-10) F1 = 2 *", "* weight_matrix) # real <- sum([891, 1]T*[891, 1] + [891,", "sql_list.append(\"\"\"SELECT PassengerId, Survived, Pclass, Sex, Age, SibSp, Parch FROM {database_name}.{table_name}", "logging.error(\"MySQL Error {error_num}: {error_info}.\".format(error_num = e.args[0], error_info = e.args[1])) logging.info(\"END", "Sex, Age, SibSp, Parch, Fare):\\ (InterceptTerm, Pclass, Sex, Age, SibSp,", "except MySQLdb.Error, e: self.con.rollback() logging.error(\"Fail in fetch data from MySQL.\")", "for list_idx in xrange(len(predict_label_list)): PassengerId = start_id + list_idx predict_label", "Pclass, Sex, Age, SibSp, Parch, Fare train_feature_intercept_term_added_tuple_list = map(lambda (PassengerId,", "def gradient_descent(self, train_feature_tuple_list, train_label_list, learning_rate = 0.01, max_iteration_time = 500,", "accuracy = compute_accuracy(train_label_list = train_label_list,\\ predict_label_list = predict_label_list) logging.info(\"right_predict_num:{0}\".format(right_predict_num)) logging.info(\"accuracy:{0}\".format(accuracy))", "[891, 1] # ) weight_matrix[1:] = weight_matrix[1:] + learning_rate *", "*[891, 1] weight_matrix[0] = weight_matrix[0] + learning_rate * (float(1)/train_sample_num) *", "int(Parch)\\ ),\\ train_data) logging.info(\"len(train_data):{0}\".format(len(train_data))) logging.info(\"train_data[0]:{0}\".format(train_data[0])) logging.info(\"type(train_data[0]):{0}\".format(type(train_data[0]))) test_data = map(lambda (PassengerId,", "CreateLogisticRegressionModel.__name__)) try: self.con = MySQLdb.connect(host='localhost', user='root', passwd='<PASSWORD>', charset='utf8') logging.info(\"Success in", "Error {error_num}: {error_info}.\".format(error_num = e.args[0], error_info = e.args[1])) train_data =", "MySQL.\") except MySQLdb.Error, e: logging.error(\"Fail in connecting MySQL.\") logging.error(\"MySQL Error", "__author__ = 'yuens' ################################### PART1 IMPORT ###################################### import MySQLdb import", "sql_idx in xrange(len(sql_list)): sql = sql_list[sql_idx] try: cursor.execute(sql) if sql_idx", "CLASS TEST ################################## \"\"\" # Initial parameters database_name = \"TitanicDB\"", "[891, 1] error = train_label_matrix - hypothesis error_list.append(error) logging.info(\"cur_iter:{0}, cost:{1},", "Age, SibSp, Parch, Fare),\\ test_feature_tuple_list) logging.info(\"len(train_feature_intercept_term_added_tuple_list):{0}\".format(len(train_feature_intercept_term_added_tuple_list))) logging.info(\"train_feature_intercept_term_added_tuple_list[0]:{0}\".format(train_feature_intercept_term_added_tuple_list[0])) logging.info(\"len(test_feature_intercept_term_added_tuple_list):{0}\".format(len(test_feature_intercept_term_added_tuple_list))) logging.info(\"test_feature_intercept_term_added_tuple_list[0]:{0}\".format(test_feature_intercept_term_added_tuple_list[0])) return", "optimal_solution['cost'] = cost optimal_solution['abs(error.sum())'] = abs(error.sum()) optimal_solution['weight_matrix'] = weight_matrix elif", "pylab from numpy import * from math import exp import", "shape(train_input_matrix) weight_matrix = ones((feature_num, 1)) cost_list = [] error_list =", "handle of {0}.\".format(result_csv_dir)) except Exception as e: logging.error(\"Fail in attaining", "= 10E-10 true_negative_num = 10E-10 predicted_positive_num = predict_label_list.count(1) predicted_negative_num =", "MySQLdb.Error, e: self.con.rollback() logging.error(\"Fail in fetch data from MySQL.\") logging.error(\"MySQL", "try: result_csv_handle = file(result_csv_dir, 'wb') logging.info(\"Success in attaining file handle", "charset='utf8') logging.info(\"Success in connecting MySQL.\") except MySQLdb.Error, e: logging.error(\"Fail in", "0 if len(train_label_list) == len(predict_label_list): for idx in xrange(len(train_label_list)): if", "database_name,\\ table_name = passenger_table_name)\\ ) # test set sql_list.append(\"\"\"SELECT PassengerId,", "PassengerId, Pclass, Sex, Age, SibSp, Parch, Fare train_feature_intercept_term_added_tuple_list = map(lambda", "hypothesis = self.sigmoid_function(train_input_matrix * weight_matrix) # real <- sum([891, 1]T*[891,", "Sex, Age, SibSp, Parch, Fare):\\ (InterceptTerm, Sex, Fare),\\ train_feature_tuple_list) train_input_matrix", "predicted_negative_num = predict_label_list.count(0) for idx in xrange(len(train_label_list)): if predict_label_list[idx] ==", "predict(self, train_feature_tuple_list, weight_matrix): ''' train_feature_tuple_list_without_PassengerId = map(lambda (PassengerId, InterceptTerm, Pclass,", "Description: # # Author: <NAME> # E-mail: <EMAIL> # Create:", "logging.error(\"Fail in connecting MySQL.\") logging.error(\"MySQL Error {error_num}: {error_info}.\".format(error_num = e.args[0],", "optimal_solution['weight_matrix'] @Decorator.log_of_function def predict(self, train_feature_tuple_list, weight_matrix): ''' train_feature_tuple_list_without_PassengerId = map(lambda", "* error #\"\"\" # find optimal solution if cur_iter ==", "console = logging.StreamHandler() console.setLevel(logging.INFO) formatter = logging.Formatter('%(asctime)s %(levelname)5s %(filename)19s[line:%(lineno)3d] %(funcName)s", "{class_name}.\".format(class_name = CreateLogisticRegressionModel.__name__)) self.end = time.clock() logging.info(\"The class {class_name} run", "0.1): ############################ # Initial parameters # learning_rate = 0.01 #", "optimal_solution['cur_iter'] = cur_iter optimal_solution['cost'] = cost optimal_solution['abs(error.sum())'] = abs(error.sum()) optimal_solution['weight_matrix']", "= 'a') console = logging.StreamHandler() console.setLevel(logging.INFO) formatter = logging.Formatter('%(asctime)s %(levelname)5s", "# compute accuracy def compute_accuracy(train_label_list, predict_label_list): right_predict_num = 0 if", "logging.info(\"len(train_data):{0}\".format(len(train_data))) logging.info(\"train_data[0]:{0}\".format(train_data[0])) logging.info(\"type(train_data[0]):{0}\".format(type(train_data[0]))) test_data = map(lambda (PassengerId, Survived, Pclass, Sex,", "# [891, 7] train_input_matrix = mat(train_feature_tuple_list_without_PassengerId) # [891, 1] train_label_matrix", "Fare),\\ train_feature_tuple_list) # [891, 7] train_input_matrix = mat(train_feature_tuple_list_without_PassengerId) # [891,", "* train_input_matrix[:, 0].transpose() * error # [6, 1] = [6,", "sql_list[sql_idx] try: cursor.execute(sql) if sql_idx == 0: train_data = cursor.fetchall()", "e: self.con.rollback() logging.error(\"Fail in quiting MySQL.\") logging.error(\"MySQL Error {error_num}: {error_info}.\".format(error_num", "in xrange(len(predict_prob_list)): predict_prob = predict_prob_list[prob_idx] if predict_prob > 0.5: predict_label_list.append(1)", "+ recall) return precision, recall, F1 right_predict_num, accuracy = compute_accuracy(train_label_list", "predict_label_list) logging.info(\"precision:{0}\".format(precision)) logging.info(\"recall:{0}\".format(recall)) logging.info(\"F1:{0}\".format(F1)) return accuracy, precision, recall, F1 @Decorator.log_of_function", "except MySQLdb.Error, e: self.con.rollback() logging.error(\"Fail in quiting MySQL.\") logging.error(\"MySQL Error", "* recall / (precision + recall) return precision, recall, F1", "cost, sum(error))) # 1 = 1 + 1 * [891,", "CreateLogisticRegressionModel(object): Decorator = decorator_of_function.CreateDecorator() @Decorator.log_of_function def __init__(self): self.start = time.clock()", "1 + 1 * [891, 1].T *[891, 1] weight_matrix[0] =", "= logging.StreamHandler() console.setLevel(logging.INFO) formatter = logging.Formatter('%(asctime)s %(levelname)5s %(filename)19s[line:%(lineno)3d] %(funcName)s %(message)s')", "MySQLdb.Error, e: self.con.rollback() logging.error(\"Fail in quiting MySQL.\") logging.error(\"MySQL Error {error_num}:", "{delta_time} seconds\".format(class_name = CreateLogisticRegressionModel.__name__, delta_time = self.end - self.start)) @Decorator.log_of_function", "= cost optimal_solution['abs(error.sum())'] = abs(error.sum()) optimal_solution['weight_matrix'] = weight_matrix elif cur_iter", "!/usr/bin/python ################################### PART0 DESCRIPTION ################################# # Filename: class_create_model_of_logistic_regression.py # Description:", "Decorator = decorator_of_function.CreateDecorator() @Decorator.log_of_function def __init__(self): self.start = time.clock() logging.basicConfig(level", "compute_accuracy(train_label_list, predict_label_list): right_predict_num = 0 if len(train_label_list) == len(predict_label_list): for", "Sex, Age, SibSp, Parch FROM {database_name}.{table_name} WHERE Is_train=0\"\"\"\\ .format(database_name =", "def compute_precision_and_recall_and_F1(train_label_list, predict_label_list): if len(train_label_list) == len(predict_label_list): # compute precision", "2016-01-23 23:32:49 # Last: __author__ = 'yuens' ################################### PART1 IMPORT", "predict_label_list = predict_label_list) logging.info(\"right_predict_num:{0}\".format(right_predict_num)) logging.info(\"accuracy:{0}\".format(accuracy)) precision, recall, F1 = compute_precision_and_recall_and_F1(train_label_list", "{class_name}.\".format(class_name = CreateLogisticRegressionModel.__name__)) try: self.con = MySQLdb.connect(host='localhost', user='root', passwd='<PASSWORD>', charset='utf8')", "logging.info(\"Success in attaining file handle of {0}.\".format(result_csv_dir)) except Exception as", "result_csv_handle.close() logging.info(\"Success in closing file handle of {0}.\".format(result_csv_dir)) except Exception", "#return optimal_solution['weight_matrix'] @Decorator.log_of_function def predict(self, train_feature_tuple_list, weight_matrix): ''' train_feature_tuple_list_without_PassengerId =", "################################### PART0 DESCRIPTION ################################# # Filename: class_create_model_of_logistic_regression.py # Description: #", "true_positive_num = 10E-10 true_negative_num = 10E-10 predicted_positive_num = predict_label_list.count(1) predicted_negative_num", "recall / (precision + recall) return precision, recall, F1 right_predict_num,", "e.args[0], error_info = e.args[1])) train_data = map(lambda (PassengerId, Survived, Pclass,", "# [891, 1] train_label_matrix = mat(train_label_list).transpose() train_sample_num, feature_num = shape(train_input_matrix)", "################################# # Filename: class_create_model_of_logistic_regression.py # Description: # # Author: <NAME>", "test set sql_list.append(\"\"\"SELECT PassengerId, Survived, Pclass, Sex, Age, SibSp, Parch", "array(weight_matrix[1:])).sum() cost_list.append(cost) # [891, 1] error = train_label_matrix - hypothesis", "@Decorator.log_of_function def write_csv_file(self, start_id, predict_label_list, result_csv_dir): # open csv file", "= self.end - self.start)) @Decorator.log_of_function def get_data_from_database(self, database_name, passenger_table_name): cursor", "0: train_data = cursor.fetchall() logging.info(\"len(train_data):{0}\".format(len(train_data))) logging.info(\"train_data[0]:{0}\".format(train_data[0])) logging.info(\"type(train_data[0]):{0}\".format(type(train_data[0]))) elif sql_idx ==", "/ (1.0 + exp(-inX)) @Decorator.log_of_function def gradient_descent(self, train_feature_tuple_list, train_label_list, learning_rate", "weight_matrix[1:] \\ ) #weight_matrix = weight_matrix + learning_rate * train_input_matrix.transpose()", "= weight_matrix + learning_rate * train_input_matrix.transpose() * error #\"\"\" #", "int(Age),\\ int(SibSp),\\ int(Parch)\\ ),\\ test_data) logging.info(\"len(test_data):{0}\".format(len(test_data))) logging.info(\"test_data[0]:{0}\".format(test_data[0])) logging.info(\"type(test_data[0]):{0}\".format(type(test_data[0]))) return train_data,", "in xrange(len(train_label_list)): if predict_label_list[idx] == train_label_list[idx] == 1: true_positive_num =", "if sql_idx == 0: train_data = cursor.fetchall() logging.info(\"len(train_data):{0}\".format(len(train_data))) logging.info(\"train_data[0]:{0}\".format(train_data[0])) logging.info(\"type(train_data[0]):{0}\".format(type(train_data[0])))", "# # Author: <NAME> # E-mail: <EMAIL> # Create: 2016-01-23", "logging.error(\"Fail in quiting MySQL.\") logging.error(\"MySQL Error {error_num}: {error_info}.\".format(error_num = e.args[0],", "<- sum([891, 1]T*[891, 1] + [891, 1]T*[891, 1]) cost =", "{0}.\".format(result_csv_dir)) except Exception as e: logging.error(\"Fail in attaining file handle", "return train_feature_intercept_term_added_tuple_list,\\ test_feature_intercept_term_added_tuple_list @Decorator.log_of_function def sigmoid_function(self, inX): return 1.0 /", "file try: result_csv_handle = file(result_csv_dir, 'wb') logging.info(\"Success in attaining file", "= logging.INFO, format = '%(asctime)s %(levelname)5s %(filename)19s[line:%(lineno)3d] %(funcName)s %(message)s', datefmt", "import time import pylab from numpy import * from math", "e: logging.error(\"Fail in connecting MySQL.\") logging.error(\"MySQL Error {error_num}: {error_info}.\".format(error_num =", "result_csv_dir): # open csv file try: result_csv_handle = file(result_csv_dir, 'wb')", "{error_num}: {error_info}.\".format(error_num = e.args[0], error_info = e.args[1])) logging.info(\"END CLASS {class_name}.\".format(class_name", "= file(result_csv_dir, 'wb') logging.info(\"Success in attaining file handle of {0}.\".format(result_csv_dir))", "Pclass, Sex, Age, SibSp, Parch, Fare),\\ train_feature_tuple_list) test_feature_intercept_term_added_tuple_list = map(lambda", "# learning_rate = 0.01 # max_iteration_time = 500 ############################ '''", "* (float(1)/train_sample_num) * train_input_matrix[:, 0].transpose() * error # [6, 1]", "0.01, max_iteration_time = 500, lambda_regularization = 0.1): ############################ # Initial", "train_label_matrix = mat(train_label_list).transpose() train_sample_num, feature_num = shape(train_input_matrix) weight_matrix = ones((feature_num,", "1] <- [891, 7]*[7, 1] hypothesis = self.sigmoid_function(train_input_matrix * weight_matrix)", "logging.info(\"test_data[0]:{0}\".format(test_data[0])) logging.info(\"type(test_data[0]):{0}\".format(type(test_data[0]))) return train_data, test_data @Decorator.log_of_function def add_intercept_term(self, train_feature_tuple_list, test_feature_tuple_list):", "test_data @Decorator.log_of_function def add_intercept_term(self, train_feature_tuple_list, test_feature_tuple_list): logging.info(\"len(train_feature_tuple_list[0]):{0}\".format(len(train_feature_tuple_list[0]))) logging.info(\"len(train_feature_tuple_list):{0}\".format(len(train_feature_tuple_list))) logging.info(\"train_feature_tuple_list[0]:{0}\".format(train_feature_tuple_list[0])) logging.info(\"test_feature_tuple_list[0]:{0}\".format(len(test_feature_tuple_list[0])))", "+ \\ lambda_regularization / (2*train_sample_num) * (array(weight_matrix[1:]) * array(weight_matrix[1:])).sum() cost_list.append(cost)", "Fare):\\ (InterceptTerm, Sex, Fare),\\ train_feature_tuple_list) train_input_matrix = mat(train_feature_tuple_list_without_PassengerId) predict_prob_matrix =", "and recall true_positive_num = 10E-10 true_negative_num = 10E-10 predicted_positive_num =", "import logging import time import pylab from numpy import *", "# PassengerId, Pclass, Sex, Age, SibSp, Parch, Fare train_feature_intercept_term_added_tuple_list =", "logging.info(\"test_feature_tuple_list[0]:{0}\".format(len(test_feature_tuple_list[0]))) logging.info(\"len(test_feature_tuple_list):{0}\".format(len(test_feature_tuple_list))) logging.info(\"test_feature_tuple_list[0]:{0}\".format(test_feature_tuple_list[0])) # len(train_feature_tuple_list[0]): 7 # PassengerId, Pclass, Sex,", "= predict_label_list.count(0) for idx in xrange(len(train_label_list)): if predict_label_list[idx] == train_label_list[idx]", "-*- coding: utf-8 -*- # !/usr/bin/python ################################### PART0 DESCRIPTION #################################", "########################### class CreateLogisticRegressionModel(object): Decorator = decorator_of_function.CreateDecorator() @Decorator.log_of_function def __init__(self): self.start", "predict_label_list = predict_label_list) logging.info(\"precision:{0}\".format(precision)) logging.info(\"recall:{0}\".format(recall)) logging.info(\"F1:{0}\".format(F1)) return accuracy, precision, recall,", "logging.info(\"precision:{0}\".format(precision)) logging.info(\"recall:{0}\".format(recall)) logging.info(\"F1:{0}\".format(F1)) return accuracy, precision, recall, F1 @Decorator.log_of_function def", "# Author: <NAME> # E-mail: <EMAIL> # Create: 2016-01-23 23:32:49", "table_name = passenger_table_name)\\ ) # test set sql_list.append(\"\"\"SELECT PassengerId, Survived,", "try: self.con = MySQLdb.connect(host='localhost', user='root', passwd='<PASSWORD>', charset='utf8') logging.info(\"Success in connecting", "* (array(weight_matrix[1:]) * array(weight_matrix[1:])).sum() cost_list.append(cost) # [891, 1] error =", "Age, SibSp, Parch, Fare):\\ (InterceptTerm, Sex, Fare),\\ train_feature_tuple_list) # [891,", "Sex, Fare),\\ train_feature_tuple_list) # [891, 7] train_input_matrix = mat(train_feature_tuple_list_without_PassengerId) #", "weight_matrix + learning_rate * train_input_matrix.transpose() * error #\"\"\" # find", "compute precision and recall true_positive_num = 10E-10 true_negative_num = 10E-10", ") #weight_matrix = weight_matrix + learning_rate * train_input_matrix.transpose() * error", "cur_iter optimal_solution['cost'] = cost optimal_solution['abs(error.sum())'] = abs(error.sum()) optimal_solution['weight_matrix'] = weight_matrix", "precision, recall, F1 @Decorator.log_of_function def write_csv_file(self, start_id, predict_label_list, result_csv_dir): #", "Is_train=1\"\"\"\\ .format(database_name = database_name,\\ table_name = passenger_table_name)\\ ) # test", "len(train_label_list) == len(predict_label_list): for idx in xrange(len(train_label_list)): if train_label_list[idx] ==", "train_data = cursor.fetchall() logging.info(\"len(train_data):{0}\".format(len(train_data))) logging.info(\"train_data[0]:{0}\".format(train_data[0])) logging.info(\"type(train_data[0]):{0}\".format(type(train_data[0]))) elif sql_idx == 1:", "Parch, Fare):\\ (InterceptTerm, Pclass, Sex, Age, SibSp, Parch, Fare),\\ train_feature_tuple_list)", "file try: result_csv_handle.close() logging.info(\"Success in closing file handle of {0}.\".format(result_csv_dir))", "passenger_table_name)\\ ) for sql_idx in xrange(len(sql_list)): sql = sql_list[sql_idx] try:", "= map(lambda (PassengerId, InterceptTerm, Pclass, Sex, Age, SibSp, Parch, Fare):\\", "/ train_sample_num * weight_matrix[1:] \\ ) #weight_matrix = weight_matrix +", "xrange(len(sql_list)): sql = sql_list[sql_idx] try: cursor.execute(sql) if sql_idx == 0:", "e: logging.error(\"Fail in closing file handle of {0}.\".format(result_csv_dir)) logging.error(e) @Decorator.log_of_function", "%(funcName)s %(message)s', datefmt = '%y-%m-%d %H:%M:%S', filename = 'main.log', filemode", "gradient_descent(self, train_feature_tuple_list, train_label_list, learning_rate = 0.01, max_iteration_time = 500, lambda_regularization", "predict_label_list @Decorator.log_of_function def accuracy(self, train_label_list, predict_label_list): logging.info(\"len(train_label_list):{0}\".format(len(train_label_list))) logging.info(\"len(predict_label_list):{0}\".format(len(predict_label_list))) # compute", "def plot_decision_bondary(self, weight_matrix): pass ################################### PART3 CLASS TEST ################################## \"\"\"", "# Last: __author__ = 'yuens' ################################### PART1 IMPORT ###################################### import", "= 0.01 # max_iteration_time = 500 ############################ ''' train_feature_tuple_list_without_PassengerId =", "= CreateLogisticRegressionModel.__name__)) self.end = time.clock() logging.info(\"The class {class_name} run time", "= right_predict_num + 1 accuracy = float(right_predict_num)/len(train_label_list) return right_predict_num, accuracy", "1] = [6, 1] + 1 * \\ # (", "result_csv_handle = file(result_csv_dir, 'wb') logging.info(\"Success in attaining file handle of", "###################################### import MySQLdb import logging import time import pylab from", "logging.error(e) @Decorator.log_of_function def plot_decision_bondary(self, weight_matrix): pass ################################### PART3 CLASS TEST", "(int(PassengerId),\\ int(Survived),\\ int(Pclass),\\ Sex,\\ int(Age),\\ int(SibSp),\\ int(Parch)\\ ),\\ train_data) logging.info(\"len(train_data):{0}\".format(len(train_data)))", "Pclass, Sex, Age, SibSp, Parch FROM {database_name}.{table_name} WHERE Is_train=1\"\"\"\\ .format(database_name", "create csv writer result_csv_writer = csv.writer(result_csv_handle) # write csv file", "int(Survived),\\ int(Pclass),\\ Sex,\\ int(Age),\\ int(SibSp),\\ int(Parch)\\ ),\\ train_data) logging.info(\"len(train_data):{0}\".format(len(train_data))) logging.info(\"train_data[0]:{0}\".format(train_data[0]))", "\\ sum( train_label_matrix.transpose()*log(hypothesis) + (1-train_label_matrix.transpose())*log(1-hypothesis) ) + \\ lambda_regularization /", "Error {error_num}: {error_info}.\".format(error_num = e.args[0], error_info = e.args[1])) logging.info(\"END CLASS", "sum( train_label_matrix.transpose()*log(hypothesis) + (1-train_label_matrix.transpose())*log(1-hypothesis) ) + \\ lambda_regularization / (2*train_sample_num)", "logging.info(\"test_feature_intercept_term_added_tuple_list[0]:{0}\".format(test_feature_intercept_term_added_tuple_list[0])) return train_feature_intercept_term_added_tuple_list,\\ test_feature_intercept_term_added_tuple_list @Decorator.log_of_function def sigmoid_function(self, inX): return 1.0", "logging.error(\"MySQL Error {error_num}: {error_info}.\".format(error_num = e.args[0], error_info = e.args[1])) @Decorator.log_of_function", "),\\ test_data) logging.info(\"len(test_data):{0}\".format(len(test_data))) logging.info(\"test_data[0]:{0}\".format(test_data[0])) logging.info(\"type(test_data[0]):{0}\".format(type(test_data[0]))) return train_data, test_data @Decorator.log_of_function def", "* array(weight_matrix[1:])).sum() cost_list.append(cost) # [891, 1] error = train_label_matrix -", "def accuracy(self, train_label_list, predict_label_list): logging.info(\"len(train_label_list):{0}\".format(len(train_label_list))) logging.info(\"len(predict_label_list):{0}\".format(len(predict_label_list))) # compute accuracy def", "passenger_table_name): cursor = self.con.cursor() sql_list = [] # training set", "result_csv_writer = csv.writer(result_csv_handle) # write csv file result_csv_writer.writerow([\"PassengerId\", \"Survived\"]) for", "F1 = 2 * precision * recall / (precision +", "weight_matrix[1:] = weight_matrix[1:] + learning_rate * \\ ( (float(1)/train_sample_num) *", "Parch, Fare train_feature_intercept_term_added_tuple_list = map(lambda (PassengerId, Pclass, Sex, Age, SibSp,", "sql_list = [] # training set sql_list.append(\"\"\"SELECT PassengerId, Survived, Pclass,", "for cur_iter in xrange(max_iteration_time): # [891, 1] <- [891, 7]*[7,", "@Decorator.log_of_function def plot_decision_bondary(self, weight_matrix): pass ################################### PART3 CLASS TEST ##################################", "InterceptTerm, Pclass, Sex, Age, SibSp, Parch, Fare):\\ (InterceptTerm, Sex, Fare),\\", "return 1.0 / (1.0 + exp(-inX)) @Decorator.log_of_function def gradient_descent(self, train_feature_tuple_list,", "* [891, 1] # ) weight_matrix[1:] = weight_matrix[1:] + learning_rate", "MySQLdb.Error, e: logging.error(\"Fail in connecting MySQL.\") logging.error(\"MySQL Error {error_num}: {error_info}.\".format(error_num", "= weight_matrix logging.info(\"optimal_solution['cur_iter']:{0}\".format(optimal_solution['cur_iter'])) logging.info(\"optimal_solution['cost':{0}\".format(optimal_solution['cost'])) logging.info(\"optimal_solution['abs(error.sum())']:{0}\".format(optimal_solution['abs(error.sum())'])) logging.info(\"optimal_solution['weight_matrix'].tolist():{0}\".format(optimal_solution['weight_matrix'].tolist())) #\"\"\" pylab.plot(cost_list) pylab.show() return", "xrange(row): print i+1, predict_label_matrix[i][0] ''' predict_prob_list = predict_prob_matrix.transpose().tolist()[0] predict_label_list =", "weight_matrix) # real <- sum([891, 1]T*[891, 1] + [891, 1]T*[891,", "xrange(len(predict_prob_list)): predict_prob = predict_prob_list[prob_idx] if predict_prob > 0.5: predict_label_list.append(1) else:", "float(true_positive_num) / (predicted_positive_num + 10E-10) recall = float(true_negative_num) / (predicted_negative_num", "xrange(len(predict_label_list)): PassengerId = start_id + list_idx predict_label = predict_label_list[list_idx] result_csv_writer.writerow([PassengerId,", "set sql_list.append(\"\"\"SELECT PassengerId, Survived, Pclass, Sex, Age, SibSp, Parch FROM", "math import exp import csv import decorator_of_function ################################### PART2 CLASS", "pylab.plot(cost_list) pylab.show() return weight_matrix #return optimal_solution['weight_matrix'] @Decorator.log_of_function def predict(self, train_feature_tuple_list,", "logging.info(\"START CLASS {class_name}.\".format(class_name = CreateLogisticRegressionModel.__name__)) try: self.con = MySQLdb.connect(host='localhost', user='root',", "logging.error(\"MySQL Error {error_num}: {error_info}.\".format(error_num = e.args[0], error_info = e.args[1])) train_data", "run time is : {delta_time} seconds\".format(class_name = CreateLogisticRegressionModel.__name__, delta_time =", "train_feature_tuple_list) # [891, 7] train_input_matrix = mat(train_feature_tuple_list_without_PassengerId) # [891, 1]", ") + \\ lambda_regularization / (2*train_sample_num) * (array(weight_matrix[1:]) * array(weight_matrix[1:])).sum()", "self.sigmoid_function(train_input_matrix * weight_matrix) ''' row, col = shape(predict_label_matrix) for i", "logging.error(\"Fail in attaining file handle of {0}.\".format(result_csv_dir)) logging.error(e) return -1", "(PassengerId, InterceptTerm, Pclass, Sex, Age, SibSp, Parch, Fare):\\ (InterceptTerm, Pclass,", "+ 1 * [891, 1].T *[891, 1] weight_matrix[0] = weight_matrix[0]", "logging.info(\"len(train_feature_tuple_list):{0}\".format(len(train_feature_tuple_list))) logging.info(\"train_feature_tuple_list[0]:{0}\".format(train_feature_tuple_list[0])) logging.info(\"test_feature_tuple_list[0]:{0}\".format(len(test_feature_tuple_list[0]))) logging.info(\"len(test_feature_tuple_list):{0}\".format(len(test_feature_tuple_list))) logging.info(\"test_feature_tuple_list[0]:{0}\".format(test_feature_tuple_list[0])) # len(train_feature_tuple_list[0]): 7 # PassengerId,", "logging.info(\"len(test_data):{0}\".format(len(test_data))) logging.info(\"test_data[0]:{0}\".format(test_data[0])) logging.info(\"type(test_data[0]):{0}\".format(type(test_data[0]))) except MySQLdb.Error, e: self.con.rollback() logging.error(\"Fail in fetch", "xrange(len(train_label_list)): if train_label_list[idx] == predict_label_list[idx]: right_predict_num = right_predict_num + 1", "/ (train_sample_num) * \\ sum( train_label_matrix.transpose()*log(hypothesis) + (1-train_label_matrix.transpose())*log(1-hypothesis) ) +", "class {class_name} run time is : {delta_time} seconds\".format(class_name = CreateLogisticRegressionModel.__name__,", "[891, 1] train_label_matrix = mat(train_label_list).transpose() train_sample_num, feature_num = shape(train_input_matrix) weight_matrix", "mat(train_feature_tuple_list_without_PassengerId) predict_prob_matrix = self.sigmoid_function(train_input_matrix * weight_matrix) ''' row, col =", "@Decorator.log_of_function def gradient_descent(self, train_feature_tuple_list, train_label_list, learning_rate = 0.01, max_iteration_time =", "xrange(max_iteration_time): # [891, 1] <- [891, 7]*[7, 1] hypothesis =", "1] + [891, 1]T*[891, 1]) cost = -float(1) / (train_sample_num)", "elif cur_iter != 0 and optimal_solution['abs(error.sum())'] > abs(error.sum()): optimal_solution['cur_iter'] =", "xrange(len(train_label_list)): if predict_label_list[idx] == train_label_list[idx] == 1: true_positive_num = true_positive_num", "right_predict_num, accuracy = compute_accuracy(train_label_list = train_label_list,\\ predict_label_list = predict_label_list) logging.info(\"right_predict_num:{0}\".format(right_predict_num))", "numpy import * from math import exp import csv import", "train_label_list, learning_rate = 0.01, max_iteration_time = 500, lambda_regularization = 0.1):", "'%y-%m-%d %H:%M:%S', filename = 'main.log', filemode = 'a') console =", "= passenger_table_name)\\ ) # test set sql_list.append(\"\"\"SELECT PassengerId, Survived, Pclass,", "write_csv_file(self, start_id, predict_label_list, result_csv_dir): # open csv file try: result_csv_handle", "in attaining file handle of {0}.\".format(result_csv_dir)) logging.error(e) return -1 #", "csv file result_csv_writer.writerow([\"PassengerId\", \"Survived\"]) for list_idx in xrange(len(predict_label_list)): PassengerId =", "+ [891, 1]T*[891, 1]) cost = -float(1) / (train_sample_num) *", "= start_id + list_idx predict_label = predict_label_list[list_idx] result_csv_writer.writerow([PassengerId, predict_label]) #", "__init__(self): self.start = time.clock() logging.basicConfig(level = logging.INFO, format = '%(asctime)s", "'%(asctime)s %(levelname)5s %(filename)19s[line:%(lineno)3d] %(funcName)s %(message)s', datefmt = '%y-%m-%d %H:%M:%S', filename", "try: self.con.close() logging.info(\"Success in quiting MySQL.\") except MySQLdb.Error, e: self.con.rollback()", "predict_prob_matrix = self.sigmoid_function(train_input_matrix * weight_matrix) ''' row, col = shape(predict_label_matrix)", "= weight_matrix[1:] + learning_rate * \\ ( (float(1)/train_sample_num) * train_input_matrix[:,", "except Exception as e: logging.error(\"Fail in attaining file handle of", "from numpy import * from math import exp import csv", "WHERE Is_train=1\"\"\"\\ .format(database_name = database_name,\\ table_name = passenger_table_name)\\ ) #", "sql = sql_list[sql_idx] try: cursor.execute(sql) if sql_idx == 0: train_data", "optimal_solution['weight_matrix'] = weight_matrix logging.info(\"optimal_solution['cur_iter']:{0}\".format(optimal_solution['cur_iter'])) logging.info(\"optimal_solution['cost':{0}\".format(optimal_solution['cost'])) logging.info(\"optimal_solution['abs(error.sum())']:{0}\".format(optimal_solution['abs(error.sum())'])) logging.info(\"optimal_solution['weight_matrix'].tolist():{0}\".format(optimal_solution['weight_matrix'].tolist())) #\"\"\" pylab.plot(cost_list) pylab.show()", "logging.info(\"END CLASS {class_name}.\".format(class_name = CreateLogisticRegressionModel.__name__)) self.end = time.clock() logging.info(\"The class", "== predict_label_list[idx]: right_predict_num = right_predict_num + 1 accuracy = float(right_predict_num)/len(train_label_list)", "error #\"\"\" # find optimal solution if cur_iter == 0:", "\\ ) #weight_matrix = weight_matrix + learning_rate * train_input_matrix.transpose() *", "0 and optimal_solution['abs(error.sum())'] > abs(error.sum()): optimal_solution['cur_iter'] = cur_iter optimal_solution['cost'] =", "(PassengerId, 1.0, Pclass, Sex, Age, SibSp, Parch, Fare),\\ test_feature_tuple_list) logging.info(\"len(train_feature_intercept_term_added_tuple_list):{0}\".format(len(train_feature_intercept_term_added_tuple_list)))", "e.args[1])) logging.info(\"END CLASS {class_name}.\".format(class_name = CreateLogisticRegressionModel.__name__)) self.end = time.clock() logging.info(\"The", "predict_label_list[idx] == train_label_list[idx] == 1: true_positive_num = true_positive_num + 1", "0].transpose() * error # [6, 1] = [6, 1] +", "PART2 CLASS && FUNCTION ########################### class CreateLogisticRegressionModel(object): Decorator = decorator_of_function.CreateDecorator()", "0: optimal_solution['cur_iter'] = cur_iter optimal_solution['cost'] = cost optimal_solution['abs(error.sum())'] = abs(error.sum())", "= e.args[1])) train_data = map(lambda (PassengerId, Survived, Pclass, Sex, Age,", "hypothesis error_list.append(error) logging.info(\"cur_iter:{0}, cost:{1}, sum(error):{2}\".format(cur_iter+1, cost, sum(error))) # 1 =", "for sql_idx in xrange(len(sql_list)): sql = sql_list[sql_idx] try: cursor.execute(sql) if", "int(Pclass),\\ Sex,\\ int(Age),\\ int(SibSp),\\ int(Parch)\\ ),\\ test_data) logging.info(\"len(test_data):{0}\".format(len(test_data))) logging.info(\"test_data[0]:{0}\".format(test_data[0])) logging.info(\"type(test_data[0]):{0}\".format(type(test_data[0])))", "logging.Formatter('%(asctime)s %(levelname)5s %(filename)19s[line:%(lineno)3d] %(funcName)s %(message)s') console.setFormatter(formatter) logging.getLogger('').addHandler(console) logging.info(\"START CLASS {class_name}.\".format(class_name", "/ (precision + recall) return precision, recall, F1 right_predict_num, accuracy", "def get_data_from_database(self, database_name, passenger_table_name): cursor = self.con.cursor() sql_list = []", "is : {delta_time} seconds\".format(class_name = CreateLogisticRegressionModel.__name__, delta_time = self.end -", "+ 1 elif predict_label_list[idx] == train_label_list[idx] == 0: true_negative_num =", "'wb') logging.info(\"Success in attaining file handle of {0}.\".format(result_csv_dir)) except Exception", "int(Age),\\ int(SibSp),\\ int(Parch)\\ ),\\ train_data) logging.info(\"len(train_data):{0}\".format(len(train_data))) logging.info(\"train_data[0]:{0}\".format(train_data[0])) logging.info(\"type(train_data[0]):{0}\".format(type(train_data[0]))) test_data =", "[891, 7] train_input_matrix = mat(train_feature_tuple_list_without_PassengerId) # [891, 1] train_label_matrix =", "SibSp, Parch, Fare),\\ train_feature_tuple_list) ''' train_feature_tuple_list_without_PassengerId = map(lambda (PassengerId, InterceptTerm,", "learning_rate * \\ ( (float(1)/train_sample_num) * train_input_matrix[:, 1::].transpose() * error", "#\"\"\" # find optimal solution if cur_iter == 0: optimal_solution['cur_iter']", "0.5: predict_label_list.append(1) else: predict_label_list.append(0) return predict_label_list @Decorator.log_of_function def accuracy(self, train_label_list,", "true_negative_num = true_negative_num + 1 precision = float(true_positive_num) / (predicted_positive_num", "'yuens' ################################### PART1 IMPORT ###################################### import MySQLdb import logging import", "open csv file try: result_csv_handle = file(result_csv_dir, 'wb') logging.info(\"Success in", "{error_info}.\".format(error_num = e.args[0], error_info = e.args[1])) train_data = map(lambda (PassengerId,", "+ exp(-inX)) @Decorator.log_of_function def gradient_descent(self, train_feature_tuple_list, train_label_list, learning_rate = 0.01,", "Sex, Age, SibSp, Parch):\\ (int(PassengerId),\\ int(Survived),\\ int(Pclass),\\ Sex,\\ int(Age),\\ int(SibSp),\\", "logging.info(\"train_data[0]:{0}\".format(train_data[0])) logging.info(\"type(train_data[0]):{0}\".format(type(train_data[0]))) elif sql_idx == 1: test_data = cursor.fetchall() logging.info(\"len(test_data):{0}\".format(len(test_data)))", "Fare),\\ test_feature_tuple_list) logging.info(\"len(train_feature_intercept_term_added_tuple_list):{0}\".format(len(train_feature_intercept_term_added_tuple_list))) logging.info(\"train_feature_intercept_term_added_tuple_list[0]:{0}\".format(train_feature_intercept_term_added_tuple_list[0])) logging.info(\"len(test_feature_intercept_term_added_tuple_list):{0}\".format(len(test_feature_intercept_term_added_tuple_list))) logging.info(\"test_feature_intercept_term_added_tuple_list[0]:{0}\".format(test_feature_intercept_term_added_tuple_list[0])) return train_feature_intercept_term_added_tuple_list,\\ test_feature_intercept_term_added_tuple_list @Decorator.log_of_function", "Sex, Age, SibSp, Parch FROM {database_name}.{table_name} WHERE Is_train=1\"\"\"\\ .format(database_name =", "# real <- sum([891, 1]T*[891, 1] + [891, 1]T*[891, 1])", "(array(weight_matrix[1:]) * array(weight_matrix[1:])).sum() cost_list.append(cost) # [891, 1] error = train_label_matrix", "# 1 = 1 + 1 * [891, 1].T *[891,", "&& FUNCTION ########################### class CreateLogisticRegressionModel(object): Decorator = decorator_of_function.CreateDecorator() @Decorator.log_of_function def", "else: predict_label_list.append(0) return predict_label_list @Decorator.log_of_function def accuracy(self, train_label_list, predict_label_list): logging.info(\"len(train_label_list):{0}\".format(len(train_label_list)))", "cost = -float(1) / (train_sample_num) * \\ sum( train_label_matrix.transpose()*log(hypothesis) +", "-1 # create csv writer result_csv_writer = csv.writer(result_csv_handle) # write", "TEST ################################## \"\"\" # Initial parameters database_name = \"TitanicDB\" passenger_table_name", "error # [6, 1] = [6, 1] + 1 *", "if len(train_label_list) == len(predict_label_list): # compute precision and recall true_positive_num", "\"Survived\"]) for list_idx in xrange(len(predict_label_list)): PassengerId = start_id + list_idx", "self.start = time.clock() logging.basicConfig(level = logging.INFO, format = '%(asctime)s %(levelname)5s", "* [891, 1].T *[891, 1] weight_matrix[0] = weight_matrix[0] + learning_rate", "+ 10E-10) recall = float(true_negative_num) / (predicted_negative_num + 10E-10) F1", "1.0 / (1.0 + exp(-inX)) @Decorator.log_of_function def gradient_descent(self, train_feature_tuple_list, train_label_list,", "* \\ ( (float(1)/train_sample_num) * train_input_matrix[:, 1::].transpose() * error -", "0.01 # max_iteration_time = 500 ############################ ''' train_feature_tuple_list_without_PassengerId = map(lambda", "logging.info(\"optimal_solution['cost':{0}\".format(optimal_solution['cost'])) logging.info(\"optimal_solution['abs(error.sum())']:{0}\".format(optimal_solution['abs(error.sum())'])) logging.info(\"optimal_solution['weight_matrix'].tolist():{0}\".format(optimal_solution['weight_matrix'].tolist())) #\"\"\" pylab.plot(cost_list) pylab.show() return weight_matrix #return optimal_solution['weight_matrix']", "recall) return precision, recall, F1 right_predict_num, accuracy = compute_accuracy(train_label_list =", "== len(predict_label_list): for idx in xrange(len(train_label_list)): if train_label_list[idx] == predict_label_list[idx]:", "(InterceptTerm, Sex, Fare),\\ train_feature_tuple_list) train_input_matrix = mat(train_feature_tuple_list_without_PassengerId) predict_prob_matrix = self.sigmoid_function(train_input_matrix", "filemode = 'a') console = logging.StreamHandler() console.setLevel(logging.INFO) formatter = logging.Formatter('%(asctime)s", "1 accuracy = float(right_predict_num)/len(train_label_list) return right_predict_num, accuracy def compute_precision_and_recall_and_F1(train_label_list, predict_label_list):", "Sex, Age, SibSp, Parch, Fare):\\ (InterceptTerm, Sex, Fare),\\ train_feature_tuple_list) #", "(train_sample_num) * \\ sum( train_label_matrix.transpose()*log(hypothesis) + (1-train_label_matrix.transpose())*log(1-hypothesis) ) + \\", "%(levelname)5s %(filename)19s[line:%(lineno)3d] %(funcName)s %(message)s') console.setFormatter(formatter) logging.getLogger('').addHandler(console) logging.info(\"START CLASS {class_name}.\".format(class_name =", "[891, 6].T * [891, 1] # ) weight_matrix[1:] = weight_matrix[1:]", ") for sql_idx in xrange(len(sql_list)): sql = sql_list[sql_idx] try: cursor.execute(sql)", "\\ (PassengerId, 1.0, Pclass, Sex, Age, SibSp, Parch, Fare),\\ test_feature_tuple_list)", "train_sample_num, feature_num = shape(train_input_matrix) weight_matrix = ones((feature_num, 1)) cost_list =", "Sex, Age, SibSp, Parch, Fare),\\ train_feature_tuple_list) ''' train_feature_tuple_list_without_PassengerId = map(lambda", "Parch, Fare),\\ train_feature_tuple_list) ''' train_feature_tuple_list_without_PassengerId = map(lambda (PassengerId, InterceptTerm, Pclass,", "Create: 2016-01-23 23:32:49 # Last: __author__ = 'yuens' ################################### PART1", "weight_matrix) ''' row, col = shape(predict_label_matrix) for i in xrange(row):", "= cost optimal_solution['abs(error.sum())'] = abs(error.sum()) optimal_solution['weight_matrix'] = weight_matrix logging.info(\"optimal_solution['cur_iter']:{0}\".format(optimal_solution['cur_iter'])) logging.info(\"optimal_solution['cost':{0}\".format(optimal_solution['cost']))", "attaining file handle of {0}.\".format(result_csv_dir)) except Exception as e: logging.error(\"Fail", "logging.info(\"accuracy:{0}\".format(accuracy)) precision, recall, F1 = compute_precision_and_recall_and_F1(train_label_list = train_label_list,\\ predict_label_list =", "optimal_solution['abs(error.sum())'] = abs(error.sum()) optimal_solution['weight_matrix'] = weight_matrix elif cur_iter != 0", "CLASS && FUNCTION ########################### class CreateLogisticRegressionModel(object): Decorator = decorator_of_function.CreateDecorator() @Decorator.log_of_function", "from math import exp import csv import decorator_of_function ################################### PART2", "int(SibSp),\\ int(Parch)\\ ),\\ train_data) logging.info(\"len(train_data):{0}\".format(len(train_data))) logging.info(\"train_data[0]:{0}\".format(train_data[0])) logging.info(\"type(train_data[0]):{0}\".format(type(train_data[0]))) test_data = map(lambda", "Error {error_num}: {error_info}.\".format(error_num = e.args[0], error_info = e.args[1])) @Decorator.log_of_function def", "seconds\".format(class_name = CreateLogisticRegressionModel.__name__, delta_time = self.end - self.start)) @Decorator.log_of_function def", "Parch, Fare),\\ train_feature_tuple_list) test_feature_intercept_term_added_tuple_list = map(lambda (PassengerId, Pclass, Sex, Age,", "# write csv file result_csv_writer.writerow([\"PassengerId\", \"Survived\"]) for list_idx in xrange(len(predict_label_list)):", "PassengerId = start_id + list_idx predict_label = predict_label_list[list_idx] result_csv_writer.writerow([PassengerId, predict_label])", "test_data = map(lambda (PassengerId, Survived, Pclass, Sex, Age, SibSp, Parch):\\", "map(lambda (PassengerId, Pclass, Sex, Age, SibSp, Parch, Fare): \\ (PassengerId,", "DESCRIPTION ################################# # Filename: class_create_model_of_logistic_regression.py # Description: # # Author:", "logging.info(\"len(train_feature_tuple_list[0]):{0}\".format(len(train_feature_tuple_list[0]))) logging.info(\"len(train_feature_tuple_list):{0}\".format(len(train_feature_tuple_list))) logging.info(\"train_feature_tuple_list[0]:{0}\".format(train_feature_tuple_list[0])) logging.info(\"test_feature_tuple_list[0]:{0}\".format(len(test_feature_tuple_list[0]))) logging.info(\"len(test_feature_tuple_list):{0}\".format(len(test_feature_tuple_list))) logging.info(\"test_feature_tuple_list[0]:{0}\".format(test_feature_tuple_list[0])) # len(train_feature_tuple_list[0]): 7 #", "in connecting MySQL.\") logging.error(\"MySQL Error {error_num}: {error_info}.\".format(error_num = e.args[0], error_info", "of {0}.\".format(result_csv_dir)) logging.error(e) return -1 # create csv writer result_csv_writer", "Age, SibSp, Parch FROM {database_name}.{table_name} WHERE Is_train=0\"\"\"\\ .format(database_name = database_name,\\", "{0}.\".format(result_csv_dir)) logging.error(e) @Decorator.log_of_function def plot_decision_bondary(self, weight_matrix): pass ################################### PART3 CLASS", "handle of {0}.\".format(result_csv_dir)) except Exception as e: logging.error(\"Fail in closing", "sigmoid_function(self, inX): return 1.0 / (1.0 + exp(-inX)) @Decorator.log_of_function def", "predict_label_list[list_idx] result_csv_writer.writerow([PassengerId, predict_label]) # close csv file try: result_csv_handle.close() logging.info(\"Success", "train_label_list[idx] == predict_label_list[idx]: right_predict_num = right_predict_num + 1 accuracy =", "== 0: true_negative_num = true_negative_num + 1 precision = float(true_positive_num)", "(InterceptTerm, Pclass, Sex, Age, SibSp, Parch, Fare),\\ train_feature_tuple_list) ''' train_feature_tuple_list_without_PassengerId", "class_create_model_of_logistic_regression.py # Description: # # Author: <NAME> # E-mail: <EMAIL>", "optimal_solution['abs(error.sum())'] = abs(error.sum()) optimal_solution['weight_matrix'] = weight_matrix logging.info(\"optimal_solution['cur_iter']:{0}\".format(optimal_solution['cur_iter'])) logging.info(\"optimal_solution['cost':{0}\".format(optimal_solution['cost'])) logging.info(\"optimal_solution['abs(error.sum())']:{0}\".format(optimal_solution['abs(error.sum())'])) logging.info(\"optimal_solution['weight_matrix'].tolist():{0}\".format(optimal_solution['weight_matrix'].tolist()))", ".format(database_name = database_name,\\ table_name = passenger_table_name)\\ ) for sql_idx in", "# open csv file try: result_csv_handle = file(result_csv_dir, 'wb') logging.info(\"Success", "1 / 1 * [891, 6].T * [891, 1] #", "== train_label_list[idx] == 1: true_positive_num = true_positive_num + 1 elif", "logging.info(\"test_feature_tuple_list[0]:{0}\".format(test_feature_tuple_list[0])) # len(train_feature_tuple_list[0]): 7 # PassengerId, Pclass, Sex, Age, SibSp,", "= map(lambda (PassengerId, Pclass, Sex, Age, SibSp, Parch, Fare): \\", "= mat(train_label_list).transpose() train_sample_num, feature_num = shape(train_input_matrix) weight_matrix = ones((feature_num, 1))", "= float(right_predict_num)/len(train_label_list) return right_predict_num, accuracy def compute_precision_and_recall_and_F1(train_label_list, predict_label_list): if len(train_label_list)", "Parch, Fare): \\ (PassengerId, 1.0, Pclass, Sex, Age, SibSp, Parch,", "= float(true_positive_num) / (predicted_positive_num + 10E-10) recall = float(true_negative_num) /", "import csv import decorator_of_function ################################### PART2 CLASS && FUNCTION ###########################", "float(right_predict_num)/len(train_label_list) return right_predict_num, accuracy def compute_precision_and_recall_and_F1(train_label_list, predict_label_list): if len(train_label_list) ==", "logging.info(\"optimal_solution['weight_matrix'].tolist():{0}\".format(optimal_solution['weight_matrix'].tolist())) #\"\"\" pylab.plot(cost_list) pylab.show() return weight_matrix #return optimal_solution['weight_matrix'] @Decorator.log_of_function def", "* precision * recall / (precision + recall) return precision,", "self.end - self.start)) @Decorator.log_of_function def get_data_from_database(self, database_name, passenger_table_name): cursor =", "CreateLogisticRegressionModel.__name__)) self.end = time.clock() logging.info(\"The class {class_name} run time is", "= weight_matrix elif cur_iter != 0 and optimal_solution['abs(error.sum())'] > abs(error.sum()):", "weight_matrix[1:] + learning_rate * \\ ( (float(1)/train_sample_num) * train_input_matrix[:, 1::].transpose()", "precision, recall, F1 right_predict_num, accuracy = compute_accuracy(train_label_list = train_label_list,\\ predict_label_list", "train_data = map(lambda (PassengerId, Survived, Pclass, Sex, Age, SibSp, Parch):\\", "7 # PassengerId, Pclass, Sex, Age, SibSp, Parch, Fare train_feature_intercept_term_added_tuple_list", "/ (predicted_positive_num + 10E-10) recall = float(true_negative_num) / (predicted_negative_num +", "error_info = e.args[1])) logging.info(\"END CLASS {class_name}.\".format(class_name = CreateLogisticRegressionModel.__name__)) self.end =", "Fare train_feature_intercept_term_added_tuple_list = map(lambda (PassengerId, Pclass, Sex, Age, SibSp, Parch,", ") # test set sql_list.append(\"\"\"SELECT PassengerId, Survived, Pclass, Sex, Age,", "self.con.cursor() sql_list = [] # training set sql_list.append(\"\"\"SELECT PassengerId, Survived,", "in fetch data from MySQL.\") logging.error(\"MySQL Error {error_num}: {error_info}.\".format(error_num =", "shape(predict_label_matrix) for i in xrange(row): print i+1, predict_label_matrix[i][0] ''' predict_prob_list", "e: self.con.rollback() logging.error(\"Fail in fetch data from MySQL.\") logging.error(\"MySQL Error", "cost:{1}, sum(error):{2}\".format(cur_iter+1, cost, sum(error))) # 1 = 1 + 1", "import exp import csv import decorator_of_function ################################### PART2 CLASS &&", "writer result_csv_writer = csv.writer(result_csv_handle) # write csv file result_csv_writer.writerow([\"PassengerId\", \"Survived\"])", "Pclass, Sex, Age, SibSp, Parch, Fare):\\ (InterceptTerm, Pclass, Sex, Age,", "csv file try: result_csv_handle.close() logging.info(\"Success in closing file handle of", "> 0.5: predict_label_list.append(1) else: predict_label_list.append(0) return predict_label_list @Decorator.log_of_function def accuracy(self,", "datefmt = '%y-%m-%d %H:%M:%S', filename = 'main.log', filemode = 'a')", "(1.0 + exp(-inX)) @Decorator.log_of_function def gradient_descent(self, train_feature_tuple_list, train_label_list, learning_rate =", "logging.info(\"len(predict_label_list):{0}\".format(len(predict_label_list))) # compute accuracy def compute_accuracy(train_label_list, predict_label_list): right_predict_num = 0", "* train_input_matrix[:, 1::].transpose() * error - \\ float(lambda_regularization) / train_sample_num", "user='root', passwd='<PASSWORD>', charset='utf8') logging.info(\"Success in connecting MySQL.\") except MySQLdb.Error, e:", "Pclass, Sex, Age, SibSp, Parch, Fare),\\ test_feature_tuple_list) logging.info(\"len(train_feature_intercept_term_added_tuple_list):{0}\".format(len(train_feature_intercept_term_added_tuple_list))) logging.info(\"train_feature_intercept_term_added_tuple_list[0]:{0}\".format(train_feature_intercept_term_added_tuple_list[0])) logging.info(\"len(test_feature_intercept_term_added_tuple_list):{0}\".format(len(test_feature_intercept_term_added_tuple_list)))", "of {0}.\".format(result_csv_dir)) except Exception as e: logging.error(\"Fail in closing file", "if predict_label_list[idx] == train_label_list[idx] == 1: true_positive_num = true_positive_num +", "list_idx predict_label = predict_label_list[list_idx] result_csv_writer.writerow([PassengerId, predict_label]) # close csv file", "utf-8 -*- # !/usr/bin/python ################################### PART0 DESCRIPTION ################################# # Filename:", "predict_prob_matrix.transpose().tolist()[0] predict_label_list = [] for prob_idx in xrange(len(predict_prob_list)): predict_prob =", "handle of {0}.\".format(result_csv_dir)) logging.error(e) @Decorator.log_of_function def plot_decision_bondary(self, weight_matrix): pass ###################################", "int(Parch)\\ ),\\ test_data) logging.info(\"len(test_data):{0}\".format(len(test_data))) logging.info(\"test_data[0]:{0}\".format(test_data[0])) logging.info(\"type(test_data[0]):{0}\".format(type(test_data[0]))) return train_data, test_data @Decorator.log_of_function", "predicted_positive_num = predict_label_list.count(1) predicted_negative_num = predict_label_list.count(0) for idx in xrange(len(train_label_list)):", "len(predict_label_list): for idx in xrange(len(train_label_list)): if train_label_list[idx] == predict_label_list[idx]: right_predict_num", "%(filename)19s[line:%(lineno)3d] %(funcName)s %(message)s', datefmt = '%y-%m-%d %H:%M:%S', filename = 'main.log',", "Author: <NAME> # E-mail: <EMAIL> # Create: 2016-01-23 23:32:49 #", "(precision + recall) return precision, recall, F1 right_predict_num, accuracy =", "= database_name,\\ table_name = passenger_table_name)\\ ) # test set sql_list.append(\"\"\"SELECT", "Parch, Fare),\\ test_feature_tuple_list) logging.info(\"len(train_feature_intercept_term_added_tuple_list):{0}\".format(len(train_feature_intercept_term_added_tuple_list))) logging.info(\"train_feature_intercept_term_added_tuple_list[0]:{0}\".format(train_feature_intercept_term_added_tuple_list[0])) logging.info(\"len(test_feature_intercept_term_added_tuple_list):{0}\".format(len(test_feature_intercept_term_added_tuple_list))) logging.info(\"test_feature_intercept_term_added_tuple_list[0]:{0}\".format(test_feature_intercept_term_added_tuple_list[0])) return train_feature_intercept_term_added_tuple_list,\\ test_feature_intercept_term_added_tuple_list", "idx in xrange(len(train_label_list)): if predict_label_list[idx] == train_label_list[idx] == 1: true_positive_num", "= 500 ############################ ''' train_feature_tuple_list_without_PassengerId = map(lambda (PassengerId, InterceptTerm, Pclass,", "def compute_accuracy(train_label_list, predict_label_list): right_predict_num = 0 if len(train_label_list) == len(predict_label_list):", "[] for prob_idx in xrange(len(predict_prob_list)): predict_prob = predict_prob_list[prob_idx] if predict_prob", "logging.info(\"train_data[0]:{0}\".format(train_data[0])) logging.info(\"type(train_data[0]):{0}\".format(type(train_data[0]))) test_data = map(lambda (PassengerId, Survived, Pclass, Sex, Age,", "= e.args[0], error_info = e.args[1])) logging.info(\"END CLASS {class_name}.\".format(class_name = CreateLogisticRegressionModel.__name__))", "predict_label_list): logging.info(\"len(train_label_list):{0}\".format(len(train_label_list))) logging.info(\"len(predict_label_list):{0}\".format(len(predict_label_list))) # compute accuracy def compute_accuracy(train_label_list, predict_label_list): right_predict_num", "logging.info(\"len(train_feature_intercept_term_added_tuple_list):{0}\".format(len(train_feature_intercept_term_added_tuple_list))) logging.info(\"train_feature_intercept_term_added_tuple_list[0]:{0}\".format(train_feature_intercept_term_added_tuple_list[0])) logging.info(\"len(test_feature_intercept_term_added_tuple_list):{0}\".format(len(test_feature_intercept_term_added_tuple_list))) logging.info(\"test_feature_intercept_term_added_tuple_list[0]:{0}\".format(test_feature_intercept_term_added_tuple_list[0])) return train_feature_intercept_term_added_tuple_list,\\ test_feature_intercept_term_added_tuple_list @Decorator.log_of_function def sigmoid_function(self,", "== train_label_list[idx] == 0: true_negative_num = true_negative_num + 1 precision", "Pclass, Sex, Age, SibSp, Parch):\\ (int(PassengerId),\\ int(Survived),\\ int(Pclass),\\ Sex,\\ int(Age),\\", "predict_label_list.count(0) for idx in xrange(len(train_label_list)): if predict_label_list[idx] == train_label_list[idx] ==", "return right_predict_num, accuracy def compute_precision_and_recall_and_F1(train_label_list, predict_label_list): if len(train_label_list) == len(predict_label_list):", "predict_prob_list[prob_idx] if predict_prob > 0.5: predict_label_list.append(1) else: predict_label_list.append(0) return predict_label_list", "= compute_accuracy(train_label_list = train_label_list,\\ predict_label_list = predict_label_list) logging.info(\"right_predict_num:{0}\".format(right_predict_num)) logging.info(\"accuracy:{0}\".format(accuracy)) precision,", "logging.info(\"len(test_feature_tuple_list):{0}\".format(len(test_feature_tuple_list))) logging.info(\"test_feature_tuple_list[0]:{0}\".format(test_feature_tuple_list[0])) # len(train_feature_tuple_list[0]): 7 # PassengerId, Pclass, Sex, Age,", "%(message)s', datefmt = '%y-%m-%d %H:%M:%S', filename = 'main.log', filemode =", "Sex, Fare),\\ train_feature_tuple_list) train_input_matrix = mat(train_feature_tuple_list_without_PassengerId) predict_prob_matrix = self.sigmoid_function(train_input_matrix *", "logging.info(\"type(train_data[0]):{0}\".format(type(train_data[0]))) elif sql_idx == 1: test_data = cursor.fetchall() logging.info(\"len(test_data):{0}\".format(len(test_data))) logging.info(\"test_data[0]:{0}\".format(test_data[0]))", "in attaining file handle of {0}.\".format(result_csv_dir)) except Exception as e:", "in closing file handle of {0}.\".format(result_csv_dir)) except Exception as e:", "cost_list.append(cost) # [891, 1] error = train_label_matrix - hypothesis error_list.append(error)", "7] train_input_matrix = mat(train_feature_tuple_list_without_PassengerId) # [891, 1] train_label_matrix = mat(train_label_list).transpose()", "= 1 + 1 * [891, 1].T *[891, 1] weight_matrix[0]", "= CreateLogisticRegressionModel.__name__)) try: self.con = MySQLdb.connect(host='localhost', user='root', passwd='<PASSWORD>', charset='utf8') logging.info(\"Success", "WHERE Is_train=0\"\"\"\\ .format(database_name = database_name,\\ table_name = passenger_table_name)\\ ) for", "- hypothesis error_list.append(error) logging.info(\"cur_iter:{0}, cost:{1}, sum(error):{2}\".format(cur_iter+1, cost, sum(error))) # 1", "parameters database_name = \"TitanicDB\" passenger_table_name = \"passenger_table\" LRModel = CreateLogisticRegressionModel()", "true_negative_num + 1 precision = float(true_positive_num) / (predicted_positive_num + 10E-10)", "1: test_data = cursor.fetchall() logging.info(\"len(test_data):{0}\".format(len(test_data))) logging.info(\"test_data[0]:{0}\".format(test_data[0])) logging.info(\"type(test_data[0]):{0}\".format(type(test_data[0]))) except MySQLdb.Error, e:", "= passenger_table_name)\\ ) for sql_idx in xrange(len(sql_list)): sql = sql_list[sql_idx]", "1] hypothesis = self.sigmoid_function(train_input_matrix * weight_matrix) # real <- sum([891,", "10E-10) F1 = 2 * precision * recall / (precision", "= 'yuens' ################################### PART1 IMPORT ###################################### import MySQLdb import logging", "pylab.show() return weight_matrix #return optimal_solution['weight_matrix'] @Decorator.log_of_function def predict(self, train_feature_tuple_list, weight_matrix):", "#\"\"\" pylab.plot(cost_list) pylab.show() return weight_matrix #return optimal_solution['weight_matrix'] @Decorator.log_of_function def predict(self,", "predict_label_list, result_csv_dir): # open csv file try: result_csv_handle = file(result_csv_dir,", "test_feature_intercept_term_added_tuple_list @Decorator.log_of_function def sigmoid_function(self, inX): return 1.0 / (1.0 +", "FROM {database_name}.{table_name} WHERE Is_train=1\"\"\"\\ .format(database_name = database_name,\\ table_name = passenger_table_name)\\", "= mat(train_feature_tuple_list_without_PassengerId) # [891, 1] train_label_matrix = mat(train_label_list).transpose() train_sample_num, feature_num", "error = train_label_matrix - hypothesis error_list.append(error) logging.info(\"cur_iter:{0}, cost:{1}, sum(error):{2}\".format(cur_iter+1, cost,", "1] train_label_matrix = mat(train_label_list).transpose() train_sample_num, feature_num = shape(train_input_matrix) weight_matrix =", "error_list = [] optimal_solution = {} for cur_iter in xrange(max_iteration_time):", "def write_csv_file(self, start_id, predict_label_list, result_csv_dir): # open csv file try:", "= CreateLogisticRegressionModel.__name__, delta_time = self.end - self.start)) @Decorator.log_of_function def get_data_from_database(self,", "################################### PART1 IMPORT ###################################### import MySQLdb import logging import time", "# Create: 2016-01-23 23:32:49 # Last: __author__ = 'yuens' ###################################", "sql_idx == 1: test_data = cursor.fetchall() logging.info(\"len(test_data):{0}\".format(len(test_data))) logging.info(\"test_data[0]:{0}\".format(test_data[0])) logging.info(\"type(test_data[0]):{0}\".format(type(test_data[0]))) except", "def add_intercept_term(self, train_feature_tuple_list, test_feature_tuple_list): logging.info(\"len(train_feature_tuple_list[0]):{0}\".format(len(train_feature_tuple_list[0]))) logging.info(\"len(train_feature_tuple_list):{0}\".format(len(train_feature_tuple_list))) logging.info(\"train_feature_tuple_list[0]:{0}\".format(train_feature_tuple_list[0])) logging.info(\"test_feature_tuple_list[0]:{0}\".format(len(test_feature_tuple_list[0]))) logging.info(\"len(test_feature_tuple_list):{0}\".format(len(test_feature_tuple_list))) logging.info(\"test_feature_tuple_list[0]:{0}\".format(test_feature_tuple_list[0]))", "[891, 1].T *[891, 1] weight_matrix[0] = weight_matrix[0] + learning_rate *", "predict_prob_list = predict_prob_matrix.transpose().tolist()[0] predict_label_list = [] for prob_idx in xrange(len(predict_prob_list)):", "0: true_negative_num = true_negative_num + 1 precision = float(true_positive_num) /", "PART1 IMPORT ###################################### import MySQLdb import logging import time import", "%(filename)19s[line:%(lineno)3d] %(funcName)s %(message)s') console.setFormatter(formatter) logging.getLogger('').addHandler(console) logging.info(\"START CLASS {class_name}.\".format(class_name = CreateLogisticRegressionModel.__name__))", ".format(database_name = database_name,\\ table_name = passenger_table_name)\\ ) # test set", "delta_time = self.end - self.start)) @Decorator.log_of_function def get_data_from_database(self, database_name, passenger_table_name):", "self.end = time.clock() logging.info(\"The class {class_name} run time is :", "SibSp, Parch FROM {database_name}.{table_name} WHERE Is_train=0\"\"\"\\ .format(database_name = database_name,\\ table_name", "= 500, lambda_regularization = 0.1): ############################ # Initial parameters #", "= {} for cur_iter in xrange(max_iteration_time): # [891, 1] <-", "FROM {database_name}.{table_name} WHERE Is_train=0\"\"\"\\ .format(database_name = database_name,\\ table_name = passenger_table_name)\\", "in xrange(len(predict_label_list)): PassengerId = start_id + list_idx predict_label = predict_label_list[list_idx]", "for idx in xrange(len(train_label_list)): if predict_label_list[idx] == train_label_list[idx] == 1:", "test_feature_tuple_list): logging.info(\"len(train_feature_tuple_list[0]):{0}\".format(len(train_feature_tuple_list[0]))) logging.info(\"len(train_feature_tuple_list):{0}\".format(len(train_feature_tuple_list))) logging.info(\"train_feature_tuple_list[0]:{0}\".format(train_feature_tuple_list[0])) logging.info(\"test_feature_tuple_list[0]:{0}\".format(len(test_feature_tuple_list[0]))) logging.info(\"len(test_feature_tuple_list):{0}\".format(len(test_feature_tuple_list))) logging.info(\"test_feature_tuple_list[0]:{0}\".format(test_feature_tuple_list[0])) # len(train_feature_tuple_list[0]): 7", "Age, SibSp, Parch, Fare):\\ (InterceptTerm, Pclass, Sex, Age, SibSp, Parch,", "CreateLogisticRegressionModel.__name__, delta_time = self.end - self.start)) @Decorator.log_of_function def get_data_from_database(self, database_name,", "-*- # !/usr/bin/python ################################### PART0 DESCRIPTION ################################# # Filename: class_create_model_of_logistic_regression.py", "Parch FROM {database_name}.{table_name} WHERE Is_train=1\"\"\"\\ .format(database_name = database_name,\\ table_name =", "MySQLdb import logging import time import pylab from numpy import", "############################ # Initial parameters # learning_rate = 0.01 # max_iteration_time", "Pclass, Sex, Age, SibSp, Parch, Fare): \\ (PassengerId, 1.0, Pclass,", "recall true_positive_num = 10E-10 true_negative_num = 10E-10 predicted_positive_num = predict_label_list.count(1)", "train_label_list[idx] == 0: true_negative_num = true_negative_num + 1 precision =", "= [] error_list = [] optimal_solution = {} for cur_iter", "__del__(self): try: self.con.close() logging.info(\"Success in quiting MySQL.\") except MySQLdb.Error, e:", "abs(error.sum()): optimal_solution['cur_iter'] = cur_iter optimal_solution['cost'] = cost optimal_solution['abs(error.sum())'] = abs(error.sum())", "= ones((feature_num, 1)) cost_list = [] error_list = [] optimal_solution", "return precision, recall, F1 right_predict_num, accuracy = compute_accuracy(train_label_list = train_label_list,\\", "( (float(1)/train_sample_num) * train_input_matrix[:, 1::].transpose() * error - \\ float(lambda_regularization)", "1::].transpose() * error - \\ float(lambda_regularization) / train_sample_num * weight_matrix[1:]", "cur_iter == 0: optimal_solution['cur_iter'] = cur_iter optimal_solution['cost'] = cost optimal_solution['abs(error.sum())']", "right_predict_num + 1 accuracy = float(right_predict_num)/len(train_label_list) return right_predict_num, accuracy def", "logging.info(\"recall:{0}\".format(recall)) logging.info(\"F1:{0}\".format(F1)) return accuracy, precision, recall, F1 @Decorator.log_of_function def write_csv_file(self,", "-float(1) / (train_sample_num) * \\ sum( train_label_matrix.transpose()*log(hypothesis) + (1-train_label_matrix.transpose())*log(1-hypothesis) )", "Filename: class_create_model_of_logistic_regression.py # Description: # # Author: <NAME> # E-mail:", "Sex, Age, SibSp, Parch, Fare train_feature_intercept_term_added_tuple_list = map(lambda (PassengerId, Pclass,", "time is : {delta_time} seconds\".format(class_name = CreateLogisticRegressionModel.__name__, delta_time = self.end", "[891, 1]T*[891, 1]) cost = -float(1) / (train_sample_num) * \\", "accuracy def compute_precision_and_recall_and_F1(train_label_list, predict_label_list): if len(train_label_list) == len(predict_label_list): # compute", "logging.info(\"optimal_solution['cur_iter']:{0}\".format(optimal_solution['cur_iter'])) logging.info(\"optimal_solution['cost':{0}\".format(optimal_solution['cost'])) logging.info(\"optimal_solution['abs(error.sum())']:{0}\".format(optimal_solution['abs(error.sum())'])) logging.info(\"optimal_solution['weight_matrix'].tolist():{0}\".format(optimal_solution['weight_matrix'].tolist())) #\"\"\" pylab.plot(cost_list) pylab.show() return weight_matrix #return", "return predict_label_list @Decorator.log_of_function def accuracy(self, train_label_list, predict_label_list): logging.info(\"len(train_label_list):{0}\".format(len(train_label_list))) logging.info(\"len(predict_label_list):{0}\".format(len(predict_label_list))) #", "+ list_idx predict_label = predict_label_list[list_idx] result_csv_writer.writerow([PassengerId, predict_label]) # close csv", "= 'main.log', filemode = 'a') console = logging.StreamHandler() console.setLevel(logging.INFO) formatter", "= [] for prob_idx in xrange(len(predict_prob_list)): predict_prob = predict_prob_list[prob_idx] if", "start_id + list_idx predict_label = predict_label_list[list_idx] result_csv_writer.writerow([PassengerId, predict_label]) # close", "Initial parameters database_name = \"TitanicDB\" passenger_table_name = \"passenger_table\" LRModel =", "7]*[7, 1] hypothesis = self.sigmoid_function(train_input_matrix * weight_matrix) # real <-", "= 2 * precision * recall / (precision + recall)", "= [] # training set sql_list.append(\"\"\"SELECT PassengerId, Survived, Pclass, Sex,", "try: result_csv_handle.close() logging.info(\"Success in closing file handle of {0}.\".format(result_csv_dir)) except", "# -*- coding: utf-8 -*- # !/usr/bin/python ################################### PART0 DESCRIPTION", "recall, F1 = compute_precision_and_recall_and_F1(train_label_list = train_label_list,\\ predict_label_list = predict_label_list) logging.info(\"precision:{0}\".format(precision))", "== len(predict_label_list): # compute precision and recall true_positive_num = 10E-10", "# Description: # # Author: <NAME> # E-mail: <EMAIL> #", "plot_decision_bondary(self, weight_matrix): pass ################################### PART3 CLASS TEST ################################## \"\"\" #", "decorator_of_function.CreateDecorator() @Decorator.log_of_function def __init__(self): self.start = time.clock() logging.basicConfig(level = logging.INFO,", "# close csv file try: result_csv_handle.close() logging.info(\"Success in closing file", "Is_train=0\"\"\"\\ .format(database_name = database_name,\\ table_name = passenger_table_name)\\ ) for sql_idx", "- \\ float(lambda_regularization) / train_sample_num * weight_matrix[1:] \\ ) #weight_matrix", "1.0, Pclass, Sex, Age, SibSp, Parch, Fare),\\ test_feature_tuple_list) logging.info(\"len(train_feature_intercept_term_added_tuple_list):{0}\".format(len(train_feature_intercept_term_added_tuple_list))) logging.info(\"train_feature_intercept_term_added_tuple_list[0]:{0}\".format(train_feature_intercept_term_added_tuple_list[0]))", "%(levelname)5s %(filename)19s[line:%(lineno)3d] %(funcName)s %(message)s', datefmt = '%y-%m-%d %H:%M:%S', filename =", "(predicted_negative_num + 10E-10) F1 = 2 * precision * recall", "optimal solution if cur_iter == 0: optimal_solution['cur_iter'] = cur_iter optimal_solution['cost']", "Sex, Age, SibSp, Parch, Fare),\\ test_feature_tuple_list) logging.info(\"len(train_feature_intercept_term_added_tuple_list):{0}\".format(len(train_feature_intercept_term_added_tuple_list))) logging.info(\"train_feature_intercept_term_added_tuple_list[0]:{0}\".format(train_feature_intercept_term_added_tuple_list[0])) logging.info(\"len(test_feature_intercept_term_added_tuple_list):{0}\".format(len(test_feature_intercept_term_added_tuple_list))) logging.info(\"test_feature_intercept_term_added_tuple_list[0]:{0}\".format(test_feature_intercept_term_added_tuple_list[0]))", "= mat(train_feature_tuple_list_without_PassengerId) predict_prob_matrix = self.sigmoid_function(train_input_matrix * weight_matrix) ''' row, col", "@Decorator.log_of_function def add_intercept_term(self, train_feature_tuple_list, test_feature_tuple_list): logging.info(\"len(train_feature_tuple_list[0]):{0}\".format(len(train_feature_tuple_list[0]))) logging.info(\"len(train_feature_tuple_list):{0}\".format(len(train_feature_tuple_list))) logging.info(\"train_feature_tuple_list[0]:{0}\".format(train_feature_tuple_list[0])) logging.info(\"test_feature_tuple_list[0]:{0}\".format(len(test_feature_tuple_list[0]))) logging.info(\"len(test_feature_tuple_list):{0}\".format(len(test_feature_tuple_list)))", "predict_label_list): right_predict_num = 0 if len(train_label_list) == len(predict_label_list): for idx", "precision and recall true_positive_num = 10E-10 true_negative_num = 10E-10 predicted_positive_num", "row, col = shape(predict_label_matrix) for i in xrange(row): print i+1,", "= database_name,\\ table_name = passenger_table_name)\\ ) for sql_idx in xrange(len(sql_list)):", "# E-mail: <EMAIL> # Create: 2016-01-23 23:32:49 # Last: __author__", "in xrange(len(train_label_list)): if train_label_list[idx] == predict_label_list[idx]: right_predict_num = right_predict_num +" ]
[ "type: ignore args = (self._writer, (filename, image)) if dill_for_apply: #", "str, image: np.ndarray): self._writer(filename, image) def save(self, image: np.ndarray): self._save(self.next_filename,", "pipes them into the subprocesses. \"\"\" def __init__(self, *args, max_workers=None,", "save(self, image: np.ndarray): self._save(self.next_filename, image) self._index += 1 def finish(self):", "else: self._sem = None self._results = [] # type: List[multiprocessing.pool.AsyncResult]", "List, Optional import numpy as np from ..util import dill_for_apply", "as np from ..util import dill_for_apply class ImageSequenceWriter: def __init__(self,", "filename, image) result = self._pool.apply_async( *args, callback=callback, error_callback=callback, ) self._results.append(result)", "finish(self, result_handler=None): try: # self._pool.close() for result in self._results: filename", "i: _writer(f, i) or f, filename, image) result = self._pool.apply_async(", "in self._results: filename = result.get() if result_handler is not None:", "{index}\") self._pattern = pattern self._writer = writer self._max_index = max_index", "next_filename(self): index = str(self._index) if self._max_index: index = \"{:0{}d}\".format(self._index, len(str(self._max_index)))", "class MultiprocessingImageSequenceWriter(ImageSequenceWriter): \"\"\"Image sequence writer that uses multiprocessing to save", "max_workers = multiprocessing.cpu_count() - 1 ctx = multiprocessing.get_context(\"spawn\") self._pool =", "waiting tasks if self._sem: self._sem.acquire() def callback(v): assert self._sem is", "if dill_for_apply: # Use dill instead of pickle, and make", "def finish(self): pass class MultiprocessingImageSequenceWriter(ImageSequenceWriter): \"\"\"Image sequence writer that uses", "writer returns the filename _writer = self._writer # Exclude self", "in parallel. This falls apart for large objects, as multiprocessing", "_save(self, filename: str, image: np.ndarray): # Limit number of waiting", "instead of pickle, and make sure writer returns the filename", "self from capture to avoid dilling _pool args = dill_for_apply(lambda", "= ctx.Pool(max_workers) if max_waiting is not None: # Semaphore's value", "self._results = [] # type: List[multiprocessing.pool.AsyncResult] def __del__(self): self.terminate() def", "number of waiting tasks if self._sem: self._sem.acquire() def callback(v): assert", "image)) if dill_for_apply: # Use dill instead of pickle, and", "import multiprocessing from typing import List, Optional import numpy as", "falls apart for large objects, as multiprocessing pickles them and", "type: List[multiprocessing.pool.AsyncResult] def __del__(self): self.terminate() def _save(self, filename: str, image:", "max_workers=None, max_waiting=None, **kwargs): super().__init__(*args, **kwargs) if max_workers is None: max_workers", "Use dill instead of pickle, and make sure writer returns", "image: np.ndarray): self._save(self.next_filename, image) self._index += 1 def finish(self): pass", "if max_workers is None: max_workers = multiprocessing.cpu_count() - 1 ctx", "pass class MultiprocessingImageSequenceWriter(ImageSequenceWriter): \"\"\"Image sequence writer that uses multiprocessing to", "import numpy as np from ..util import dill_for_apply class ImageSequenceWriter:", "self._sem = ctx.Semaphore( max_waiting ) # type: Optional[multiprocessing.synchronize.Semaphore] else: self._sem", "else: callback = None # type: ignore args = (self._writer,", "sure writer returns the filename _writer = self._writer # Exclude", "avoid dilling _pool args = dill_for_apply(lambda f, i: _writer(f, i)", "them and pipes them into the subprocesses. \"\"\" def __init__(self,", "dilling _pool args = dill_for_apply(lambda f, i: _writer(f, i) or", "must be string\") if pattern.format(1, index=\"1\") == pattern.format(2, index=\"2\"): raise", "image) def save(self, image: np.ndarray): self._save(self.next_filename, image) self._index += 1", "from typing import List, Optional import numpy as np from", "1 @property def next_filename(self): index = str(self._index) if self._max_index: index", "**kwargs) if max_workers is None: max_workers = multiprocessing.cpu_count() - 1", "or f, filename, image) result = self._pool.apply_async( *args, callback=callback, error_callback=callback,", "= None self._results = [] # type: List[multiprocessing.pool.AsyncResult] def __del__(self):", "pattern.format(2, index=\"2\"): raise ValueError(\"Pattern must use {} or {index}\") self._pattern", "and pipes them into the subprocesses. \"\"\" def __init__(self, *args,", "self._max_index = max_index self._index = 1 @property def next_filename(self): index", "multiprocessing pickles them and pipes them into the subprocesses. \"\"\"", "several images in parallel. This falls apart for large objects,", "self._pool = ctx.Pool(max_workers) if max_waiting is not None: # Semaphore's", "type(pattern) is not str: raise ValueError(\"Pattern must be string\") if", "not str: raise ValueError(\"Pattern must be string\") if pattern.format(1, index=\"1\")", "writer, *, max_index=None): if type(pattern) is not str: raise ValueError(\"Pattern", "pickles them and pipes them into the subprocesses. \"\"\" def", "def _save(self, filename: str, image: np.ndarray): self._writer(filename, image) def save(self,", "pattern, writer, *, max_index=None): if type(pattern) is not str: raise", "_save(self, filename: str, image: np.ndarray): self._writer(filename, image) def save(self, image:", "make sure writer returns the filename _writer = self._writer #", "+= 1 def finish(self): pass class MultiprocessingImageSequenceWriter(ImageSequenceWriter): \"\"\"Image sequence writer", "self._sem.release() else: callback = None # type: ignore args =", "if type(pattern) is not str: raise ValueError(\"Pattern must be string\")", "self._index = 1 @property def next_filename(self): index = str(self._index) if", "image: np.ndarray): self._writer(filename, image) def save(self, image: np.ndarray): self._save(self.next_filename, image)", "type: Optional[multiprocessing.synchronize.Semaphore] else: self._sem = None self._results = [] #", "pattern self._writer = writer self._max_index = max_index self._index = 1", "terminate(self): self._pool.terminate() self._pool.join() def finish(self, result_handler=None): try: # self._pool.close() for", "use {} or {index}\") self._pattern = pattern self._writer = writer", "def finish(self, result_handler=None): try: # self._pool.close() for result in self._results:", "max_index=None): if type(pattern) is not str: raise ValueError(\"Pattern must be", "image) result = self._pool.apply_async( *args, callback=callback, error_callback=callback, ) self._results.append(result) def", "tasks if self._sem: self._sem.acquire() def callback(v): assert self._sem is not", "= str(self._index) if self._max_index: index = \"{:0{}d}\".format(self._index, len(str(self._max_index))) return self._pattern.format(self._index,", "# type: ignore args = (self._writer, (filename, image)) if dill_for_apply:", "assert self._sem is not None self._sem.release() else: callback = None", "= self._pool.apply_async( *args, callback=callback, error_callback=callback, ) self._results.append(result) def terminate(self): self._pool.terminate()", "result.get() if result_handler is not None: result_handler(filename) self._pool.close() except KeyboardInterrupt:", "raise ValueError(\"Pattern must use {} or {index}\") self._pattern = pattern", "self._sem.acquire() def callback(v): assert self._sem is not None self._sem.release() else:", "*, max_index=None): if type(pattern) is not str: raise ValueError(\"Pattern must", "- 1 ctx = multiprocessing.get_context(\"spawn\") self._pool = ctx.Pool(max_workers) if max_waiting", "filename: str, image: np.ndarray): # Limit number of waiting tasks", "def __init__(self, *args, max_workers=None, max_waiting=None, **kwargs): super().__init__(*args, **kwargs) if max_workers", "self._pool.join() def finish(self, result_handler=None): try: # self._pool.close() for result in", "uses multiprocessing to save several images in parallel. This falls", "image) self._index += 1 def finish(self): pass class MultiprocessingImageSequenceWriter(ImageSequenceWriter): \"\"\"Image", "= (self._writer, (filename, image)) if dill_for_apply: # Use dill instead", "wait in self._sem = ctx.Semaphore( max_waiting ) # type: Optional[multiprocessing.synchronize.Semaphore]", "parallel. This falls apart for large objects, as multiprocessing pickles", "def __init__(self, pattern, writer, *, max_index=None): if type(pattern) is not", "self._writer = writer self._max_index = max_index self._index = 1 @property", "Optional[multiprocessing.synchronize.Semaphore] else: self._sem = None self._results = [] # type:", "if pattern.format(1, index=\"1\") == pattern.format(2, index=\"2\"): raise ValueError(\"Pattern must use", "ValueError(\"Pattern must use {} or {index}\") self._pattern = pattern self._writer", "len(str(self._max_index))) return self._pattern.format(self._index, index=index) def _save(self, filename: str, image: np.ndarray):", "of waiting tasks if self._sem: self._sem.acquire() def callback(v): assert self._sem", "multiprocessing from typing import List, Optional import numpy as np", "= writer self._max_index = max_index self._index = 1 @property def", "super().__init__(*args, **kwargs) if max_workers is None: max_workers = multiprocessing.cpu_count() -", "for large objects, as multiprocessing pickles them and pipes them", "error_callback=callback, ) self._results.append(result) def terminate(self): self._pool.terminate() self._pool.join() def finish(self, result_handler=None):", "writer that uses multiprocessing to save several images in parallel.", "return self._pattern.format(self._index, index=index) def _save(self, filename: str, image: np.ndarray): self._writer(filename,", "**kwargs): super().__init__(*args, **kwargs) if max_workers is None: max_workers = multiprocessing.cpu_count()", "is not None: # Semaphore's value is number of slots", "callback=callback, error_callback=callback, ) self._results.append(result) def terminate(self): self._pool.terminate() self._pool.join() def finish(self,", "\"{:0{}d}\".format(self._index, len(str(self._max_index))) return self._pattern.format(self._index, index=index) def _save(self, filename: str, image:", "in self._sem = ctx.Semaphore( max_waiting ) # type: Optional[multiprocessing.synchronize.Semaphore] else:", "_pool args = dill_for_apply(lambda f, i: _writer(f, i) or f,", "self._pool.close() for result in self._results: filename = result.get() if result_handler", "value is number of slots available for tasks to wait", "(self._writer, (filename, image)) if dill_for_apply: # Use dill instead of", "available for tasks to wait in self._sem = ctx.Semaphore( max_waiting", "index = \"{:0{}d}\".format(self._index, len(str(self._max_index))) return self._pattern.format(self._index, index=index) def _save(self, filename:", ") # type: Optional[multiprocessing.synchronize.Semaphore] else: self._sem = None self._results =", "f, filename, image) result = self._pool.apply_async( *args, callback=callback, error_callback=callback, )", "# type: Optional[multiprocessing.synchronize.Semaphore] else: self._sem = None self._results = []", "= max_index self._index = 1 @property def next_filename(self): index =", "string\") if pattern.format(1, index=\"1\") == pattern.format(2, index=\"2\"): raise ValueError(\"Pattern must", "# Use dill instead of pickle, and make sure writer", "self._sem is not None self._sem.release() else: callback = None #", "args = dill_for_apply(lambda f, i: _writer(f, i) or f, filename,", "def terminate(self): self._pool.terminate() self._pool.join() def finish(self, result_handler=None): try: # self._pool.close()", "images in parallel. This falls apart for large objects, as", "returns the filename _writer = self._writer # Exclude self from", "objects, as multiprocessing pickles them and pipes them into the", "self._writer(filename, image) def save(self, image: np.ndarray): self._save(self.next_filename, image) self._index +=", "them into the subprocesses. \"\"\" def __init__(self, *args, max_workers=None, max_waiting=None,", "to save several images in parallel. This falls apart for", "__del__(self): self.terminate() def _save(self, filename: str, image: np.ndarray): # Limit", "dill_for_apply: # Use dill instead of pickle, and make sure", "ValueError(\"Pattern must be string\") if pattern.format(1, index=\"1\") == pattern.format(2, index=\"2\"):", "typing import List, Optional import numpy as np from ..util", "None self._results = [] # type: List[multiprocessing.pool.AsyncResult] def __del__(self): self.terminate()", "be string\") if pattern.format(1, index=\"1\") == pattern.format(2, index=\"2\"): raise ValueError(\"Pattern", "large objects, as multiprocessing pickles them and pipes them into", "capture to avoid dilling _pool args = dill_for_apply(lambda f, i:", "not None self._sem.release() else: callback = None # type: ignore", "# Semaphore's value is number of slots available for tasks", "def callback(v): assert self._sem is not None self._sem.release() else: callback", "max_waiting is not None: # Semaphore's value is number of", "tasks to wait in self._sem = ctx.Semaphore( max_waiting ) #", "pattern.format(1, index=\"1\") == pattern.format(2, index=\"2\"): raise ValueError(\"Pattern must use {}", "= pattern self._writer = writer self._max_index = max_index self._index =", "multiprocessing to save several images in parallel. This falls apart", "sequence writer that uses multiprocessing to save several images in", "= dill_for_apply(lambda f, i: _writer(f, i) or f, filename, image)", "== pattern.format(2, index=\"2\"): raise ValueError(\"Pattern must use {} or {index}\")", "# Limit number of waiting tasks if self._sem: self._sem.acquire() def", "f, i: _writer(f, i) or f, filename, image) result =", "self._pool.apply_async( *args, callback=callback, error_callback=callback, ) self._results.append(result) def terminate(self): self._pool.terminate() self._pool.join()", "multiprocessing.get_context(\"spawn\") self._pool = ctx.Pool(max_workers) if max_waiting is not None: #", "max_waiting ) # type: Optional[multiprocessing.synchronize.Semaphore] else: self._sem = None self._results", "i) or f, filename, image) result = self._pool.apply_async( *args, callback=callback,", "is None: max_workers = multiprocessing.cpu_count() - 1 ctx = multiprocessing.get_context(\"spawn\")", "result = self._pool.apply_async( *args, callback=callback, error_callback=callback, ) self._results.append(result) def terminate(self):", "index=\"2\"): raise ValueError(\"Pattern must use {} or {index}\") self._pattern =", "args = (self._writer, (filename, image)) if dill_for_apply: # Use dill", "if result_handler is not None: result_handler(filename) self._pool.close() except KeyboardInterrupt: self._pool.terminate()", "dill instead of pickle, and make sure writer returns the", "max_workers is None: max_workers = multiprocessing.cpu_count() - 1 ctx =", "dill_for_apply(lambda f, i: _writer(f, i) or f, filename, image) result", "filename _writer = self._writer # Exclude self from capture to", "def _save(self, filename: str, image: np.ndarray): # Limit number of", "and make sure writer returns the filename _writer = self._writer", "= ctx.Semaphore( max_waiting ) # type: Optional[multiprocessing.synchronize.Semaphore] else: self._sem =", "index = str(self._index) if self._max_index: index = \"{:0{}d}\".format(self._index, len(str(self._max_index))) return", "= result.get() if result_handler is not None: result_handler(filename) self._pool.close() except", "*args, max_workers=None, max_waiting=None, **kwargs): super().__init__(*args, **kwargs) if max_workers is None:", "def save(self, image: np.ndarray): self._save(self.next_filename, image) self._index += 1 def", "\"\"\"Image sequence writer that uses multiprocessing to save several images", "as multiprocessing pickles them and pipes them into the subprocesses.", "MultiprocessingImageSequenceWriter(ImageSequenceWriter): \"\"\"Image sequence writer that uses multiprocessing to save several", "= [] # type: List[multiprocessing.pool.AsyncResult] def __del__(self): self.terminate() def _save(self,", "if max_waiting is not None: # Semaphore's value is number", "= multiprocessing.cpu_count() - 1 ctx = multiprocessing.get_context(\"spawn\") self._pool = ctx.Pool(max_workers)", "result_handler=None): try: # self._pool.close() for result in self._results: filename =", "np from ..util import dill_for_apply class ImageSequenceWriter: def __init__(self, pattern,", "\"\"\" def __init__(self, *args, max_workers=None, max_waiting=None, **kwargs): super().__init__(*args, **kwargs) if", "def next_filename(self): index = str(self._index) if self._max_index: index = \"{:0{}d}\".format(self._index,", "self._save(self.next_filename, image) self._index += 1 def finish(self): pass class MultiprocessingImageSequenceWriter(ImageSequenceWriter):", "the filename _writer = self._writer # Exclude self from capture", "__init__(self, *args, max_workers=None, max_waiting=None, **kwargs): super().__init__(*args, **kwargs) if max_workers is", "ctx.Pool(max_workers) if max_waiting is not None: # Semaphore's value is", "= None # type: ignore args = (self._writer, (filename, image))", "None self._sem.release() else: callback = None # type: ignore args", "Optional import numpy as np from ..util import dill_for_apply class", "to avoid dilling _pool args = dill_for_apply(lambda f, i: _writer(f,", "Exclude self from capture to avoid dilling _pool args =", "{} or {index}\") self._pattern = pattern self._writer = writer self._max_index", "self._sem = None self._results = [] # type: List[multiprocessing.pool.AsyncResult] def", "self._pattern = pattern self._writer = writer self._max_index = max_index self._index", "is not None self._sem.release() else: callback = None # type:", "ignore args = (self._writer, (filename, image)) if dill_for_apply: # Use", "np.ndarray): self._save(self.next_filename, image) self._index += 1 def finish(self): pass class", "for tasks to wait in self._sem = ctx.Semaphore( max_waiting )", "_writer(f, i) or f, filename, image) result = self._pool.apply_async( *args,", "def __del__(self): self.terminate() def _save(self, filename: str, image: np.ndarray): #", "for result in self._results: filename = result.get() if result_handler is", "This falls apart for large objects, as multiprocessing pickles them", "self._writer # Exclude self from capture to avoid dilling _pool", "try: # self._pool.close() for result in self._results: filename = result.get()", "None: max_workers = multiprocessing.cpu_count() - 1 ctx = multiprocessing.get_context(\"spawn\") self._pool", "ImageSequenceWriter: def __init__(self, pattern, writer, *, max_index=None): if type(pattern) is", "1 def finish(self): pass class MultiprocessingImageSequenceWriter(ImageSequenceWriter): \"\"\"Image sequence writer that", "number of slots available for tasks to wait in self._sem", "class ImageSequenceWriter: def __init__(self, pattern, writer, *, max_index=None): if type(pattern)", "of pickle, and make sure writer returns the filename _writer", "ctx = multiprocessing.get_context(\"spawn\") self._pool = ctx.Pool(max_workers) if max_waiting is not", "slots available for tasks to wait in self._sem = ctx.Semaphore(", "numpy as np from ..util import dill_for_apply class ImageSequenceWriter: def", "save several images in parallel. This falls apart for large", "not None: # Semaphore's value is number of slots available", "Semaphore's value is number of slots available for tasks to", "ctx.Semaphore( max_waiting ) # type: Optional[multiprocessing.synchronize.Semaphore] else: self._sem = None", "callback(v): assert self._sem is not None self._sem.release() else: callback =", "callback = None # type: ignore args = (self._writer, (filename,", "np.ndarray): self._writer(filename, image) def save(self, image: np.ndarray): self._save(self.next_filename, image) self._index", "1 ctx = multiprocessing.get_context(\"spawn\") self._pool = ctx.Pool(max_workers) if max_waiting is", "(filename, image)) if dill_for_apply: # Use dill instead of pickle,", "# self._pool.close() for result in self._results: filename = result.get() if", "index=index) def _save(self, filename: str, image: np.ndarray): self._writer(filename, image) def", "import dill_for_apply class ImageSequenceWriter: def __init__(self, pattern, writer, *, max_index=None):", "self._pattern.format(self._index, index=index) def _save(self, filename: str, image: np.ndarray): self._writer(filename, image)", "into the subprocesses. \"\"\" def __init__(self, *args, max_workers=None, max_waiting=None, **kwargs):", "Limit number of waiting tasks if self._sem: self._sem.acquire() def callback(v):", "str: raise ValueError(\"Pattern must be string\") if pattern.format(1, index=\"1\") ==", "or {index}\") self._pattern = pattern self._writer = writer self._max_index =", "writer self._max_index = max_index self._index = 1 @property def next_filename(self):", "import List, Optional import numpy as np from ..util import", "the subprocesses. \"\"\" def __init__(self, *args, max_workers=None, max_waiting=None, **kwargs): super().__init__(*args,", "= multiprocessing.get_context(\"spawn\") self._pool = ctx.Pool(max_workers) if max_waiting is not None:", "# type: List[multiprocessing.pool.AsyncResult] def __del__(self): self.terminate() def _save(self, filename: str,", "is not str: raise ValueError(\"Pattern must be string\") if pattern.format(1,", "self._results: filename = result.get() if result_handler is not None: result_handler(filename)", "result in self._results: filename = result.get() if result_handler is not", "must use {} or {index}\") self._pattern = pattern self._writer =", "if self._sem: self._sem.acquire() def callback(v): assert self._sem is not None", "self._pool.terminate() self._pool.join() def finish(self, result_handler=None): try: # self._pool.close() for result", "dill_for_apply class ImageSequenceWriter: def __init__(self, pattern, writer, *, max_index=None): if", "is not None: result_handler(filename) self._pool.close() except KeyboardInterrupt: self._pool.terminate() finally: self._pool.join()", "None # type: ignore args = (self._writer, (filename, image)) if", "self._results.append(result) def terminate(self): self._pool.terminate() self._pool.join() def finish(self, result_handler=None): try: #", "[] # type: List[multiprocessing.pool.AsyncResult] def __del__(self): self.terminate() def _save(self, filename:", "None: # Semaphore's value is number of slots available for", "str(self._index) if self._max_index: index = \"{:0{}d}\".format(self._index, len(str(self._max_index))) return self._pattern.format(self._index, index=index)", "str, image: np.ndarray): # Limit number of waiting tasks if", "*args, callback=callback, error_callback=callback, ) self._results.append(result) def terminate(self): self._pool.terminate() self._pool.join() def", "self._index += 1 def finish(self): pass class MultiprocessingImageSequenceWriter(ImageSequenceWriter): \"\"\"Image sequence", "@property def next_filename(self): index = str(self._index) if self._max_index: index =", "max_waiting=None, **kwargs): super().__init__(*args, **kwargs) if max_workers is None: max_workers =", "self.terminate() def _save(self, filename: str, image: np.ndarray): # Limit number", "of slots available for tasks to wait in self._sem =", "from ..util import dill_for_apply class ImageSequenceWriter: def __init__(self, pattern, writer,", "= \"{:0{}d}\".format(self._index, len(str(self._max_index))) return self._pattern.format(self._index, index=index) def _save(self, filename: str,", "# Exclude self from capture to avoid dilling _pool args", "self._max_index: index = \"{:0{}d}\".format(self._index, len(str(self._max_index))) return self._pattern.format(self._index, index=index) def _save(self,", "..util import dill_for_apply class ImageSequenceWriter: def __init__(self, pattern, writer, *,", "apart for large objects, as multiprocessing pickles them and pipes", "index=\"1\") == pattern.format(2, index=\"2\"): raise ValueError(\"Pattern must use {} or", "subprocesses. \"\"\" def __init__(self, *args, max_workers=None, max_waiting=None, **kwargs): super().__init__(*args, **kwargs)", "is number of slots available for tasks to wait in", "that uses multiprocessing to save several images in parallel. This", "np.ndarray): # Limit number of waiting tasks if self._sem: self._sem.acquire()", "image: np.ndarray): # Limit number of waiting tasks if self._sem:", "List[multiprocessing.pool.AsyncResult] def __del__(self): self.terminate() def _save(self, filename: str, image: np.ndarray):", "__init__(self, pattern, writer, *, max_index=None): if type(pattern) is not str:", "pickle, and make sure writer returns the filename _writer =", "from capture to avoid dilling _pool args = dill_for_apply(lambda f,", "max_index self._index = 1 @property def next_filename(self): index = str(self._index)", "if self._max_index: index = \"{:0{}d}\".format(self._index, len(str(self._max_index))) return self._pattern.format(self._index, index=index) def", "raise ValueError(\"Pattern must be string\") if pattern.format(1, index=\"1\") == pattern.format(2,", "result_handler is not None: result_handler(filename) self._pool.close() except KeyboardInterrupt: self._pool.terminate() finally:", "= self._writer # Exclude self from capture to avoid dilling", "to wait in self._sem = ctx.Semaphore( max_waiting ) # type:", ") self._results.append(result) def terminate(self): self._pool.terminate() self._pool.join() def finish(self, result_handler=None): try:", "= 1 @property def next_filename(self): index = str(self._index) if self._max_index:", "multiprocessing.cpu_count() - 1 ctx = multiprocessing.get_context(\"spawn\") self._pool = ctx.Pool(max_workers) if", "_writer = self._writer # Exclude self from capture to avoid", "filename = result.get() if result_handler is not None: result_handler(filename) self._pool.close()", "self._sem: self._sem.acquire() def callback(v): assert self._sem is not None self._sem.release()", "filename: str, image: np.ndarray): self._writer(filename, image) def save(self, image: np.ndarray):", "finish(self): pass class MultiprocessingImageSequenceWriter(ImageSequenceWriter): \"\"\"Image sequence writer that uses multiprocessing" ]
[ "int \"\"\" nums.sort() res = [0] * (target + 1)", "the question to allow negative numbers? class Solution: def combinationSum4(self,", "i in range(1, len(res)): for num in nums: if num", "question to allow negative numbers? class Solution: def combinationSum4(self, nums,", "are allowed in the given array? # How does it", "\"\"\" nums.sort() res = [0] * (target + 1) for", "+ [0] * target for i in range(1, target+1): for", "[1] + [0] * target for i in range(1, target+1):", "How does it change the problem? # What limitation we", "combinationSum4(self, nums, target): dp = [1] + [0] * target", "Solution: def combinationSum4(self, nums, target): \"\"\" :type nums: List[int] :type", "= 4 # # The possible combination ways are: #", "# 377 Combination Sum IV # Given an integer array", "problem? # What limitation we need to add to the", "elif num == i: res[i] += 1 else: res[i] +=", "all positive numbers and no duplicates, # find the number", "def combinationSum4(self, nums, target): \"\"\" :type nums: List[int] :type target:", "# (2, 1, 1) # (2, 2) # (3, 1)", "possible combination ways are: # (1, 1, 1, 1) #", "if num > i: break elif num == i: res[i]", "nums.sort() res = [0] * (target + 1) for i", "no duplicates, # find the number of possible combinations that", "+= 1 else: res[i] += res[i-num] return res[target] # https://www.hrwhisper.me/leetcode-combination-sum-iv/", "7. # # Follow up: # What if negative numbers", "given array? # How does it change the problem? #", "the number of possible combinations that add up to a", "possible combinations that add up to a positive integer target.", "to allow negative numbers? class Solution: def combinationSum4(self, nums, target):", "num == i: res[i] += 1 else: res[i] += res[i-num]", "nums = [1, 2, 3] # target = 4 #", "in nums: if num > i: break elif num ==", "dp = [1] + [0] * target for i in", "negative numbers are allowed in the given array? # How", "1) for i in range(1, len(res)): for num in nums:", "i in range(1, target+1): for num in nums: if i", "2, 3] # target = 4 # # The possible", "in the given array? # How does it change the", "integer target. # # Example: # # nums = [1,", "# dp[i] += dp[i-num] def combinationSum4(self, nums, target): dp =", "(2, 1, 1) # (2, 2) # (3, 1) #", "1) # (2, 2) # (3, 1) # # Note", "1) # (1, 1, 2) # (1, 2, 1) #", "different sequences are counted as different combinations. # # Therefore", "range(1, len(res)): for num in nums: if num > i:", "377 Combination Sum IV # Given an integer array with", "add up to a positive integer target. # # Example:", "# nums = [1, 2, 3] # target = 4", "dp[i-num] def combinationSum4(self, nums, target): dp = [1] + [0]", "target for i in range(1, target+1): for num in nums:", "are counted as different combinations. # # Therefore the output", "allow negative numbers? class Solution: def combinationSum4(self, nums, target): \"\"\"", "numbers? class Solution: def combinationSum4(self, nums, target): \"\"\" :type nums:", "* (target + 1) for i in range(1, len(res)): for", "Note that different sequences are counted as different combinations. #", "= [0] * (target + 1) for i in range(1,", "[0] * target for i in range(1, target+1): for num", "1, 1) # (2, 2) # (3, 1) # #", "with all positive numbers and no duplicates, # find the", "find the number of possible combinations that add up to", "target = 4 # # The possible combination ways are:", "the output is 7. # # Follow up: # What", "# # Therefore the output is 7. # # Follow", ":rtype: int \"\"\" nums.sort() res = [0] * (target +", "== i: res[i] += 1 else: res[i] += res[i-num] return", "# (1, 1, 2) # (1, 2, 1) # (1,", "# (2, 2) # (3, 1) # # Note that", "res = [0] * (target + 1) for i in", "array with all positive numbers and no duplicates, # find", "nums, target): dp = [1] + [0] * target for", "dp[i] += dp[i-num] def combinationSum4(self, nums, target): dp = [1]", "are: # (1, 1, 1, 1) # (1, 1, 2)", "(1, 2, 1) # (1, 3) # (2, 1, 1)", "[1, 2, 3] # target = 4 # # The", "def combinationSum4(self, nums, target): dp = [1] + [0] *", "# (1, 3) # (2, 1, 1) # (2, 2)", "positive integer target. # # Example: # # nums =", "add to the question to allow negative numbers? class Solution:", "numbers and no duplicates, # find the number of possible", "does it change the problem? # What limitation we need", "return res[target] # https://www.hrwhisper.me/leetcode-combination-sum-iv/ # dp[i] += dp[i-num] def combinationSum4(self,", "nums: if i >= num: dp[i] += dp[i-num] return dp[target]", "Sum IV # Given an integer array with all positive", "# What limitation we need to add to the question", "target): dp = [1] + [0] * target for i", "2, 1) # (1, 3) # (2, 1, 1) #", "2) # (3, 1) # # Note that different sequences", "break elif num == i: res[i] += 1 else: res[i]", "res[i] += res[i-num] return res[target] # https://www.hrwhisper.me/leetcode-combination-sum-iv/ # dp[i] +=", "What limitation we need to add to the question to", "change the problem? # What limitation we need to add", "the problem? # What limitation we need to add to", "# The possible combination ways are: # (1, 1, 1,", "* target for i in range(1, target+1): for num in", "(target + 1) for i in range(1, len(res)): for num", "res[i-num] return res[target] # https://www.hrwhisper.me/leetcode-combination-sum-iv/ # dp[i] += dp[i-num] def", "IV # Given an integer array with all positive numbers", "to a positive integer target. # # Example: # #", "2) # (1, 2, 1) # (1, 3) # (2,", "(3, 1) # # Note that different sequences are counted", "+= dp[i-num] def combinationSum4(self, nums, target): dp = [1] +", "for num in nums: if num > i: break elif", "1, 1, 1) # (1, 1, 2) # (1, 2,", "numbers are allowed in the given array? # How does", "# Therefore the output is 7. # # Follow up:", "\"\"\" :type nums: List[int] :type target: int :rtype: int \"\"\"", "# https://www.hrwhisper.me/leetcode-combination-sum-iv/ # dp[i] += dp[i-num] def combinationSum4(self, nums, target):", "# target = 4 # # The possible combination ways", "num in nums: if i >= num: dp[i] += dp[i-num]", "1) # # Note that different sequences are counted as", "int :rtype: int \"\"\" nums.sort() res = [0] * (target", "Combination Sum IV # Given an integer array with all", "(1, 1, 1, 1) # (1, 1, 2) # (1,", "1) # (1, 3) # (2, 1, 1) # (2,", "List[int] :type target: int :rtype: int \"\"\" nums.sort() res =", "for num in nums: if i >= num: dp[i] +=", "# Given an integer array with all positive numbers and", "in range(1, target+1): for num in nums: if i >=", "Given an integer array with all positive numbers and no", "3] # target = 4 # # The possible combination", "(1, 3) # (2, 1, 1) # (2, 2) #", ":type nums: List[int] :type target: int :rtype: int \"\"\" nums.sort()", "if negative numbers are allowed in the given array? #", "(2, 2) # (3, 1) # # Note that different", "number of possible combinations that add up to a positive", "allowed in the given array? # How does it change", "# # Note that different sequences are counted as different", "4 # # The possible combination ways are: # (1,", "What if negative numbers are allowed in the given array?", "len(res)): for num in nums: if num > i: break", "1 else: res[i] += res[i-num] return res[target] # https://www.hrwhisper.me/leetcode-combination-sum-iv/ #", "# Note that different sequences are counted as different combinations.", "# (1, 1, 1, 1) # (1, 1, 2) #", "# (1, 2, 1) # (1, 3) # (2, 1,", "Therefore the output is 7. # # Follow up: #", "combination ways are: # (1, 1, 1, 1) # (1,", "up to a positive integer target. # # Example: #", "> i: break elif num == i: res[i] += 1", "num: dp[i] += dp[i-num] return dp[target] print(Solution().combinationSum4([1, 2, 3], 4))", "The possible combination ways are: # (1, 1, 1, 1)", "# # Follow up: # What if negative numbers are", "[0] * (target + 1) for i in range(1, len(res)):", "combinations. # # Therefore the output is 7. # #", "1, 1) # (1, 1, 2) # (1, 2, 1)", "the given array? # How does it change the problem?", "as different combinations. # # Therefore the output is 7.", "up: # What if negative numbers are allowed in the", "and no duplicates, # find the number of possible combinations", "nums, target): \"\"\" :type nums: List[int] :type target: int :rtype:", "output is 7. # # Follow up: # What if", "counted as different combinations. # # Therefore the output is", "negative numbers? class Solution: def combinationSum4(self, nums, target): \"\"\" :type", "an integer array with all positive numbers and no duplicates,", "i: break elif num == i: res[i] += 1 else:", "target+1): for num in nums: if i >= num: dp[i]", "# # Example: # # nums = [1, 2, 3]", "num in nums: if num > i: break elif num", "i: res[i] += 1 else: res[i] += res[i-num] return res[target]", "that different sequences are counted as different combinations. # #", "sequences are counted as different combinations. # # Therefore the", "is 7. # # Follow up: # What if negative", "+ 1) for i in range(1, len(res)): for num in", "class Solution: def combinationSum4(self, nums, target): \"\"\" :type nums: List[int]", "Follow up: # What if negative numbers are allowed in", "array? # How does it change the problem? # What", "range(1, target+1): for num in nums: if i >= num:", "different combinations. # # Therefore the output is 7. #", "else: res[i] += res[i-num] return res[target] # https://www.hrwhisper.me/leetcode-combination-sum-iv/ # dp[i]", "to add to the question to allow negative numbers? class", "(1, 1, 2) # (1, 2, 1) # (1, 3)", "# Follow up: # What if negative numbers are allowed", "# What if negative numbers are allowed in the given", ">= num: dp[i] += dp[i-num] return dp[target] print(Solution().combinationSum4([1, 2, 3],", "of possible combinations that add up to a positive integer", "duplicates, # find the number of possible combinations that add", "nums: if num > i: break elif num == i:", "= [1] + [0] * target for i in range(1,", "positive numbers and no duplicates, # find the number of", "# # nums = [1, 2, 3] # target =", "ways are: # (1, 1, 1, 1) # (1, 1,", "1, 2) # (1, 2, 1) # (1, 3) #", "# Example: # # nums = [1, 2, 3] #", "3) # (2, 1, 1) # (2, 2) # (3,", "in nums: if i >= num: dp[i] += dp[i-num] return", ":type target: int :rtype: int \"\"\" nums.sort() res = [0]", "a positive integer target. # # Example: # # nums", "= [1, 2, 3] # target = 4 # #", "need to add to the question to allow negative numbers?", "to the question to allow negative numbers? class Solution: def", "# # The possible combination ways are: # (1, 1,", "combinationSum4(self, nums, target): \"\"\" :type nums: List[int] :type target: int", "# find the number of possible combinations that add up", "integer array with all positive numbers and no duplicates, #", "nums: List[int] :type target: int :rtype: int \"\"\" nums.sort() res", "# (3, 1) # # Note that different sequences are", "target): \"\"\" :type nums: List[int] :type target: int :rtype: int", "if i >= num: dp[i] += dp[i-num] return dp[target] print(Solution().combinationSum4([1,", "target: int :rtype: int \"\"\" nums.sort() res = [0] *", "it change the problem? # What limitation we need to", "# How does it change the problem? # What limitation", "res[target] # https://www.hrwhisper.me/leetcode-combination-sum-iv/ # dp[i] += dp[i-num] def combinationSum4(self, nums,", "num > i: break elif num == i: res[i] +=", "we need to add to the question to allow negative", "in range(1, len(res)): for num in nums: if num >", "https://www.hrwhisper.me/leetcode-combination-sum-iv/ # dp[i] += dp[i-num] def combinationSum4(self, nums, target): dp", "combinations that add up to a positive integer target. #", "that add up to a positive integer target. # #", "limitation we need to add to the question to allow", "res[i] += 1 else: res[i] += res[i-num] return res[target] #", "for i in range(1, target+1): for num in nums: if", "i >= num: dp[i] += dp[i-num] return dp[target] print(Solution().combinationSum4([1, 2,", "Example: # # nums = [1, 2, 3] # target", "+= res[i-num] return res[target] # https://www.hrwhisper.me/leetcode-combination-sum-iv/ # dp[i] += dp[i-num]", "target. # # Example: # # nums = [1, 2,", "for i in range(1, len(res)): for num in nums: if" ]
[ "False] } default_options = \"shared=False\", \"fPIC=True\", \"use_OpenMP=True\" generators = \"cmake\"", "self.options.fPIC def source(self): url = \"https://github.com/castano/nvidia-texture-tools/archive/{}.zip\".format(self.version) tools.get(url) os.rename('nvidia-texture-tools-{}'.format(self.version), self.source_subfolder) tools.replace_in_file(os.path.join(self.source_subfolder,", "image processing and texture manipulation tools, designed to be integrated", "cmake.build() def package(self): self.copy(\"license*\", src=self.source_subfolder, ignore_case=True, keep_path=False) self.copy(\"nvtt.h\", dst=\"include/nvtt\", src=os.path.join(self.source_subfolder,", "package(self): self.copy(\"license*\", src=self.source_subfolder, ignore_case=True, keep_path=False) self.copy(\"nvtt.h\", dst=\"include/nvtt\", src=os.path.join(self.source_subfolder, \"src\", \"nvtt\"),", "libname in STATIC_LIBS: libs += [lib for lib in all_libs", "tools and asset processing pipelines.\" settings = \"os\", \"compiler\", \"build_type\",", "= \"MIT\" author = \"koeleck\" url = \"<Package recipe repository", "config_options(self): if self.settings.os == \"Windows\": del self.options.fPIC def source(self): url", "[True, False], \"use_OpenMP\": [True, False] } default_options = \"shared=False\", \"fPIC=True\",", "source(self): url = \"https://github.com/castano/nvidia-texture-tools/archive/{}.zip\".format(self.version) tools.get(url) os.rename('nvidia-texture-tools-{}'.format(self.version), self.source_subfolder) tools.replace_in_file(os.path.join(self.source_subfolder, \"CMakeLists.txt\"), \"PROJECT(NV)\",", "conan_basic_setup()''') def build(self): cmake = CMake(self) cmake.definitions[\"HAVE_CUDA\"] = False cmake.definitions[\"HAVE_OPENMP\"]", "= CMake(self) cmake.definitions[\"HAVE_CUDA\"] = False cmake.definitions[\"HAVE_OPENMP\"] = self.options.use_OpenMP cmake.configure(source_folder=self.source_subfolder) cmake.build()", "collection of image processing and texture manipulation tools, designed to", "dst=\"include/nvtt\", src=os.path.join(self.source_subfolder, \"src\", \"nvtt\"), keep_path=False) if self.options.shared: for libname in", "== \"Windows\": del self.options.fPIC def source(self): url = \"https://github.com/castano/nvidia-texture-tools/archive/{}.zip\".format(self.version) tools.get(url)", "= \"koeleck\" url = \"<Package recipe repository url here, for", "\"PROJECT(NV)\", '''PROJECT(NV) include(${CMAKE_BINARY_DIR}/conanbuildinfo.cmake) conan_basic_setup()''') def build(self): cmake = CMake(self) cmake.definitions[\"HAVE_CUDA\"]", "[True, False], \"fPIC\": [True, False], \"use_OpenMP\": [True, False] } default_options", "tools.collect_libs(self) if self.options.shared: libs = all_libs else: libs = []", "= self.options.use_OpenMP cmake.configure(source_folder=self.source_subfolder) cmake.build() def package(self): self.copy(\"license*\", src=self.source_subfolder, ignore_case=True, keep_path=False)", "issues about the package>\" description = \"The NVIDIA Texture Tools", "Texture Tools is a collection of image processing and texture", "= {\"shared\": [True, False], \"fPIC\": [True, False], \"use_OpenMP\": [True, False]", "= \"shared=False\", \"fPIC=True\", \"use_OpenMP=True\" generators = \"cmake\" def config_options(self): if", "dst=\"lib\", src=os.path.join(self.build_folder, \"lib\"), keep_path=False) else: for libname in STATIC_LIBS: self.copy(\"*{}*.a\".format(libname),", "= \"os\", \"compiler\", \"build_type\", \"arch\" source_subfolder = \"nvtt\" no_copy_source =", "url = \"https://github.com/castano/nvidia-texture-tools/archive/{}.zip\".format(self.version) tools.get(url) os.rename('nvidia-texture-tools-{}'.format(self.version), self.source_subfolder) tools.replace_in_file(os.path.join(self.source_subfolder, \"CMakeLists.txt\"), \"PROJECT(NV)\", '''PROJECT(NV)", "libname in lib] self.cpp_info.libs = libs if self.settings.os == \"Linux\":", "'''PROJECT(NV) include(${CMAKE_BINARY_DIR}/conanbuildinfo.cmake) conan_basic_setup()''') def build(self): cmake = CMake(self) cmake.definitions[\"HAVE_CUDA\"] =", "a collection of image processing and texture manipulation tools, designed", "\"shared=False\", \"fPIC=True\", \"use_OpenMP=True\" generators = \"cmake\" def config_options(self): if self.settings.os", "package>\" description = \"The NVIDIA Texture Tools is a collection", "url here, for issues about the package>\" description = \"The", "\"https://github.com/castano/nvidia-texture-tools/archive/{}.zip\".format(self.version) tools.get(url) os.rename('nvidia-texture-tools-{}'.format(self.version), self.source_subfolder) tools.replace_in_file(os.path.join(self.source_subfolder, \"CMakeLists.txt\"), \"PROJECT(NV)\", '''PROJECT(NV) include(${CMAKE_BINARY_DIR}/conanbuildinfo.cmake) conan_basic_setup()''')", "no_copy_source = True options = {\"shared\": [True, False], \"fPIC\": [True,", "STATIC_LIBS: libs += [lib for lib in all_libs if libname", "self.source_subfolder) tools.replace_in_file(os.path.join(self.source_subfolder, \"CMakeLists.txt\"), \"PROJECT(NV)\", '''PROJECT(NV) include(${CMAKE_BINARY_DIR}/conanbuildinfo.cmake) conan_basic_setup()''') def build(self): cmake", "self.settings.os == \"Linux\": self.cpp_info.libs.extend([\"dl\", \"pthread\"]) if self.options.shared: self.cpp_info.defines = [\"NVTT_SHARED=1\"]", "from conans import ConanFile, CMake, tools import os STATIC_LIBS =", "\"lib\"), keep_path=False) def package_info(self): all_libs = tools.collect_libs(self) if self.options.shared: libs", "\"src\", \"nvtt\"), keep_path=False) self.copy(\"nvtt_wrapper.h\", dst=\"include/nvtt\", src=os.path.join(self.source_subfolder, \"src\", \"nvtt\"), keep_path=False) if", "in all_libs if libname in lib] self.cpp_info.libs = libs if", "and texture manipulation tools, designed to be integrated in game", "\"lib\"), keep_path=False) self.copy(\"*{}*.lib\".format(libname), dst=\"lib\", src=os.path.join(self.build_folder, \"lib\"), keep_path=False) def package_info(self): all_libs", "SHARED_LIBS = [\"nvtt\", \"nvimage\", \"nvthread\", \"nvmath\", \"nvcore\"] class NvidiatexturetoolsConan(ConanFile): name", "libs = [] for libname in STATIC_LIBS: libs += [lib", "libname in STATIC_LIBS: self.copy(\"*{}*.a\".format(libname), dst=\"lib\", src=os.path.join(self.build_folder, \"lib\"), keep_path=False) self.copy(\"*{}*.lib\".format(libname), dst=\"lib\",", "src=self.source_subfolder, ignore_case=True, keep_path=False) self.copy(\"nvtt.h\", dst=\"include/nvtt\", src=os.path.join(self.source_subfolder, \"src\", \"nvtt\"), keep_path=False) self.copy(\"nvtt_wrapper.h\",", "[True, False] } default_options = \"shared=False\", \"fPIC=True\", \"use_OpenMP=True\" generators =", "tools.replace_in_file(os.path.join(self.source_subfolder, \"CMakeLists.txt\"), \"PROJECT(NV)\", '''PROJECT(NV) include(${CMAKE_BINARY_DIR}/conanbuildinfo.cmake) conan_basic_setup()''') def build(self): cmake =", "= \"nvidia-texture-tools\" version = \"662d223626185f7c6c7e0d822a4796a691acc05a\" license = \"MIT\" author =", "self.copy(\"*{}*.lib\".format(libname), dst=\"lib\", src=os.path.join(self.build_folder, \"lib\"), keep_path=False) def package_info(self): all_libs = tools.collect_libs(self)", "generators = \"cmake\" def config_options(self): if self.settings.os == \"Windows\": del", "\"os\", \"compiler\", \"build_type\", \"arch\" source_subfolder = \"nvtt\" no_copy_source = True", "for libname in STATIC_LIBS: self.copy(\"*{}*.a\".format(libname), dst=\"lib\", src=os.path.join(self.build_folder, \"lib\"), keep_path=False) self.copy(\"*{}*.lib\".format(libname),", "in lib] self.cpp_info.libs = libs if self.settings.os == \"Linux\": self.cpp_info.libs.extend([\"dl\",", "\"bc7\", \"nvmath\", \"nvthread\", \"nvcore\"] SHARED_LIBS = [\"nvtt\", \"nvimage\", \"nvthread\", \"nvmath\",", "self.options.shared: for libname in SHARED_LIBS: self.copy(\"*{}*.dll\".format(libname), dst=\"bin\", src=os.path.join(self.build_folder, \"bin\"), keep_path=False)", "for issues about the package>\" description = \"The NVIDIA Texture", "CMake(self) cmake.definitions[\"HAVE_CUDA\"] = False cmake.definitions[\"HAVE_OPENMP\"] = self.options.use_OpenMP cmake.configure(source_folder=self.source_subfolder) cmake.build() def", "libname in SHARED_LIBS: self.copy(\"*{}*.dll\".format(libname), dst=\"bin\", src=os.path.join(self.build_folder, \"bin\"), keep_path=False) self.copy(\"*{}*.lib\".format(libname), dst=\"lib\",", "} default_options = \"shared=False\", \"fPIC=True\", \"use_OpenMP=True\" generators = \"cmake\" def", "keep_path=False) self.copy(\"nvtt.h\", dst=\"include/nvtt\", src=os.path.join(self.source_subfolder, \"src\", \"nvtt\"), keep_path=False) self.copy(\"nvtt_wrapper.h\", dst=\"include/nvtt\", src=os.path.join(self.source_subfolder,", "self.copy(\"*{}*.dll\".format(libname), dst=\"bin\", src=os.path.join(self.build_folder, \"bin\"), keep_path=False) self.copy(\"*{}*.lib\".format(libname), dst=\"lib\", src=os.path.join(self.build_folder, \"lib\"), keep_path=False)", "class NvidiatexturetoolsConan(ConanFile): name = \"nvidia-texture-tools\" version = \"662d223626185f7c6c7e0d822a4796a691acc05a\" license =", "= \"<Package recipe repository url here, for issues about the", "author = \"koeleck\" url = \"<Package recipe repository url here,", "processing and texture manipulation tools, designed to be integrated in", "<reponame>koeleck/conan-packages<gh_stars>0 from conans import ConanFile, CMake, tools import os STATIC_LIBS", "False], \"fPIC\": [True, False], \"use_OpenMP\": [True, False] } default_options =", "\"CMakeLists.txt\"), \"PROJECT(NV)\", '''PROJECT(NV) include(${CMAKE_BINARY_DIR}/conanbuildinfo.cmake) conan_basic_setup()''') def build(self): cmake = CMake(self)", "game tools and asset processing pipelines.\" settings = \"os\", \"compiler\",", "pipelines.\" settings = \"os\", \"compiler\", \"build_type\", \"arch\" source_subfolder = \"nvtt\"", "def build(self): cmake = CMake(self) cmake.definitions[\"HAVE_CUDA\"] = False cmake.definitions[\"HAVE_OPENMP\"] =", "\"compiler\", \"build_type\", \"arch\" source_subfolder = \"nvtt\" no_copy_source = True options", "and asset processing pipelines.\" settings = \"os\", \"compiler\", \"build_type\", \"arch\"", "self.copy(\"*{}*.a\".format(libname), dst=\"lib\", src=os.path.join(self.build_folder, \"lib\"), keep_path=False) self.copy(\"*{}*.lib\".format(libname), dst=\"lib\", src=os.path.join(self.build_folder, \"lib\"), keep_path=False)", "libs += [lib for lib in all_libs if libname in", "src=os.path.join(self.build_folder, \"lib\"), keep_path=False) def package_info(self): all_libs = tools.collect_libs(self) if self.options.shared:", "def config_options(self): if self.settings.os == \"Windows\": del self.options.fPIC def source(self):", "keep_path=False) self.copy(\"nvtt_wrapper.h\", dst=\"include/nvtt\", src=os.path.join(self.source_subfolder, \"src\", \"nvtt\"), keep_path=False) if self.options.shared: for", "self.copy(\"*{}*.lib\".format(libname), dst=\"lib\", src=os.path.join(self.build_folder, \"lib\"), keep_path=False) self.copy(\"*{}*.so*\".format(libname), dst=\"lib\", src=os.path.join(self.build_folder, \"lib\"), keep_path=False)", "src=os.path.join(self.source_subfolder, \"src\", \"nvtt\"), keep_path=False) if self.options.shared: for libname in SHARED_LIBS:", "SHARED_LIBS: self.copy(\"*{}*.dll\".format(libname), dst=\"bin\", src=os.path.join(self.build_folder, \"bin\"), keep_path=False) self.copy(\"*{}*.lib\".format(libname), dst=\"lib\", src=os.path.join(self.build_folder, \"lib\"),", "= all_libs else: libs = [] for libname in STATIC_LIBS:", "else: libs = [] for libname in STATIC_LIBS: libs +=", "\"rg_etc1\", \"nvimage\", \"bc6h\", \"posh\", \"bc7\", \"nvmath\", \"nvthread\", \"nvcore\"] SHARED_LIBS =", "processing pipelines.\" settings = \"os\", \"compiler\", \"build_type\", \"arch\" source_subfolder =", "= \"https://github.com/castano/nvidia-texture-tools/archive/{}.zip\".format(self.version) tools.get(url) os.rename('nvidia-texture-tools-{}'.format(self.version), self.source_subfolder) tools.replace_in_file(os.path.join(self.source_subfolder, \"CMakeLists.txt\"), \"PROJECT(NV)\", '''PROJECT(NV) include(${CMAKE_BINARY_DIR}/conanbuildinfo.cmake)", "import os STATIC_LIBS = [\"nvtt\", \"squish\", \"rg_etc1\", \"nvimage\", \"bc6h\", \"posh\",", "\"nvimage\", \"bc6h\", \"posh\", \"bc7\", \"nvmath\", \"nvthread\", \"nvcore\"] SHARED_LIBS = [\"nvtt\",", "manipulation tools, designed to be integrated in game tools and", "be integrated in game tools and asset processing pipelines.\" settings", "\"nvtt\" no_copy_source = True options = {\"shared\": [True, False], \"fPIC\":", "options = {\"shared\": [True, False], \"fPIC\": [True, False], \"use_OpenMP\": [True,", "\"fPIC=True\", \"use_OpenMP=True\" generators = \"cmake\" def config_options(self): if self.settings.os ==", "cmake.definitions[\"HAVE_CUDA\"] = False cmake.definitions[\"HAVE_OPENMP\"] = self.options.use_OpenMP cmake.configure(source_folder=self.source_subfolder) cmake.build() def package(self):", "def source(self): url = \"https://github.com/castano/nvidia-texture-tools/archive/{}.zip\".format(self.version) tools.get(url) os.rename('nvidia-texture-tools-{}'.format(self.version), self.source_subfolder) tools.replace_in_file(os.path.join(self.source_subfolder, \"CMakeLists.txt\"),", "tools import os STATIC_LIBS = [\"nvtt\", \"squish\", \"rg_etc1\", \"nvimage\", \"bc6h\",", "ConanFile, CMake, tools import os STATIC_LIBS = [\"nvtt\", \"squish\", \"rg_etc1\",", "self.copy(\"nvtt_wrapper.h\", dst=\"include/nvtt\", src=os.path.join(self.source_subfolder, \"src\", \"nvtt\"), keep_path=False) if self.options.shared: for libname", "else: for libname in STATIC_LIBS: self.copy(\"*{}*.a\".format(libname), dst=\"lib\", src=os.path.join(self.build_folder, \"lib\"), keep_path=False)", "version = \"662d223626185f7c6c7e0d822a4796a691acc05a\" license = \"MIT\" author = \"koeleck\" url", "self.copy(\"license*\", src=self.source_subfolder, ignore_case=True, keep_path=False) self.copy(\"nvtt.h\", dst=\"include/nvtt\", src=os.path.join(self.source_subfolder, \"src\", \"nvtt\"), keep_path=False)", "\"662d223626185f7c6c7e0d822a4796a691acc05a\" license = \"MIT\" author = \"koeleck\" url = \"<Package", "license = \"MIT\" author = \"koeleck\" url = \"<Package recipe", "def package_info(self): all_libs = tools.collect_libs(self) if self.options.shared: libs = all_libs", "os STATIC_LIBS = [\"nvtt\", \"squish\", \"rg_etc1\", \"nvimage\", \"bc6h\", \"posh\", \"bc7\",", "if self.options.shared: libs = all_libs else: libs = [] for", "NVIDIA Texture Tools is a collection of image processing and", "NvidiatexturetoolsConan(ConanFile): name = \"nvidia-texture-tools\" version = \"662d223626185f7c6c7e0d822a4796a691acc05a\" license = \"MIT\"", "integrated in game tools and asset processing pipelines.\" settings =", "description = \"The NVIDIA Texture Tools is a collection of", "for lib in all_libs if libname in lib] self.cpp_info.libs =", "self.settings.os == \"Windows\": del self.options.fPIC def source(self): url = \"https://github.com/castano/nvidia-texture-tools/archive/{}.zip\".format(self.version)", "lib] self.cpp_info.libs = libs if self.settings.os == \"Linux\": self.cpp_info.libs.extend([\"dl\", \"pthread\"])", "Tools is a collection of image processing and texture manipulation", "\"nvidia-texture-tools\" version = \"662d223626185f7c6c7e0d822a4796a691acc05a\" license = \"MIT\" author = \"koeleck\"", "build(self): cmake = CMake(self) cmake.definitions[\"HAVE_CUDA\"] = False cmake.definitions[\"HAVE_OPENMP\"] = self.options.use_OpenMP", "in STATIC_LIBS: libs += [lib for lib in all_libs if", "of image processing and texture manipulation tools, designed to be", "\"nvthread\", \"nvmath\", \"nvcore\"] class NvidiatexturetoolsConan(ConanFile): name = \"nvidia-texture-tools\" version =", "\"arch\" source_subfolder = \"nvtt\" no_copy_source = True options = {\"shared\":", "about the package>\" description = \"The NVIDIA Texture Tools is", "= \"cmake\" def config_options(self): if self.settings.os == \"Windows\": del self.options.fPIC", "+= [lib for lib in all_libs if libname in lib]", "repository url here, for issues about the package>\" description =", "{\"shared\": [True, False], \"fPIC\": [True, False], \"use_OpenMP\": [True, False] }", "\"fPIC\": [True, False], \"use_OpenMP\": [True, False] } default_options = \"shared=False\",", "\"use_OpenMP=True\" generators = \"cmake\" def config_options(self): if self.settings.os == \"Windows\":", "\"lib\"), keep_path=False) self.copy(\"*{}*.so*\".format(libname), dst=\"lib\", src=os.path.join(self.build_folder, \"lib\"), keep_path=False) else: for libname", "del self.options.fPIC def source(self): url = \"https://github.com/castano/nvidia-texture-tools/archive/{}.zip\".format(self.version) tools.get(url) os.rename('nvidia-texture-tools-{}'.format(self.version), self.source_subfolder)", "\"nvcore\"] SHARED_LIBS = [\"nvtt\", \"nvimage\", \"nvthread\", \"nvmath\", \"nvcore\"] class NvidiatexturetoolsConan(ConanFile):", "url = \"<Package recipe repository url here, for issues about", "dst=\"lib\", src=os.path.join(self.build_folder, \"lib\"), keep_path=False) self.copy(\"*{}*.so*\".format(libname), dst=\"lib\", src=os.path.join(self.build_folder, \"lib\"), keep_path=False) else:", "all_libs = tools.collect_libs(self) if self.options.shared: libs = all_libs else: libs", "cmake.definitions[\"HAVE_OPENMP\"] = self.options.use_OpenMP cmake.configure(source_folder=self.source_subfolder) cmake.build() def package(self): self.copy(\"license*\", src=self.source_subfolder, ignore_case=True,", "\"Windows\": del self.options.fPIC def source(self): url = \"https://github.com/castano/nvidia-texture-tools/archive/{}.zip\".format(self.version) tools.get(url) os.rename('nvidia-texture-tools-{}'.format(self.version),", "dst=\"include/nvtt\", src=os.path.join(self.source_subfolder, \"src\", \"nvtt\"), keep_path=False) self.copy(\"nvtt_wrapper.h\", dst=\"include/nvtt\", src=os.path.join(self.source_subfolder, \"src\", \"nvtt\"),", "CMake, tools import os STATIC_LIBS = [\"nvtt\", \"squish\", \"rg_etc1\", \"nvimage\",", "\"nvmath\", \"nvthread\", \"nvcore\"] SHARED_LIBS = [\"nvtt\", \"nvimage\", \"nvthread\", \"nvmath\", \"nvcore\"]", "\"build_type\", \"arch\" source_subfolder = \"nvtt\" no_copy_source = True options =", "dst=\"lib\", src=os.path.join(self.build_folder, \"lib\"), keep_path=False) def package_info(self): all_libs = tools.collect_libs(self) if", "name = \"nvidia-texture-tools\" version = \"662d223626185f7c6c7e0d822a4796a691acc05a\" license = \"MIT\" author", "\"The NVIDIA Texture Tools is a collection of image processing", "libs if self.settings.os == \"Linux\": self.cpp_info.libs.extend([\"dl\", \"pthread\"]) if self.options.shared: self.cpp_info.defines", "= \"662d223626185f7c6c7e0d822a4796a691acc05a\" license = \"MIT\" author = \"koeleck\" url =", "the package>\" description = \"The NVIDIA Texture Tools is a", "keep_path=False) self.copy(\"*{}*.lib\".format(libname), dst=\"lib\", src=os.path.join(self.build_folder, \"lib\"), keep_path=False) def package_info(self): all_libs =", "src=os.path.join(self.source_subfolder, \"src\", \"nvtt\"), keep_path=False) self.copy(\"nvtt_wrapper.h\", dst=\"include/nvtt\", src=os.path.join(self.source_subfolder, \"src\", \"nvtt\"), keep_path=False)", "src=os.path.join(self.build_folder, \"lib\"), keep_path=False) self.copy(\"*{}*.so*\".format(libname), dst=\"lib\", src=os.path.join(self.build_folder, \"lib\"), keep_path=False) else: for", "self.options.use_OpenMP cmake.configure(source_folder=self.source_subfolder) cmake.build() def package(self): self.copy(\"license*\", src=self.source_subfolder, ignore_case=True, keep_path=False) self.copy(\"nvtt.h\",", "in STATIC_LIBS: self.copy(\"*{}*.a\".format(libname), dst=\"lib\", src=os.path.join(self.build_folder, \"lib\"), keep_path=False) self.copy(\"*{}*.lib\".format(libname), dst=\"lib\", src=os.path.join(self.build_folder,", "\"cmake\" def config_options(self): if self.settings.os == \"Windows\": del self.options.fPIC def", "lib in all_libs if libname in lib] self.cpp_info.libs = libs", "settings = \"os\", \"compiler\", \"build_type\", \"arch\" source_subfolder = \"nvtt\" no_copy_source", "for libname in STATIC_LIBS: libs += [lib for lib in", "ignore_case=True, keep_path=False) self.copy(\"nvtt.h\", dst=\"include/nvtt\", src=os.path.join(self.source_subfolder, \"src\", \"nvtt\"), keep_path=False) self.copy(\"nvtt_wrapper.h\", dst=\"include/nvtt\",", "tools, designed to be integrated in game tools and asset", "source_subfolder = \"nvtt\" no_copy_source = True options = {\"shared\": [True,", "\"bc6h\", \"posh\", \"bc7\", \"nvmath\", \"nvthread\", \"nvcore\"] SHARED_LIBS = [\"nvtt\", \"nvimage\",", "= [\"nvtt\", \"squish\", \"rg_etc1\", \"nvimage\", \"bc6h\", \"posh\", \"bc7\", \"nvmath\", \"nvthread\",", "os.rename('nvidia-texture-tools-{}'.format(self.version), self.source_subfolder) tools.replace_in_file(os.path.join(self.source_subfolder, \"CMakeLists.txt\"), \"PROJECT(NV)\", '''PROJECT(NV) include(${CMAKE_BINARY_DIR}/conanbuildinfo.cmake) conan_basic_setup()''') def build(self):", "cmake.configure(source_folder=self.source_subfolder) cmake.build() def package(self): self.copy(\"license*\", src=self.source_subfolder, ignore_case=True, keep_path=False) self.copy(\"nvtt.h\", dst=\"include/nvtt\",", "recipe repository url here, for issues about the package>\" description", "def package(self): self.copy(\"license*\", src=self.source_subfolder, ignore_case=True, keep_path=False) self.copy(\"nvtt.h\", dst=\"include/nvtt\", src=os.path.join(self.source_subfolder, \"src\",", "default_options = \"shared=False\", \"fPIC=True\", \"use_OpenMP=True\" generators = \"cmake\" def config_options(self):", "if self.settings.os == \"Linux\": self.cpp_info.libs.extend([\"dl\", \"pthread\"]) if self.options.shared: self.cpp_info.defines =", "= [] for libname in STATIC_LIBS: libs += [lib for", "[lib for lib in all_libs if libname in lib] self.cpp_info.libs", "\"<Package recipe repository url here, for issues about the package>\"", "\"squish\", \"rg_etc1\", \"nvimage\", \"bc6h\", \"posh\", \"bc7\", \"nvmath\", \"nvthread\", \"nvcore\"] SHARED_LIBS", "False], \"use_OpenMP\": [True, False] } default_options = \"shared=False\", \"fPIC=True\", \"use_OpenMP=True\"", "conans import ConanFile, CMake, tools import os STATIC_LIBS = [\"nvtt\",", "self.copy(\"nvtt.h\", dst=\"include/nvtt\", src=os.path.join(self.source_subfolder, \"src\", \"nvtt\"), keep_path=False) self.copy(\"nvtt_wrapper.h\", dst=\"include/nvtt\", src=os.path.join(self.source_subfolder, \"src\",", "True options = {\"shared\": [True, False], \"fPIC\": [True, False], \"use_OpenMP\":", "in SHARED_LIBS: self.copy(\"*{}*.dll\".format(libname), dst=\"bin\", src=os.path.join(self.build_folder, \"bin\"), keep_path=False) self.copy(\"*{}*.lib\".format(libname), dst=\"lib\", src=os.path.join(self.build_folder,", "= \"The NVIDIA Texture Tools is a collection of image", "texture manipulation tools, designed to be integrated in game tools", "= [\"nvtt\", \"nvimage\", \"nvthread\", \"nvmath\", \"nvcore\"] class NvidiatexturetoolsConan(ConanFile): name =", "[] for libname in STATIC_LIBS: libs += [lib for lib", "if self.settings.os == \"Windows\": del self.options.fPIC def source(self): url =", "\"bin\"), keep_path=False) self.copy(\"*{}*.lib\".format(libname), dst=\"lib\", src=os.path.join(self.build_folder, \"lib\"), keep_path=False) self.copy(\"*{}*.so*\".format(libname), dst=\"lib\", src=os.path.join(self.build_folder,", "self.options.shared: libs = all_libs else: libs = [] for libname", "\"nvtt\"), keep_path=False) if self.options.shared: for libname in SHARED_LIBS: self.copy(\"*{}*.dll\".format(libname), dst=\"bin\",", "self.copy(\"*{}*.so*\".format(libname), dst=\"lib\", src=os.path.join(self.build_folder, \"lib\"), keep_path=False) else: for libname in STATIC_LIBS:", "[\"nvtt\", \"nvimage\", \"nvthread\", \"nvmath\", \"nvcore\"] class NvidiatexturetoolsConan(ConanFile): name = \"nvidia-texture-tools\"", "\"posh\", \"bc7\", \"nvmath\", \"nvthread\", \"nvcore\"] SHARED_LIBS = [\"nvtt\", \"nvimage\", \"nvthread\",", "src=os.path.join(self.build_folder, \"bin\"), keep_path=False) self.copy(\"*{}*.lib\".format(libname), dst=\"lib\", src=os.path.join(self.build_folder, \"lib\"), keep_path=False) self.copy(\"*{}*.so*\".format(libname), dst=\"lib\",", "here, for issues about the package>\" description = \"The NVIDIA", "include(${CMAKE_BINARY_DIR}/conanbuildinfo.cmake) conan_basic_setup()''') def build(self): cmake = CMake(self) cmake.definitions[\"HAVE_CUDA\"] = False", "\"lib\"), keep_path=False) else: for libname in STATIC_LIBS: self.copy(\"*{}*.a\".format(libname), dst=\"lib\", src=os.path.join(self.build_folder,", "keep_path=False) else: for libname in STATIC_LIBS: self.copy(\"*{}*.a\".format(libname), dst=\"lib\", src=os.path.join(self.build_folder, \"lib\"),", "= False cmake.definitions[\"HAVE_OPENMP\"] = self.options.use_OpenMP cmake.configure(source_folder=self.source_subfolder) cmake.build() def package(self): self.copy(\"license*\",", "\"nvmath\", \"nvcore\"] class NvidiatexturetoolsConan(ConanFile): name = \"nvidia-texture-tools\" version = \"662d223626185f7c6c7e0d822a4796a691acc05a\"", "STATIC_LIBS = [\"nvtt\", \"squish\", \"rg_etc1\", \"nvimage\", \"bc6h\", \"posh\", \"bc7\", \"nvmath\",", "\"nvtt\"), keep_path=False) self.copy(\"nvtt_wrapper.h\", dst=\"include/nvtt\", src=os.path.join(self.source_subfolder, \"src\", \"nvtt\"), keep_path=False) if self.options.shared:", "\"nvthread\", \"nvcore\"] SHARED_LIBS = [\"nvtt\", \"nvimage\", \"nvthread\", \"nvmath\", \"nvcore\"] class", "keep_path=False) self.copy(\"*{}*.so*\".format(libname), dst=\"lib\", src=os.path.join(self.build_folder, \"lib\"), keep_path=False) else: for libname in", "all_libs if libname in lib] self.cpp_info.libs = libs if self.settings.os", "import ConanFile, CMake, tools import os STATIC_LIBS = [\"nvtt\", \"squish\",", "\"nvimage\", \"nvthread\", \"nvmath\", \"nvcore\"] class NvidiatexturetoolsConan(ConanFile): name = \"nvidia-texture-tools\" version", "to be integrated in game tools and asset processing pipelines.\"", "src=os.path.join(self.build_folder, \"lib\"), keep_path=False) else: for libname in STATIC_LIBS: self.copy(\"*{}*.a\".format(libname), dst=\"lib\",", "in game tools and asset processing pipelines.\" settings = \"os\",", "dst=\"bin\", src=os.path.join(self.build_folder, \"bin\"), keep_path=False) self.copy(\"*{}*.lib\".format(libname), dst=\"lib\", src=os.path.join(self.build_folder, \"lib\"), keep_path=False) self.copy(\"*{}*.so*\".format(libname),", "False cmake.definitions[\"HAVE_OPENMP\"] = self.options.use_OpenMP cmake.configure(source_folder=self.source_subfolder) cmake.build() def package(self): self.copy(\"license*\", src=self.source_subfolder,", "package_info(self): all_libs = tools.collect_libs(self) if self.options.shared: libs = all_libs else:", "\"nvcore\"] class NvidiatexturetoolsConan(ConanFile): name = \"nvidia-texture-tools\" version = \"662d223626185f7c6c7e0d822a4796a691acc05a\" license", "= libs if self.settings.os == \"Linux\": self.cpp_info.libs.extend([\"dl\", \"pthread\"]) if self.options.shared:", "is a collection of image processing and texture manipulation tools,", "for libname in SHARED_LIBS: self.copy(\"*{}*.dll\".format(libname), dst=\"bin\", src=os.path.join(self.build_folder, \"bin\"), keep_path=False) self.copy(\"*{}*.lib\".format(libname),", "cmake = CMake(self) cmake.definitions[\"HAVE_CUDA\"] = False cmake.definitions[\"HAVE_OPENMP\"] = self.options.use_OpenMP cmake.configure(source_folder=self.source_subfolder)", "= tools.collect_libs(self) if self.options.shared: libs = all_libs else: libs =", "= \"nvtt\" no_copy_source = True options = {\"shared\": [True, False],", "if self.options.shared: for libname in SHARED_LIBS: self.copy(\"*{}*.dll\".format(libname), dst=\"bin\", src=os.path.join(self.build_folder, \"bin\"),", "STATIC_LIBS: self.copy(\"*{}*.a\".format(libname), dst=\"lib\", src=os.path.join(self.build_folder, \"lib\"), keep_path=False) self.copy(\"*{}*.lib\".format(libname), dst=\"lib\", src=os.path.join(self.build_folder, \"lib\"),", "dst=\"lib\", src=os.path.join(self.build_folder, \"lib\"), keep_path=False) self.copy(\"*{}*.lib\".format(libname), dst=\"lib\", src=os.path.join(self.build_folder, \"lib\"), keep_path=False) def", "= True options = {\"shared\": [True, False], \"fPIC\": [True, False],", "\"use_OpenMP\": [True, False] } default_options = \"shared=False\", \"fPIC=True\", \"use_OpenMP=True\" generators", "keep_path=False) def package_info(self): all_libs = tools.collect_libs(self) if self.options.shared: libs =", "all_libs else: libs = [] for libname in STATIC_LIBS: libs", "\"src\", \"nvtt\"), keep_path=False) if self.options.shared: for libname in SHARED_LIBS: self.copy(\"*{}*.dll\".format(libname),", "[\"nvtt\", \"squish\", \"rg_etc1\", \"nvimage\", \"bc6h\", \"posh\", \"bc7\", \"nvmath\", \"nvthread\", \"nvcore\"]", "keep_path=False) self.copy(\"*{}*.lib\".format(libname), dst=\"lib\", src=os.path.join(self.build_folder, \"lib\"), keep_path=False) self.copy(\"*{}*.so*\".format(libname), dst=\"lib\", src=os.path.join(self.build_folder, \"lib\"),", "keep_path=False) if self.options.shared: for libname in SHARED_LIBS: self.copy(\"*{}*.dll\".format(libname), dst=\"bin\", src=os.path.join(self.build_folder,", "if libname in lib] self.cpp_info.libs = libs if self.settings.os ==", "tools.get(url) os.rename('nvidia-texture-tools-{}'.format(self.version), self.source_subfolder) tools.replace_in_file(os.path.join(self.source_subfolder, \"CMakeLists.txt\"), \"PROJECT(NV)\", '''PROJECT(NV) include(${CMAKE_BINARY_DIR}/conanbuildinfo.cmake) conan_basic_setup()''') def", "self.cpp_info.libs = libs if self.settings.os == \"Linux\": self.cpp_info.libs.extend([\"dl\", \"pthread\"]) if", "asset processing pipelines.\" settings = \"os\", \"compiler\", \"build_type\", \"arch\" source_subfolder", "libs = all_libs else: libs = [] for libname in", "designed to be integrated in game tools and asset processing", "src=os.path.join(self.build_folder, \"lib\"), keep_path=False) self.copy(\"*{}*.lib\".format(libname), dst=\"lib\", src=os.path.join(self.build_folder, \"lib\"), keep_path=False) def package_info(self):", "\"koeleck\" url = \"<Package recipe repository url here, for issues", "\"MIT\" author = \"koeleck\" url = \"<Package recipe repository url" ]
[ "containing the categories.', ) parser.add_argument('--gpu', action=\"store_true\", dest=\"use_gpu\", default=False, help='Use the", "action=\"store\", default=0.001, type=float, help='Learning rate') hp.add_argument('--hidden_units', '-hu', action=\"store\", dest=\"hidden_units\", default=[4096],", "categories.', ) parser.add_argument('--gpu', action=\"store_true\", dest=\"use_gpu\", default=False, help='Use the GPU to", "model.\", usage=\"python3 train.py flowers/train --gpu --learning_rate 0.001 --epochs 11 --gpu", "print(f'Command line argument utility for train.py.\\nTry \"python train.py -h\".') if", "for train.py.\\nTry \"python train.py -h\".') if __name__ == '__main__': main()", "get_args(): \"\"\" \"\"\" parser = argparse.ArgumentParser( description=\"This script lets you", "parser.add_argument('--categories_json', action=\"store\", default=\"cat_to_name.json\", dest='categories_json', type=str, help='Path to file containing the", "help='Epochs to train the model for') parser.parse_args() return parser def", "\"\"\" Main Function \"\"\" print(f'Command line argument utility for train.py.\\nTry", "the CPU') hp = parser.add_argument_group('hyperparameters') hp.add_argument('--learning_rate', action=\"store\", default=0.001, type=float, help='Learning", "help='Hidden layer units') hp.add_argument('--epochs', action=\"store\", dest=\"epochs\", default=1, type=int, help='Epochs to", "train instead of the CPU') hp = parser.add_argument_group('hyperparameters') hp.add_argument('--learning_rate', action=\"store\",", "return parser def main(): \"\"\" Main Function \"\"\" print(f'Command line", "if __name__ == '__main__': main() \"\"\" main() is called if", "\"\"\" parser = argparse.ArgumentParser( description=\"This script lets you train and", "lets you train and save your model.\", usage=\"python3 train.py flowers/train", "default=\"alexnet\", dest='arch', type=str, help='Directory to save the model file.', )", "nargs='+', help='Hidden layer units') hp.add_argument('--epochs', action=\"store\", dest=\"epochs\", default=1, type=int, help='Epochs", "parser.add_argument('--gpu', action=\"store_true\", dest=\"use_gpu\", default=False, help='Use the GPU to train instead", "to save the model file.', ) parser.add_argument('--save_dir', action=\"store\", default=\".\", dest='save_dir',", "dest=\"epochs\", default=1, type=int, help='Epochs to train the model for') parser.parse_args()", "Function \"\"\" print(f'Command line argument utility for train.py.\\nTry \"python train.py", "parser.add_argument('data_directory', action=\"store\") parser.add_argument('--arch', action=\"store\", default=\"alexnet\", dest='arch', type=str, help='Directory to save", "-h\".') if __name__ == '__main__': main() \"\"\" main() is called", "action=\"store\", default=\"alexnet\", dest='arch', type=str, help='Directory to save the model file.',", "save the model file.', ) parser.add_argument('--save_dir', action=\"store\", default=\".\", dest='save_dir', type=str,", "default=1, type=int, help='Epochs to train the model for') parser.parse_args() return", "save the model file.', ) parser.add_argument('--save_name', action=\"store\", default=\"checkpoint\", dest='save_name', type=str,", "model file.', ) parser.add_argument('--save_dir', action=\"store\", default=\".\", dest='save_dir', type=str, help='Directory to", "argparse.ArgumentParser( description=\"This script lets you train and save your model.\",", "--hidden_units 500\", formatter_class=argparse.ArgumentDefaultsHelpFormatter ) parser.add_argument('data_directory', action=\"store\") parser.add_argument('--arch', action=\"store\", default=\"alexnet\", dest='arch',", "your model.\", usage=\"python3 train.py flowers/train --gpu --learning_rate 0.001 --epochs 11", "hp = parser.add_argument_group('hyperparameters') hp.add_argument('--learning_rate', action=\"store\", default=0.001, type=float, help='Learning rate') hp.add_argument('--hidden_units',", "= parser.add_argument_group('hyperparameters') hp.add_argument('--learning_rate', action=\"store\", default=0.001, type=float, help='Learning rate') hp.add_argument('--hidden_units', '-hu',", "main(): \"\"\" Main Function \"\"\" print(f'Command line argument utility for", "flowers/train --gpu --learning_rate 0.001 --epochs 11 --gpu --hidden_units 500\", formatter_class=argparse.ArgumentDefaultsHelpFormatter", "hp.add_argument('--epochs', action=\"store\", dest=\"epochs\", default=1, type=int, help='Epochs to train the model", ") parser.add_argument('--save_name', action=\"store\", default=\"checkpoint\", dest='save_name', type=str, help='Checkpoint filename.', ) parser.add_argument('--categories_json',", "is called if script is executed on it's own. \"\"\"", "#!/usr/bin/env python3 \"\"\" train_args.py train_args.py command-line args. \"\"\" import argparse", "__name__ == '__main__': main() \"\"\" main() is called if script", "type=str, help='Checkpoint filename.', ) parser.add_argument('--categories_json', action=\"store\", default=\"cat_to_name.json\", dest='categories_json', type=str, help='Path", "save your model.\", usage=\"python3 train.py flowers/train --gpu --learning_rate 0.001 --epochs", "action=\"store\", default=\"cat_to_name.json\", dest='categories_json', type=str, help='Path to file containing the categories.',", "train the model for') parser.parse_args() return parser def main(): \"\"\"", "hp.add_argument('--hidden_units', '-hu', action=\"store\", dest=\"hidden_units\", default=[4096], type=int, nargs='+', help='Hidden layer units')", "train.py.\\nTry \"python train.py -h\".') if __name__ == '__main__': main() \"\"\"", "11 --gpu --hidden_units 500\", formatter_class=argparse.ArgumentDefaultsHelpFormatter ) parser.add_argument('data_directory', action=\"store\") parser.add_argument('--arch', action=\"store\",", "the categories.', ) parser.add_argument('--gpu', action=\"store_true\", dest=\"use_gpu\", default=False, help='Use the GPU", "hp.add_argument('--learning_rate', action=\"store\", default=0.001, type=float, help='Learning rate') hp.add_argument('--hidden_units', '-hu', action=\"store\", dest=\"hidden_units\",", "help='Checkpoint filename.', ) parser.add_argument('--categories_json', action=\"store\", default=\"cat_to_name.json\", dest='categories_json', type=str, help='Path to", "main() \"\"\" main() is called if script is executed on", "default=\"cat_to_name.json\", dest='categories_json', type=str, help='Path to file containing the categories.', )", "to train instead of the CPU') hp = parser.add_argument_group('hyperparameters') hp.add_argument('--learning_rate',", "the model file.', ) parser.add_argument('--save_name', action=\"store\", default=\"checkpoint\", dest='save_name', type=str, help='Checkpoint", "units') hp.add_argument('--epochs', action=\"store\", dest=\"epochs\", default=1, type=int, help='Epochs to train the", "--gpu --learning_rate 0.001 --epochs 11 --gpu --hidden_units 500\", formatter_class=argparse.ArgumentDefaultsHelpFormatter )", "action=\"store_true\", dest=\"use_gpu\", default=False, help='Use the GPU to train instead of", "train.py -h\".') if __name__ == '__main__': main() \"\"\" main() is", "the model file.', ) parser.add_argument('--save_dir', action=\"store\", default=\".\", dest='save_dir', type=str, help='Directory", "GPU to train instead of the CPU') hp = parser.add_argument_group('hyperparameters')", "parser.parse_args() return parser def main(): \"\"\" Main Function \"\"\" print(f'Command", "you train and save your model.\", usage=\"python3 train.py flowers/train --gpu", "--gpu --hidden_units 500\", formatter_class=argparse.ArgumentDefaultsHelpFormatter ) parser.add_argument('data_directory', action=\"store\") parser.add_argument('--arch', action=\"store\", default=\"alexnet\",", "for') parser.parse_args() return parser def main(): \"\"\" Main Function \"\"\"", "parser = argparse.ArgumentParser( description=\"This script lets you train and save", "formatter_class=argparse.ArgumentDefaultsHelpFormatter ) parser.add_argument('data_directory', action=\"store\") parser.add_argument('--arch', action=\"store\", default=\"alexnet\", dest='arch', type=str, help='Directory", "file.', ) parser.add_argument('--save_name', action=\"store\", default=\"checkpoint\", dest='save_name', type=str, help='Checkpoint filename.', )", "help='Learning rate') hp.add_argument('--hidden_units', '-hu', action=\"store\", dest=\"hidden_units\", default=[4096], type=int, nargs='+', help='Hidden", "parser def main(): \"\"\" Main Function \"\"\" print(f'Command line argument", "python3 \"\"\" train_args.py train_args.py command-line args. \"\"\" import argparse def", "\"\"\" import argparse def get_args(): \"\"\" \"\"\" parser = argparse.ArgumentParser(", "type=int, nargs='+', help='Hidden layer units') hp.add_argument('--epochs', action=\"store\", dest=\"epochs\", default=1, type=int,", ") parser.add_argument('data_directory', action=\"store\") parser.add_argument('--arch', action=\"store\", default=\"alexnet\", dest='arch', type=str, help='Directory to", "Main Function \"\"\" print(f'Command line argument utility for train.py.\\nTry \"python", "\"\"\" \"\"\" parser = argparse.ArgumentParser( description=\"This script lets you train", "type=str, help='Directory to save the model file.', ) parser.add_argument('--save_dir', action=\"store\",", "--epochs 11 --gpu --hidden_units 500\", formatter_class=argparse.ArgumentDefaultsHelpFormatter ) parser.add_argument('data_directory', action=\"store\") parser.add_argument('--arch',", "default=0.001, type=float, help='Learning rate') hp.add_argument('--hidden_units', '-hu', action=\"store\", dest=\"hidden_units\", default=[4096], type=int,", "filename.', ) parser.add_argument('--categories_json', action=\"store\", default=\"cat_to_name.json\", dest='categories_json', type=str, help='Path to file", "the GPU to train instead of the CPU') hp =", "argument utility for train.py.\\nTry \"python train.py -h\".') if __name__ ==", "500\", formatter_class=argparse.ArgumentDefaultsHelpFormatter ) parser.add_argument('data_directory', action=\"store\") parser.add_argument('--arch', action=\"store\", default=\"alexnet\", dest='arch', type=str,", "train.py flowers/train --gpu --learning_rate 0.001 --epochs 11 --gpu --hidden_units 500\",", "help='Directory to save the model file.', ) parser.add_argument('--save_dir', action=\"store\", default=\".\",", "to train the model for') parser.parse_args() return parser def main():", "of the CPU') hp = parser.add_argument_group('hyperparameters') hp.add_argument('--learning_rate', action=\"store\", default=0.001, type=float,", "file.', ) parser.add_argument('--save_dir', action=\"store\", default=\".\", dest='save_dir', type=str, help='Directory to save", "<reponame>MyWay/Create-Your-Own-Image-Classifier #!/usr/bin/env python3 \"\"\" train_args.py train_args.py command-line args. \"\"\" import", "model file.', ) parser.add_argument('--save_name', action=\"store\", default=\"checkpoint\", dest='save_name', type=str, help='Checkpoint filename.',", "help='Directory to save the model file.', ) parser.add_argument('--save_name', action=\"store\", default=\"checkpoint\",", "action=\"store\", dest=\"hidden_units\", default=[4096], type=int, nargs='+', help='Hidden layer units') hp.add_argument('--epochs', action=\"store\",", "dest='save_name', type=str, help='Checkpoint filename.', ) parser.add_argument('--categories_json', action=\"store\", default=\"cat_to_name.json\", dest='categories_json', type=str,", "= argparse.ArgumentParser( description=\"This script lets you train and save your", "train and save your model.\", usage=\"python3 train.py flowers/train --gpu --learning_rate", "default=[4096], type=int, nargs='+', help='Hidden layer units') hp.add_argument('--epochs', action=\"store\", dest=\"epochs\", default=1,", "rate') hp.add_argument('--hidden_units', '-hu', action=\"store\", dest=\"hidden_units\", default=[4096], type=int, nargs='+', help='Hidden layer", "layer units') hp.add_argument('--epochs', action=\"store\", dest=\"epochs\", default=1, type=int, help='Epochs to train", "default=\".\", dest='save_dir', type=str, help='Directory to save the model file.', )", "dest='categories_json', type=str, help='Path to file containing the categories.', ) parser.add_argument('--gpu',", "parser.add_argument('--save_name', action=\"store\", default=\"checkpoint\", dest='save_name', type=str, help='Checkpoint filename.', ) parser.add_argument('--categories_json', action=\"store\",", "action=\"store\", default=\".\", dest='save_dir', type=str, help='Directory to save the model file.',", ") parser.add_argument('--categories_json', action=\"store\", default=\"cat_to_name.json\", dest='categories_json', type=str, help='Path to file containing", "file containing the categories.', ) parser.add_argument('--gpu', action=\"store_true\", dest=\"use_gpu\", default=False, help='Use", "action=\"store\", dest=\"epochs\", default=1, type=int, help='Epochs to train the model for')", "dest=\"hidden_units\", default=[4096], type=int, nargs='+', help='Hidden layer units') hp.add_argument('--epochs', action=\"store\", dest=\"epochs\",", "default=\"checkpoint\", dest='save_name', type=str, help='Checkpoint filename.', ) parser.add_argument('--categories_json', action=\"store\", default=\"cat_to_name.json\", dest='categories_json',", "default=False, help='Use the GPU to train instead of the CPU')", "\"\"\" print(f'Command line argument utility for train.py.\\nTry \"python train.py -h\".')", "dest='arch', type=str, help='Directory to save the model file.', ) parser.add_argument('--save_dir',", "line argument utility for train.py.\\nTry \"python train.py -h\".') if __name__", "train_args.py command-line args. \"\"\" import argparse def get_args(): \"\"\" \"\"\"", ") parser.add_argument('--save_dir', action=\"store\", default=\".\", dest='save_dir', type=str, help='Directory to save the", "dest='save_dir', type=str, help='Directory to save the model file.', ) parser.add_argument('--save_name',", "0.001 --epochs 11 --gpu --hidden_units 500\", formatter_class=argparse.ArgumentDefaultsHelpFormatter ) parser.add_argument('data_directory', action=\"store\")", "== '__main__': main() \"\"\" main() is called if script is", "import argparse def get_args(): \"\"\" \"\"\" parser = argparse.ArgumentParser( description=\"This", "type=int, help='Epochs to train the model for') parser.parse_args() return parser", "utility for train.py.\\nTry \"python train.py -h\".') if __name__ == '__main__':", "'__main__': main() \"\"\" main() is called if script is executed", "args. \"\"\" import argparse def get_args(): \"\"\" \"\"\" parser =", "action=\"store\", default=\"checkpoint\", dest='save_name', type=str, help='Checkpoint filename.', ) parser.add_argument('--categories_json', action=\"store\", default=\"cat_to_name.json\",", "type=float, help='Learning rate') hp.add_argument('--hidden_units', '-hu', action=\"store\", dest=\"hidden_units\", default=[4096], type=int, nargs='+',", "parser.add_argument('--arch', action=\"store\", default=\"alexnet\", dest='arch', type=str, help='Directory to save the model", "script lets you train and save your model.\", usage=\"python3 train.py", "def get_args(): \"\"\" \"\"\" parser = argparse.ArgumentParser( description=\"This script lets", "and save your model.\", usage=\"python3 train.py flowers/train --gpu --learning_rate 0.001", "argparse def get_args(): \"\"\" \"\"\" parser = argparse.ArgumentParser( description=\"This script", "help='Path to file containing the categories.', ) parser.add_argument('--gpu', action=\"store_true\", dest=\"use_gpu\",", "action=\"store\") parser.add_argument('--arch', action=\"store\", default=\"alexnet\", dest='arch', type=str, help='Directory to save the", "\"python train.py -h\".') if __name__ == '__main__': main() \"\"\" main()", "def main(): \"\"\" Main Function \"\"\" print(f'Command line argument utility", "\"\"\" main() is called if script is executed on it's", "model for') parser.parse_args() return parser def main(): \"\"\" Main Function", "parser.add_argument_group('hyperparameters') hp.add_argument('--learning_rate', action=\"store\", default=0.001, type=float, help='Learning rate') hp.add_argument('--hidden_units', '-hu', action=\"store\",", "parser.add_argument('--save_dir', action=\"store\", default=\".\", dest='save_dir', type=str, help='Directory to save the model", "to file containing the categories.', ) parser.add_argument('--gpu', action=\"store_true\", dest=\"use_gpu\", default=False,", "help='Use the GPU to train instead of the CPU') hp", "\"\"\" train_args.py train_args.py command-line args. \"\"\" import argparse def get_args():", "'-hu', action=\"store\", dest=\"hidden_units\", default=[4096], type=int, nargs='+', help='Hidden layer units') hp.add_argument('--epochs',", "main() is called if script is executed on it's own.", "usage=\"python3 train.py flowers/train --gpu --learning_rate 0.001 --epochs 11 --gpu --hidden_units", "CPU') hp = parser.add_argument_group('hyperparameters') hp.add_argument('--learning_rate', action=\"store\", default=0.001, type=float, help='Learning rate')", "command-line args. \"\"\" import argparse def get_args(): \"\"\" \"\"\" parser", "--learning_rate 0.001 --epochs 11 --gpu --hidden_units 500\", formatter_class=argparse.ArgumentDefaultsHelpFormatter ) parser.add_argument('data_directory',", "train_args.py train_args.py command-line args. \"\"\" import argparse def get_args(): \"\"\"", ") parser.add_argument('--gpu', action=\"store_true\", dest=\"use_gpu\", default=False, help='Use the GPU to train", "the model for') parser.parse_args() return parser def main(): \"\"\" Main", "type=str, help='Path to file containing the categories.', ) parser.add_argument('--gpu', action=\"store_true\",", "type=str, help='Directory to save the model file.', ) parser.add_argument('--save_name', action=\"store\",", "to save the model file.', ) parser.add_argument('--save_name', action=\"store\", default=\"checkpoint\", dest='save_name',", "description=\"This script lets you train and save your model.\", usage=\"python3", "dest=\"use_gpu\", default=False, help='Use the GPU to train instead of the", "instead of the CPU') hp = parser.add_argument_group('hyperparameters') hp.add_argument('--learning_rate', action=\"store\", default=0.001," ]
[ "exp_year = int(request.POST.get('exp-date').split('/')[1]) cvc = request.POST.get('cvc') card = { \"name\":", "100 context['currency'] = 'tl' return context def post(self, request): name", "PaymentLog from apps.payment.stripe import get_token, get_payment_charge from apps.subscription.views import start_subscription", "from django.views.generic import TemplateView from apps.payment.models import PaymentLog from apps.payment.stripe", "name, \"number\": card_number, \"exp_month\": exp_month, \"exp_year\": exp_year, \"cvc\": cvc }", "currency=\"usd\", description=\"test\", token=token.stripe_id) if charge.paid: log_payment(user=request.user, data=charge) start_subscription(request.user) return HttpResponseRedirect('/')", "int(request.POST.get('exp-date').split('/')[0]) exp_year = int(request.POST.get('exp-date').split('/')[1]) cvc = request.POST.get('cvc') card = {", "get_payment_charge(amount=100, currency=\"usd\", description=\"test\", token=token.stripe_id) if charge.paid: log_payment(user=request.user, data=charge) start_subscription(request.user) return", "from django.conf import settings from django.views.generic import TemplateView from apps.payment.models", "request): name = request.POST.get('name') card_number = request.POST.get('cardnumber') exp_month = int(request.POST.get('exp-date').split('/')[0])", "django.conf import settings from django.views.generic import TemplateView from apps.payment.models import", "} token = get_token(card) charge = get_payment_charge(amount=100, currency=\"usd\", description=\"test\", token=token.stripe_id)", "token = get_token(card) charge = get_payment_charge(amount=100, currency=\"usd\", description=\"test\", token=token.stripe_id) if", "{ \"name\": name, \"number\": card_number, \"exp_month\": exp_month, \"exp_year\": exp_year, \"cvc\":", "import PaymentLog from apps.payment.stripe import get_token, get_payment_charge from apps.subscription.views import", "cvc } token = get_token(card) charge = get_payment_charge(amount=100, currency=\"usd\", description=\"test\",", "settings.STRIPE_PUBLISHABLE_KEY context['amount'] = 100 context['currency'] = 'tl' return context def", "= super().get_context_data(**kwargs) context['stripe_public_key'] = settings.STRIPE_PUBLISHABLE_KEY context['amount'] = 100 context['currency'] =", "= 'tl' return context def post(self, request): name = request.POST.get('name')", "\"exp_month\": exp_month, \"exp_year\": exp_year, \"cvc\": cvc } token = get_token(card)", "context = super().get_context_data(**kwargs) context['stripe_public_key'] = settings.STRIPE_PUBLISHABLE_KEY context['amount'] = 100 context['currency']", "from apps.payment.models import PaymentLog from apps.payment.stripe import get_token, get_payment_charge from", "context['amount'] = 100 context['currency'] = 'tl' return context def post(self,", "django.views.generic import TemplateView from apps.payment.models import PaymentLog from apps.payment.stripe import", "exp_month, \"exp_year\": exp_year, \"cvc\": cvc } token = get_token(card) charge", "TemplateView from apps.payment.models import PaymentLog from apps.payment.stripe import get_token, get_payment_charge", "return context def post(self, request): name = request.POST.get('name') card_number =", "request.POST.get('name') card_number = request.POST.get('cardnumber') exp_month = int(request.POST.get('exp-date').split('/')[0]) exp_year = int(request.POST.get('exp-date').split('/')[1])", "log_payment(user=request.user, data=charge) start_subscription(request.user) return HttpResponseRedirect('/') def log_payment(user, data): PaymentLog.objects.create(user=user, data=data)", "def post(self, request): name = request.POST.get('name') card_number = request.POST.get('cardnumber') exp_month", "charge.paid: log_payment(user=request.user, data=charge) start_subscription(request.user) return HttpResponseRedirect('/') def log_payment(user, data): PaymentLog.objects.create(user=user,", "**kwargs): context = super().get_context_data(**kwargs) context['stripe_public_key'] = settings.STRIPE_PUBLISHABLE_KEY context['amount'] = 100", "= request.POST.get('cardnumber') exp_month = int(request.POST.get('exp-date').split('/')[0]) exp_year = int(request.POST.get('exp-date').split('/')[1]) cvc =", "\"name\": name, \"number\": card_number, \"exp_month\": exp_month, \"exp_year\": exp_year, \"cvc\": cvc", "get_payment_charge from apps.subscription.views import start_subscription class ChargeView(TemplateView): template_name = 'payment/charge.html'", "import settings from django.views.generic import TemplateView from apps.payment.models import PaymentLog", "def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['stripe_public_key'] = settings.STRIPE_PUBLISHABLE_KEY context['amount']", "= { \"name\": name, \"number\": card_number, \"exp_month\": exp_month, \"exp_year\": exp_year,", "request.POST.get('cvc') card = { \"name\": name, \"number\": card_number, \"exp_month\": exp_month,", "= int(request.POST.get('exp-date').split('/')[1]) cvc = request.POST.get('cvc') card = { \"name\": name,", "request.POST.get('cardnumber') exp_month = int(request.POST.get('exp-date').split('/')[0]) exp_year = int(request.POST.get('exp-date').split('/')[1]) cvc = request.POST.get('cvc')", "name = request.POST.get('name') card_number = request.POST.get('cardnumber') exp_month = int(request.POST.get('exp-date').split('/')[0]) exp_year", "template_name = 'payment/charge.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['stripe_public_key']", "from apps.payment.stripe import get_token, get_payment_charge from apps.subscription.views import start_subscription class", "import TemplateView from apps.payment.models import PaymentLog from apps.payment.stripe import get_token,", "= int(request.POST.get('exp-date').split('/')[0]) exp_year = int(request.POST.get('exp-date').split('/')[1]) cvc = request.POST.get('cvc') card =", "<reponame>canadiyaman/thetask<filename>apps/payment/views.py<gh_stars>0 from django.http import HttpResponseRedirect from django.conf import settings from", "if charge.paid: log_payment(user=request.user, data=charge) start_subscription(request.user) return HttpResponseRedirect('/') def log_payment(user, data):", "card = { \"name\": name, \"number\": card_number, \"exp_month\": exp_month, \"exp_year\":", "from apps.subscription.views import start_subscription class ChargeView(TemplateView): template_name = 'payment/charge.html' def", "description=\"test\", token=token.stripe_id) if charge.paid: log_payment(user=request.user, data=charge) start_subscription(request.user) return HttpResponseRedirect('/') def", "get_token, get_payment_charge from apps.subscription.views import start_subscription class ChargeView(TemplateView): template_name =", "apps.payment.models import PaymentLog from apps.payment.stripe import get_token, get_payment_charge from apps.subscription.views", "HttpResponseRedirect from django.conf import settings from django.views.generic import TemplateView from", "class ChargeView(TemplateView): template_name = 'payment/charge.html' def get_context_data(self, **kwargs): context =", "= 100 context['currency'] = 'tl' return context def post(self, request):", "int(request.POST.get('exp-date').split('/')[1]) cvc = request.POST.get('cvc') card = { \"name\": name, \"number\":", "from django.http import HttpResponseRedirect from django.conf import settings from django.views.generic", "apps.subscription.views import start_subscription class ChargeView(TemplateView): template_name = 'payment/charge.html' def get_context_data(self,", "\"number\": card_number, \"exp_month\": exp_month, \"exp_year\": exp_year, \"cvc\": cvc } token", "context['stripe_public_key'] = settings.STRIPE_PUBLISHABLE_KEY context['amount'] = 100 context['currency'] = 'tl' return", "get_token(card) charge = get_payment_charge(amount=100, currency=\"usd\", description=\"test\", token=token.stripe_id) if charge.paid: log_payment(user=request.user,", "= get_token(card) charge = get_payment_charge(amount=100, currency=\"usd\", description=\"test\", token=token.stripe_id) if charge.paid:", "exp_month = int(request.POST.get('exp-date').split('/')[0]) exp_year = int(request.POST.get('exp-date').split('/')[1]) cvc = request.POST.get('cvc') card", "settings from django.views.generic import TemplateView from apps.payment.models import PaymentLog from", "\"exp_year\": exp_year, \"cvc\": cvc } token = get_token(card) charge =", "= 'payment/charge.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['stripe_public_key'] =", "charge = get_payment_charge(amount=100, currency=\"usd\", description=\"test\", token=token.stripe_id) if charge.paid: log_payment(user=request.user, data=charge)", "= request.POST.get('cvc') card = { \"name\": name, \"number\": card_number, \"exp_month\":", "card_number, \"exp_month\": exp_month, \"exp_year\": exp_year, \"cvc\": cvc } token =", "= settings.STRIPE_PUBLISHABLE_KEY context['amount'] = 100 context['currency'] = 'tl' return context", "card_number = request.POST.get('cardnumber') exp_month = int(request.POST.get('exp-date').split('/')[0]) exp_year = int(request.POST.get('exp-date').split('/')[1]) cvc", "= request.POST.get('name') card_number = request.POST.get('cardnumber') exp_month = int(request.POST.get('exp-date').split('/')[0]) exp_year =", "exp_year, \"cvc\": cvc } token = get_token(card) charge = get_payment_charge(amount=100,", "token=token.stripe_id) if charge.paid: log_payment(user=request.user, data=charge) start_subscription(request.user) return HttpResponseRedirect('/') def log_payment(user,", "django.http import HttpResponseRedirect from django.conf import settings from django.views.generic import", "import start_subscription class ChargeView(TemplateView): template_name = 'payment/charge.html' def get_context_data(self, **kwargs):", "super().get_context_data(**kwargs) context['stripe_public_key'] = settings.STRIPE_PUBLISHABLE_KEY context['amount'] = 100 context['currency'] = 'tl'", "\"cvc\": cvc } token = get_token(card) charge = get_payment_charge(amount=100, currency=\"usd\",", "start_subscription class ChargeView(TemplateView): template_name = 'payment/charge.html' def get_context_data(self, **kwargs): context", "context def post(self, request): name = request.POST.get('name') card_number = request.POST.get('cardnumber')", "apps.payment.stripe import get_token, get_payment_charge from apps.subscription.views import start_subscription class ChargeView(TemplateView):", "'payment/charge.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['stripe_public_key'] = settings.STRIPE_PUBLISHABLE_KEY", "'tl' return context def post(self, request): name = request.POST.get('name') card_number", "ChargeView(TemplateView): template_name = 'payment/charge.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs)", "import get_token, get_payment_charge from apps.subscription.views import start_subscription class ChargeView(TemplateView): template_name", "import HttpResponseRedirect from django.conf import settings from django.views.generic import TemplateView", "get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['stripe_public_key'] = settings.STRIPE_PUBLISHABLE_KEY context['amount'] =", "context['currency'] = 'tl' return context def post(self, request): name =", "cvc = request.POST.get('cvc') card = { \"name\": name, \"number\": card_number,", "post(self, request): name = request.POST.get('name') card_number = request.POST.get('cardnumber') exp_month =", "= get_payment_charge(amount=100, currency=\"usd\", description=\"test\", token=token.stripe_id) if charge.paid: log_payment(user=request.user, data=charge) start_subscription(request.user)" ]
[ "for automatic profile creation for user def ready(self): import users.signals", "UsersConfig(AppConfig): name = 'users' # below piece of code is", "= 'users' # below piece of code is needed for", "needed for automatic profile creation for user def ready(self): import", "piece of code is needed for automatic profile creation for", "name = 'users' # below piece of code is needed", "django.apps import AppConfig class UsersConfig(AppConfig): name = 'users' # below", "below piece of code is needed for automatic profile creation", "from django.apps import AppConfig class UsersConfig(AppConfig): name = 'users' #", "is needed for automatic profile creation for user def ready(self):", "# below piece of code is needed for automatic profile", "of code is needed for automatic profile creation for user", "class UsersConfig(AppConfig): name = 'users' # below piece of code", "'users' # below piece of code is needed for automatic", "code is needed for automatic profile creation for user def", "import AppConfig class UsersConfig(AppConfig): name = 'users' # below piece", "AppConfig class UsersConfig(AppConfig): name = 'users' # below piece of" ]
[ "secure data container NAME.\"\"\" try: config = sds.read_config(config) sds.create(config, name)", "sds.read_config(config) sds.mount(config, name) except (sds.ContainerError, sds.GCFSError, sds.ConfigError, sds.MountError) as err:", "@click.argument('name') @click.option('--config', help='Path to config file', default='~/.sdsrc') def open(name, config=None):", "sds.read_config(config) sds.create(config, name) except (sds.ContainerError, sds.GCFSError, FileExistsError, sds.ConfigError) as err:", "sds.mount(config, name) except (sds.ContainerError, sds.GCFSError, sds.ConfigError, sds.MountError) as err: print(err)", "@click.option('--config', help='Path to config file', default='~/.sdsrc') def close(name, config=None): \"\"\"Close", "@main.command() @click.argument('name') @click.option('--config', help='Path to config file', default='~/.sdsrc') def create(name,", "config = sds.read_config(config) sds.create(config, name) except (sds.ContainerError, sds.GCFSError, FileExistsError, sds.ConfigError)", "= sds.read_config(config) sds.create(config, name) except (sds.ContainerError, sds.GCFSError, FileExistsError, sds.ConfigError) as", "the opened, clear-text container.\"\"\" try: config = sds.read_config(config) sds.mount(config, name)", "container NAME.\"\"\" try: config = sds.read_config(config) sds.create(config, name) except (sds.ContainerError,", "\"\"\"Open an existing secure data container NAME. Will print path", "\"\"\"Console script for secure_data_store.\"\"\" import click from . import secure_data_store", "NAME. Will print path to the opened, clear-text container.\"\"\" try:", "data container NAME. Will print path to the opened, clear-text", "secure_data_store as sds CONFIG='~/.sdsrc' @click.group() def main(): \"\"\"Wrapper for GoCryptFS\"\"\"", "print path to the opened, clear-text container.\"\"\" try: config =", "as err: print(err) @main.command() @click.argument('name') @click.option('--config', help='Path to config file',", "@click.group() def main(): \"\"\"Wrapper for GoCryptFS\"\"\" @main.command() @click.argument('name') @click.option('--config', help='Path", "name) except (sds.ContainerError, sds.GCFSError, FileExistsError, sds.ConfigError) as err: print(err) @main.command()", "as sds CONFIG='~/.sdsrc' @click.group() def main(): \"\"\"Wrapper for GoCryptFS\"\"\" @main.command()", "= sds.read_config(config) sds.unmount(config, name) except (sds.ContainerError, sds.GCFSError, sds.ConfigError) as err:", "close(name, config=None): \"\"\"Close an opend data container NAME.\"\"\" try: config", "def open(name, config=None): \"\"\"Open an existing secure data container NAME.", "create(name, config=None): \"\"\"Create a new secure data container NAME.\"\"\" try:", "def main(): \"\"\"Wrapper for GoCryptFS\"\"\" @main.command() @click.argument('name') @click.option('--config', help='Path to", "sds.MountError) as err: print(err) @main.command() @click.argument('name') @click.option('--config', help='Path to config", "NAME.\"\"\" try: config = sds.read_config(config) sds.unmount(config, name) except (sds.ContainerError, sds.GCFSError,", "container NAME. Will print path to the opened, clear-text container.\"\"\"", "an existing secure data container NAME. Will print path to", "GoCryptFS\"\"\" @main.command() @click.argument('name') @click.option('--config', help='Path to config file', default='~/.sdsrc') def", "@click.option('--config', help='Path to config file', default='~/.sdsrc') def open(name, config=None): \"\"\"Open", "config = sds.read_config(config) sds.mount(config, name) except (sds.ContainerError, sds.GCFSError, sds.ConfigError, sds.MountError)", "to the opened, clear-text container.\"\"\" try: config = sds.read_config(config) sds.mount(config,", "path to the opened, clear-text container.\"\"\" try: config = sds.read_config(config)", "\"\"\"Wrapper for GoCryptFS\"\"\" @main.command() @click.argument('name') @click.option('--config', help='Path to config file',", "default='~/.sdsrc') def open(name, config=None): \"\"\"Open an existing secure data container", "@main.command() @click.argument('name') @click.option('--config', help='Path to config file', default='~/.sdsrc') def open(name,", "main(): \"\"\"Wrapper for GoCryptFS\"\"\" @main.command() @click.argument('name') @click.option('--config', help='Path to config", "\"\"\"Close an opend data container NAME.\"\"\" try: config = sds.read_config(config)", "from . import secure_data_store as sds CONFIG='~/.sdsrc' @click.group() def main():", "config = sds.read_config(config) sds.unmount(config, name) except (sds.ContainerError, sds.GCFSError, sds.ConfigError) as", "for secure_data_store.\"\"\" import click from . import secure_data_store as sds", "coding: utf-8 -*- \"\"\"Console script for secure_data_store.\"\"\" import click from", "help='Path to config file', default='~/.sdsrc') def close(name, config=None): \"\"\"Close an", "open(name, config=None): \"\"\"Open an existing secure data container NAME. Will", "config=None): \"\"\"Open an existing secure data container NAME. Will print", "(sds.ContainerError, sds.GCFSError, sds.ConfigError, sds.MountError) as err: print(err) @main.command() @click.argument('name') @click.option('--config',", "Will print path to the opened, clear-text container.\"\"\" try: config", "secure_data_store.\"\"\" import click from . import secure_data_store as sds CONFIG='~/.sdsrc'", "try: config = sds.read_config(config) sds.unmount(config, name) except (sds.ContainerError, sds.GCFSError, sds.ConfigError)", "@click.argument('name') @click.option('--config', help='Path to config file', default='~/.sdsrc') def close(name, config=None):", "opened, clear-text container.\"\"\" try: config = sds.read_config(config) sds.mount(config, name) except", "help='Path to config file', default='~/.sdsrc') def create(name, config=None): \"\"\"Create a", "default='~/.sdsrc') def create(name, config=None): \"\"\"Create a new secure data container", "sds.read_config(config) sds.unmount(config, name) except (sds.ContainerError, sds.GCFSError, sds.ConfigError) as err: print(err)", "sds CONFIG='~/.sdsrc' @click.group() def main(): \"\"\"Wrapper for GoCryptFS\"\"\" @main.command() @click.argument('name')", "CONFIG='~/.sdsrc' @click.group() def main(): \"\"\"Wrapper for GoCryptFS\"\"\" @main.command() @click.argument('name') @click.option('--config',", "existing secure data container NAME. Will print path to the", ". import secure_data_store as sds CONFIG='~/.sdsrc' @click.group() def main(): \"\"\"Wrapper", "NAME.\"\"\" try: config = sds.read_config(config) sds.create(config, name) except (sds.ContainerError, sds.GCFSError,", "FileExistsError, sds.ConfigError) as err: print(err) @main.command() @click.argument('name') @click.option('--config', help='Path to", "file', default='~/.sdsrc') def open(name, config=None): \"\"\"Open an existing secure data", "help='Path to config file', default='~/.sdsrc') def open(name, config=None): \"\"\"Open an", "name) except (sds.ContainerError, sds.GCFSError, sds.ConfigError, sds.MountError) as err: print(err) @main.command()", "config file', default='~/.sdsrc') def close(name, config=None): \"\"\"Close an opend data", "for GoCryptFS\"\"\" @main.command() @click.argument('name') @click.option('--config', help='Path to config file', default='~/.sdsrc')", "config=None): \"\"\"Create a new secure data container NAME.\"\"\" try: config", "sds.unmount(config, name) except (sds.ContainerError, sds.GCFSError, sds.ConfigError) as err: print(err) main()", "# -*- coding: utf-8 -*- \"\"\"Console script for secure_data_store.\"\"\" import", "utf-8 -*- \"\"\"Console script for secure_data_store.\"\"\" import click from .", "err: print(err) @main.command() @click.argument('name') @click.option('--config', help='Path to config file', default='~/.sdsrc')", "= sds.read_config(config) sds.mount(config, name) except (sds.ContainerError, sds.GCFSError, sds.ConfigError, sds.MountError) as", "print(err) @main.command() @click.argument('name') @click.option('--config', help='Path to config file', default='~/.sdsrc') def", "file', default='~/.sdsrc') def close(name, config=None): \"\"\"Close an opend data container", "try: config = sds.read_config(config) sds.create(config, name) except (sds.ContainerError, sds.GCFSError, FileExistsError,", "config file', default='~/.sdsrc') def create(name, config=None): \"\"\"Create a new secure", "def close(name, config=None): \"\"\"Close an opend data container NAME.\"\"\" try:", "<reponame>HumanBrainProject/secure-data-store # -*- coding: utf-8 -*- \"\"\"Console script for secure_data_store.\"\"\"", "sds.ConfigError) as err: print(err) @main.command() @click.argument('name') @click.option('--config', help='Path to config", "opend data container NAME.\"\"\" try: config = sds.read_config(config) sds.unmount(config, name)", "sds.GCFSError, FileExistsError, sds.ConfigError) as err: print(err) @main.command() @click.argument('name') @click.option('--config', help='Path", "a new secure data container NAME.\"\"\" try: config = sds.read_config(config)", "(sds.ContainerError, sds.GCFSError, FileExistsError, sds.ConfigError) as err: print(err) @main.command() @click.argument('name') @click.option('--config',", "config file', default='~/.sdsrc') def open(name, config=None): \"\"\"Open an existing secure", "import secure_data_store as sds CONFIG='~/.sdsrc' @click.group() def main(): \"\"\"Wrapper for", "to config file', default='~/.sdsrc') def open(name, config=None): \"\"\"Open an existing", "@click.option('--config', help='Path to config file', default='~/.sdsrc') def create(name, config=None): \"\"\"Create", "click from . import secure_data_store as sds CONFIG='~/.sdsrc' @click.group() def", "data container NAME.\"\"\" try: config = sds.read_config(config) sds.create(config, name) except", "container NAME.\"\"\" try: config = sds.read_config(config) sds.unmount(config, name) except (sds.ContainerError,", "-*- \"\"\"Console script for secure_data_store.\"\"\" import click from . import", "to config file', default='~/.sdsrc') def create(name, config=None): \"\"\"Create a new", "\"\"\"Create a new secure data container NAME.\"\"\" try: config =", "except (sds.ContainerError, sds.GCFSError, FileExistsError, sds.ConfigError) as err: print(err) @main.command() @click.argument('name')", "clear-text container.\"\"\" try: config = sds.read_config(config) sds.mount(config, name) except (sds.ContainerError,", "default='~/.sdsrc') def close(name, config=None): \"\"\"Close an opend data container NAME.\"\"\"", "secure data container NAME. Will print path to the opened,", "container.\"\"\" try: config = sds.read_config(config) sds.mount(config, name) except (sds.ContainerError, sds.GCFSError,", "@main.command() @click.argument('name') @click.option('--config', help='Path to config file', default='~/.sdsrc') def close(name,", "config=None): \"\"\"Close an opend data container NAME.\"\"\" try: config =", "@click.argument('name') @click.option('--config', help='Path to config file', default='~/.sdsrc') def create(name, config=None):", "try: config = sds.read_config(config) sds.mount(config, name) except (sds.ContainerError, sds.GCFSError, sds.ConfigError,", "script for secure_data_store.\"\"\" import click from . import secure_data_store as", "-*- coding: utf-8 -*- \"\"\"Console script for secure_data_store.\"\"\" import click", "an opend data container NAME.\"\"\" try: config = sds.read_config(config) sds.unmount(config,", "to config file', default='~/.sdsrc') def close(name, config=None): \"\"\"Close an opend", "new secure data container NAME.\"\"\" try: config = sds.read_config(config) sds.create(config,", "sds.create(config, name) except (sds.ContainerError, sds.GCFSError, FileExistsError, sds.ConfigError) as err: print(err)", "sds.GCFSError, sds.ConfigError, sds.MountError) as err: print(err) @main.command() @click.argument('name') @click.option('--config', help='Path", "data container NAME.\"\"\" try: config = sds.read_config(config) sds.unmount(config, name) except", "def create(name, config=None): \"\"\"Create a new secure data container NAME.\"\"\"", "except (sds.ContainerError, sds.GCFSError, sds.ConfigError, sds.MountError) as err: print(err) @main.command() @click.argument('name')", "sds.ConfigError, sds.MountError) as err: print(err) @main.command() @click.argument('name') @click.option('--config', help='Path to", "import click from . import secure_data_store as sds CONFIG='~/.sdsrc' @click.group()", "file', default='~/.sdsrc') def create(name, config=None): \"\"\"Create a new secure data" ]
[ "Institute of Technology # (C) 1998-2003 All Rights Reserved #", "of Technology # (C) 1998-2003 All Rights Reserved # #", "None, \"fontsize\" : None, \"height\" : None, \"label\" : None,", "self._id = id return _validAttributes = { \"color\" : None,", "Reserved # # <LicenseText> # # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # from Drawable", ": None, \"shapefile\" : None, \"style\" : None, \"width\" :", "# version __id__ = \"$Id$\" # # End of file", "\"width\" : None } # version __id__ = \"$Id$\" #", "return self._id def __init__(self, id): Drawable.__init__(self) self._id = id return", "\"style\" : None, \"width\" : None } # version __id__", "\"\"\"return a list of valid attributes for Node\"\"\" return Node._validAttributes.keys()", "None, \"shapefile\" : None, \"style\" : None, \"width\" : None", "# California Institute of Technology # (C) 1998-2003 All Rights", "<LicenseText> # # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # from Drawable import Drawable def", "None } # version __id__ = \"$Id$\" # # End", "id(self): return self._id def __init__(self, id): Drawable.__init__(self) self._id = id", "{ \"color\" : None, \"fontcolor\" : None, \"fontname\" : None,", ": None, \"fontsize\" : None, \"height\" : None, \"label\" :", "self._id def __init__(self, id): Drawable.__init__(self) self._id = id return _validAttributes", "# # <LicenseText> # # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # from Drawable import", "} # version __id__ = \"$Id$\" # # End of", "Rights Reserved # # <LicenseText> # # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # from", ": None, \"shape\" : None, \"shapefile\" : None, \"style\" :", ": None, \"fontcolor\" : None, \"fontname\" : None, \"fontsize\" :", "# <LicenseText> # # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # from Drawable import Drawable", "California Institute of Technology # (C) 1998-2003 All Rights Reserved", "#!/usr/bin/env python # # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # # <NAME> # California", "id): Drawable.__init__(self) self._id = id return _validAttributes = { \"color\"", "None, \"label\" : None, \"layer\" : None, \"shape\" : None,", "None, \"fontcolor\" : None, \"fontname\" : None, \"fontsize\" : None,", "return Node._validAttributes.keys() class Node(Drawable): def id(self): return self._id def __init__(self,", "None, \"layer\" : None, \"shape\" : None, \"shapefile\" : None,", "_validAttributes = { \"color\" : None, \"fontcolor\" : None, \"fontname\"", "\"label\" : None, \"layer\" : None, \"shape\" : None, \"shapefile\"", "All Rights Reserved # # <LicenseText> # # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #", "\"color\" : None, \"fontcolor\" : None, \"fontname\" : None, \"fontsize\"", ": None, \"height\" : None, \"label\" : None, \"layer\" :", "# # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # # <NAME> # California Institute of", "Drawable import Drawable def nodeAttributes(): \"\"\"return a list of valid", "a list of valid attributes for Node\"\"\" return Node._validAttributes.keys() class", "1998-2003 All Rights Reserved # # <LicenseText> # # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~", "id return _validAttributes = { \"color\" : None, \"fontcolor\" :", "= id return _validAttributes = { \"color\" : None, \"fontcolor\"", "def nodeAttributes(): \"\"\"return a list of valid attributes for Node\"\"\"", "# <NAME> # California Institute of Technology # (C) 1998-2003", "attributes for Node\"\"\" return Node._validAttributes.keys() class Node(Drawable): def id(self): return", "return _validAttributes = { \"color\" : None, \"fontcolor\" : None,", "Node(Drawable): def id(self): return self._id def __init__(self, id): Drawable.__init__(self) self._id", "\"shape\" : None, \"shapefile\" : None, \"style\" : None, \"width\"", "for Node\"\"\" return Node._validAttributes.keys() class Node(Drawable): def id(self): return self._id", "Node._validAttributes.keys() class Node(Drawable): def id(self): return self._id def __init__(self, id):", "\"shapefile\" : None, \"style\" : None, \"width\" : None }", "None, \"shape\" : None, \"shapefile\" : None, \"style\" : None,", ": None, \"style\" : None, \"width\" : None } #", "# # <NAME> # California Institute of Technology # (C)", "class Node(Drawable): def id(self): return self._id def __init__(self, id): Drawable.__init__(self)", "None, \"style\" : None, \"width\" : None } # version", "# (C) 1998-2003 All Rights Reserved # # <LicenseText> #", "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # # <NAME> # California Institute of Technology #", "Node\"\"\" return Node._validAttributes.keys() class Node(Drawable): def id(self): return self._id def", "Drawable.__init__(self) self._id = id return _validAttributes = { \"color\" :", "\"height\" : None, \"label\" : None, \"layer\" : None, \"shape\"", "= { \"color\" : None, \"fontcolor\" : None, \"fontname\" :", "Technology # (C) 1998-2003 All Rights Reserved # # <LicenseText>", "<NAME> # California Institute of Technology # (C) 1998-2003 All", "None, \"fontname\" : None, \"fontsize\" : None, \"height\" : None,", "# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # from Drawable import Drawable def nodeAttributes(): \"\"\"return", "# from Drawable import Drawable def nodeAttributes(): \"\"\"return a list", "\"layer\" : None, \"shape\" : None, \"shapefile\" : None, \"style\"", ": None, \"label\" : None, \"layer\" : None, \"shape\" :", "(C) 1998-2003 All Rights Reserved # # <LicenseText> # #", "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # from Drawable import Drawable def nodeAttributes(): \"\"\"return a", "# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # # <NAME> # California Institute of Technology", "import Drawable def nodeAttributes(): \"\"\"return a list of valid attributes", "valid attributes for Node\"\"\" return Node._validAttributes.keys() class Node(Drawable): def id(self):", "__init__(self, id): Drawable.__init__(self) self._id = id return _validAttributes = {", ": None, \"fontname\" : None, \"fontsize\" : None, \"height\" :", "\"fontname\" : None, \"fontsize\" : None, \"height\" : None, \"label\"", "nodeAttributes(): \"\"\"return a list of valid attributes for Node\"\"\" return", "def __init__(self, id): Drawable.__init__(self) self._id = id return _validAttributes =", "\"fontcolor\" : None, \"fontname\" : None, \"fontsize\" : None, \"height\"", "\"fontsize\" : None, \"height\" : None, \"label\" : None, \"layer\"", ": None, \"width\" : None } # version __id__ =", ": None } # version __id__ = \"$Id$\" # #", ": None, \"layer\" : None, \"shape\" : None, \"shapefile\" :", "from Drawable import Drawable def nodeAttributes(): \"\"\"return a list of", "def id(self): return self._id def __init__(self, id): Drawable.__init__(self) self._id =", "Drawable def nodeAttributes(): \"\"\"return a list of valid attributes for", "list of valid attributes for Node\"\"\" return Node._validAttributes.keys() class Node(Drawable):", "None, \"width\" : None } # version __id__ = \"$Id$\"", "None, \"height\" : None, \"label\" : None, \"layer\" : None,", "# # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # from Drawable import Drawable def nodeAttributes():", "python # # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # # <NAME> # California Institute", "of valid attributes for Node\"\"\" return Node._validAttributes.keys() class Node(Drawable): def" ]
[ "'#fcd9c8' elif (riskScore == 3): return '#f7ac91' elif (riskScore ==", "b.dbProxy self.dpi = 100 self.fig = Figure((5.0, 4.0), dpi=self.dpi) self.canvas", "self.dbProxy.getDimensionNames('environment') self.envCombo = wx.ComboBox(self,RISKSCATTER_COMBOENVIRONMENT_ID,envs[0],choices=envs,size=(300,-1),style=wx.CB_DROPDOWN) self.envCombo.Bind(wx.EVT_COMBOBOX,self.onEnvironmentChange) self.vbox = wx.BoxSizer(wx.VERTICAL) self.vbox.Add(self.toolbar, 0,", "OF ANY # KIND, either express or implied. See the", "return '#e42626' elif (riskScore == 7): return '#b9051a' elif (riskScore", "more contributor license agreements. See the NOTICE file # distributed", "drawScatter(self,envName): self.axes.clear() self.axes.grid(True) self.axes.set_xlabel('Severity') self.axes.set_ylabel('Likelihood') self.axes.set_xbound(0,4) self.axes.set_ybound(0,5) xs,ys,cs = self.dbProxy.riskScatter(envName)", "Apache Software Foundation (ASF) under one # or more contributor", "(riskScore == 2): return '#fcd9c8' elif (riskScore == 3): return", "WARRANTIES OR CONDITIONS OF ANY # KIND, either express or", "b = Borg() self.dbProxy = b.dbProxy self.dpi = 100 self.fig", "import matplotlib matplotlib.use('WXAgg') from matplotlib.figure import Figure from matplotlib.backends.backend_wxagg import", "> 0)): self.axes.scatter(xs,ys,c=ccs,marker='d') self.canvas.draw() def onEnvironmentChange(self,evt): envName = self.envCombo.GetStringSelection() self.drawScatter(envName)", "event): fileChoices = \"PNG (*.png)|*.png\" dlg = wx.FileDialog(self,message=\"Save risk scatter\",defaultDir=os.getcwd(),defaultFile=\"scatter.png\",wildcard=fileChoices,style=wx.SAVE)", "2.0 (the # \"License\"); you may not use this file", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "8): return '#900014' else: return '#52000D' class RiskScatterPanel(wx.Panel): def __init__(self,parent):", "(len(ys) > 0)): self.axes.scatter(xs,ys,c=ccs,marker='d') self.canvas.draw() def onEnvironmentChange(self,evt): envName = self.envCombo.GetStringSelection()", "specific language governing permissions and limitations # under the License.", "under the License is distributed on an # \"AS IS\"", "== 4): return '#f67e61' elif (riskScore == 5): return '#f2543d'", "BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either", "= self.dbProxy.getDimensionNames('environment') self.envCombo = wx.ComboBox(self,RISKSCATTER_COMBOENVIRONMENT_ID,envs[0],choices=envs,size=(300,-1),style=wx.CB_DROPDOWN) self.envCombo.Bind(wx.EVT_COMBOBOX,self.onEnvironmentChange) self.vbox = wx.BoxSizer(wx.VERTICAL) self.vbox.Add(self.toolbar,", "\"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY #", "0) and (len(ys) > 0)): self.axes.scatter(xs,ys,c=ccs,marker='d') self.canvas.draw() def onEnvironmentChange(self,evt): envName", "matplotlib matplotlib.use('WXAgg') from matplotlib.figure import Figure from matplotlib.backends.backend_wxagg import \\", "distributed with this work for additional information # regarding copyright", "elif (riskScore == 6): return '#e42626' elif (riskScore == 7):", "for the # specific language governing permissions and limitations #", "= [] for c in cs: ccs.append(riskColourCode(c)) if ((len(xs) >", "FigCanvas(self, -1, self.fig) self.axes = self.fig.add_subplot(111,xlabel='Severity',ylabel='Likelihood',autoscale_on=False) self.axes.set_xticklabels(['Marginal','Critical','Catastrophic']) self.axes.set_yticks([0,1,2,3,4,5]) self.toolbar =", "See the License for the # specific language governing permissions", "to in writing, # software distributed under the License is", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "import os import pprint import random import wx from cairis.core.armid", "return '#b9051a' elif (riskScore == 8): return '#900014' else: return", "__init__(self,parent): wx.Panel.__init__(self,parent,RISKSCATTER_ID) b = Borg() self.dbProxy = b.dbProxy self.dpi =", "== 2): return '#fcd9c8' elif (riskScore == 3): return '#f7ac91'", "the License. import os import pprint import random import wx", "file # distributed with this work for additional information #", "self.envCombo.Bind(wx.EVT_COMBOBOX,self.onEnvironmentChange) self.vbox = wx.BoxSizer(wx.VERTICAL) self.vbox.Add(self.toolbar, 0, wx.EXPAND) self.vbox.Add(self.envCombo,0, wx.EXPAND) self.vbox.Add(self.canvas,", "import \\ FigureCanvasWxAgg as FigCanvas, \\ NavigationToolbar2WxAgg as NavigationToolbar def", "= wx.BoxSizer(wx.VERTICAL) self.vbox.Add(self.toolbar, 0, wx.EXPAND) self.vbox.Add(self.envCombo,0, wx.EXPAND) self.vbox.Add(self.canvas, 1, wx.LEFT", "== 6): return '#e42626' elif (riskScore == 7): return '#b9051a'", "self.axes.scatter(xs,ys,c=ccs,marker='d') self.canvas.draw() def onEnvironmentChange(self,evt): envName = self.envCombo.GetStringSelection() self.drawScatter(envName) def on_save_plot(self,", "permissions and limitations # under the License. import os import", "ccs.append(riskColourCode(c)) if ((len(xs) > 0) and (len(ys) > 0)): self.axes.scatter(xs,ys,c=ccs,marker='d')", "implied. See the License for the # specific language governing", "to you under the Apache License, Version 2.0 (the #", "= wx.ComboBox(self,RISKSCATTER_COMBOENVIRONMENT_ID,envs[0],choices=envs,size=(300,-1),style=wx.CB_DROPDOWN) self.envCombo.Bind(wx.EVT_COMBOBOX,self.onEnvironmentChange) self.vbox = wx.BoxSizer(wx.VERTICAL) self.vbox.Add(self.toolbar, 0, wx.EXPAND) self.vbox.Add(self.envCombo,0,", "pprint import random import wx from cairis.core.armid import * from", "may not use this file except in compliance # with", "self.dbProxy = b.dbProxy self.dpi = 100 self.fig = Figure((5.0, 4.0),", "7): return '#b9051a' elif (riskScore == 8): return '#900014' else:", "def __init__(self,parent): wx.Panel.__init__(self,parent,RISKSCATTER_ID) b = Borg() self.dbProxy = b.dbProxy self.dpi", "(riskScore == 3): return '#f7ac91' elif (riskScore == 4): return", "cs: ccs.append(riskColourCode(c)) if ((len(xs) > 0) and (len(ys) > 0)):", "License, Version 2.0 (the # \"License\"); you may not use", "self.vbox.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW) self.SetSizer(self.vbox) self.vbox.Fit(self) self.drawScatter(envs[0])", "either express or implied. See the License for the #", "scatter\",defaultDir=os.getcwd(),defaultFile=\"scatter.png\",wildcard=fileChoices,style=wx.SAVE) if dlg.ShowModal() == wx.ID_OK: path = dlg.GetPath() self.canvas.print_figure(path, dpi=self.dpi)", "= wx.FileDialog(self,message=\"Save risk scatter\",defaultDir=os.getcwd(),defaultFile=\"scatter.png\",wildcard=fileChoices,style=wx.SAVE) if dlg.ShowModal() == wx.ID_OK: path =", "additional information # regarding copyright ownership. The ASF licenses this", "if ((len(xs) > 0) and (len(ys) > 0)): self.axes.scatter(xs,ys,c=ccs,marker='d') self.canvas.draw()", "self.axes.set_xbound(0,4) self.axes.set_ybound(0,5) xs,ys,cs = self.dbProxy.riskScatter(envName) ccs = [] for c", "See the NOTICE file # distributed with this work for", "| wx.GROW) self.SetSizer(self.vbox) self.vbox.Fit(self) self.drawScatter(envs[0]) def drawScatter(self,envName): self.axes.clear() self.axes.grid(True) self.axes.set_xlabel('Severity')", "| wx.TOP | wx.GROW) self.SetSizer(self.vbox) self.vbox.Fit(self) self.drawScatter(envs[0]) def drawScatter(self,envName): self.axes.clear()", "Apache License, Version 2.0 (the # \"License\"); you may not", "6): return '#e42626' elif (riskScore == 7): return '#b9051a' elif", "wx from cairis.core.armid import * from cairis.core.Borg import Borg import", "self.vbox = wx.BoxSizer(wx.VERTICAL) self.vbox.Add(self.toolbar, 0, wx.EXPAND) self.vbox.Add(self.envCombo,0, wx.EXPAND) self.vbox.Add(self.canvas, 1,", "'#f67e61' elif (riskScore == 5): return '#f2543d' elif (riskScore ==", "'#900014' else: return '#52000D' class RiskScatterPanel(wx.Panel): def __init__(self,parent): wx.Panel.__init__(self,parent,RISKSCATTER_ID) b", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "file except in compliance # with the License. You may", "self.axes.set_ybound(0,5) xs,ys,cs = self.dbProxy.riskScatter(envName) ccs = [] for c in", "# specific language governing permissions and limitations # under the", "0)): self.axes.scatter(xs,ys,c=ccs,marker='d') self.canvas.draw() def onEnvironmentChange(self,evt): envName = self.envCombo.GetStringSelection() self.drawScatter(envName) def", "you may not use this file except in compliance #", "use this file except in compliance # with the License.", "elif (riskScore == 4): return '#f67e61' elif (riskScore == 5):", "xs,ys,cs = self.dbProxy.riskScatter(envName) ccs = [] for c in cs:", "Borg import matplotlib matplotlib.use('WXAgg') from matplotlib.figure import Figure from matplotlib.backends.backend_wxagg", "4.0), dpi=self.dpi) self.canvas = FigCanvas(self, -1, self.fig) self.axes = self.fig.add_subplot(111,xlabel='Severity',ylabel='Likelihood',autoscale_on=False)", "contributor license agreements. See the NOTICE file # distributed with", "elif (riskScore == 5): return '#f2543d' elif (riskScore == 6):", "def onEnvironmentChange(self,evt): envName = self.envCombo.GetStringSelection() self.drawScatter(envName) def on_save_plot(self, event): fileChoices", "os import pprint import random import wx from cairis.core.armid import", "import * from cairis.core.Borg import Borg import matplotlib matplotlib.use('WXAgg') from", "an # \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF", "elif (riskScore == 2): return '#fcd9c8' elif (riskScore == 3):", "self.canvas.draw() def onEnvironmentChange(self,evt): envName = self.envCombo.GetStringSelection() self.drawScatter(envName) def on_save_plot(self, event):", "WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express", "return '#900014' else: return '#52000D' class RiskScatterPanel(wx.Panel): def __init__(self,parent): wx.Panel.__init__(self,parent,RISKSCATTER_ID)", "(riskScore == 8): return '#900014' else: return '#52000D' class RiskScatterPanel(wx.Panel):", "with this work for additional information # regarding copyright ownership.", "and limitations # under the License. import os import pprint", "self.drawScatter(envName) def on_save_plot(self, event): fileChoices = \"PNG (*.png)|*.png\" dlg =", "work for additional information # regarding copyright ownership. The ASF", "distributed under the License is distributed on an # \"AS", "return '#fcd9c8' elif (riskScore == 3): return '#f7ac91' elif (riskScore", "# software distributed under the License is distributed on an", "-1, self.fig) self.axes = self.fig.add_subplot(111,xlabel='Severity',ylabel='Likelihood',autoscale_on=False) self.axes.set_xticklabels(['Marginal','Critical','Catastrophic']) self.axes.set_yticks([0,1,2,3,4,5]) self.toolbar = NavigationToolbar(self.canvas)", "under the License. import os import pprint import random import", "the License. You may obtain a copy of the License", "risk scatter\",defaultDir=os.getcwd(),defaultFile=\"scatter.png\",wildcard=fileChoices,style=wx.SAVE) if dlg.ShowModal() == wx.ID_OK: path = dlg.GetPath() self.canvas.print_figure(path,", "cairis.core.armid import * from cairis.core.Borg import Borg import matplotlib matplotlib.use('WXAgg')", "== 8): return '#900014' else: return '#52000D' class RiskScatterPanel(wx.Panel): def", "under the Apache License, Version 2.0 (the # \"License\"); you", "distributed on an # \"AS IS\" BASIS, WITHOUT WARRANTIES OR", "regarding copyright ownership. The ASF licenses this file # to", "or agreed to in writing, # software distributed under the", "== 7): return '#b9051a' elif (riskScore == 8): return '#900014'", "* from cairis.core.Borg import Borg import matplotlib matplotlib.use('WXAgg') from matplotlib.figure", "NavigationToolbar def riskColourCode(riskScore): if (riskScore <= 1): return '#fef2ec' elif", "self.fig.add_subplot(111,xlabel='Severity',ylabel='Likelihood',autoscale_on=False) self.axes.set_xticklabels(['Marginal','Critical','Catastrophic']) self.axes.set_yticks([0,1,2,3,4,5]) self.toolbar = NavigationToolbar(self.canvas) envs = self.dbProxy.getDimensionNames('environment') self.envCombo", "or more contributor license agreements. See the NOTICE file #", "this work for additional information # regarding copyright ownership. The", "the NOTICE file # distributed with this work for additional", "= self.envCombo.GetStringSelection() self.drawScatter(envName) def on_save_plot(self, event): fileChoices = \"PNG (*.png)|*.png\"", "self.axes.grid(True) self.axes.set_xlabel('Severity') self.axes.set_ylabel('Likelihood') self.axes.set_xbound(0,4) self.axes.set_ybound(0,5) xs,ys,cs = self.dbProxy.riskScatter(envName) ccs =", "'#f7ac91' elif (riskScore == 4): return '#f67e61' elif (riskScore ==", "random import wx from cairis.core.armid import * from cairis.core.Borg import", "(*.png)|*.png\" dlg = wx.FileDialog(self,message=\"Save risk scatter\",defaultDir=os.getcwd(),defaultFile=\"scatter.png\",wildcard=fileChoices,style=wx.SAVE) if dlg.ShowModal() == wx.ID_OK:", "\\ FigureCanvasWxAgg as FigCanvas, \\ NavigationToolbar2WxAgg as NavigationToolbar def riskColourCode(riskScore):", "cairis.core.Borg import Borg import matplotlib matplotlib.use('WXAgg') from matplotlib.figure import Figure", "from cairis.core.armid import * from cairis.core.Borg import Borg import matplotlib", "KIND, either express or implied. See the License for the", "wx.GROW) self.SetSizer(self.vbox) self.vbox.Fit(self) self.drawScatter(envs[0]) def drawScatter(self,envName): self.axes.clear() self.axes.grid(True) self.axes.set_xlabel('Severity') self.axes.set_ylabel('Likelihood')", "== 5): return '#f2543d' elif (riskScore == 6): return '#e42626'", "return '#f2543d' elif (riskScore == 6): return '#e42626' elif (riskScore", "if (riskScore <= 1): return '#fef2ec' elif (riskScore == 2):", "from matplotlib.figure import Figure from matplotlib.backends.backend_wxagg import \\ FigureCanvasWxAgg as", "or implied. See the License for the # specific language", "# under the License. import os import pprint import random", "express or implied. See the License for the # specific", "limitations # under the License. import os import pprint import", "the # specific language governing permissions and limitations # under", "dpi=self.dpi) self.canvas = FigCanvas(self, -1, self.fig) self.axes = self.fig.add_subplot(111,xlabel='Severity',ylabel='Likelihood',autoscale_on=False) self.axes.set_xticklabels(['Marginal','Critical','Catastrophic'])", "may obtain a copy of the License at # #", "The ASF licenses this file # to you under the", "self.vbox.Add(self.toolbar, 0, wx.EXPAND) self.vbox.Add(self.envCombo,0, wx.EXPAND) self.vbox.Add(self.canvas, 1, wx.LEFT | wx.TOP", "# Licensed to the Apache Software Foundation (ASF) under one", "self.fig = Figure((5.0, 4.0), dpi=self.dpi) self.canvas = FigCanvas(self, -1, self.fig)", "<= 1): return '#fef2ec' elif (riskScore == 2): return '#fcd9c8'", "return '#52000D' class RiskScatterPanel(wx.Panel): def __init__(self,parent): wx.Panel.__init__(self,parent,RISKSCATTER_ID) b = Borg()", "elif (riskScore == 7): return '#b9051a' elif (riskScore == 8):", "law or agreed to in writing, # software distributed under", "Foundation (ASF) under one # or more contributor license agreements.", "return '#f7ac91' elif (riskScore == 4): return '#f67e61' elif (riskScore", "self.axes.set_yticks([0,1,2,3,4,5]) self.toolbar = NavigationToolbar(self.canvas) envs = self.dbProxy.getDimensionNames('environment') self.envCombo = wx.ComboBox(self,RISKSCATTER_COMBOENVIRONMENT_ID,envs[0],choices=envs,size=(300,-1),style=wx.CB_DROPDOWN)", "onEnvironmentChange(self,evt): envName = self.envCombo.GetStringSelection() self.drawScatter(envName) def on_save_plot(self, event): fileChoices =", "and (len(ys) > 0)): self.axes.scatter(xs,ys,c=ccs,marker='d') self.canvas.draw() def onEnvironmentChange(self,evt): envName =", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "import Figure from matplotlib.backends.backend_wxagg import \\ FigureCanvasWxAgg as FigCanvas, \\", "Software Foundation (ASF) under one # or more contributor license", "3): return '#f7ac91' elif (riskScore == 4): return '#f67e61' elif", "= 100 self.fig = Figure((5.0, 4.0), dpi=self.dpi) self.canvas = FigCanvas(self,", "# regarding copyright ownership. The ASF licenses this file #", "in compliance # with the License. You may obtain a", "# to you under the Apache License, Version 2.0 (the", "License for the # specific language governing permissions and limitations", "OR CONDITIONS OF ANY # KIND, either express or implied.", "= NavigationToolbar(self.canvas) envs = self.dbProxy.getDimensionNames('environment') self.envCombo = wx.ComboBox(self,RISKSCATTER_COMBOENVIRONMENT_ID,envs[0],choices=envs,size=(300,-1),style=wx.CB_DROPDOWN) self.envCombo.Bind(wx.EVT_COMBOBOX,self.onEnvironmentChange) self.vbox", "Borg() self.dbProxy = b.dbProxy self.dpi = 100 self.fig = Figure((5.0,", "matplotlib.figure import Figure from matplotlib.backends.backend_wxagg import \\ FigureCanvasWxAgg as FigCanvas,", "this file # to you under the Apache License, Version", "2): return '#fcd9c8' elif (riskScore == 3): return '#f7ac91' elif", "import Borg import matplotlib matplotlib.use('WXAgg') from matplotlib.figure import Figure from", "copyright ownership. The ASF licenses this file # to you", "ccs = [] for c in cs: ccs.append(riskColourCode(c)) if ((len(xs)", "NavigationToolbar(self.canvas) envs = self.dbProxy.getDimensionNames('environment') self.envCombo = wx.ComboBox(self,RISKSCATTER_COMBOENVIRONMENT_ID,envs[0],choices=envs,size=(300,-1),style=wx.CB_DROPDOWN) self.envCombo.Bind(wx.EVT_COMBOBOX,self.onEnvironmentChange) self.vbox =", "in writing, # software distributed under the License is distributed", "== 3): return '#f7ac91' elif (riskScore == 4): return '#f67e61'", "wx.ComboBox(self,RISKSCATTER_COMBOENVIRONMENT_ID,envs[0],choices=envs,size=(300,-1),style=wx.CB_DROPDOWN) self.envCombo.Bind(wx.EVT_COMBOBOX,self.onEnvironmentChange) self.vbox = wx.BoxSizer(wx.VERTICAL) self.vbox.Add(self.toolbar, 0, wx.EXPAND) self.vbox.Add(self.envCombo,0, wx.EXPAND)", "RiskScatterPanel(wx.Panel): def __init__(self,parent): wx.Panel.__init__(self,parent,RISKSCATTER_ID) b = Borg() self.dbProxy = b.dbProxy", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "License is distributed on an # \"AS IS\" BASIS, WITHOUT", "= Figure((5.0, 4.0), dpi=self.dpi) self.canvas = FigCanvas(self, -1, self.fig) self.axes", "# \"License\"); you may not use this file except in", "# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY", "to the Apache Software Foundation (ASF) under one # or", "\"License\"); you may not use this file except in compliance", "[] for c in cs: ccs.append(riskColourCode(c)) if ((len(xs) > 0)", "self.dpi = 100 self.fig = Figure((5.0, 4.0), dpi=self.dpi) self.canvas =", "riskColourCode(riskScore): if (riskScore <= 1): return '#fef2ec' elif (riskScore ==", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "# distributed with this work for additional information # regarding", "writing, # software distributed under the License is distributed on", "def on_save_plot(self, event): fileChoices = \"PNG (*.png)|*.png\" dlg = wx.FileDialog(self,message=\"Save", "governing permissions and limitations # under the License. import os", "5): return '#f2543d' elif (riskScore == 6): return '#e42626' elif", "self.axes = self.fig.add_subplot(111,xlabel='Severity',ylabel='Likelihood',autoscale_on=False) self.axes.set_xticklabels(['Marginal','Critical','Catastrophic']) self.axes.set_yticks([0,1,2,3,4,5]) self.toolbar = NavigationToolbar(self.canvas) envs =", "= Borg() self.dbProxy = b.dbProxy self.dpi = 100 self.fig =", "CONDITIONS OF ANY # KIND, either express or implied. See", "envs = self.dbProxy.getDimensionNames('environment') self.envCombo = wx.ComboBox(self,RISKSCATTER_COMBOENVIRONMENT_ID,envs[0],choices=envs,size=(300,-1),style=wx.CB_DROPDOWN) self.envCombo.Bind(wx.EVT_COMBOBOX,self.onEnvironmentChange) self.vbox = wx.BoxSizer(wx.VERTICAL)", "elif (riskScore == 3): return '#f7ac91' elif (riskScore == 4):", "for additional information # regarding copyright ownership. The ASF licenses", "the Apache Software Foundation (ASF) under one # or more", "# # Unless required by applicable law or agreed to", "Version 2.0 (the # \"License\"); you may not use this", "one # or more contributor license agreements. See the NOTICE", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "self.drawScatter(envs[0]) def drawScatter(self,envName): self.axes.clear() self.axes.grid(True) self.axes.set_xlabel('Severity') self.axes.set_ylabel('Likelihood') self.axes.set_xbound(0,4) self.axes.set_ybound(0,5) xs,ys,cs", "except in compliance # with the License. You may obtain", "'#52000D' class RiskScatterPanel(wx.Panel): def __init__(self,parent): wx.Panel.__init__(self,parent,RISKSCATTER_ID) b = Borg() self.dbProxy", "self.vbox.Fit(self) self.drawScatter(envs[0]) def drawScatter(self,envName): self.axes.clear() self.axes.grid(True) self.axes.set_xlabel('Severity') self.axes.set_ylabel('Likelihood') self.axes.set_xbound(0,4) self.axes.set_ybound(0,5)", "NOTICE file # distributed with this work for additional information", "this file except in compliance # with the License. You", "FigCanvas, \\ NavigationToolbar2WxAgg as NavigationToolbar def riskColourCode(riskScore): if (riskScore <=", "self.axes.set_xticklabels(['Marginal','Critical','Catastrophic']) self.axes.set_yticks([0,1,2,3,4,5]) self.toolbar = NavigationToolbar(self.canvas) envs = self.dbProxy.getDimensionNames('environment') self.envCombo =", "license agreements. See the NOTICE file # distributed with this", "required by applicable law or agreed to in writing, #", "self.axes.set_xlabel('Severity') self.axes.set_ylabel('Likelihood') self.axes.set_xbound(0,4) self.axes.set_ybound(0,5) xs,ys,cs = self.dbProxy.riskScatter(envName) ccs = []", "wx.TOP | wx.GROW) self.SetSizer(self.vbox) self.vbox.Fit(self) self.drawScatter(envs[0]) def drawScatter(self,envName): self.axes.clear() self.axes.grid(True)", "for c in cs: ccs.append(riskColourCode(c)) if ((len(xs) > 0) and", "on_save_plot(self, event): fileChoices = \"PNG (*.png)|*.png\" dlg = wx.FileDialog(self,message=\"Save risk", "from cairis.core.Borg import Borg import matplotlib matplotlib.use('WXAgg') from matplotlib.figure import", "4): return '#f67e61' elif (riskScore == 5): return '#f2543d' elif", "self.axes.set_ylabel('Likelihood') self.axes.set_xbound(0,4) self.axes.set_ybound(0,5) xs,ys,cs = self.dbProxy.riskScatter(envName) ccs = [] for", "License. import os import pprint import random import wx from", "the License for the # specific language governing permissions and", "= FigCanvas(self, -1, self.fig) self.axes = self.fig.add_subplot(111,xlabel='Severity',ylabel='Likelihood',autoscale_on=False) self.axes.set_xticklabels(['Marginal','Critical','Catastrophic']) self.axes.set_yticks([0,1,2,3,4,5]) self.toolbar", "(riskScore == 6): return '#e42626' elif (riskScore == 7): return", "ANY # KIND, either express or implied. See the License", "the License is distributed on an # \"AS IS\" BASIS,", "self.envCombo.GetStringSelection() self.drawScatter(envName) def on_save_plot(self, event): fileChoices = \"PNG (*.png)|*.png\" dlg", "import wx from cairis.core.armid import * from cairis.core.Borg import Borg", "self.fig) self.axes = self.fig.add_subplot(111,xlabel='Severity',ylabel='Likelihood',autoscale_on=False) self.axes.set_xticklabels(['Marginal','Critical','Catastrophic']) self.axes.set_yticks([0,1,2,3,4,5]) self.toolbar = NavigationToolbar(self.canvas) envs", "1, wx.LEFT | wx.TOP | wx.GROW) self.SetSizer(self.vbox) self.vbox.Fit(self) self.drawScatter(envs[0]) def", "> 0) and (len(ys) > 0)): self.axes.scatter(xs,ys,c=ccs,marker='d') self.canvas.draw() def onEnvironmentChange(self,evt):", "(riskScore == 5): return '#f2543d' elif (riskScore == 6): return", "self.SetSizer(self.vbox) self.vbox.Fit(self) self.drawScatter(envs[0]) def drawScatter(self,envName): self.axes.clear() self.axes.grid(True) self.axes.set_xlabel('Severity') self.axes.set_ylabel('Likelihood') self.axes.set_xbound(0,4)", "\\ NavigationToolbar2WxAgg as NavigationToolbar def riskColourCode(riskScore): if (riskScore <= 1):", "not use this file except in compliance # with the", "dlg = wx.FileDialog(self,message=\"Save risk scatter\",defaultDir=os.getcwd(),defaultFile=\"scatter.png\",wildcard=fileChoices,style=wx.SAVE) if dlg.ShowModal() == wx.ID_OK: path", "as FigCanvas, \\ NavigationToolbar2WxAgg as NavigationToolbar def riskColourCode(riskScore): if (riskScore", "else: return '#52000D' class RiskScatterPanel(wx.Panel): def __init__(self,parent): wx.Panel.__init__(self,parent,RISKSCATTER_ID) b =", "'#e42626' elif (riskScore == 7): return '#b9051a' elif (riskScore ==", "self.dbProxy.riskScatter(envName) ccs = [] for c in cs: ccs.append(riskColourCode(c)) if", "Unless required by applicable law or agreed to in writing,", "wx.Panel.__init__(self,parent,RISKSCATTER_ID) b = Borg() self.dbProxy = b.dbProxy self.dpi = 100", "((len(xs) > 0) and (len(ys) > 0)): self.axes.scatter(xs,ys,c=ccs,marker='d') self.canvas.draw() def", "(ASF) under one # or more contributor license agreements. See", "wx.FileDialog(self,message=\"Save risk scatter\",defaultDir=os.getcwd(),defaultFile=\"scatter.png\",wildcard=fileChoices,style=wx.SAVE) if dlg.ShowModal() == wx.ID_OK: path = dlg.GetPath()", "self.axes.clear() self.axes.grid(True) self.axes.set_xlabel('Severity') self.axes.set_ylabel('Likelihood') self.axes.set_xbound(0,4) self.axes.set_ybound(0,5) xs,ys,cs = self.dbProxy.riskScatter(envName) ccs", "# or more contributor license agreements. See the NOTICE file", "agreed to in writing, # software distributed under the License", "self.envCombo = wx.ComboBox(self,RISKSCATTER_COMBOENVIRONMENT_ID,envs[0],choices=envs,size=(300,-1),style=wx.CB_DROPDOWN) self.envCombo.Bind(wx.EVT_COMBOBOX,self.onEnvironmentChange) self.vbox = wx.BoxSizer(wx.VERTICAL) self.vbox.Add(self.toolbar, 0, wx.EXPAND)", "'#f2543d' elif (riskScore == 6): return '#e42626' elif (riskScore ==", "c in cs: ccs.append(riskColourCode(c)) if ((len(xs) > 0) and (len(ys)", "'#b9051a' elif (riskScore == 8): return '#900014' else: return '#52000D'", "(riskScore <= 1): return '#fef2ec' elif (riskScore == 2): return", "class RiskScatterPanel(wx.Panel): def __init__(self,parent): wx.Panel.__init__(self,parent,RISKSCATTER_ID) b = Borg() self.dbProxy =", "wx.LEFT | wx.TOP | wx.GROW) self.SetSizer(self.vbox) self.vbox.Fit(self) self.drawScatter(envs[0]) def drawScatter(self,envName):", "self.toolbar = NavigationToolbar(self.canvas) envs = self.dbProxy.getDimensionNames('environment') self.envCombo = wx.ComboBox(self,RISKSCATTER_COMBOENVIRONMENT_ID,envs[0],choices=envs,size=(300,-1),style=wx.CB_DROPDOWN) self.envCombo.Bind(wx.EVT_COMBOBOX,self.onEnvironmentChange)", "def drawScatter(self,envName): self.axes.clear() self.axes.grid(True) self.axes.set_xlabel('Severity') self.axes.set_ylabel('Likelihood') self.axes.set_xbound(0,4) self.axes.set_ybound(0,5) xs,ys,cs =", "(the # \"License\"); you may not use this file except", "matplotlib.use('WXAgg') from matplotlib.figure import Figure from matplotlib.backends.backend_wxagg import \\ FigureCanvasWxAgg", "ASF licenses this file # to you under the Apache", "on an # \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS", "Figure from matplotlib.backends.backend_wxagg import \\ FigureCanvasWxAgg as FigCanvas, \\ NavigationToolbar2WxAgg", "Figure((5.0, 4.0), dpi=self.dpi) self.canvas = FigCanvas(self, -1, self.fig) self.axes =", "ownership. The ASF licenses this file # to you under", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "with the License. You may obtain a copy of the", "100 self.fig = Figure((5.0, 4.0), dpi=self.dpi) self.canvas = FigCanvas(self, -1,", "applicable law or agreed to in writing, # software distributed", "= self.fig.add_subplot(111,xlabel='Severity',ylabel='Likelihood',autoscale_on=False) self.axes.set_xticklabels(['Marginal','Critical','Catastrophic']) self.axes.set_yticks([0,1,2,3,4,5]) self.toolbar = NavigationToolbar(self.canvas) envs = self.dbProxy.getDimensionNames('environment')", "self.vbox.Add(self.envCombo,0, wx.EXPAND) self.vbox.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW) self.SetSizer(self.vbox)", "elif (riskScore == 8): return '#900014' else: return '#52000D' class", "import pprint import random import wx from cairis.core.armid import *", "is distributed on an # \"AS IS\" BASIS, WITHOUT WARRANTIES", "file # to you under the Apache License, Version 2.0", "# with the License. You may obtain a copy of", "1): return '#fef2ec' elif (riskScore == 2): return '#fcd9c8' elif", "(riskScore == 4): return '#f67e61' elif (riskScore == 5): return", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "wx.EXPAND) self.vbox.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW) self.SetSizer(self.vbox) self.vbox.Fit(self)", "(riskScore == 7): return '#b9051a' elif (riskScore == 8): return", "software distributed under the License is distributed on an #", "Licensed to the Apache Software Foundation (ASF) under one #", "wx.EXPAND) self.vbox.Add(self.envCombo,0, wx.EXPAND) self.vbox.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW)", "under one # or more contributor license agreements. See the", "0, wx.EXPAND) self.vbox.Add(self.envCombo,0, wx.EXPAND) self.vbox.Add(self.canvas, 1, wx.LEFT | wx.TOP |", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "FigureCanvasWxAgg as FigCanvas, \\ NavigationToolbar2WxAgg as NavigationToolbar def riskColourCode(riskScore): if", "information # regarding copyright ownership. The ASF licenses this file", "the Apache License, Version 2.0 (the # \"License\"); you may", "in cs: ccs.append(riskColourCode(c)) if ((len(xs) > 0) and (len(ys) >", "= self.dbProxy.riskScatter(envName) ccs = [] for c in cs: ccs.append(riskColourCode(c))", "you under the Apache License, Version 2.0 (the # \"License\");", "= \"PNG (*.png)|*.png\" dlg = wx.FileDialog(self,message=\"Save risk scatter\",defaultDir=os.getcwd(),defaultFile=\"scatter.png\",wildcard=fileChoices,style=wx.SAVE) if dlg.ShowModal()", "# KIND, either express or implied. See the License for", "return '#f67e61' elif (riskScore == 5): return '#f2543d' elif (riskScore", "matplotlib.backends.backend_wxagg import \\ FigureCanvasWxAgg as FigCanvas, \\ NavigationToolbar2WxAgg as NavigationToolbar", "agreements. See the NOTICE file # distributed with this work", "language governing permissions and limitations # under the License. import", "NavigationToolbar2WxAgg as NavigationToolbar def riskColourCode(riskScore): if (riskScore <= 1): return", "fileChoices = \"PNG (*.png)|*.png\" dlg = wx.FileDialog(self,message=\"Save risk scatter\",defaultDir=os.getcwd(),defaultFile=\"scatter.png\",wildcard=fileChoices,style=wx.SAVE) if", "licenses this file # to you under the Apache License,", "\"PNG (*.png)|*.png\" dlg = wx.FileDialog(self,message=\"Save risk scatter\",defaultDir=os.getcwd(),defaultFile=\"scatter.png\",wildcard=fileChoices,style=wx.SAVE) if dlg.ShowModal() ==", "by applicable law or agreed to in writing, # software", "# Unless required by applicable law or agreed to in", "from matplotlib.backends.backend_wxagg import \\ FigureCanvasWxAgg as FigCanvas, \\ NavigationToolbar2WxAgg as", "IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND,", "License. You may obtain a copy of the License at", "= b.dbProxy self.dpi = 100 self.fig = Figure((5.0, 4.0), dpi=self.dpi)", "You may obtain a copy of the License at #", "as NavigationToolbar def riskColourCode(riskScore): if (riskScore <= 1): return '#fef2ec'", "wx.BoxSizer(wx.VERTICAL) self.vbox.Add(self.toolbar, 0, wx.EXPAND) self.vbox.Add(self.envCombo,0, wx.EXPAND) self.vbox.Add(self.canvas, 1, wx.LEFT |", "'#fef2ec' elif (riskScore == 2): return '#fcd9c8' elif (riskScore ==", "envName = self.envCombo.GetStringSelection() self.drawScatter(envName) def on_save_plot(self, event): fileChoices = \"PNG", "self.canvas = FigCanvas(self, -1, self.fig) self.axes = self.fig.add_subplot(111,xlabel='Severity',ylabel='Likelihood',autoscale_on=False) self.axes.set_xticklabels(['Marginal','Critical','Catastrophic']) self.axes.set_yticks([0,1,2,3,4,5])", "compliance # with the License. You may obtain a copy", "import random import wx from cairis.core.armid import * from cairis.core.Borg", "def riskColourCode(riskScore): if (riskScore <= 1): return '#fef2ec' elif (riskScore", "return '#fef2ec' elif (riskScore == 2): return '#fcd9c8' elif (riskScore" ]
[ "if location and not isinstance(location, str): raise TypeError(\"Expected argument 'location'", "__args__, opts=opts, typ=GetRegistryResult).value return AwaitableGetRegistryResult( admin_enabled=__ret__.admin_enabled, admin_password=__ret__.admin_password, admin_username=__ret__.admin_username, id=__ret__.id, location=__ret__.location,", "isinstance(id, str): raise TypeError(\"Expected argument 'id' to be a str\")", "AwaitableGetRegistryResult( admin_enabled=__ret__.admin_enabled, admin_password=__ret__.admin_password, admin_username=__ret__.admin_username, id=__ret__.id, location=__ret__.location, login_server=__ret__.login_server, name=__ret__.name, resource_group_name=__ret__.resource_group_name, sku=__ret__.sku,", "a str\") pulumi.set(__self__, \"admin_password\", <PASSWORD>) if admin_username and not isinstance(admin_username,", "a str\") pulumi.set(__self__, \"admin_username\", admin_username) if id and not isinstance(id,", "managed resource. \"\"\" return pulumi.get(self, \"id\") @property @pulumi.getter def location(self)", "Tool. *** # *** Do not edit by hand unless", "argument 'storage_account_id' to be a str\") pulumi.set(__self__, \"storage_account_id\", storage_account_id) if", "if name and not isinstance(name, str): raise TypeError(\"Expected argument 'name'", "be a str\") pulumi.set(__self__, \"sku\", sku) if storage_account_id and not", "argument 'location' to be a str\") pulumi.set(__self__, \"location\", location) if", "not isinstance(tags, dict): raise TypeError(\"Expected argument 'tags' to be a", "\"name\") @property @pulumi.getter(name=\"resourceGroupName\") def resource_group_name(self) -> str: return pulumi.get(self, \"resource_group_name\")", "of tags assigned to the Container Registry. \"\"\" return pulumi.get(self,", "None: opts = pulumi.InvokeOptions() if opts.version is None: opts.version =", "admin_password=__ret__.admin_password, admin_username=__ret__.admin_username, id=__ret__.id, location=__ret__.location, login_server=__ret__.login_server, name=__ret__.name, resource_group_name=__ret__.resource_group_name, sku=__ret__.sku, storage_account_id=__ret__.storage_account_id, tags=__ret__.tags)", "\"\"\" The ID of the Storage Account used for this", "not isinstance(storage_account_id, str): raise TypeError(\"Expected argument 'storage_account_id' to be a", "TypeError(\"Expected argument 'storage_account_id' to be a str\") pulumi.set(__self__, \"storage_account_id\", storage_account_id)", "admin_enabled) if admin_password and not isinstance(admin_password, str): raise TypeError(\"Expected argument", "a str\") pulumi.set(__self__, \"id\", id) if location and not isinstance(location,", "admin_password(self) -> str: \"\"\" The Password associated with the Container", "is enabled. \"\"\" return pulumi.get(self, \"admin_password\") @property @pulumi.getter(name=\"adminUsername\") def admin_username(self)", "provider-assigned unique ID for this managed resource. \"\"\" return pulumi.get(self,", "pulumi.set(__self__, \"name\", name) if resource_group_name and not isinstance(resource_group_name, str): raise", "'storage_account_id' to be a str\") pulumi.set(__self__, \"storage_account_id\", storage_account_id) if tags", "bool\") pulumi.set(__self__, \"admin_enabled\", admin_enabled) if admin_password and not isinstance(admin_password, str):", "'admin_username' to be a str\") pulumi.set(__self__, \"admin_username\", admin_username) if id", "[ 'GetRegistryResult', 'AwaitableGetRegistryResult', 'get_registry', ] @pulumi.output_type class GetRegistryResult: \"\"\" A", "collection of values returned by getRegistry. \"\"\" def __init__(__self__, admin_enabled=None,", "the Administrator account enabled for this Container Registry. \"\"\" return", "this Container Registry exists. \"\"\" return pulumi.get(self, \"location\") @property @pulumi.getter(name=\"loginServer\")", "@property @pulumi.getter def location(self) -> str: \"\"\" The Azure Region", "storage_account_id(self) -> str: \"\"\" The ID of the Storage Account", "def get_registry(name: Optional[str] = None, resource_group_name: Optional[str] = None, opts:", "this Container Registry exists. \"\"\" __args__ = dict() __args__['name'] =", "if opts is None: opts = pulumi.InvokeOptions() if opts.version is", "TypeError(\"Expected argument 'tags' to be a dict\") pulumi.set(__self__, \"tags\", tags)", "account enabled for this Container Registry. \"\"\" return pulumi.get(self, \"admin_enabled\")", "sku=None, storage_account_id=None, tags=None): if admin_enabled and not isinstance(admin_enabled, bool): raise", "Container Registry. This is only returned for `Classic` SKU's. \"\"\"", "\"admin_enabled\") @property @pulumi.getter(name=\"adminPassword\") def admin_password(self) -> str: \"\"\" The Password", "isinstance(sku, str): raise TypeError(\"Expected argument 'sku' to be a str\")", "pulumi.get(self, \"sku\") @property @pulumi.getter(name=\"storageAccountId\") def storage_account_id(self) -> str: \"\"\" The", "Container Registry. \"\"\" return pulumi.get(self, \"admin_enabled\") @property @pulumi.getter(name=\"adminPassword\") def admin_password(self)", "GetRegistryResult: \"\"\" A collection of values returned by getRegistry. \"\"\"", "pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence,", "name: The name of the Container Registry. :param str resource_group_name:", "@property @pulumi.getter def name(self) -> str: return pulumi.get(self, \"name\") @property", "pulumi.get(self, \"resource_group_name\") @property @pulumi.getter def sku(self) -> str: \"\"\" The", "for this managed resource. \"\"\" return pulumi.get(self, \"id\") @property @pulumi.getter", "def tags(self) -> Mapping[str, str]: \"\"\" A map of tags", "raise TypeError(\"Expected argument 'location' to be a str\") pulumi.set(__self__, \"location\",", "return GetRegistryResult( admin_enabled=self.admin_enabled, admin_password=<PASSWORD>, admin_username=self.admin_username, id=self.id, location=self.location, login_server=self.login_server, name=self.name, resource_group_name=self.resource_group_name,", "TypeError(\"Expected argument 'resource_group_name' to be a str\") pulumi.set(__self__, \"resource_group_name\", resource_group_name)", "account - if the admin account is enabled. \"\"\" return", "Usage ```python import pulumi import pulumi_azure as azure example =", "\"\"\" The SKU of this Container Registry, such as `Basic`.", "be a str\") pulumi.set(__self__, \"login_server\", login_server) if name and not", "return pulumi.get(self, \"sku\") @property @pulumi.getter(name=\"storageAccountId\") def storage_account_id(self) -> str: \"\"\"", "dict() __args__['name'] = name __args__['resourceGroupName'] = resource_group_name if opts is", "@property @pulumi.getter def sku(self) -> str: \"\"\" The SKU of", "this data source to access information about an existing Container", "Registry exists. \"\"\" __args__ = dict() __args__['name'] = name __args__['resourceGroupName']", "The ID of the Storage Account used for this Container", "\"\"\" A collection of values returned by getRegistry. \"\"\" def", "str: return pulumi.get(self, \"name\") @property @pulumi.getter(name=\"resourceGroupName\") def resource_group_name(self) -> str:", "admin_username) if id and not isinstance(id, str): raise TypeError(\"Expected argument", "dict\") pulumi.set(__self__, \"tags\", tags) @property @pulumi.getter(name=\"adminEnabled\") def admin_enabled(self) -> bool:", "The name of the Container Registry. :param str resource_group_name: The", "not isinstance(location, str): raise TypeError(\"Expected argument 'location' to be a", "getRegistry. \"\"\" def __init__(__self__, admin_enabled=None, admin_password=None, admin_username=None, id=None, location=None, login_server=None,", "pulumi.set(__self__, \"location\", location) if login_server and not isinstance(login_server, str): raise", "generated by the Pulumi Terraform Bridge (tfgen) Tool. *** #", "argument 'admin_password' to be a str\") pulumi.set(__self__, \"admin_password\", <PASSWORD>) if", "__init__(__self__, admin_enabled=None, admin_password=None, admin_username=None, id=None, location=None, login_server=None, name=None, resource_group_name=None, sku=None,", "the Container Registry Admin account - if the admin account", "isinstance(admin_password, str): raise TypeError(\"Expected argument 'admin_password' to be a str\")", "def storage_account_id(self) -> str: \"\"\" The ID of the Storage", "argument 'resource_group_name' to be a str\") pulumi.set(__self__, \"resource_group_name\", resource_group_name) if", "pulumi_azure as azure example = azure.containerservice.get_registry(name=\"testacr\", resource_group_name=\"test\") pulumi.export(\"loginServer\", example.login_server) ```", "str: return pulumi.get(self, \"resource_group_name\") @property @pulumi.getter def sku(self) -> str:", "'id' to be a str\") pulumi.set(__self__, \"id\", id) if location", "resource_group_name=None, sku=None, storage_account_id=None, tags=None): if admin_enabled and not isinstance(admin_enabled, bool):", "<PASSWORD>) if admin_username and not isinstance(admin_username, str): raise TypeError(\"Expected argument", "into the container registry. \"\"\" return pulumi.get(self, \"login_server\") @property @pulumi.getter", "-> str: \"\"\" The ID of the Storage Account used", "@pulumi.getter def tags(self) -> Mapping[str, str]: \"\"\" A map of", "def admin_password(self) -> str: \"\"\" The Password associated with the", "to be a str\") pulumi.set(__self__, \"resource_group_name\", resource_group_name) if sku and", "\"\"\" return pulumi.get(self, \"location\") @property @pulumi.getter(name=\"loginServer\") def login_server(self) -> str:", "Container Registry, such as `Basic`. \"\"\" return pulumi.get(self, \"sku\") @property", "The Username associated with the Container Registry Admin account -", "import pulumi import pulumi_azure as azure example = azure.containerservice.get_registry(name=\"testacr\", resource_group_name=\"test\")", "Container Registry. \"\"\" return pulumi.get(self, \"tags\") class AwaitableGetRegistryResult(GetRegistryResult): # pylint:", "not isinstance(id, str): raise TypeError(\"Expected argument 'id' to be a", "def location(self) -> str: \"\"\" The Azure Region in which", "isinstance(resource_group_name, str): raise TypeError(\"Expected argument 'resource_group_name' to be a str\")", "Container Registry exists. \"\"\" return pulumi.get(self, \"location\") @property @pulumi.getter(name=\"loginServer\") def", "pulumi.get(self, \"name\") @property @pulumi.getter(name=\"resourceGroupName\") def resource_group_name(self) -> str: return pulumi.get(self,", "Use this data source to access information about an existing", "if storage_account_id and not isinstance(storage_account_id, str): raise TypeError(\"Expected argument 'storage_account_id'", "str): raise TypeError(\"Expected argument 'name' to be a str\") pulumi.set(__self__,", "Container Registry. :param str resource_group_name: The Name of the Resource", "admin_enabled=None, admin_password=None, admin_username=None, id=None, location=None, login_server=None, name=None, resource_group_name=None, sku=None, storage_account_id=None,", "str: \"\"\" The provider-assigned unique ID for this managed resource.", "\"login_server\", login_server) if name and not isinstance(name, str): raise TypeError(\"Expected", "as azure example = azure.containerservice.get_registry(name=\"testacr\", resource_group_name=\"test\") pulumi.export(\"loginServer\", example.login_server) ``` :param", "-> str: \"\"\" The URL that can be used to", "hand unless you're certain you know what you are doing!", "None, resource_group_name: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) ->", "\"\"\" return pulumi.get(self, \"storage_account_id\") @property @pulumi.getter def tags(self) -> Mapping[str,", "account is enabled. \"\"\" return pulumi.get(self, \"admin_password\") @property @pulumi.getter(name=\"adminUsername\") def", "argument 'tags' to be a dict\") pulumi.set(__self__, \"tags\", tags) @property", "a str\") pulumi.set(__self__, \"name\", name) if resource_group_name and not isinstance(resource_group_name,", "login_server and not isinstance(login_server, str): raise TypeError(\"Expected argument 'login_server' to", "'admin_enabled' to be a bool\") pulumi.set(__self__, \"admin_enabled\", admin_enabled) if admin_password", "@pulumi.getter(name=\"resourceGroupName\") def resource_group_name(self) -> str: return pulumi.get(self, \"resource_group_name\") @property @pulumi.getter", "azure example = azure.containerservice.get_registry(name=\"testacr\", resource_group_name=\"test\") pulumi.export(\"loginServer\", example.login_server) ``` :param str", "\"\"\" __args__ = dict() __args__['name'] = name __args__['resourceGroupName'] = resource_group_name", "unless you're certain you know what you are doing! ***", "this Container Registry. This is only returned for `Classic` SKU's.", "@property @pulumi.getter(name=\"resourceGroupName\") def resource_group_name(self) -> str: return pulumi.get(self, \"resource_group_name\") @property", "that can be used to log into the container registry.", "if sku and not isinstance(sku, str): raise TypeError(\"Expected argument 'sku'", "was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***", "about an existing Container Registry. ## Example Usage ```python import", "used for this Container Registry. This is only returned for", "__args__ = dict() __args__['name'] = name __args__['resourceGroupName'] = resource_group_name if", "admin_enabled=self.admin_enabled, admin_password=<PASSWORD>, admin_username=self.admin_username, id=self.id, location=self.location, login_server=self.login_server, name=self.name, resource_group_name=self.resource_group_name, sku=self.sku, storage_account_id=self.storage_account_id,", "The Name of the Resource Group where this Container Registry", "`Basic`. \"\"\" return pulumi.get(self, \"sku\") @property @pulumi.getter(name=\"storageAccountId\") def storage_account_id(self) ->", "admin_username=None, id=None, location=None, login_server=None, name=None, resource_group_name=None, sku=None, storage_account_id=None, tags=None): if", "opts is None: opts = pulumi.InvokeOptions() if opts.version is None:", "to access information about an existing Container Registry. ## Example", "-> str: \"\"\" The SKU of this Container Registry, such", "str: \"\"\" The Username associated with the Container Registry Admin", "the Container Registry. :param str resource_group_name: The Name of the", "by the Pulumi Terraform Bridge (tfgen) Tool. *** # ***", "str: \"\"\" The ID of the Storage Account used for", "Group where this Container Registry exists. \"\"\" __args__ = dict()", "be a bool\") pulumi.set(__self__, \"admin_enabled\", admin_enabled) if admin_password and not", "existing Container Registry. ## Example Usage ```python import pulumi import", "pulumi.runtime.invoke('azure:containerservice/getRegistry:getRegistry', __args__, opts=opts, typ=GetRegistryResult).value return AwaitableGetRegistryResult( admin_enabled=__ret__.admin_enabled, admin_password=__ret__.admin_password, admin_username=__ret__.admin_username, id=__ret__.id,", "Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not", "Optional[str] = None, resource_group_name: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] =", "and not isinstance(admin_username, str): raise TypeError(\"Expected argument 'admin_username' to be", "\"name\", name) if resource_group_name and not isinstance(resource_group_name, str): raise TypeError(\"Expected", "name __args__['resourceGroupName'] = resource_group_name if opts is None: opts =", "\"sku\", sku) if storage_account_id and not isinstance(storage_account_id, str): raise TypeError(\"Expected", "import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union,", "what you are doing! *** import warnings import pulumi import", "pulumi.get(self, \"id\") @property @pulumi.getter def location(self) -> str: \"\"\" The", "and not isinstance(location, str): raise TypeError(\"Expected argument 'location' to be", "'AwaitableGetRegistryResult', 'get_registry', ] @pulumi.output_type class GetRegistryResult: \"\"\" A collection of", "not isinstance(name, str): raise TypeError(\"Expected argument 'name' to be a", "this Container Registry, such as `Basic`. \"\"\" return pulumi.get(self, \"sku\")", "= None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetRegistryResult: \"\"\" Use", "the Resource Group where this Container Registry exists. \"\"\" __args__", "raise TypeError(\"Expected argument 'name' to be a str\") pulumi.set(__self__, \"name\",", "Region in which this Container Registry exists. \"\"\" return pulumi.get(self,", "opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetRegistryResult: \"\"\" Use this data", "this Container Registry. \"\"\" return pulumi.get(self, \"admin_enabled\") @property @pulumi.getter(name=\"adminPassword\") def", "\"\"\" The Azure Region in which this Container Registry exists.", "opts = pulumi.InvokeOptions() if opts.version is None: opts.version = _utilities.get_version()", "ID for this managed resource. \"\"\" return pulumi.get(self, \"id\") @property", "admin account is enabled. \"\"\" return pulumi.get(self, \"admin_password\") @property @pulumi.getter(name=\"adminUsername\")", "storage_account_id=None, tags=None): if admin_enabled and not isinstance(admin_enabled, bool): raise TypeError(\"Expected", "pulumi.set(__self__, \"storage_account_id\", storage_account_id) if tags and not isinstance(tags, dict): raise", "sku) if storage_account_id and not isinstance(storage_account_id, str): raise TypeError(\"Expected argument", "to be a str\") pulumi.set(__self__, \"location\", location) if login_server and", "if admin_enabled and not isinstance(admin_enabled, bool): raise TypeError(\"Expected argument 'admin_enabled'", "pulumi.export(\"loginServer\", example.login_server) ``` :param str name: The name of the", "pulumi.get(self, \"admin_username\") @property @pulumi.getter def id(self) -> str: \"\"\" The", "and not isinstance(admin_password, str): raise TypeError(\"Expected argument 'admin_password' to be", "TypeError(\"Expected argument 'location' to be a str\") pulumi.set(__self__, \"location\", location)", "dict): raise TypeError(\"Expected argument 'tags' to be a dict\") pulumi.set(__self__,", "to be a str\") pulumi.set(__self__, \"admin_password\", <PASSWORD>) if admin_username and", "id(self) -> str: \"\"\" The provider-assigned unique ID for this", "Registry. \"\"\" return pulumi.get(self, \"tags\") class AwaitableGetRegistryResult(GetRegistryResult): # pylint: disable=using-constant-test", "argument 'sku' to be a str\") pulumi.set(__self__, \"sku\", sku) if", "registry. \"\"\" return pulumi.get(self, \"login_server\") @property @pulumi.getter def name(self) ->", "id) if location and not isinstance(location, str): raise TypeError(\"Expected argument", "the container registry. \"\"\" return pulumi.get(self, \"login_server\") @property @pulumi.getter def", "'resource_group_name' to be a str\") pulumi.set(__self__, \"resource_group_name\", resource_group_name) if sku", "isinstance(login_server, str): raise TypeError(\"Expected argument 'login_server' to be a str\")", "\"admin_password\") @property @pulumi.getter(name=\"adminUsername\") def admin_username(self) -> str: \"\"\" The Username", "# pylint: disable=using-constant-test def __await__(self): if False: yield self return", "and not isinstance(name, str): raise TypeError(\"Expected argument 'name' to be", "str: \"\"\" The SKU of this Container Registry, such as", "str resource_group_name: The Name of the Resource Group where this", "= [ 'GetRegistryResult', 'AwaitableGetRegistryResult', 'get_registry', ] @pulumi.output_type class GetRegistryResult: \"\"\"", "not isinstance(resource_group_name, str): raise TypeError(\"Expected argument 'resource_group_name' to be a", "warnings import pulumi import pulumi.runtime from typing import Any, Mapping,", "@pulumi.getter(name=\"loginServer\") def login_server(self) -> str: \"\"\" The URL that can", "is None: opts.version = _utilities.get_version() __ret__ = pulumi.runtime.invoke('azure:containerservice/getRegistry:getRegistry', __args__, opts=opts,", "admin_username(self) -> str: \"\"\" The Username associated with the Container", "# coding=utf-8 # *** WARNING: this file was generated by", "import warnings import pulumi import pulumi.runtime from typing import Any,", "'location' to be a str\") pulumi.set(__self__, \"location\", location) if login_server", "associated with the Container Registry Admin account - if the", "A map of tags assigned to the Container Registry. \"\"\"", "``` :param str name: The name of the Container Registry.", "import pulumi_azure as azure example = azure.containerservice.get_registry(name=\"testacr\", resource_group_name=\"test\") pulumi.export(\"loginServer\", example.login_server)", "*** import warnings import pulumi import pulumi.runtime from typing import", "def __init__(__self__, admin_enabled=None, admin_password=None, admin_username=None, id=None, location=None, login_server=None, name=None, resource_group_name=None,", "isinstance(location, str): raise TypeError(\"Expected argument 'location' to be a str\")", "\"\"\" return pulumi.get(self, \"admin_enabled\") @property @pulumi.getter(name=\"adminPassword\") def admin_password(self) -> str:", "a str\") pulumi.set(__self__, \"location\", location) if login_server and not isinstance(login_server,", "This is only returned for `Classic` SKU's. \"\"\" return pulumi.get(self,", "\"\"\" The Password associated with the Container Registry Admin account", "a str\") pulumi.set(__self__, \"login_server\", login_server) if name and not isinstance(name,", "is enabled. \"\"\" return pulumi.get(self, \"admin_username\") @property @pulumi.getter def id(self)", "you know what you are doing! *** import warnings import", "TypeError(\"Expected argument 'name' to be a str\") pulumi.set(__self__, \"name\", name)", "Container Registry. ## Example Usage ```python import pulumi import pulumi_azure", "Container Registry exists. \"\"\" __args__ = dict() __args__['name'] = name", "= azure.containerservice.get_registry(name=\"testacr\", resource_group_name=\"test\") pulumi.export(\"loginServer\", example.login_server) ``` :param str name: The", "be a str\") pulumi.set(__self__, \"id\", id) if location and not", "argument 'id' to be a str\") pulumi.set(__self__, \"id\", id) if", "location=self.location, login_server=self.login_server, name=self.name, resource_group_name=self.resource_group_name, sku=self.sku, storage_account_id=self.storage_account_id, tags=self.tags) def get_registry(name: Optional[str]", "import _utilities __all__ = [ 'GetRegistryResult', 'AwaitableGetRegistryResult', 'get_registry', ] @pulumi.output_type", "raise TypeError(\"Expected argument 'admin_enabled' to be a bool\") pulumi.set(__self__, \"admin_enabled\",", "if login_server and not isinstance(login_server, str): raise TypeError(\"Expected argument 'login_server'", "pulumi.get(self, \"storage_account_id\") @property @pulumi.getter def tags(self) -> Mapping[str, str]: \"\"\"", "False: yield self return GetRegistryResult( admin_enabled=self.admin_enabled, admin_password=<PASSWORD>, admin_username=self.admin_username, id=self.id, location=self.location,", "from .. import _utilities __all__ = [ 'GetRegistryResult', 'AwaitableGetRegistryResult', 'get_registry',", "__all__ = [ 'GetRegistryResult', 'AwaitableGetRegistryResult', 'get_registry', ] @pulumi.output_type class GetRegistryResult:", "admin_password and not isinstance(admin_password, str): raise TypeError(\"Expected argument 'admin_password' to", "tags) @property @pulumi.getter(name=\"adminEnabled\") def admin_enabled(self) -> bool: \"\"\" Is the", "storage_account_id=self.storage_account_id, tags=self.tags) def get_registry(name: Optional[str] = None, resource_group_name: Optional[str] =", "returned by getRegistry. \"\"\" def __init__(__self__, admin_enabled=None, admin_password=None, admin_username=None, id=None,", "GetRegistryResult( admin_enabled=self.admin_enabled, admin_password=<PASSWORD>, admin_username=self.admin_username, id=self.id, location=self.location, login_server=self.login_server, name=self.name, resource_group_name=self.resource_group_name, sku=self.sku,", "pulumi.set(__self__, \"id\", id) if location and not isinstance(location, str): raise", "the Storage Account used for this Container Registry. This is", "which this Container Registry exists. \"\"\" return pulumi.get(self, \"location\") @property", "opts=opts, typ=GetRegistryResult).value return AwaitableGetRegistryResult( admin_enabled=__ret__.admin_enabled, admin_password=__ret__.admin_password, admin_username=__ret__.admin_username, id=__ret__.id, location=__ret__.location, login_server=__ret__.login_server,", "pulumi.set(__self__, \"resource_group_name\", resource_group_name) if sku and not isinstance(sku, str): raise", "container registry. \"\"\" return pulumi.get(self, \"login_server\") @property @pulumi.getter def name(self)", "returned for `Classic` SKU's. \"\"\" return pulumi.get(self, \"storage_account_id\") @property @pulumi.getter", "str\") pulumi.set(__self__, \"login_server\", login_server) if name and not isinstance(name, str):", "of values returned by getRegistry. \"\"\" def __init__(__self__, admin_enabled=None, admin_password=None,", "raise TypeError(\"Expected argument 'admin_username' to be a str\") pulumi.set(__self__, \"admin_username\",", "to the Container Registry. \"\"\" return pulumi.get(self, \"tags\") class AwaitableGetRegistryResult(GetRegistryResult):", "= name __args__['resourceGroupName'] = resource_group_name if opts is None: opts", "argument 'admin_username' to be a str\") pulumi.set(__self__, \"admin_username\", admin_username) if", "such as `Basic`. \"\"\" return pulumi.get(self, \"sku\") @property @pulumi.getter(name=\"storageAccountId\") def", "if the admin account is enabled. \"\"\" return pulumi.get(self, \"admin_password\")", "The provider-assigned unique ID for this managed resource. \"\"\" return", "this file was generated by the Pulumi Terraform Bridge (tfgen)", "not isinstance(sku, str): raise TypeError(\"Expected argument 'sku' to be a", "isinstance(admin_enabled, bool): raise TypeError(\"Expected argument 'admin_enabled' to be a bool\")", "if admin_username and not isinstance(admin_username, str): raise TypeError(\"Expected argument 'admin_username'", "*** # *** Do not edit by hand unless you're", "*** Do not edit by hand unless you're certain you", "pulumi.set(__self__, \"admin_enabled\", admin_enabled) if admin_password and not isinstance(admin_password, str): raise", "ID of the Storage Account used for this Container Registry.", "data source to access information about an existing Container Registry.", "tags(self) -> Mapping[str, str]: \"\"\" A map of tags assigned", "be a str\") pulumi.set(__self__, \"storage_account_id\", storage_account_id) if tags and not", "a str\") pulumi.set(__self__, \"sku\", sku) if storage_account_id and not isinstance(storage_account_id,", "\"admin_password\", <PASSWORD>) if admin_username and not isinstance(admin_username, str): raise TypeError(\"Expected", "sku=self.sku, storage_account_id=self.storage_account_id, tags=self.tags) def get_registry(name: Optional[str] = None, resource_group_name: Optional[str]", "example.login_server) ``` :param str name: The name of the Container", "pulumi import pulumi_azure as azure example = azure.containerservice.get_registry(name=\"testacr\", resource_group_name=\"test\") pulumi.export(\"loginServer\",", "@pulumi.getter def location(self) -> str: \"\"\" The Azure Region in", "resource_group_name(self) -> str: return pulumi.get(self, \"resource_group_name\") @property @pulumi.getter def sku(self)", "def login_server(self) -> str: \"\"\" The URL that can be", "= pulumi.InvokeOptions() if opts.version is None: opts.version = _utilities.get_version() __ret__", "@pulumi.getter(name=\"adminPassword\") def admin_password(self) -> str: \"\"\" The Password associated with", "str): raise TypeError(\"Expected argument 'storage_account_id' to be a str\") pulumi.set(__self__,", "if resource_group_name and not isinstance(resource_group_name, str): raise TypeError(\"Expected argument 'resource_group_name'", "an existing Container Registry. ## Example Usage ```python import pulumi", "Storage Account used for this Container Registry. This is only", "'admin_password' to be a str\") pulumi.set(__self__, \"admin_password\", <PASSWORD>) if admin_username", "for this Container Registry. This is only returned for `Classic`", "raise TypeError(\"Expected argument 'resource_group_name' to be a str\") pulumi.set(__self__, \"resource_group_name\",", "\"\"\" The provider-assigned unique ID for this managed resource. \"\"\"", "```python import pulumi import pulumi_azure as azure example = azure.containerservice.get_registry(name=\"testacr\",", "\"admin_username\", admin_username) if id and not isinstance(id, str): raise TypeError(\"Expected", "storage_account_id) if tags and not isinstance(tags, dict): raise TypeError(\"Expected argument", "doing! *** import warnings import pulumi import pulumi.runtime from typing", "str name: The name of the Container Registry. :param str", "@property @pulumi.getter(name=\"adminEnabled\") def admin_enabled(self) -> bool: \"\"\" Is the Administrator", "= dict() __args__['name'] = name __args__['resourceGroupName'] = resource_group_name if opts", "Registry. This is only returned for `Classic` SKU's. \"\"\" return", "be a str\") pulumi.set(__self__, \"location\", location) if login_server and not", "resource. \"\"\" return pulumi.get(self, \"id\") @property @pulumi.getter def location(self) ->", "Account used for this Container Registry. This is only returned", "overload from .. import _utilities __all__ = [ 'GetRegistryResult', 'AwaitableGetRegistryResult',", "@pulumi.getter(name=\"adminEnabled\") def admin_enabled(self) -> bool: \"\"\" Is the Administrator account", "resource_group_name: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetRegistryResult:", "Name of the Resource Group where this Container Registry exists.", "if id and not isinstance(id, str): raise TypeError(\"Expected argument 'id'", "typing import Any, Mapping, Optional, Sequence, Union, overload from ..", "assigned to the Container Registry. \"\"\" return pulumi.get(self, \"tags\") class", "str): raise TypeError(\"Expected argument 'admin_username' to be a str\") pulumi.set(__self__,", "admin_enabled(self) -> bool: \"\"\" Is the Administrator account enabled for", "Registry. :param str resource_group_name: The Name of the Resource Group", "_utilities __all__ = [ 'GetRegistryResult', 'AwaitableGetRegistryResult', 'get_registry', ] @pulumi.output_type class", "'GetRegistryResult', 'AwaitableGetRegistryResult', 'get_registry', ] @pulumi.output_type class GetRegistryResult: \"\"\" A collection", "\"location\") @property @pulumi.getter(name=\"loginServer\") def login_server(self) -> str: \"\"\" The URL", "\"storage_account_id\", storage_account_id) if tags and not isinstance(tags, dict): raise TypeError(\"Expected", "name(self) -> str: return pulumi.get(self, \"name\") @property @pulumi.getter(name=\"resourceGroupName\") def resource_group_name(self)", "str\") pulumi.set(__self__, \"sku\", sku) if storage_account_id and not isinstance(storage_account_id, str):", "Admin account - if the admin account is enabled. \"\"\"", "'name' to be a str\") pulumi.set(__self__, \"name\", name) if resource_group_name", "return AwaitableGetRegistryResult( admin_enabled=__ret__.admin_enabled, admin_password=__ret__.admin_password, admin_username=__ret__.admin_username, id=__ret__.id, location=__ret__.location, login_server=__ret__.login_server, name=__ret__.name, resource_group_name=__ret__.resource_group_name,", "to be a bool\") pulumi.set(__self__, \"admin_enabled\", admin_enabled) if admin_password and", "= pulumi.runtime.invoke('azure:containerservice/getRegistry:getRegistry', __args__, opts=opts, typ=GetRegistryResult).value return AwaitableGetRegistryResult( admin_enabled=__ret__.admin_enabled, admin_password=__ret__.admin_password, admin_username=__ret__.admin_username,", "\"\"\" def __init__(__self__, admin_enabled=None, admin_password=None, admin_username=None, id=None, location=None, login_server=None, name=None,", "pulumi.get(self, \"admin_password\") @property @pulumi.getter(name=\"adminUsername\") def admin_username(self) -> str: \"\"\" The", "def name(self) -> str: return pulumi.get(self, \"name\") @property @pulumi.getter(name=\"resourceGroupName\") def", "name of the Container Registry. :param str resource_group_name: The Name", "\"\"\" return pulumi.get(self, \"id\") @property @pulumi.getter def location(self) -> str:", "resource_group_name) if sku and not isinstance(sku, str): raise TypeError(\"Expected argument", "'tags' to be a dict\") pulumi.set(__self__, \"tags\", tags) @property @pulumi.getter(name=\"adminEnabled\")", "enabled. \"\"\" return pulumi.get(self, \"admin_password\") @property @pulumi.getter(name=\"adminUsername\") def admin_username(self) ->", "pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload", "not isinstance(admin_username, str): raise TypeError(\"Expected argument 'admin_username' to be a", "str\") pulumi.set(__self__, \"name\", name) if resource_group_name and not isinstance(resource_group_name, str):", "str: \"\"\" The Password associated with the Container Registry Admin", "str): raise TypeError(\"Expected argument 'sku' to be a str\") pulumi.set(__self__,", "\"resource_group_name\") @property @pulumi.getter def sku(self) -> str: \"\"\" The SKU", "str\") pulumi.set(__self__, \"admin_username\", admin_username) if id and not isinstance(id, str):", "to log into the container registry. \"\"\" return pulumi.get(self, \"login_server\")", "Registry. \"\"\" return pulumi.get(self, \"admin_enabled\") @property @pulumi.getter(name=\"adminPassword\") def admin_password(self) ->", "A collection of values returned by getRegistry. \"\"\" def __init__(__self__,", "def __await__(self): if False: yield self return GetRegistryResult( admin_enabled=self.admin_enabled, admin_password=<PASSWORD>,", "to be a str\") pulumi.set(__self__, \"name\", name) if resource_group_name and", "Username associated with the Container Registry Admin account - if", "resource_group_name and not isinstance(resource_group_name, str): raise TypeError(\"Expected argument 'resource_group_name' to", "by getRegistry. \"\"\" def __init__(__self__, admin_enabled=None, admin_password=None, admin_username=None, id=None, location=None,", "argument 'login_server' to be a str\") pulumi.set(__self__, \"login_server\", login_server) if", "login_server) if name and not isinstance(name, str): raise TypeError(\"Expected argument", "tags=None): if admin_enabled and not isinstance(admin_enabled, bool): raise TypeError(\"Expected argument", "the admin account is enabled. \"\"\" return pulumi.get(self, \"admin_username\") @property", "@pulumi.getter(name=\"storageAccountId\") def storage_account_id(self) -> str: \"\"\" The ID of the", "source to access information about an existing Container Registry. ##", "bool: \"\"\" Is the Administrator account enabled for this Container", "name=None, resource_group_name=None, sku=None, storage_account_id=None, tags=None): if admin_enabled and not isinstance(admin_enabled,", "enabled for this Container Registry. \"\"\" return pulumi.get(self, \"admin_enabled\") @property", "and not isinstance(sku, str): raise TypeError(\"Expected argument 'sku' to be", "return pulumi.get(self, \"name\") @property @pulumi.getter(name=\"resourceGroupName\") def resource_group_name(self) -> str: return", "@pulumi.output_type class GetRegistryResult: \"\"\" A collection of values returned by", "Password associated with the Container Registry Admin account - if", "from typing import Any, Mapping, Optional, Sequence, Union, overload from", "TypeError(\"Expected argument 'admin_enabled' to be a bool\") pulumi.set(__self__, \"admin_enabled\", admin_enabled)", "location=None, login_server=None, name=None, resource_group_name=None, sku=None, storage_account_id=None, tags=None): if admin_enabled and", "Registry Admin account - if the admin account is enabled.", "\"location\", location) if login_server and not isinstance(login_server, str): raise TypeError(\"Expected", "map of tags assigned to the Container Registry. \"\"\" return", "\"\"\" return pulumi.get(self, \"sku\") @property @pulumi.getter(name=\"storageAccountId\") def storage_account_id(self) -> str:", "str]: \"\"\" A map of tags assigned to the Container", "know what you are doing! *** import warnings import pulumi", "yield self return GetRegistryResult( admin_enabled=self.admin_enabled, admin_password=<PASSWORD>, admin_username=self.admin_username, id=self.id, location=self.location, login_server=self.login_server,", "\"\"\" return pulumi.get(self, \"admin_username\") @property @pulumi.getter def id(self) -> str:", "exists. \"\"\" __args__ = dict() __args__['name'] = name __args__['resourceGroupName'] =", "Is the Administrator account enabled for this Container Registry. \"\"\"", "Any, Mapping, Optional, Sequence, Union, overload from .. import _utilities", "to be a str\") pulumi.set(__self__, \"admin_username\", admin_username) if id and", "raise TypeError(\"Expected argument 'login_server' to be a str\") pulumi.set(__self__, \"login_server\",", "Example Usage ```python import pulumi import pulumi_azure as azure example", "certain you know what you are doing! *** import warnings", "raise TypeError(\"Expected argument 'tags' to be a dict\") pulumi.set(__self__, \"tags\",", "-> str: return pulumi.get(self, \"resource_group_name\") @property @pulumi.getter def sku(self) ->", "be used to log into the container registry. \"\"\" return", "example = azure.containerservice.get_registry(name=\"testacr\", resource_group_name=\"test\") pulumi.export(\"loginServer\", example.login_server) ``` :param str name:", "Terraform Bridge (tfgen) Tool. *** # *** Do not edit", "bool): raise TypeError(\"Expected argument 'admin_enabled' to be a bool\") pulumi.set(__self__,", "def sku(self) -> str: \"\"\" The SKU of this Container", "\"resource_group_name\", resource_group_name) if sku and not isinstance(sku, str): raise TypeError(\"Expected", "you're certain you know what you are doing! *** import", "\"\"\" A map of tags assigned to the Container Registry.", "coding=utf-8 # *** WARNING: this file was generated by the", "with the Container Registry Admin account - if the admin", "(tfgen) Tool. *** # *** Do not edit by hand", "Administrator account enabled for this Container Registry. \"\"\" return pulumi.get(self,", "resource_group_name=\"test\") pulumi.export(\"loginServer\", example.login_server) ``` :param str name: The name of", "typ=GetRegistryResult).value return AwaitableGetRegistryResult( admin_enabled=__ret__.admin_enabled, admin_password=__ret__.admin_password, admin_username=__ret__.admin_username, id=__ret__.id, location=__ret__.location, login_server=__ret__.login_server, name=__ret__.name,", "@property @pulumi.getter def tags(self) -> Mapping[str, str]: \"\"\" A map", "admin_username and not isinstance(admin_username, str): raise TypeError(\"Expected argument 'admin_username' to", "\"\"\" return pulumi.get(self, \"tags\") class AwaitableGetRegistryResult(GetRegistryResult): # pylint: disable=using-constant-test def", "not isinstance(login_server, str): raise TypeError(\"Expected argument 'login_server' to be a", "\"\"\" The URL that can be used to log into", "azure.containerservice.get_registry(name=\"testacr\", resource_group_name=\"test\") pulumi.export(\"loginServer\", example.login_server) ``` :param str name: The name", "pulumi.get(self, \"admin_enabled\") @property @pulumi.getter(name=\"adminPassword\") def admin_password(self) -> str: \"\"\" The", "to be a dict\") pulumi.set(__self__, \"tags\", tags) @property @pulumi.getter(name=\"adminEnabled\") def", "str: \"\"\" The Azure Region in which this Container Registry", "__args__['name'] = name __args__['resourceGroupName'] = resource_group_name if opts is None:", "@pulumi.getter def sku(self) -> str: \"\"\" The SKU of this", "Sequence, Union, overload from .. import _utilities __all__ = [", "return pulumi.get(self, \"login_server\") @property @pulumi.getter def name(self) -> str: return", "pylint: disable=using-constant-test def __await__(self): if False: yield self return GetRegistryResult(", "not edit by hand unless you're certain you know what", "@property @pulumi.getter def id(self) -> str: \"\"\" The provider-assigned unique", "and not isinstance(id, str): raise TypeError(\"Expected argument 'id' to be", "Registry, such as `Basic`. \"\"\" return pulumi.get(self, \"sku\") @property @pulumi.getter(name=\"storageAccountId\")", "storage_account_id and not isinstance(storage_account_id, str): raise TypeError(\"Expected argument 'storage_account_id' to", "Container Registry Admin account - if the admin account is", "# *** WARNING: this file was generated by the Pulumi", "Registry exists. \"\"\" return pulumi.get(self, \"location\") @property @pulumi.getter(name=\"loginServer\") def login_server(self)", "Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetRegistryResult: \"\"\"", "'sku' to be a str\") pulumi.set(__self__, \"sku\", sku) if storage_account_id", "argument 'admin_enabled' to be a bool\") pulumi.set(__self__, \"admin_enabled\", admin_enabled) if", "id=self.id, location=self.location, login_server=self.login_server, name=self.name, resource_group_name=self.resource_group_name, sku=self.sku, storage_account_id=self.storage_account_id, tags=self.tags) def get_registry(name:", "= _utilities.get_version() __ret__ = pulumi.runtime.invoke('azure:containerservice/getRegistry:getRegistry', __args__, opts=opts, typ=GetRegistryResult).value return AwaitableGetRegistryResult(", "this managed resource. \"\"\" return pulumi.get(self, \"id\") @property @pulumi.getter def", "disable=using-constant-test def __await__(self): if False: yield self return GetRegistryResult( admin_enabled=self.admin_enabled,", "return pulumi.get(self, \"admin_password\") @property @pulumi.getter(name=\"adminUsername\") def admin_username(self) -> str: \"\"\"", "by hand unless you're certain you know what you are", "## Example Usage ```python import pulumi import pulumi_azure as azure", "@property @pulumi.getter(name=\"adminUsername\") def admin_username(self) -> str: \"\"\" The Username associated", ":param str resource_group_name: The Name of the Resource Group where", "= None, resource_group_name: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None)", "opts.version is None: opts.version = _utilities.get_version() __ret__ = pulumi.runtime.invoke('azure:containerservice/getRegistry:getRegistry', __args__,", "return pulumi.get(self, \"admin_enabled\") @property @pulumi.getter(name=\"adminPassword\") def admin_password(self) -> str: \"\"\"", "-> str: return pulumi.get(self, \"name\") @property @pulumi.getter(name=\"resourceGroupName\") def resource_group_name(self) ->", "pulumi.set(__self__, \"admin_password\", <PASSWORD>) if admin_username and not isinstance(admin_username, str): raise", "pulumi.get(self, \"login_server\") @property @pulumi.getter def name(self) -> str: return pulumi.get(self,", "None: opts.version = _utilities.get_version() __ret__ = pulumi.runtime.invoke('azure:containerservice/getRegistry:getRegistry', __args__, opts=opts, typ=GetRegistryResult).value", "the Container Registry. \"\"\" return pulumi.get(self, \"tags\") class AwaitableGetRegistryResult(GetRegistryResult): #", "as `Basic`. \"\"\" return pulumi.get(self, \"sku\") @property @pulumi.getter(name=\"storageAccountId\") def storage_account_id(self)", "you are doing! *** import warnings import pulumi import pulumi.runtime", "TypeError(\"Expected argument 'admin_password' to be a str\") pulumi.set(__self__, \"admin_password\", <PASSWORD>)", "admin_password=<PASSWORD>, admin_username=self.admin_username, id=self.id, location=self.location, login_server=self.login_server, name=self.name, resource_group_name=self.resource_group_name, sku=self.sku, storage_account_id=self.storage_account_id, tags=self.tags)", "\"\"\" return pulumi.get(self, \"admin_password\") @property @pulumi.getter(name=\"adminUsername\") def admin_username(self) -> str:", "sku(self) -> str: \"\"\" The SKU of this Container Registry,", "Mapping, Optional, Sequence, Union, overload from .. import _utilities __all__", "str\") pulumi.set(__self__, \"resource_group_name\", resource_group_name) if sku and not isinstance(sku, str):", "-> AwaitableGetRegistryResult: \"\"\" Use this data source to access information", "-> str: \"\"\" The Username associated with the Container Registry", "SKU's. \"\"\" return pulumi.get(self, \"storage_account_id\") @property @pulumi.getter def tags(self) ->", "- if the admin account is enabled. \"\"\" return pulumi.get(self,", "id=None, location=None, login_server=None, name=None, resource_group_name=None, sku=None, storage_account_id=None, tags=None): if admin_enabled", "TypeError(\"Expected argument 'id' to be a str\") pulumi.set(__self__, \"id\", id)", "to be a str\") pulumi.set(__self__, \"login_server\", login_server) if name and", "information about an existing Container Registry. ## Example Usage ```python", "Bridge (tfgen) Tool. *** # *** Do not edit by", "a str\") pulumi.set(__self__, \"storage_account_id\", storage_account_id) if tags and not isinstance(tags,", "if the admin account is enabled. \"\"\" return pulumi.get(self, \"admin_username\")", "\"\"\" Use this data source to access information about an", "WARNING: this file was generated by the Pulumi Terraform Bridge", "Registry. ## Example Usage ```python import pulumi import pulumi_azure as", "not isinstance(admin_enabled, bool): raise TypeError(\"Expected argument 'admin_enabled' to be a", "login_server=None, name=None, resource_group_name=None, sku=None, storage_account_id=None, tags=None): if admin_enabled and not", "opts.version = _utilities.get_version() __ret__ = pulumi.runtime.invoke('azure:containerservice/getRegistry:getRegistry', __args__, opts=opts, typ=GetRegistryResult).value return", "\"id\") @property @pulumi.getter def location(self) -> str: \"\"\" The Azure", "*** WARNING: this file was generated by the Pulumi Terraform", "@property @pulumi.getter(name=\"adminPassword\") def admin_password(self) -> str: \"\"\" The Password associated", "and not isinstance(admin_enabled, bool): raise TypeError(\"Expected argument 'admin_enabled' to be", "admin account is enabled. \"\"\" return pulumi.get(self, \"admin_username\") @property @pulumi.getter", "return pulumi.get(self, \"admin_username\") @property @pulumi.getter def id(self) -> str: \"\"\"", "pulumi.set(__self__, \"sku\", sku) if storage_account_id and not isinstance(storage_account_id, str): raise", "return pulumi.get(self, \"id\") @property @pulumi.getter def location(self) -> str: \"\"\"", ":param str name: The name of the Container Registry. :param", "__await__(self): if False: yield self return GetRegistryResult( admin_enabled=self.admin_enabled, admin_password=<PASSWORD>, admin_username=self.admin_username,", "is only returned for `Classic` SKU's. \"\"\" return pulumi.get(self, \"storage_account_id\")", "str\") pulumi.set(__self__, \"admin_password\", <PASSWORD>) if admin_username and not isinstance(admin_username, str):", "@pulumi.getter def id(self) -> str: \"\"\" The provider-assigned unique ID", "str): raise TypeError(\"Expected argument 'id' to be a str\") pulumi.set(__self__,", "only returned for `Classic` SKU's. \"\"\" return pulumi.get(self, \"storage_account_id\") @property", "location) if login_server and not isinstance(login_server, str): raise TypeError(\"Expected argument", "def id(self) -> str: \"\"\" The provider-assigned unique ID for", "str\") pulumi.set(__self__, \"storage_account_id\", storage_account_id) if tags and not isinstance(tags, dict):", "resource_group_name=self.resource_group_name, sku=self.sku, storage_account_id=self.storage_account_id, tags=self.tags) def get_registry(name: Optional[str] = None, resource_group_name:", "get_registry(name: Optional[str] = None, resource_group_name: Optional[str] = None, opts: Optional[pulumi.InvokeOptions]", "if admin_password and not isinstance(admin_password, str): raise TypeError(\"Expected argument 'admin_password'", "pulumi.get(self, \"tags\") class AwaitableGetRegistryResult(GetRegistryResult): # pylint: disable=using-constant-test def __await__(self): if", "Resource Group where this Container Registry exists. \"\"\" __args__ =", "import pulumi import pulumi.runtime from typing import Any, Mapping, Optional,", "isinstance(storage_account_id, str): raise TypeError(\"Expected argument 'storage_account_id' to be a str\")", "return pulumi.get(self, \"location\") @property @pulumi.getter(name=\"loginServer\") def login_server(self) -> str: \"\"\"", "URL that can be used to log into the container", "name) if resource_group_name and not isinstance(resource_group_name, str): raise TypeError(\"Expected argument", "= None) -> AwaitableGetRegistryResult: \"\"\" Use this data source to", "-> Mapping[str, str]: \"\"\" A map of tags assigned to", "None) -> AwaitableGetRegistryResult: \"\"\" Use this data source to access", "and not isinstance(tags, dict): raise TypeError(\"Expected argument 'tags' to be", "SKU of this Container Registry, such as `Basic`. \"\"\" return", "str\") pulumi.set(__self__, \"location\", location) if login_server and not isinstance(login_server, str):", "str: \"\"\" The URL that can be used to log", "-> str: \"\"\" The provider-assigned unique ID for this managed", "be a dict\") pulumi.set(__self__, \"tags\", tags) @property @pulumi.getter(name=\"adminEnabled\") def admin_enabled(self)", "isinstance(admin_username, str): raise TypeError(\"Expected argument 'admin_username' to be a str\")", "where this Container Registry exists. \"\"\" __args__ = dict() __args__['name']", "and not isinstance(login_server, str): raise TypeError(\"Expected argument 'login_server' to be", "be a str\") pulumi.set(__self__, \"admin_username\", admin_username) if id and not", "\"id\", id) if location and not isinstance(location, str): raise TypeError(\"Expected", "login_server(self) -> str: \"\"\" The URL that can be used", "-> str: \"\"\" The Password associated with the Container Registry", "import Any, Mapping, Optional, Sequence, Union, overload from .. import", "AwaitableGetRegistryResult: \"\"\" Use this data source to access information about", "Optional[pulumi.InvokeOptions] = None) -> AwaitableGetRegistryResult: \"\"\" Use this data source", "the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do", ".. import _utilities __all__ = [ 'GetRegistryResult', 'AwaitableGetRegistryResult', 'get_registry', ]", "a dict\") pulumi.set(__self__, \"tags\", tags) @property @pulumi.getter(name=\"adminEnabled\") def admin_enabled(self) ->", "raise TypeError(\"Expected argument 'admin_password' to be a str\") pulumi.set(__self__, \"admin_password\",", "to be a str\") pulumi.set(__self__, \"storage_account_id\", storage_account_id) if tags and", "Azure Region in which this Container Registry exists. \"\"\" return", "the admin account is enabled. \"\"\" return pulumi.get(self, \"admin_password\") @property", "def admin_username(self) -> str: \"\"\" The Username associated with the", "used to log into the container registry. \"\"\" return pulumi.get(self,", "argument 'name' to be a str\") pulumi.set(__self__, \"name\", name) if", "admin_enabled and not isinstance(admin_enabled, bool): raise TypeError(\"Expected argument 'admin_enabled' to", "are doing! *** import warnings import pulumi import pulumi.runtime from", "\"storage_account_id\") @property @pulumi.getter def tags(self) -> Mapping[str, str]: \"\"\" A", "a str\") pulumi.set(__self__, \"resource_group_name\", resource_group_name) if sku and not isinstance(sku,", "class AwaitableGetRegistryResult(GetRegistryResult): # pylint: disable=using-constant-test def __await__(self): if False: yield", "The Password associated with the Container Registry Admin account -", "resource_group_name if opts is None: opts = pulumi.InvokeOptions() if opts.version", "\"tags\", tags) @property @pulumi.getter(name=\"adminEnabled\") def admin_enabled(self) -> bool: \"\"\" Is", "return pulumi.get(self, \"storage_account_id\") @property @pulumi.getter def tags(self) -> Mapping[str, str]:", "can be used to log into the container registry. \"\"\"", "pulumi.InvokeOptions() if opts.version is None: opts.version = _utilities.get_version() __ret__ =", "\"login_server\") @property @pulumi.getter def name(self) -> str: return pulumi.get(self, \"name\")", "isinstance(name, str): raise TypeError(\"Expected argument 'name' to be a str\")", "access information about an existing Container Registry. ## Example Usage", "_utilities.get_version() __ret__ = pulumi.runtime.invoke('azure:containerservice/getRegistry:getRegistry', __args__, opts=opts, typ=GetRegistryResult).value return AwaitableGetRegistryResult( admin_enabled=__ret__.admin_enabled,", "= resource_group_name if opts is None: opts = pulumi.InvokeOptions() if", "to be a str\") pulumi.set(__self__, \"sku\", sku) if storage_account_id and", "not isinstance(admin_password, str): raise TypeError(\"Expected argument 'admin_password' to be a", "admin_enabled=__ret__.admin_enabled, admin_password=__ret__.admin_password, admin_username=__ret__.admin_username, id=__ret__.id, location=__ret__.location, login_server=__ret__.login_server, name=__ret__.name, resource_group_name=__ret__.resource_group_name, sku=__ret__.sku, storage_account_id=__ret__.storage_account_id,", "pulumi.set(__self__, \"login_server\", login_server) if name and not isinstance(name, str): raise", "to be a str\") pulumi.set(__self__, \"id\", id) if location and", "account is enabled. \"\"\" return pulumi.get(self, \"admin_username\") @property @pulumi.getter def", "str): raise TypeError(\"Expected argument 'resource_group_name' to be a str\") pulumi.set(__self__,", "edit by hand unless you're certain you know what you", "pulumi.get(self, \"location\") @property @pulumi.getter(name=\"loginServer\") def login_server(self) -> str: \"\"\" The", "@pulumi.getter def name(self) -> str: return pulumi.get(self, \"name\") @property @pulumi.getter(name=\"resourceGroupName\")", "if False: yield self return GetRegistryResult( admin_enabled=self.admin_enabled, admin_password=<PASSWORD>, admin_username=self.admin_username, id=self.id,", "TypeError(\"Expected argument 'login_server' to be a str\") pulumi.set(__self__, \"login_server\", login_server)", "exists. \"\"\" return pulumi.get(self, \"location\") @property @pulumi.getter(name=\"loginServer\") def login_server(self) ->", "tags and not isinstance(tags, dict): raise TypeError(\"Expected argument 'tags' to", "AwaitableGetRegistryResult(GetRegistryResult): # pylint: disable=using-constant-test def __await__(self): if False: yield self", "Do not edit by hand unless you're certain you know", "str\") pulumi.set(__self__, \"id\", id) if location and not isinstance(location, str):", "TypeError(\"Expected argument 'admin_username' to be a str\") pulumi.set(__self__, \"admin_username\", admin_username)", "raise TypeError(\"Expected argument 'sku' to be a str\") pulumi.set(__self__, \"sku\",", "unique ID for this managed resource. \"\"\" return pulumi.get(self, \"id\")", "@pulumi.getter(name=\"adminUsername\") def admin_username(self) -> str: \"\"\" The Username associated with", "Union, overload from .. import _utilities __all__ = [ 'GetRegistryResult',", "TypeError(\"Expected argument 'sku' to be a str\") pulumi.set(__self__, \"sku\", sku)", "`Classic` SKU's. \"\"\" return pulumi.get(self, \"storage_account_id\") @property @pulumi.getter def tags(self)", "str): raise TypeError(\"Expected argument 'admin_password' to be a str\") pulumi.set(__self__,", "return pulumi.get(self, \"resource_group_name\") @property @pulumi.getter def sku(self) -> str: \"\"\"", "str): raise TypeError(\"Expected argument 'location' to be a str\") pulumi.set(__self__,", "isinstance(tags, dict): raise TypeError(\"Expected argument 'tags' to be a dict\")", "for `Classic` SKU's. \"\"\" return pulumi.get(self, \"storage_account_id\") @property @pulumi.getter def", "__args__['resourceGroupName'] = resource_group_name if opts is None: opts = pulumi.InvokeOptions()", "self return GetRegistryResult( admin_enabled=self.admin_enabled, admin_password=<PASSWORD>, admin_username=self.admin_username, id=self.id, location=self.location, login_server=self.login_server, name=self.name,", "of the Container Registry. :param str resource_group_name: The Name of", "in which this Container Registry exists. \"\"\" return pulumi.get(self, \"location\")", "# *** Do not edit by hand unless you're certain", "class GetRegistryResult: \"\"\" A collection of values returned by getRegistry.", "\"admin_enabled\", admin_enabled) if admin_password and not isinstance(admin_password, str): raise TypeError(\"Expected", "str): raise TypeError(\"Expected argument 'login_server' to be a str\") pulumi.set(__self__,", "if tags and not isinstance(tags, dict): raise TypeError(\"Expected argument 'tags'", "Optional, Sequence, Union, overload from .. import _utilities __all__ =", "] @pulumi.output_type class GetRegistryResult: \"\"\" A collection of values returned", "and not isinstance(storage_account_id, str): raise TypeError(\"Expected argument 'storage_account_id' to be", "for this Container Registry. \"\"\" return pulumi.get(self, \"admin_enabled\") @property @pulumi.getter(name=\"adminPassword\")", "The Azure Region in which this Container Registry exists. \"\"\"", "'login_server' to be a str\") pulumi.set(__self__, \"login_server\", login_server) if name", "and not isinstance(resource_group_name, str): raise TypeError(\"Expected argument 'resource_group_name' to be", "of this Container Registry, such as `Basic`. \"\"\" return pulumi.get(self,", "\"sku\") @property @pulumi.getter(name=\"storageAccountId\") def storage_account_id(self) -> str: \"\"\" The ID", "be a str\") pulumi.set(__self__, \"resource_group_name\", resource_group_name) if sku and not", "-> str: \"\"\" The Azure Region in which this Container", "admin_username=self.admin_username, id=self.id, location=self.location, login_server=self.login_server, name=self.name, resource_group_name=self.resource_group_name, sku=self.sku, storage_account_id=self.storage_account_id, tags=self.tags) def", "def admin_enabled(self) -> bool: \"\"\" Is the Administrator account enabled", "is None: opts = pulumi.InvokeOptions() if opts.version is None: opts.version", "Mapping[str, str]: \"\"\" A map of tags assigned to the", "\"\"\" Is the Administrator account enabled for this Container Registry.", "\"admin_username\") @property @pulumi.getter def id(self) -> str: \"\"\" The provider-assigned", "raise TypeError(\"Expected argument 'storage_account_id' to be a str\") pulumi.set(__self__, \"storage_account_id\",", "tags assigned to the Container Registry. \"\"\" return pulumi.get(self, \"tags\")", "a bool\") pulumi.set(__self__, \"admin_enabled\", admin_enabled) if admin_password and not isinstance(admin_password,", "__ret__ = pulumi.runtime.invoke('azure:containerservice/getRegistry:getRegistry', __args__, opts=opts, typ=GetRegistryResult).value return AwaitableGetRegistryResult( admin_enabled=__ret__.admin_enabled, admin_password=__ret__.admin_password,", "resource_group_name: The Name of the Resource Group where this Container", "return pulumi.get(self, \"tags\") class AwaitableGetRegistryResult(GetRegistryResult): # pylint: disable=using-constant-test def __await__(self):", "location(self) -> str: \"\"\" The Azure Region in which this", "@property @pulumi.getter(name=\"loginServer\") def login_server(self) -> str: \"\"\" The URL that", "-> bool: \"\"\" Is the Administrator account enabled for this", "enabled. \"\"\" return pulumi.get(self, \"admin_username\") @property @pulumi.getter def id(self) ->", "'get_registry', ] @pulumi.output_type class GetRegistryResult: \"\"\" A collection of values", "raise TypeError(\"Expected argument 'id' to be a str\") pulumi.set(__self__, \"id\",", "@property @pulumi.getter(name=\"storageAccountId\") def storage_account_id(self) -> str: \"\"\" The ID of", "be a str\") pulumi.set(__self__, \"admin_password\", <PASSWORD>) if admin_username and not", "be a str\") pulumi.set(__self__, \"name\", name) if resource_group_name and not", "file was generated by the Pulumi Terraform Bridge (tfgen) Tool.", "def resource_group_name(self) -> str: return pulumi.get(self, \"resource_group_name\") @property @pulumi.getter def", "id and not isinstance(id, str): raise TypeError(\"Expected argument 'id' to", "if opts.version is None: opts.version = _utilities.get_version() __ret__ = pulumi.runtime.invoke('azure:containerservice/getRegistry:getRegistry',", "None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetRegistryResult: \"\"\" Use this", "The SKU of this Container Registry, such as `Basic`. \"\"\"", "name and not isinstance(name, str): raise TypeError(\"Expected argument 'name' to", "name=self.name, resource_group_name=self.resource_group_name, sku=self.sku, storage_account_id=self.storage_account_id, tags=self.tags) def get_registry(name: Optional[str] = None,", "values returned by getRegistry. \"\"\" def __init__(__self__, admin_enabled=None, admin_password=None, admin_username=None,", "pulumi.set(__self__, \"tags\", tags) @property @pulumi.getter(name=\"adminEnabled\") def admin_enabled(self) -> bool: \"\"\"", "of the Storage Account used for this Container Registry. This", "\"\"\" return pulumi.get(self, \"login_server\") @property @pulumi.getter def name(self) -> str:", "login_server=self.login_server, name=self.name, resource_group_name=self.resource_group_name, sku=self.sku, storage_account_id=self.storage_account_id, tags=self.tags) def get_registry(name: Optional[str] =", "admin_password=None, admin_username=None, id=None, location=None, login_server=None, name=None, resource_group_name=None, sku=None, storage_account_id=None, tags=None):", "of the Resource Group where this Container Registry exists. \"\"\"", "\"tags\") class AwaitableGetRegistryResult(GetRegistryResult): # pylint: disable=using-constant-test def __await__(self): if False:", "location and not isinstance(location, str): raise TypeError(\"Expected argument 'location' to", "\"\"\" The Username associated with the Container Registry Admin account", "The URL that can be used to log into the", "sku and not isinstance(sku, str): raise TypeError(\"Expected argument 'sku' to", "pulumi.set(__self__, \"admin_username\", admin_username) if id and not isinstance(id, str): raise", "log into the container registry. \"\"\" return pulumi.get(self, \"login_server\") @property", "tags=self.tags) def get_registry(name: Optional[str] = None, resource_group_name: Optional[str] = None," ]
[ "else: #We do wrap the archive higherEnd = higher['offset'] +", "average? myPackedPoint = struct.pack(pointFormat,lowerIntervalStart,aggregateValue) fh.seek(lower['offset']) packedPoint = fh.read(pointSize) (lowerBaseInterval,lowerBaseValue) =", "2.0 (the \"License\"); # you may not use this file", "StopIteration: #debug(' update_many no more archives!') currentArchive = None break", "step timeInfo = (fromInterval,untilInterval,step) valueList = [None] * points return", "propagateFurther = True #debug(' __archive_update_many Successful propagation!') #debug(' __archive_update_many propagateFurther=%s'", "(byteDistance % archive['size']) fh.seek(myOffset) archiveEnd = archive['offset'] + archive['size'] bytesBeyond", "#XXX Make this a NOP, use os.stat(filename).st_mtime instead startBlock('__changeLastUpdate()') originalOffset", "#startBlock('complete update') value = float(value) fh = open(path,'r+b') if LOCK:", "NOP, use os.stat(filename).st_mtime instead startBlock('__changeLastUpdate()') originalOffset = fh.tell() fh.seek(0) #Based", "= archive['offset'] + (byteDistance % archive['size']) fh.seek(myOffset) fh.write(myPackedPoint) #Now we", "__readHeader(fh) now = int( time.time() ) archives = iter( header['archives']", "% baseInterval) #Write all of our packed strings in locations", "# Header = Metadata,ArchiveInfo+ # Metadata = lastUpdate,maxRetention,xFilesFactor,archiveCount # ArchiveInfo", "assert archive[0] < next[0],\\ \"You cannot configure two archives with", "step #Propagate aggregateValue to propagate from neighborValues if we have", "from StringIO import StringIO import memcache global open, exists, drop", "= False for interval in uniqueLowerIntervals: #debug(' __archive_update_many propagating from", "def close(self): if self.mode == \"r+b\" or self.mode == \"wb\":", "+ higher['size'] seriesString = fh.read(higherEnd - higherFirstOffset) fh.seek(higher['offset']) seriesString +=", "a string value is a float timestamp is either an", "open(path,'r+b') if LOCK: fcntl.flock( fh.fileno(), fcntl.LOCK_EX ) header = __readHeader(fh)", "for interval in uniqueLowerIntervals: #debug(' __archive_update_many propagating from %d to", "def __init__(self,*args,**kwargs): self.name = args[0] self.mode = args[1] if self.mode", "fh.write( packedString[:-bytesBeyond] ) #debug('We wrapped an archive!') assert fh.tell() ==", "if LOCK: fcntl.flock( fh.fileno(), fcntl.LOCK_EX ) lastUpdate = struct.pack( timestampFormat,", "(baseInterval,baseValue) = struct.unpack(pointFormat,packedPoint) if baseInterval == 0: step = archive['secondsPerPoint']", "in uniqueLowerIntervals: #debug(' __archive_update_many propagating from %d to %d, interval=%d'", "fh.read(pointSize) (higherBaseInterval,higherBaseValue) = struct.unpack(pointFormat,packedPoint) if higherBaseInterval == 0: higherFirstOffset =", "fromTime < (now - header['maxRetention']): fromTime = now - header['maxRetention']", "in chronological order __archive_update_many(fh,header,currentArchive,currentPoints) currentPoints = [] try: currentArchive =", "the base, so we start at the start #debug('__archive_update_many baseInterval", "took %.5f seconds\" % (name,time.time() - __timingBlocks.pop(name))) def __readHeader(fh): info", "the header assert not exists(path), \"File %s already exists!\" %", "__headerCache = {} longFormat = \"!L\" longSize = struct.calcsize(longFormat) floatFormat", "is a string value is a float timestamp is either", "besides average? myPackedPoint = struct.pack(pointFormat,lowerIntervalStart,aggregateValue) fh.seek(lower['offset']) packedPoint = fh.read(pointSize) (lowerBaseInterval,lowerBaseValue)", "else: fh.write(packedString) #endBlock('__archive_update_many write() operations') #Now we propagate the updates", "write(self,data): self.writeCount += 1 debug('WRITE %d bytes #%d' % (len(data),self.writeCount))", "update') def update_many(path,points): \"\"\"update_many(path,points) path is a string points is", "data we just read byteOrder,pointTypes = pointFormat[0],pointFormat[1:] points = len(seriesString)", "to packedStrings startInterval=%s currentString=%d bytes' % (startInterval,len(currentString))) packedStrings.append( (startInterval,currentString) )", "= float(value) fh = open(path,'r+b') if LOCK: fcntl.flock( fh.fileno(), fcntl.LOCK_EX", "we start at the start #debug('__archive_update_many baseInterval is %s' %", "modified version of whisper.py For details on the modification, read", "struct.pack(archiveInfoFormat, archiveOffsetPointer, secondsPerPoint, points) fh.write(archiveInfo) archiveOffsetPointer += (points * pointSize)", "% (myOffset,len(packedString),archiveEnd,bytesBeyond)) if bytesBeyond > 0: fh.write( packedString[:-bytesBeyond] ) #debug('We", "precision %s,%s\" % (archive[0],next[0]) retention = archive[0] * archive[1] nextRetention", "= pointValue #in-place reassignment is faster than append() currentInterval +=", "archives later break #First we update the highest-precision archive myInterval", "= now - header['maxRetention'] assert fromTime < untilTime, \"Invalid time", "list of values (optimize this!) valueList = [None] * points", "License for the specific language governing permissions and # limitations", "% archive['size']) #Determine untilOffset timeDistance = untilInterval - baseInterval pointDistance", "= __readHeader(fh) now = int( time.time() ) archives = iter(", "% higher['size']) higherPoints = lower['secondsPerPoint'] / higher['secondsPerPoint'] higherSize = higherPoints", "#Now we propagate the update to lower-precision archives #startBlock('update propagation')", "can fit currentPoints.reverse() #put points in chronological order __archive_update_many(fh,header,currentArchive,currentPoints) currentPoints", "None] knownPercent = float(len(knownValues)) / float(len(neighborValues)) if knownPercent >= xff:", "- timestamp assert diff < header['maxRetention'] and diff >= 0,", "forget to commit after we've checked all the archives currentPoints.reverse()", "* len(currentString) / pointSize) + step numberOfPoints = len(currentString) /", "lowerBaseInterval pointDistance = timeDistance / lower['secondsPerPoint'] byteDistance = pointDistance *", "assert (next[0] % archive[0]) == 0,\\ \"Higher precision archives' precision", "bytesBeyond=%d len(packedString)=%d\" % (archiveEnd,fh.tell(),bytesBeyond,len(packedString)) fh.seek( archive['offset'] ) fh.write( packedString[-bytesBeyond:] )", "basic layout of a whisper data file # # File", "struct.pack( floatFormat, float(xFilesFactor) ) archiveCount = struct.pack(longFormat, len(archiveList)) packedMetadata =", "= header['archives'][i+1:] #We'll pass on the update to these lower", "Whisper database API # Here is the basic layout of", "= untilInterval - baseInterval pointDistance = timeDistance / archive['secondsPerPoint'] byteDistance", "(now - header['maxRetention']): fromTime = now - header['maxRetention'] assert fromTime", "args[1] if self.mode == \"r+b\" or self.mode == \"rb\": StringIO.__init__(self,", "seriesString = fh.read(archiveEnd - fromOffset) fh.seek(archive['offset']) seriesString += fh.read(untilOffset -", "knownPercent = float(len(knownValues)) / float(len(neighborValues)) if knownPercent >= xff: #we", "for point in points: age = now - point[0] #debug('", "is also an epoch time, but defaults to now \"\"\"", "pointDistance = timeDistance / step byteDistance = pointDistance * pointSize", "MC.get(path) != None def drop(path): MC.delete(path) def enableDebug(): global open,", "fh.read(higherEnd - higherFirstOffset) fh.seek(higher['offset']) seriesString += fh.read(higherLastOffset - higher['offset']) #Now", "p in alignedPoints] uniqueLowerIntervals = set(lowerIntervals) #debug(' __archive_update_many points=%d unique=%d'", ") packedTime = struct.pack(timestampFormat,now) fh.write(packedTime) fh.seek(originalOffset) endBlock('__changeLastUpdate()') def create(path,archiveList,xFilesFactor=0.5): \"\"\"create(path,archiveList,xFilesFactor=0.5)", "create(path,archiveList,xFilesFactor=0.5): \"\"\"create(path,archiveList,xFilesFactor=0.5) path is a string archiveList is a list", "lower archives' % len(lowerArchives)) for lower in lowerArchives: fit =", "% message) __timingBlocks = {} def startBlock(name): __timingBlocks[name] = time.time()", "writes will start fh.seek(archive['offset']) packedBasePoint = fh.read(pointSize) (baseInterval,baseValue) = struct.unpack(pointFormat,packedBasePoint)", "global open, debug, startBlock, endBlock class open(file): def __init__(self,*args,**kwargs): file.__init__(self,*args,**kwargs)", "either an int or float \"\"\" #startBlock('complete update') value =", "#!/usr/bin/env python # Copyright 2008 Orbitz WorldWide # # Licensed", "unpack the series data we just read byteOrder,pointTypes = pointFormat[0],pointFormat[1:]", "precision archives' precision %s,%s\" % (archive[0],next[0]) retention = archive[0] *", "update_many done iterating points') if currentArchive and currentPoints: #don't forget", "= lower #endBlock('update propagation') __changeLastUpdate(fh) fh.close() #endBlock('complete update') def update_many(path,points):", "to this lower archive timeDistance = lowerIntervalStart - lowerBaseInterval pointDistance", "to this lower archive fh.seek(lower['offset']) fh.write(myPackedPoint) else: #Not our first", "[] for point in points: age = now - point[0]", "offset, 'secondsPerPoint' : secondsPerPoint, 'points' : points, 'retention' : secondsPerPoint", "% (startInterval,len(currentString))) packedStrings.append( (startInterval,currentString) ) currentString = struct.pack(pointFormat,interval,value) previousInterval =", "archive['retention'] >= diff: break fromInterval = int( fromTime - (fromTime", "def endBlock(name): debug(\"%s took %.5f seconds\" % (name,time.time() - __timingBlocks.pop(name)))", "step byteDistance = pointDistance * pointSize myOffset = archive['offset'] +", "* pointSize fromOffset = archive['offset'] + (byteDistance % archive['size']) #Determine", "{ 'lastUpdate' : lastUpdate, 'maxRetention' : maxRetention, 'xFilesFactor' : xff,", "now - timestamp assert diff < header['maxRetention'] and diff >=", "higher = archive for lower in lowerArchives: if not __propagate(fh,myInterval,header['xFilesFactor'],higher,lower):", "diff: break fromInterval = int( fromTime - (fromTime % archive['secondsPerPoint'])", "drop MC = memcache.Client(servers) class open(StringIO): def __init__(self,*args,**kwargs): self.name =", "we just read (anything faster than unpack?) byteOrder,pointTypes = pointFormat[0],pointFormat[1:]", "if CACHE_HEADERS: __headerCache[fh.name] = info #endBlock('__readHeader') return info def __changeLastUpdate(fh):", "= struct.pack(pointFormat,lowerIntervalStart,aggregateValue) fh.seek(lower['offset']) packedPoint = fh.read(pointSize) (lowerBaseInterval,lowerBaseValue) = struct.unpack(pointFormat,packedPoint) if", "struct.unpack(pointFormat,packedPoint) if baseInterval == 0: #This file's first update fh.seek(archive['offset'])", "propagating from %d to %d, interval=%d' % (higher['secondsPerPoint'],lower['secondsPerPoint'],interval)) if __propagate(fh,interval,header['xFilesFactor'],higher,lower):", "= struct.pack(archiveInfoFormat, archiveOffsetPointer, secondsPerPoint, points) fh.write(archiveInfo) archiveOffsetPointer += (points *", "points currentInterval = lowerIntervalStart step = higher['secondsPerPoint'] for i in", "don't wrap the archive seriesString = fh.read(higherLastOffset - higherFirstOffset) else:", "os.remove(path) def enableMemcache(servers = ['127.0.0.1:11211'], min_compress_len = 0): from StringIO", "import memcache global open, exists, drop MC = memcache.Client(servers) class", "def drop(path): os.remove(path) def enableMemcache(servers = ['127.0.0.1:11211'], min_compress_len = 0):", "packedTime = struct.pack(timestampFormat,now) fh.write(packedTime) fh.seek(originalOffset) endBlock('__changeLastUpdate()') def create(path,archiveList,xFilesFactor=0.5): \"\"\"create(path,archiveList,xFilesFactor=0.5) path", "= archive['offset'] + (byteDistance % archive['size']) fh.seek(myOffset) archiveEnd = archive['offset']", "interval) if (not previousInterval) or (interval == previousInterval + step):", "- higherFirstOffset) else: #We do wrap the archive higherEnd =", "of values (optimize this!) valueList = [None] * points #pre-allocate", "archiveInfo = struct.pack(archiveInfoFormat, archiveOffsetPointer, secondsPerPoint, points) fh.write(archiveInfo) archiveOffsetPointer += (points", "for each contiguous sequence of points #startBlock('__archive_update_many string packing') packedStrings", "our writes will start fh.seek(archive['offset']) packedBasePoint = fh.read(pointSize) (baseInterval,baseValue) =", "OF ANY KIND, either express or implied. # See the", "See the License for the specific language governing permissions and", "global open, exists, drop MC = memcache.Client(servers) class open(StringIO): def", "whisper.py For details on the modification, read https://bugs.launchpad.net/graphite/+bug/245835 \"\"\" import", "to in writing, software # distributed under the License is", "is None or untilTime > now: untilTime = now if", "currentString += struct.pack(pointFormat,interval,value) previousInterval = interval else: numberOfPoints = len(currentString)", "if i == len(archiveList) - 1: break next = archiveList[i+1]", "pointSize lowerOffset = lower['offset'] + (byteDistance % lower['size']) fh.seek(lowerOffset) fh.write(myPackedPoint)", "the fraction of data points in a propagation interval that", "CACHE_HEADERS = False __headerCache = {} longFormat = \"!L\" longSize", "at least one archive configuration!\" archiveList.sort(key=lambda a: a[0]) #sort by", "points') if currentArchive and currentPoints: #don't forget to commit after", "or agreed to in writing, software # distributed under the", "#endBlock('complete update') def update_many(path,points): \"\"\"update_many(path,points) path is a string points", "previousInterval) or (interval == previousInterval + step): #debug('__archive_update_many was expected,", "len(currentString) / pointSize startInterval = previousInterval - (step * (numberOfPoints-1))", "packedStrings startInterval=%s currentString=%d bytes' % (startInterval,len(currentString))) packedStrings.append( (startInterval,currentString) ) currentString", "info = __headerCache.get(fh.name) if info: return info #startBlock('__readHeader') originalOffset =", "= archive['secondsPerPoint'] #startBlock('__archive_update_many file=%s archive=%s points=%d' % (fh.name,step,len(points))) alignedPoints =", "read byteOrder,pointTypes = pointFormat[0],pointFormat[1:] points = len(seriesString) / pointSize seriesFormat", "now = int( time.time() ) packedTime = struct.pack(timestampFormat,now) fh.write(packedTime) fh.seek(originalOffset)", "archive['secondsPerPoint']) myPackedPoint = struct.pack(pointFormat,myInterval,value) fh.seek(archive['offset']) packedPoint = fh.read(pointSize) (baseInterval,baseValue) =", "= time.time() def endBlock(name): debug(\"%s took %.5f seconds\" % (name,time.time()", "int( untilTime - (untilTime % archive['secondsPerPoint']) ) fh.seek(archive['offset']) packedPoint =", "% lower['size']) fh.seek(lowerOffset) fh.write(myPackedPoint) return True else: return False def", "lastUpdate + maxRetention + xFilesFactor + archiveCount fh.write(packedMetadata) headerSize =", "#debug(' update_many iterating points, point=%s age=%d' % (str(point),age)) while currentArchive['retention']", "so we start at the start #debug('__archive_update_many baseInterval is %s'", "- baseInterval pointDistance = timeDistance / step byteDistance = pointDistance", "of the form (secondsPerPoint,numberOfPoints) xFilesFactor specifies the fraction of data", "__archive_update_many propagateFurther=%s' % propagateFurther) if not propagateFurther: break higher =", "compliance with the License. # You may obtain a copy", "next(archives) #debug(' update_many currentArchive=%s' % str(currentArchive)) currentPoints = [] for", "interval\" diff = now - fromTime for archive in header['archives']:", ": secondsPerPoint, 'points' : points, 'retention' : secondsPerPoint * points,", "struct.unpack(metadataFormat,packedMetadata) archives = [] for i in xrange(archiveCount): packedArchiveInfo =", "= {} def startBlock(name): __timingBlocks[name] = time.time() def endBlock(name): debug(\"%s", "= [ (int(t),float(v)) for (t,v) in points] points.sort(key=lambda p: p[0],reverse=True)", "< (now - header['maxRetention']): fromTime = now - header['maxRetention'] assert", "time.time() ) if untilTime is None or untilTime > now:", "not use this file except in compliance with the License.", "higherPoints = lower['secondsPerPoint'] / higher['secondsPerPoint'] higherSize = higherPoints * pointSize", "lowerOffset = lower['offset'] + (byteDistance % lower['size']) fh.seek(lowerOffset) fh.write(myPackedPoint) return", "archives = iter( header['archives'] ) currentArchive = next(archives) #debug(' update_many", "value) for (timestamp,value) in points ] #Create a packed string", "# ArchiveInfo = Offset,SecondsPerPoint,Points # Data = Archive+ # Archive", "the updates to lower-precision archives #startBlock('__archive_update_many propagation') higher = archive", "you may not use this file except in compliance with", "the archive higherEnd = higher['offset'] + higher['size'] seriesString = fh.read(higherEnd", "points #startBlock('__archive_update_many string packing') packedStrings = [] previousInterval = None", "# Copyright 2008 Orbitz WorldWide # # Licensed under the", "a value! aggregateValue = float(sum(knownValues)) / float(len(knownValues)) #TODO another CF", "#startBlock('__archive_update_many propagation') higher = archive lowerArchives = [arc for arc", "#And finally we construct a list of values (optimize this!)", "(retention checking logic above) else: fh.write(packedString) #endBlock('__archive_update_many write() operations') #Now", "fh.read(higherLastOffset - higherFirstOffset) else: #We do wrap the archive higherEnd", "finally we construct a list of values neighborValues = [None]", "fromInterval - baseInterval pointDistance = timeDistance / archive['secondsPerPoint'] byteDistance =", "timestampFormat, int(time.time()) ) oldest = sorted([secondsPerPoint * points for secondsPerPoint,points", "uniqueLowerIntervals = set(lowerIntervals) #debug(' __archive_update_many points=%d unique=%d' % (len(alignedPoints),len(uniqueLowerIntervals))) propagateFurther", "headerSize = metadataSize + (archiveInfoSize * len(archiveList)) archiveOffsetPointer = headerSize", "is a list of archives, each of which is of", "for i,archive in enumerate(header['archives']): #Find the highest-precision archive that covers", "%s,%s\" % (archive,next) #Looks good, now we create the file", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "archive fh.seek(lower['offset']) fh.write(myPackedPoint) else: #Not our first propagated update to", "* points for secondsPerPoint,points in archiveList])[-1] maxRetention = struct.pack( longFormat,", "propagation') higher = archive lowerArchives = [arc for arc in", "= struct.pack( timestampFormat, int(time.time()) ) oldest = sorted([secondsPerPoint * points", "class open(StringIO): def __init__(self,*args,**kwargs): self.name = args[0] self.mode = args[1]", "def update_many(path,points): \"\"\"update_many(path,points) path is a string points is a", "= {} longFormat = \"!L\" longSize = struct.calcsize(longFormat) floatFormat =", "fh.seek(lowerOffset) fh.write(myPackedPoint) return True else: return False def update(path,value,timestamp=None): \"\"\"update(path,value,timestamp=None)", "is not None] knownPercent = float(len(knownValues)) / float(len(neighborValues)) if knownPercent", "the Whisper database API # Here is the basic layout", "if LOCK: fcntl.flock( fh.fileno(), fcntl.LOCK_EX ) header = __readHeader(fh) now", "%s' % message) __timingBlocks = {} def startBlock(name): __timingBlocks[name] =", "start at the start #debug('__archive_update_many baseInterval is %s' % baseInterval)", "lowerBaseInterval == 0: #First propagated update to this lower archive", "#drop remaining points that don't fit in the database #debug('", "fromOffset) else: #We do wrap around the archive, so we", "= \"\" for (interval,value) in alignedPoints: #debug('__archive_update_many iterating alignedPoint at", "(archiveInfoSize * len(archiveList)) archiveOffsetPointer = headerSize for secondsPerPoint,points in archiveList:", "bytesBeyond = (myOffset + len(packedString)) - archiveEnd #debug(' __archive_update_many myOffset=%d", "== 0: step = archive['secondsPerPoint'] points = (untilInterval - fromInterval)", "/ float(len(neighborValues)) if knownPercent >= xff: #we have enough data", "\"!3L\" archiveInfoSize = struct.calcsize(archiveInfoFormat) debug = startBlock = endBlock =", "return os.path.exists(path) def drop(path): os.remove(path) def enableMemcache(servers = ['127.0.0.1:11211'], min_compress_len", "lowerArchives: fit = lambda i: i - (i % lower['secondsPerPoint'])", "= timestamp - (timestamp % lower['secondsPerPoint']) lowerIntervalEnd = lowerIntervalStart +", "in alignedPoints: #debug('__archive_update_many iterating alignedPoint at %s' % interval) if", "a string points is a list of (timestamp,value) points \"\"\"", ") lastUpdate = struct.pack( timestampFormat, int(time.time()) ) oldest = sorted([secondsPerPoint", "False CACHE_HEADERS = False __headerCache = {} longFormat = \"!L\"", "= unpackedSeries[i] if pointTime == currentInterval: pointValue = unpackedSeries[i+1] valueList[i/2]", "(anything faster than unpack?) byteOrder,pointTypes = pointFormat[0],pointFormat[1:] points = len(seriesString)", "* points) unpackedSeries = struct.unpack(seriesFormat, seriesString) #And finally we construct", "pointSize startInterval = previousInterval - (step * (numberOfPoints-1)) #debug('__archive_update_many done", "an int or float \"\"\" #startBlock('complete update') value = float(value)", "assert fh.tell() == archiveEnd, \"archiveEnd=%d fh.tell=%d bytesBeyond=%d len(packedString)=%d\" % (archiveEnd,fh.tell(),bytesBeyond,len(packedString))", "propagateFurther = False for interval in uniqueLowerIntervals: #debug(' __archive_update_many propagating", "info def __changeLastUpdate(fh): return #XXX Make this a NOP, use", "% archive['secondsPerPoint']) myPackedPoint = struct.pack(pointFormat,myInterval,value) fh.seek(archive['offset']) packedPoint = fh.read(pointSize) (baseInterval,baseValue)", "path=%s points=%d' % (path,len(points))) def __archive_update_many(fh,header,archive,points): step = archive['secondsPerPoint'] #startBlock('__archive_update_many", "packedString[-bytesBeyond:] ) #safe because it can't exceed the archive (retention", "propagate the update to lower-precision archives #startBlock('update propagation') higher =", "(timestamp,value) points \"\"\" #startBlock('complete update_many path=%s points=%d' % (path,len(points))) if", "archives %s,%s\" % (archive,next) #Looks good, now we create the", "= info #endBlock('__readHeader') return info def __changeLastUpdate(fh): return #XXX Make", "fromInterval) / step timeInfo = (fromInterval,untilInterval,step) valueList = [None] *", "archive['secondsPerPoint']) ) fh.seek(archive['offset']) packedPoint = fh.read(pointSize) (baseInterval,baseValue) = struct.unpack(pointFormat,packedPoint) if", "more archives!') currentArchive = None break if not currentArchive: break", "remaining points that don't fit in the database #debug(' update_many", "fh.close() def __propagate(fh,timestamp,xff,higher,lower): lowerIntervalStart = timestamp - (timestamp % lower['secondsPerPoint'])", "p[0],reverse=True) #order points by timestamp, newest first fh = open(path,'r+b')", "timestamp is either an int or float \"\"\" #startBlock('complete update')", "struct.pack(pointFormat,lowerIntervalStart,aggregateValue) fh.seek(lower['offset']) packedPoint = fh.read(pointSize) (lowerBaseInterval,lowerBaseValue) = struct.unpack(pointFormat,packedPoint) if lowerBaseInterval", "(higher['secondsPerPoint'],lower['secondsPerPoint'],interval)) if __propagate(fh,interval,header['xFilesFactor'],higher,lower): propagateFurther = True #debug(' __archive_update_many Successful propagation!')", "lower archive timeDistance = lowerIntervalStart - lowerBaseInterval pointDistance = timeDistance", "(name,time.time() - __timingBlocks.pop(name))) def __readHeader(fh): info = __headerCache.get(fh.name) if info:", "#Looks good, now we create the file and write the", "of the Whisper database API # Here is the basic", "def drop(path): MC.delete(path) def enableDebug(): global open, debug, startBlock, endBlock", "pointFormat[0],pointFormat[1:] points = len(seriesString) / pointSize seriesFormat = byteOrder +", "previousInterval - (step * (numberOfPoints-1)) #debug('__archive_update_many was NOT expected, appending", "except ImportError: CAN_LOCK = False LOCK = False CACHE_HEADERS =", "lowerArchives = [arc for arc in header['archives'] if arc['secondsPerPoint'] >", "retention,\\ \"Lower precision archives must cover larger time intervals than", "\"\"\" #startBlock('complete update_many path=%s points=%d' % (path,len(points))) if not points:", "def exists(path): return MC.get(path) != None def drop(path): MC.delete(path) def", "expected, packing onto currentString') currentString += struct.pack(pointFormat,interval,value) previousInterval = interval", "if not propagateFurther: break higher = lower #endBlock('__archive_update_many propagation') #endBlock('__archive_update_many", "/ higher['secondsPerPoint'] higherSize = higherPoints * pointSize higherLastOffset = higherFirstOffset", "update to this lower archive timeDistance = lowerIntervalStart - lowerBaseInterval", "packedStrings.append( (startInterval,currentString) ) #endBlock('__archive_update_many string packing') #Read base point and", "= unpackedSeries[i] if pointTime == currentInterval: neighborValues[i/2] = unpackedSeries[i+1] currentInterval", "maxRetention = struct.pack( longFormat, oldest ) xFilesFactor = struct.pack( floatFormat,", "currentPoints: #commit all the points we've found that it can", "= Header,Data # Header = Metadata,ArchiveInfo+ # Metadata = lastUpdate,maxRetention,xFilesFactor,archiveCount", "if self.mode == \"r+b\" or self.mode == \"rb\": StringIO.__init__(self, MC.get(self.name))", "that must have known values for a propagation to occur", "to occur \"\"\" #Validate archive configurations... assert archiveList, \"You must", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "an implementation of the Whisper database API # Here is", "fh.seek(higherFirstOffset) if higherFirstOffset < higherLastOffset: #we don't wrap the archive", "points, point=%s age=%d' % (str(point),age)) while currentArchive['retention'] < age: #we", "points=%d' % (path,len(points))) if not points: return points = [", "%s' % baseInterval) #Write all of our packed strings in", "pointTime == currentInterval: neighborValues[i/2] = unpackedSeries[i+1] currentInterval += step #Propagate", "finally we construct a list of values (optimize this!) valueList", "= byteOrder + (pointTypes * points) unpackedSeries = struct.unpack(seriesFormat, seriesString)", "the form (secondsPerPoint,numberOfPoints) xFilesFactor specifies the fraction of data points", "#debug('__archive_update_many done iterating alignedPoints, remainder currentString of %d bytes, startInterval=%s'", "struct.pack(longFormat, len(archiveList)) packedMetadata = lastUpdate + maxRetention + xFilesFactor +", "seriesString += fh.read(untilOffset - archive['offset']) #Now we unpack the series", "if archive['retention'] < diff: continue lowerArchives = header['archives'][i+1:] #We'll pass", "higherFirstOffset < higherLastOffset: #we don't wrap the archive seriesString =", "fh = open(path,'rb') info = __readHeader(fh) fh.close() return info def", "byteDistance = pointDistance * pointSize lowerOffset = lower['offset'] + (byteDistance", "file except in compliance with the License. # You may", "to lower-precision archives #startBlock('update propagation') higher = archive for lower", "min_compress_len = 0): from StringIO import StringIO import memcache global", "% archive['size']) fh.seek(myOffset) archiveEnd = archive['offset'] + archive['size'] bytesBeyond =", "= [] for i in xrange(archiveCount): packedArchiveInfo = fh.read(archiveInfoSize) (offset,secondsPerPoint,points)", "already exists!\" % path fh = open(path,'wb') if LOCK: fcntl.flock(", "unpackedSeries[i+1] currentInterval += step #Propagate aggregateValue to propagate from neighborValues", "and determine where our writes will start fh.seek(archive['offset']) packedBasePoint =", "if not points: return points = [ (int(t),float(v)) for (t,v)", "'\\x00' * (archiveOffsetPointer - headerSize) fh.write(zeroes) fh.close() def __propagate(fh,timestamp,xff,higher,lower): lowerIntervalStart", "0: fh.write( packedString[:-bytesBeyond] ) #debug('We wrapped an archive!') assert fh.tell()", "packedMetadata = lastUpdate + maxRetention + xFilesFactor + archiveCount fh.write(packedMetadata)", "'xFilesFactor' : xff, 'archives' : archives, } if CACHE_HEADERS: __headerCache[fh.name]", "alignedPoints = [ (timestamp - (timestamp % step), value) for", "originalOffset = fh.tell() fh.seek(0) #Based on assumption that first field", "(archiveOffsetPointer - headerSize) fh.write(zeroes) fh.close() def __propagate(fh,timestamp,xff,higher,lower): lowerIntervalStart = timestamp", ") archiveCount = struct.pack(longFormat, len(archiveList)) packedMetadata = lastUpdate + maxRetention", ": points, 'retention' : secondsPerPoint * points, 'size' : points", "= now - timestamp assert diff < header['maxRetention'] and diff", "if we have enough known points knownValues = [v for", "precision archives %s,%s\" % (archive,next) #Looks good, now we create", "/ archive['secondsPerPoint'] byteDistance = pointDistance * pointSize fromOffset = archive['offset']", "seriesFormat = byteOrder + (pointTypes * points) unpackedSeries = struct.unpack(seriesFormat,", "the start #debug('__archive_update_many baseInterval is %s' % baseInterval) #Write all", "#Now we unpack the series data we just read (anything", "we just read byteOrder,pointTypes = pointFormat[0],pointFormat[1:] points = len(seriesString) /", "#startBlock('update propagation') higher = archive for lower in lowerArchives: if", "for lower in lowerArchives: fit = lambda i: i -", "all the archives currentPoints.reverse() __archive_update_many(fh,header,currentArchive,currentPoints) __changeLastUpdate(fh) fh.close() #endBlock('complete update_many path=%s", "# Data = Archive+ # Archive = Point+ # Point", "we construct a list of values neighborValues = [None] *", "(step * (numberOfPoints-1)) #debug('__archive_update_many was NOT expected, appending to packedStrings", "retention = archive[0] * archive[1] nextRetention = next[0] * next[1]", "update to these lower precision archives later break #First we", "and currentPoints: #don't forget to commit after we've checked all", "len(archiveList)) archiveOffsetPointer = headerSize for secondsPerPoint,points in archiveList: archiveInfo =", "a list of values neighborValues = [None] * points currentInterval", "aggregateValue = float(sum(knownValues)) / float(len(knownValues)) #TODO another CF besides average?", "lower['secondsPerPoint'] / higher['secondsPerPoint'] higherSize = higherPoints * pointSize higherLastOffset =", "knownPercent >= xff: #we have enough data to propagate a", "str(point)) currentPoints.append(point) #debug(' update_many done iterating points') if currentArchive and", "diff >= 0, \"Timestamp not covered by any archives in", "int(time.time()) ) oldest = sorted([secondsPerPoint * points for secondsPerPoint,points in", "xFilesFactor = struct.pack( floatFormat, float(xFilesFactor) ) archiveCount = struct.pack(longFormat, len(archiveList))", "KIND, either express or implied. # See the License for", "in points] points.sort(key=lambda p: p[0],reverse=True) #order points by timestamp, newest", "packedStrings.append( (startInterval,currentString) ) currentString = struct.pack(pointFormat,interval,value) previousInterval = interval if", "= struct.unpack(pointFormat,packedPoint) if baseInterval == 0: #This file's first update", "time untilTime is also an epoch time, but defaults to", "(timestamp - (timestamp % step), value) for (timestamp,value) in points", "= None break if not currentArchive: break #drop remaining points", "now = int( time.time() ) if untilTime is None or", "higher['offset'] + (byteDistance % higher['size']) higherPoints = lower['secondsPerPoint'] / higher['secondsPerPoint']", "(fromInterval,untilInterval,step) valueList = [None] * points return (timeInfo,valueList) #Determine fromOffset", "\"\"\" import os, struct, time try: import fcntl CAN_LOCK =", "\"\"\"update(path,value,timestamp=None) path is a string value is a float timestamp", "for (t,v) in points] points.sort(key=lambda p: p[0],reverse=True) #order points by", "all of our packed strings in locations determined by the", "= next[0] * next[1] assert nextRetention > retention,\\ \"Lower precision", "#We do wrap the archive higherEnd = higher['offset'] + higher['size']", "pointDistance * pointSize lowerOffset = lower['offset'] + (byteDistance % lower['size'])", "- (untilTime % archive['secondsPerPoint']) ) fh.seek(archive['offset']) packedPoint = fh.read(pointSize) (baseInterval,baseValue)", "float timestamp is either an int or float \"\"\" #startBlock('complete", "higherBaseInterval == 0: higherFirstOffset = higher['offset'] else: timeDistance = lowerIntervalStart", "archive lowerArchives = [arc for arc in header['archives'] if arc['secondsPerPoint']", "< next[0],\\ \"You cannot configure two archives with the same", "(the \"License\"); # you may not use this file except", "nextRetention > retention,\\ \"Lower precision archives must cover larger time", "higherBaseInterval pointDistance = timeDistance / higher['secondsPerPoint'] byteDistance = pointDistance *", "fh.seek(archive['offset']) seriesString += fh.read(untilOffset - archive['offset']) #Now we unpack the", "timestampSize = struct.calcsize(timestampFormat) valueFormat = \"!d\" valueSize = struct.calcsize(valueFormat) pointFormat", "self.mode == \"wb\": MC.set(self.name, self.getvalue(), min_compress_len = min_compress_len) StringIO.close(self) def", "< diff: continue lowerArchives = header['archives'][i+1:] #We'll pass on the", "= pointDistance * pointSize untilOffset = archive['offset'] + (byteDistance %", "= int( fromTime - (fromTime % archive['secondsPerPoint']) ) untilInterval =", "fh.write(archiveInfo) archiveOffsetPointer += (points * pointSize) zeroes = '\\x00' *", "= [None] * points #pre-allocate entire list for speed currentInterval", "secondsPerPoint, points) fh.write(archiveInfo) archiveOffsetPointer += (points * pointSize) zeroes =", "# # Unless required by applicable law or agreed to", "class open(file): def __init__(self,*args,**kwargs): file.__init__(self,*args,**kwargs) self.writeCount = 0 self.readCount =", "= iter( header['archives'] ) currentArchive = next(archives) #debug(' update_many currentArchive=%s'", "= pointDistance * pointSize myOffset = archive['offset'] + (byteDistance %", "of whisper.py For details on the modification, read https://bugs.launchpad.net/graphite/+bug/245835 \"\"\"", "/ pointSize seriesFormat = byteOrder + (pointTypes * points) unpackedSeries", "untilTime is None or untilTime > now: untilTime = now", "fcntl.LOCK_EX ) lastUpdate = struct.pack( timestampFormat, int(time.time()) ) oldest =", "fh = open(path,'rb') header = __readHeader(fh) now = int( time.time()", "(archive[0],next[0]) retention = archive[0] * archive[1] nextRetention = next[0] *", "(secondsPerPoint,numberOfPoints) xFilesFactor specifies the fraction of data points in a", "the archive seriesString = fh.read(higherLastOffset - higherFirstOffset) else: #We do", "fh.close() #endBlock('complete update') def update_many(path,points): \"\"\"update_many(path,points) path is a string", "implied. # See the License for the specific language governing", "step), value) for (timestamp,value) in points ] #Create a packed", "= interval - baseInterval pointDistance = timeDistance / step byteDistance", "epoch time untilTime is also an epoch time, but defaults", "fh.read(archiveEnd - fromOffset) fh.seek(archive['offset']) seriesString += fh.read(untilOffset - archive['offset']) #Now", "= \"!L\" timestampSize = struct.calcsize(timestampFormat) valueFormat = \"!d\" valueSize =", "pointTime = unpackedSeries[i] if pointTime == currentInterval: neighborValues[i/2] = unpackedSeries[i+1]", "exists(path): return MC.get(path) != None def drop(path): MC.delete(path) def enableDebug():", "float(sum(knownValues)) / float(len(knownValues)) #TODO another CF besides average? myPackedPoint =", "we don't wrap around the archive seriesString = fh.read(untilOffset -", "i in xrange(archiveCount): packedArchiveInfo = fh.read(archiveInfoSize) (offset,secondsPerPoint,points) = struct.unpack(archiveInfoFormat,packedArchiveInfo) archiveInfo", "= timeDistance / step byteDistance = pointDistance * pointSize myOffset", "+ (byteDistance % archive['size']) fh.seek(myOffset) fh.write(myPackedPoint) #Now we propagate the", "= Offset,SecondsPerPoint,Points # Data = Archive+ # Archive = Point+", "higherLastOffset: #we don't wrap the archive seriesString = fh.read(higherLastOffset -", "lowerIntervals = [fit(p[0]) for p in alignedPoints] uniqueLowerIntervals = set(lowerIntervals)", "numberOfPoints = len(currentString) / pointSize startInterval = previousInterval - (step", "we update the highest-precision archive myInterval = timestamp - (timestamp", "False __headerCache = {} longFormat = \"!L\" longSize = struct.calcsize(longFormat)", "propagate from neighborValues if we have enough known points knownValues", "'secondsPerPoint' : secondsPerPoint, 'points' : points, 'retention' : secondsPerPoint *", "lowerIntervalEnd = lowerIntervalStart + lower['secondsPerPoint'] fh.seek(higher['offset']) packedPoint = fh.read(pointSize) (higherBaseInterval,higherBaseValue)", "archives!') currentArchive = None break if not currentArchive: break #drop", "__changeLastUpdate(fh) fh.close() #endBlock('complete update_many path=%s points=%d' % (path,len(points))) def __archive_update_many(fh,header,archive,points):", "start #debug('__archive_update_many baseInterval is %s' % baseInterval) #Write all of", "for archive in header['archives']: if archive['retention'] >= diff: break fromInterval", "byteOrder,pointTypes = pointFormat[0],pointFormat[1:] points = len(seriesString) / pointSize seriesFormat =", "entire list for speed currentInterval = fromInterval step = archive['secondsPerPoint']", "- fromTime for archive in header['archives']: if archive['retention'] >= diff:", "float(len(knownValues)) #TODO another CF besides average? myPackedPoint = struct.pack(pointFormat,lowerIntervalStart,aggregateValue) fh.seek(lower['offset'])", "* pointSize myOffset = archive['offset'] + (byteDistance % archive['size']) fh.seek(myOffset)", "iterating alignedPoints, remainder currentString of %d bytes, startInterval=%s' % (len(currentString),startInterval))", "update_many using next archive %s' % str(currentArchive)) except StopIteration: #debug('", "timeDistance = interval - baseInterval pointDistance = timeDistance / step", ">= xff: #we have enough data to propagate a value!", "just read (anything faster than unpack?) byteOrder,pointTypes = pointFormat[0],pointFormat[1:] points", "list of (timestamp,value) points \"\"\" #startBlock('complete update_many path=%s points=%d' %", "enough known points knownValues = [v for v in neighborValues", "archiveList.sort(key=lambda a: a[0]) #sort by precision (secondsPerPoint) for i,archive in", ") #safe because it can't exceed the archive (retention checking", "= (fromInterval,untilInterval,step) valueList = [None] * points return (timeInfo,valueList) #Determine", "/ float(len(knownValues)) #TODO another CF besides average? myPackedPoint = struct.pack(pointFormat,lowerIntervalStart,aggregateValue)", "Unless required by applicable law or agreed to in writing,", "propagation') __changeLastUpdate(fh) fh.close() #endBlock('complete update') def update_many(path,points): \"\"\"update_many(path,points) path is", "larger time intervals than higher precision archives %s,%s\" % (archive,next)", "} archives.append(archiveInfo) fh.seek(originalOffset) info = { 'lastUpdate' : lastUpdate, 'maxRetention'", "/ lower['secondsPerPoint'] byteDistance = pointDistance * pointSize lowerOffset = lower['offset']", "fh.read(pointSize) (baseInterval,baseValue) = struct.unpack(pointFormat,packedBasePoint) if baseInterval == 0: #This file's", "v in neighborValues if v is not None] knownPercent =", "+= 1 debug('WRITE %d bytes #%d' % (len(data),self.writeCount)) return file.write(self,data)", "the specific language governing permissions and # limitations under the", "myPackedPoint = struct.pack(pointFormat,lowerIntervalStart,aggregateValue) fh.seek(lower['offset']) packedPoint = fh.read(pointSize) (lowerBaseInterval,lowerBaseValue) = struct.unpack(pointFormat,packedPoint)", "lastUpdate, 'maxRetention' : maxRetention, 'xFilesFactor' : xff, 'archives' : archives,", "the database #debug(' update_many adding point=%s' % str(point)) currentPoints.append(point) #debug('", "\"rb\": StringIO.__init__(self, MC.get(self.name)) else: StringIO.__init__(self) def close(self): if self.mode ==", "good, now we create the file and write the header", "oldest ) xFilesFactor = struct.pack( floatFormat, float(xFilesFactor) ) archiveCount =", "__archive_update_many(fh,header,currentArchive,currentPoints) currentPoints = [] try: currentArchive = next(archives) #debug(' update_many", "] #Create a packed string for each contiguous sequence of", "for i in xrange(0,len(unpackedSeries),2): pointTime = unpackedSeries[i] if pointTime ==", "# Here is the basic layout of a whisper data", "= lambda i: i - (i % lower['secondsPerPoint']) lowerIntervals =", "enough data to propagate a value! aggregateValue = float(sum(knownValues)) /", "for i in xrange(archiveCount): packedArchiveInfo = fh.read(archiveInfoSize) (offset,secondsPerPoint,points) = struct.unpack(archiveInfoFormat,packedArchiveInfo)", "interval if currentString: #startInterval = previousInterval - (step * len(currentString)", "of (timestamp,value) points \"\"\" #startBlock('complete update_many path=%s points=%d' % (path,len(points)))", "timestamp, newest first fh = open(path,'r+b') if LOCK: fcntl.flock( fh.fileno(),", "points in this archive #debug(' update_many this point is too", "float \"\"\" #startBlock('complete update') value = float(value) fh = open(path,'r+b')", "the archives currentPoints.reverse() __archive_update_many(fh,header,currentArchive,currentPoints) __changeLastUpdate(fh) fh.close() #endBlock('complete update_many path=%s points=%d'", "that covers timestamp if archive['retention'] < diff: continue lowerArchives =", "archive['size'] bytesBeyond = (myOffset + len(packedString)) - archiveEnd #debug(' __archive_update_many", "fh.read(pointSize) (baseInterval,baseValue) = struct.unpack(pointFormat,packedPoint) if baseInterval == 0: #This file's", "= __readHeader(fh) now = int( time.time() ) if timestamp is", "seriesString = fh.read(higherLastOffset - higherFirstOffset) else: #We do wrap the", "adding point=%s' % str(point)) currentPoints.append(point) #debug(' update_many done iterating points')", "#Based on assumption that first field is lastUpdate now =", "= int( time.time() ) packedTime = struct.pack(timestampFormat,now) fh.write(packedTime) fh.seek(originalOffset) endBlock('__changeLastUpdate()')", "each contiguous sequence of points #startBlock('__archive_update_many string packing') packedStrings =", "= startBlock = endBlock = lambda *a,**k: None def exists(path):", "neighborValues[i/2] = unpackedSeries[i+1] currentInterval += step #Propagate aggregateValue to propagate", "at %s' % interval) if (not previousInterval) or (interval ==", "timeDistance / step byteDistance = pointDistance * pointSize myOffset =", "= 0 self.readCount = 0 def write(self,data): self.writeCount += 1", "or untilTime > now: untilTime = now if fromTime <", "xrange(0,len(unpackedSeries),2): pointTime = unpackedSeries[i] if pointTime == currentInterval: pointValue =", "= fh.tell() fh.seek(0) #Based on assumption that first field is", "xrange(0,len(unpackedSeries),2): pointTime = unpackedSeries[i] if pointTime == currentInterval: neighborValues[i/2] =", "(byteDistance % lower['size']) fh.seek(lowerOffset) fh.write(myPackedPoint) return True else: return False", "= struct.calcsize(metadataFormat) archiveInfoFormat = \"!3L\" archiveInfoSize = struct.calcsize(archiveInfoFormat) debug =", "currentArchive = next(archives) #debug(' update_many using next archive %s' %", "\"Invalid time interval\" diff = now - fromTime for archive", "< higherLastOffset: #we don't wrap the archive seriesString = fh.read(higherLastOffset", "(myOffset + len(packedString)) - archiveEnd #debug(' __archive_update_many myOffset=%d packedString=%d archiveEnd=%d", "from neighborValues if we have enough known points knownValues =", "struct.pack(pointFormat,interval,value) previousInterval = interval else: numberOfPoints = len(currentString) / pointSize", "list of archives, each of which is of the form", "file.write(self,data) def read(self,bytes): self.readCount += 1 debug('READ %d bytes #%d'", "packedStrings: timeDistance = interval - baseInterval pointDistance = timeDistance /", "if baseInterval == 0: step = archive['secondsPerPoint'] points = (untilInterval", "updates to lower-precision archives #startBlock('__archive_update_many propagation') higher = archive lowerArchives", "lowerIntervalStart = timestamp - (timestamp % lower['secondsPerPoint']) lowerIntervalEnd = lowerIntervalStart", "(timestamp,value) in points ] #Create a packed string for each", "currentInterval: pointValue = unpackedSeries[i+1] valueList[i/2] = pointValue #in-place reassignment is", "archives, } if CACHE_HEADERS: __headerCache[fh.name] = info #endBlock('__readHeader') return info", "a modified version of whisper.py For details on the modification,", "archive['secondsPerPoint']) ) untilInterval = int( untilTime - (untilTime % archive['secondsPerPoint'])", "propagateFurther=%s' % propagateFurther) if not propagateFurther: break higher = lower", ") oldest = sorted([secondsPerPoint * points for secondsPerPoint,points in archiveList])[-1]", "must cover larger time intervals than higher precision archives %s,%s\"", "fromTime < untilTime, \"Invalid time interval\" diff = now -", "file and write the header assert not exists(path), \"File %s", "as the base, so we start at the start #debug('__archive_update_many", "in header['archives']: if archive['retention'] >= diff: break fromInterval = int(", "debug, startBlock, endBlock class open(file): def __init__(self,*args,**kwargs): file.__init__(self,*args,**kwargs) self.writeCount =", "__archive_update_many propagating from %d to %d, interval=%d' % (higher['secondsPerPoint'],lower['secondsPerPoint'],interval)) if", "= myInterval,value else: #Not our first update timeDistance = myInterval", "archiveList])[-1] maxRetention = struct.pack( longFormat, oldest ) xFilesFactor = struct.pack(", "evenly divide all lower precision archives' precision %s,%s\" % (archive[0],next[0])", "first field is lastUpdate now = int( time.time() ) packedTime", "in lowerArchives: fit = lambda i: i - (i %", "archiveEnd = archive['offset'] + archive['size'] bytesBeyond = (myOffset + len(packedString))", "* next[1] assert nextRetention > retention,\\ \"Lower precision archives must", "#debug('__archive_update_many first update') baseInterval = packedStrings[0][0] #use our first string", "if baseInterval == 0: #This file's first update #debug('__archive_update_many first", "database API # Here is the basic layout of a", "expected, appending to packedStrings startInterval=%s currentString=%d bytes' % (startInterval,len(currentString))) packedStrings.append(", "drop(path): MC.delete(path) def enableDebug(): global open, debug, startBlock, endBlock class", "archives' precision must evenly divide all lower precision archives' precision", "currentInterval += step #Propagate aggregateValue to propagate from neighborValues if", "fromOffset = archive['offset'] + (byteDistance % archive['size']) #Determine untilOffset timeDistance", "fit here, currentPoints=%d' % len(currentPoints)) if currentPoints: #commit all the", "packedArchiveInfo = fh.read(archiveInfoSize) (offset,secondsPerPoint,points) = struct.unpack(archiveInfoFormat,packedArchiveInfo) archiveInfo = { 'offset'", "fh.seek(0) #Based on assumption that first field is lastUpdate now", "higher['offset']) #Now we unpack the series data we just read", "drop(path): os.remove(path) def enableMemcache(servers = ['127.0.0.1:11211'], min_compress_len = 0): from", "lastUpdate = struct.pack( timestampFormat, int(time.time()) ) oldest = sorted([secondsPerPoint *", "if baseInterval == 0: #This file's first update fh.seek(archive['offset']) fh.write(myPackedPoint)", "#debug(' update_many done iterating points') if currentArchive and currentPoints: #don't", "= packedStrings[0][0] #use our first string as the base, so", "if __propagate(fh,interval,header['xFilesFactor'],higher,lower): propagateFurther = True #debug(' __archive_update_many Successful propagation!') #debug('", "now timestamp = int(timestamp) diff = now - timestamp assert", "time interval\" diff = now - fromTime for archive in", "points: age = now - point[0] #debug(' update_many iterating points,", "< untilOffset: #If we don't wrap around the archive seriesString", "\"\"\" fh = open(path,'rb') info = __readHeader(fh) fh.close() return info", "+= fh.read(untilOffset - archive['offset']) #Now we unpack the series data", "= ['127.0.0.1:11211'], min_compress_len = 0): from StringIO import StringIO import", "a float timestamp is either an int or float \"\"\"", "#We'll pass on the update to these lower precision archives", "have known values for a propagation to occur \"\"\" #Validate", "= previousInterval - (step * len(currentString) / pointSize) + step", "higherPoints * pointSize higherLastOffset = higherFirstOffset + (higherSize % higher['size'])", "pointSize = struct.calcsize(pointFormat) metadataFormat = \"!2LfL\" metadataSize = struct.calcsize(metadataFormat) archiveInfoFormat", "info = __readHeader(fh) fh.close() return info def fetch(path,fromTime,untilTime=None): \"\"\"fetch(path,fromTime,untilTime=None) path", "(step * len(currentString) / pointSize) + step numberOfPoints = len(currentString)", "= { 'lastUpdate' : lastUpdate, 'maxRetention' : maxRetention, 'xFilesFactor' :", "in packedStrings: timeDistance = interval - baseInterval pointDistance = timeDistance", "= True except ImportError: CAN_LOCK = False LOCK = False", "= archive['offset'] + archive['size'] bytesBeyond = (myOffset + len(packedString)) -", "too old to fit here, currentPoints=%d' % len(currentPoints)) if currentPoints:", "archive[1] nextRetention = next[0] * next[1] assert nextRetention > retention,\\", "% (len(currentString),startInterval)) packedStrings.append( (startInterval,currentString) ) #endBlock('__archive_update_many string packing') #Read base", "of data points in a propagation interval that must have", "bytes #%d' % (len(data),self.writeCount)) return file.write(self,data) def read(self,bytes): self.readCount +=", "= higher['offset'] + higher['size'] seriesString = fh.read(higherEnd - higherFirstOffset) fh.seek(higher['offset'])", "2008 Orbitz WorldWide # # Licensed under the Apache License,", "= False __headerCache = {} longFormat = \"!L\" longSize =", "(startInterval,currentString) ) currentString = struct.pack(pointFormat,interval,value) previousInterval = interval if currentString:", ": lastUpdate, 'maxRetention' : maxRetention, 'xFilesFactor' : xff, 'archives' :", "create the file and write the header assert not exists(path),", "update timeDistance = myInterval - baseInterval pointDistance = timeDistance /", "else: numberOfPoints = len(currentString) / pointSize startInterval = previousInterval -", "higherEnd = higher['offset'] + higher['size'] seriesString = fh.read(higherEnd - higherFirstOffset)", "len(packedString)) - archiveEnd #debug(' __archive_update_many myOffset=%d packedString=%d archiveEnd=%d bytesBeyond=%d' %", "= lastUpdate,maxRetention,xFilesFactor,archiveCount # ArchiveInfo = Offset,SecondsPerPoint,Points # Data = Archive+", "break next = archiveList[i+1] assert archive[0] < next[0],\\ \"You cannot", "fh = open(path,'r+b') if LOCK: fcntl.flock( fh.fileno(), fcntl.LOCK_EX ) header", "points in the interval fh.seek(fromOffset) if fromOffset < untilOffset: #If", "pass on the update to these lower precision archives later", "You may obtain a copy of the License at #", "= struct.unpack(metadataFormat,packedMetadata) archives = [] for i in xrange(archiveCount): packedArchiveInfo", "currentArchive = None break if not currentArchive: break #drop remaining", "file=%s archive=%s points=%d' % (fh.name,step,len(points))) alignedPoints = [ (timestamp -", "file's first update fh.seek(archive['offset']) fh.write(myPackedPoint) baseInterval,baseValue = myInterval,value else: #Not", "= '\\x00' * (archiveOffsetPointer - headerSize) fh.write(zeroes) fh.close() def __propagate(fh,timestamp,xff,higher,lower):", "/ archive['secondsPerPoint'] byteDistance = pointDistance * pointSize untilOffset = archive['offset']", "* points, 'size' : points * pointSize, } archives.append(archiveInfo) fh.seek(originalOffset)", "archive=%s points=%d' % (fh.name,step,len(points))) alignedPoints = [ (timestamp - (timestamp", "archives currentPoints.reverse() __archive_update_many(fh,header,currentArchive,currentPoints) __changeLastUpdate(fh) fh.close() #endBlock('complete update_many path=%s points=%d' %", "= endBlock = lambda *a,**k: None def exists(path): return os.path.exists(path)", "Data = Archive+ # Archive = Point+ # Point =", "higher = lower #endBlock('update propagation') __changeLastUpdate(fh) fh.close() #endBlock('complete update') def", "\"Timestamp not covered by any archives in this database\" for", "ImportError: CAN_LOCK = False LOCK = False CACHE_HEADERS = False", "an epoch time, but defaults to now \"\"\" fh =", "time.time() ) if timestamp is None: timestamp = now timestamp", "(len(alignedPoints),len(uniqueLowerIntervals))) propagateFurther = False for interval in uniqueLowerIntervals: #debug(' __archive_update_many", "timestamp = int(timestamp) diff = now - timestamp assert diff", "untilTime is also an epoch time, but defaults to now", "int( time.time() ) packedTime = struct.pack(timestampFormat,now) fh.write(packedTime) fh.seek(originalOffset) endBlock('__changeLastUpdate()') def", "self.mode == \"r+b\" or self.mode == \"wb\": MC.set(self.name, self.getvalue(), min_compress_len", "NOT expected, appending to packedStrings startInterval=%s currentString=%d bytes' % (startInterval,len(currentString)))", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "list of values neighborValues = [None] * points currentInterval =", "fh.seek(originalOffset) endBlock('__changeLastUpdate()') def create(path,archiveList,xFilesFactor=0.5): \"\"\"create(path,archiveList,xFilesFactor=0.5) path is a string archiveList", "update_many(path,points): \"\"\"update_many(path,points) path is a string points is a list", "originalOffset = fh.tell() fh.seek(0) packedMetadata = fh.read(metadataSize) (lastUpdate,maxRetention,xff,archiveCount) = struct.unpack(metadataFormat,packedMetadata)", "on assumption that first field is lastUpdate now = int(", "(byteDistance % archive['size']) #Read all the points in the interval", "fit = lambda i: i - (i % lower['secondsPerPoint']) lowerIntervals", "= struct.unpack(pointFormat,packedPoint) if lowerBaseInterval == 0: #First propagated update to", "return points = [ (int(t),float(v)) for (t,v) in points] points.sort(key=lambda", "= interval else: numberOfPoints = len(currentString) / pointSize startInterval =", "pointSize higherLastOffset = higherFirstOffset + (higherSize % higher['size']) fh.seek(higherFirstOffset) if", "= fh.read(metadataSize) (lastUpdate,maxRetention,xff,archiveCount) = struct.unpack(metadataFormat,packedMetadata) archives = [] for i", "CAN_LOCK = True except ImportError: CAN_LOCK = False LOCK =", "def __propagate(fh,timestamp,xff,higher,lower): lowerIntervalStart = timestamp - (timestamp % lower['secondsPerPoint']) lowerIntervalEnd", "archiveEnd, \"archiveEnd=%d fh.tell=%d bytesBeyond=%d len(packedString)=%d\" % (archiveEnd,fh.tell(),bytesBeyond,len(packedString)) fh.seek( archive['offset'] )", "= \"!d\" valueSize = struct.calcsize(valueFormat) pointFormat = \"!Ld\" pointSize =", "def enableDebug(): global open, debug, startBlock, endBlock class open(file): def", "not exists(path), \"File %s already exists!\" % path fh =", "0: step = archive['secondsPerPoint'] points = (untilInterval - fromInterval) /", "= pointDistance * pointSize fromOffset = archive['offset'] + (byteDistance %", "%s,%s\" % (archive,next) assert (next[0] % archive[0]) == 0,\\ \"Higher", "fromOffset < untilOffset: #If we don't wrap around the archive", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "- (i % lower['secondsPerPoint']) lowerIntervals = [fit(p[0]) for p in", "currentString = \"\" for (interval,value) in alignedPoints: #debug('__archive_update_many iterating alignedPoint", "update') value = float(value) fh = open(path,'r+b') if LOCK: fcntl.flock(", "break higher = lower #endBlock('__archive_update_many propagation') #endBlock('__archive_update_many file=%s archive=%s points=%d'", "License. # You may obtain a copy of the License", "is of the form (secondsPerPoint,numberOfPoints) xFilesFactor specifies the fraction of", "len(archiveList) - 1: break next = archiveList[i+1] assert archive[0] <", "we've checked all the archives currentPoints.reverse() __archive_update_many(fh,header,currentArchive,currentPoints) __changeLastUpdate(fh) fh.close() #endBlock('complete", "+ archiveCount fh.write(packedMetadata) headerSize = metadataSize + (archiveInfoSize * len(archiveList))", "archive #debug(' update_many this point is too old to fit", "% (higher['secondsPerPoint'],lower['secondsPerPoint'],interval)) if __propagate(fh,interval,header['xFilesFactor'],higher,lower): propagateFurther = True #debug(' __archive_update_many Successful", "exists!\" % path fh = open(path,'wb') if LOCK: fcntl.flock( fh.fileno(),", "StringIO.__init__(self, MC.get(self.name)) else: StringIO.__init__(self) def close(self): if self.mode == \"r+b\"", "secondsPerPoint, 'points' : points, 'retention' : secondsPerPoint * points, 'size'", "* points currentInterval = lowerIntervalStart step = higher['secondsPerPoint'] for i", "header['archives'][i+1:] #We'll pass on the update to these lower precision", "precision archives must cover larger time intervals than higher precision", "higherFirstOffset = higher['offset'] + (byteDistance % higher['size']) higherPoints = lower['secondsPerPoint']", "startBlock(name): __timingBlocks[name] = time.time() def endBlock(name): debug(\"%s took %.5f seconds\"", "a packed string for each contiguous sequence of points #startBlock('__archive_update_many", "values neighborValues = [None] * points currentInterval = lowerIntervalStart step", "or float \"\"\" #startBlock('complete update') value = float(value) fh =", "if arc['secondsPerPoint'] > archive['secondsPerPoint']] #debug('__archive_update_many I have %d lower archives'", "layout of a whisper data file # # File =", "= fh.read(archiveEnd - fromOffset) fh.seek(archive['offset']) seriesString += fh.read(untilOffset - archive['offset'])", "= struct.calcsize(timestampFormat) valueFormat = \"!d\" valueSize = struct.calcsize(valueFormat) pointFormat =", "/ step timeInfo = (fromInterval,untilInterval,step) valueList = [None] * points", "or self.mode == \"wb\": MC.set(self.name, self.getvalue(), min_compress_len = min_compress_len) StringIO.close(self)", "struct.pack(pointFormat,interval,value) previousInterval = interval if currentString: #startInterval = previousInterval -", "try: import fcntl CAN_LOCK = True except ImportError: CAN_LOCK =", "archive configurations... assert archiveList, \"You must specify at least one", "timeDistance = lowerIntervalStart - higherBaseInterval pointDistance = timeDistance / higher['secondsPerPoint']", "no more archives!') currentArchive = None break if not currentArchive:", "defaults to now \"\"\" fh = open(path,'rb') header = __readHeader(fh)", "archive['offset'] ) fh.write( packedString[-bytesBeyond:] ) #safe because it can't exceed", "if higherFirstOffset < higherLastOffset: #we don't wrap the archive seriesString", "this point is too old to fit here, currentPoints=%d' %", "remainder currentString of %d bytes, startInterval=%s' % (len(currentString),startInterval)) packedStrings.append( (startInterval,currentString)", "our first string as the base, so we start at", "byteOrder + (pointTypes * points) unpackedSeries = struct.unpack(seriesFormat, seriesString) #And", "# File = Header,Data # Header = Metadata,ArchiveInfo+ # Metadata", "append() currentInterval += step fh.close() timeInfo = (fromInterval,untilInterval,step) return (timeInfo,valueList)", "= int( untilTime - (untilTime % archive['secondsPerPoint']) ) fh.seek(archive['offset']) packedPoint", "fh.seek(lower['offset']) fh.write(myPackedPoint) else: #Not our first propagated update to this", "diff < header['maxRetention'] and diff >= 0, \"Timestamp not covered", "the same precision %s,%s\" % (archive,next) assert (next[0] % archive[0])", "__archive_update_many(fh,header,archive,points): step = archive['secondsPerPoint'] #startBlock('__archive_update_many file=%s archive=%s points=%d' % (fh.name,step,len(points)))", "\"wb\": MC.set(self.name, self.getvalue(), min_compress_len = min_compress_len) StringIO.close(self) def exists(path): return", "if fromTime < (now - header['maxRetention']): fromTime = now -", "#use our first string as the base, so we start", "baseInterval is %s' % baseInterval) #Write all of our packed", "= timestamp - (timestamp % archive['secondsPerPoint']) myPackedPoint = struct.pack(pointFormat,myInterval,value) fh.seek(archive['offset'])", "#And finally we construct a list of values neighborValues =", "lower archive fh.seek(lower['offset']) fh.write(myPackedPoint) else: #Not our first propagated update", "archive[0] * archive[1] nextRetention = next[0] * next[1] assert nextRetention", "not None] knownPercent = float(len(knownValues)) / float(len(neighborValues)) if knownPercent >=", "#Now we unpack the series data we just read byteOrder,pointTypes", "(t,v) in points] points.sort(key=lambda p: p[0],reverse=True) #order points by timestamp,", "age: #we can't fit any more points in this archive", "\"!L\" timestampSize = struct.calcsize(timestampFormat) valueFormat = \"!d\" valueSize = struct.calcsize(valueFormat)", "fromInterval = int( fromTime - (fromTime % archive['secondsPerPoint']) ) untilInterval", "= struct.unpack(pointFormat,packedBasePoint) if baseInterval == 0: #This file's first update", "#Create a packed string for each contiguous sequence of points", "or (interval == previousInterval + step): #debug('__archive_update_many was expected, packing", "and diff >= 0, \"Timestamp not covered by any archives", "int(timestamp) diff = now - timestamp assert diff < header['maxRetention']", "baseInterval == 0: #This file's first update fh.seek(archive['offset']) fh.write(myPackedPoint) baseInterval,baseValue", "base point and determine where our writes will start fh.seek(archive['offset'])", "operations') for (interval,packedString) in packedStrings: timeDistance = interval - baseInterval", "have %d lower archives' % len(lowerArchives)) for lower in lowerArchives:", "this archive #debug(' update_many this point is too old to", "pointDistance = timeDistance / lower['secondsPerPoint'] byteDistance = pointDistance * pointSize", "assert nextRetention > retention,\\ \"Lower precision archives must cover larger", "myOffset = archive['offset'] + (byteDistance % archive['size']) fh.seek(myOffset) archiveEnd =", "version of whisper.py For details on the modification, read https://bugs.launchpad.net/graphite/+bug/245835", "update to this lower archive fh.seek(lower['offset']) fh.write(myPackedPoint) else: #Not our", "points return (timeInfo,valueList) #Determine fromOffset timeDistance = fromInterval - baseInterval", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "#endBlock('__readHeader') return info def __changeLastUpdate(fh): return #XXX Make this a", "[] previousInterval = None currentString = \"\" for (interval,value) in", "#debug('__archive_update_many was expected, packing onto currentString') currentString += struct.pack(pointFormat,interval,value) previousInterval", "in xrange(0,len(unpackedSeries),2): pointTime = unpackedSeries[i] if pointTime == currentInterval: neighborValues[i/2]", "= [] try: currentArchive = next(archives) #debug(' update_many using next", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "for the specific language governing permissions and # limitations under", "== \"r+b\" or self.mode == \"rb\": StringIO.__init__(self, MC.get(self.name)) else: StringIO.__init__(self)", "+ lower['secondsPerPoint'] fh.seek(higher['offset']) packedPoint = fh.read(pointSize) (higherBaseInterval,higherBaseValue) = struct.unpack(pointFormat,packedPoint) if", "untilInterval - baseInterval pointDistance = timeDistance / archive['secondsPerPoint'] byteDistance =", "known values for a propagation to occur \"\"\" #Validate archive", ") if timestamp is None: timestamp = now timestamp =", "This module is an implementation of the Whisper database API", "int( fromTime - (fromTime % archive['secondsPerPoint']) ) untilInterval = int(", "else: timeDistance = lowerIntervalStart - higherBaseInterval pointDistance = timeDistance /", "# # # This module is an implementation of the", "language governing permissions and # limitations under the License. #", "CAN_LOCK = False LOCK = False CACHE_HEADERS = False __headerCache", "= None currentString = \"\" for (interval,value) in alignedPoints: #debug('__archive_update_many", "required by applicable law or agreed to in writing, software", "set(lowerIntervals) #debug(' __archive_update_many points=%d unique=%d' % (len(alignedPoints),len(uniqueLowerIntervals))) propagateFurther = False", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "field is lastUpdate now = int( time.time() ) packedTime =", "== \"wb\": MC.set(self.name, self.getvalue(), min_compress_len = min_compress_len) StringIO.close(self) def exists(path):", "headerSize for secondsPerPoint,points in archiveList: archiveInfo = struct.pack(archiveInfoFormat, archiveOffsetPointer, secondsPerPoint,", "is a string archiveList is a list of archives, each", "= \"!2LfL\" metadataSize = struct.calcsize(metadataFormat) archiveInfoFormat = \"!3L\" archiveInfoSize =", "for arc in header['archives'] if arc['secondsPerPoint'] > archive['secondsPerPoint']] #debug('__archive_update_many I", "License. # # # This module is an implementation of", "archive['offset'] + (byteDistance % archive['size']) #Determine untilOffset timeDistance = untilInterval", "['127.0.0.1:11211'], min_compress_len = 0): from StringIO import StringIO import memcache", "self.name = args[0] self.mode = args[1] if self.mode == \"r+b\"", "strings in locations determined by the baseInterval #startBlock('__archive_update_many write() operations')", "instead startBlock('__changeLastUpdate()') originalOffset = fh.tell() fh.seek(0) #Based on assumption that", "in archiveList: archiveInfo = struct.pack(archiveInfoFormat, archiveOffsetPointer, secondsPerPoint, points) fh.write(archiveInfo) archiveOffsetPointer", "len(seriesString) / pointSize seriesFormat = byteOrder + (pointTypes * points)", "[ (timestamp - (timestamp % step), value) for (timestamp,value) in", "configuration!\" archiveList.sort(key=lambda a: a[0]) #sort by precision (secondsPerPoint) for i,archive", "(fromTime % archive['secondsPerPoint']) ) untilInterval = int( untilTime - (untilTime", "agreed to in writing, software # distributed under the License", "interval in uniqueLowerIntervals: #debug(' __archive_update_many propagating from %d to %d,", "distributed under the License is distributed on an \"AS IS\"", "(secondsPerPoint) for i,archive in enumerate(archiveList): if i == len(archiveList) -", "packedBasePoint = fh.read(pointSize) (baseInterval,baseValue) = struct.unpack(pointFormat,packedBasePoint) if baseInterval == 0:", "pointDistance = timeDistance / archive['secondsPerPoint'] byteDistance = pointDistance * pointSize", "another CF besides average? myPackedPoint = struct.pack(pointFormat,lowerIntervalStart,aggregateValue) fh.seek(lower['offset']) packedPoint =", "= pointDistance * pointSize lowerOffset = lower['offset'] + (byteDistance %", "a string archiveList is a list of archives, each of", "%d, interval=%d' % (higher['secondsPerPoint'],lower['secondsPerPoint'],interval)) if __propagate(fh,interval,header['xFilesFactor'],higher,lower): propagateFurther = True #debug('", "string fromTime is an epoch time untilTime is also an", "(higherSize % higher['size']) fh.seek(higherFirstOffset) if higherFirstOffset < higherLastOffset: #we don't", "packedStrings = [] previousInterval = None currentString = \"\" for", "precision archives' precision must evenly divide all lower precision archives'", "currentString=%d bytes' % (startInterval,len(currentString))) packedStrings.append( (startInterval,currentString) ) currentString = struct.pack(pointFormat,interval,value)", "can't fit any more points in this archive #debug(' update_many", "fh.write(packedString) #endBlock('__archive_update_many write() operations') #Now we propagate the updates to", "LOCK = False CACHE_HEADERS = False __headerCache = {} longFormat", "byteDistance = pointDistance * pointSize fromOffset = archive['offset'] + (byteDistance", ">= 0, \"Timestamp not covered by any archives in this", "points we've found that it can fit currentPoints.reverse() #put points", "timestamp = now timestamp = int(timestamp) diff = now -", "propagated update to this lower archive fh.seek(lower['offset']) fh.write(myPackedPoint) else: #Not", "timestamp assert diff < header['maxRetention'] and diff >= 0, \"Timestamp", "= [fit(p[0]) for p in alignedPoints] uniqueLowerIntervals = set(lowerIntervals) #debug('", "propagateFurther) if not propagateFurther: break higher = lower #endBlock('__archive_update_many propagation')", "knownValues = [v for v in neighborValues if v is", "= higher['secondsPerPoint'] for i in xrange(0,len(unpackedSeries),2): pointTime = unpackedSeries[i] if", "0 self.readCount = 0 def write(self,data): self.writeCount += 1 debug('WRITE", "points=%d' % (path,len(points))) def __archive_update_many(fh,header,archive,points): step = archive['secondsPerPoint'] #startBlock('__archive_update_many file=%s", "we propagate the update to lower-precision archives #startBlock('update propagation') higher", "for secondsPerPoint,points in archiveList])[-1] maxRetention = struct.pack( longFormat, oldest )", "lower['secondsPerPoint'] byteDistance = pointDistance * pointSize lowerOffset = lower['offset'] +", "enumerate(header['archives']): #Find the highest-precision archive that covers timestamp if archive['retention']", "same precision %s,%s\" % (archive,next) assert (next[0] % archive[0]) ==", "#Read all the points in the interval fh.seek(fromOffset) if fromOffset", "for (interval,packedString) in packedStrings: timeDistance = interval - baseInterval pointDistance", "#Find the highest-precision archive that covers timestamp if archive['retention'] <", "logic above) else: fh.write(packedString) #endBlock('__archive_update_many write() operations') #Now we propagate", "- (timestamp % lower['secondsPerPoint']) lowerIntervalEnd = lowerIntervalStart + lower['secondsPerPoint'] fh.seek(higher['offset'])", "return True else: return False def update(path,value,timestamp=None): \"\"\"update(path,value,timestamp=None) path is", "now = int( time.time() ) if timestamp is None: timestamp", "timeDistance / archive['secondsPerPoint'] byteDistance = pointDistance * pointSize myOffset =", "points for secondsPerPoint,points in archiveList])[-1] maxRetention = struct.pack( longFormat, oldest", "[v for v in neighborValues if v is not None]", "[] try: currentArchive = next(archives) #debug(' update_many using next archive", "# This module is an implementation of the Whisper database", "a: a[0]) #sort by precision (secondsPerPoint) for i,archive in enumerate(archiveList):", "Point+ # Point = timestamp,value \"\"\" NOTE: This is a", "pointFormat = \"!Ld\" pointSize = struct.calcsize(pointFormat) metadataFormat = \"!2LfL\" metadataSize", "archiveList[i+1] assert archive[0] < next[0],\\ \"You cannot configure two archives", "is a string \"\"\" fh = open(path,'rb') info = __readHeader(fh)", "header = __readHeader(fh) now = int( time.time() ) if timestamp", "is None: timestamp = now timestamp = int(timestamp) diff =", "lower['size']) fh.seek(lowerOffset) fh.write(myPackedPoint) return True else: return False def update(path,value,timestamp=None):", "fh.write(zeroes) fh.close() def __propagate(fh,timestamp,xff,higher,lower): lowerIntervalStart = timestamp - (timestamp %", "OR CONDITIONS OF ANY KIND, either express or implied. #", "False LOCK = False CACHE_HEADERS = False __headerCache = {}", "string packing') packedStrings = [] previousInterval = None currentString =", "configure two archives with the same precision %s,%s\" % (archive,next)", "#Write all of our packed strings in locations determined by", "the License is distributed on an \"AS IS\" BASIS, #", "if self.mode == \"r+b\" or self.mode == \"wb\": MC.set(self.name, self.getvalue(),", "= Archive+ # Archive = Point+ # Point = timestamp,value", "propagateFurther: break higher = lower #endBlock('__archive_update_many propagation') #endBlock('__archive_update_many file=%s archive=%s", "archiveInfoSize = struct.calcsize(archiveInfoFormat) debug = startBlock = endBlock = lambda", "next[0] * next[1] assert nextRetention > retention,\\ \"Lower precision archives", "= unpackedSeries[i+1] valueList[i/2] = pointValue #in-place reassignment is faster than", "baseInterval pointDistance = timeDistance / step byteDistance = pointDistance *", "open(file): def __init__(self,*args,**kwargs): file.__init__(self,*args,**kwargs) self.writeCount = 0 self.readCount = 0", "construct a list of values (optimize this!) valueList = [None]", "= (myOffset + len(packedString)) - archiveEnd #debug(' __archive_update_many myOffset=%d packedString=%d", "untilOffset: #If we don't wrap around the archive seriesString =", "the series data we just read (anything faster than unpack?)", "None currentString = \"\" for (interval,value) in alignedPoints: #debug('__archive_update_many iterating", "timestampFormat = \"!L\" timestampSize = struct.calcsize(timestampFormat) valueFormat = \"!d\" valueSize", "= (untilInterval - fromInterval) / step timeInfo = (fromInterval,untilInterval,step) valueList", "law or agreed to in writing, software # distributed under", "#debug(' update_many no more archives!') currentArchive = None break if", "= open(path,'rb') info = __readHeader(fh) fh.close() return info def fetch(path,fromTime,untilTime=None):", "to commit after we've checked all the archives currentPoints.reverse() __archive_update_many(fh,header,currentArchive,currentPoints)", "timestamp - (timestamp % lower['secondsPerPoint']) lowerIntervalEnd = lowerIntervalStart + lower['secondsPerPoint']", "= lastUpdate + maxRetention + xFilesFactor + archiveCount fh.write(packedMetadata) headerSize", "previousInterval - (step * (numberOfPoints-1)) #debug('__archive_update_many done iterating alignedPoints, remainder", "fh.tell() fh.seek(0) packedMetadata = fh.read(metadataSize) (lastUpdate,maxRetention,xff,archiveCount) = struct.unpack(metadataFormat,packedMetadata) archives =", "secondsPerPoint * points, 'size' : points * pointSize, } archives.append(archiveInfo)", "is either an int or float \"\"\" #startBlock('complete update') value", "for a propagation to occur \"\"\" #Validate archive configurations... assert", "fh.read(untilOffset - archive['offset']) #Now we unpack the series data we", "fh.seek(higher['offset']) packedPoint = fh.read(pointSize) (higherBaseInterval,higherBaseValue) = struct.unpack(pointFormat,packedPoint) if higherBaseInterval ==", "may obtain a copy of the License at # #", "%s' % str(currentArchive)) except StopIteration: #debug(' update_many no more archives!')", "timestamp is None: timestamp = now timestamp = int(timestamp) diff", "fetch(path,fromTime,untilTime=None): \"\"\"fetch(path,fromTime,untilTime=None) path is a string fromTime is an epoch", "by timestamp, newest first fh = open(path,'r+b') if LOCK: fcntl.flock(", "#commit all the points we've found that it can fit", "xff, 'archives' : archives, } if CACHE_HEADERS: __headerCache[fh.name] = info", "* pointSize) zeroes = '\\x00' * (archiveOffsetPointer - headerSize) fh.write(zeroes)", "highest-precision archive that covers timestamp if archive['retention'] < diff: continue", "if (not previousInterval) or (interval == previousInterval + step): #debug('__archive_update_many", "may not use this file except in compliance with the", "that it can fit currentPoints.reverse() #put points in chronological order", "% (archive,next) #Looks good, now we create the file and", "archive timeDistance = lowerIntervalStart - lowerBaseInterval pointDistance = timeDistance /", "whisper data file # # File = Header,Data # Header", "__timingBlocks = {} def startBlock(name): __timingBlocks[name] = time.time() def endBlock(name):", "this file except in compliance with the License. # You", "= [] previousInterval = None currentString = \"\" for (interval,value)", "longFormat = \"!L\" longSize = struct.calcsize(longFormat) floatFormat = \"!f\" floatSize", "= args[1] if self.mode == \"r+b\" or self.mode == \"rb\":", "struct.calcsize(archiveInfoFormat) debug = startBlock = endBlock = lambda *a,**k: None", "points] points.sort(key=lambda p: p[0],reverse=True) #order points by timestamp, newest first", "# Point = timestamp,value \"\"\" NOTE: This is a modified", "= timeDistance / archive['secondsPerPoint'] byteDistance = pointDistance * pointSize untilOffset", "pointSize, } archives.append(archiveInfo) fh.seek(originalOffset) info = { 'lastUpdate' : lastUpdate,", "seconds\" % (name,time.time() - __timingBlocks.pop(name))) def __readHeader(fh): info = __headerCache.get(fh.name)", "+ (byteDistance % lower['size']) fh.seek(lowerOffset) fh.write(myPackedPoint) return True else: return", "#Validate archive configurations... assert archiveList, \"You must specify at least", "# # Licensed under the Apache License, Version 2.0 (the", "in points ] #Create a packed string for each contiguous", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "form (secondsPerPoint,numberOfPoints) xFilesFactor specifies the fraction of data points in", "interval else: numberOfPoints = len(currentString) / pointSize startInterval = previousInterval", "timeDistance = untilInterval - baseInterval pointDistance = timeDistance / archive['secondsPerPoint']", "our first propagated update to this lower archive timeDistance =", "time.time() ) archives = iter( header['archives'] ) currentArchive = next(archives)", ") header = __readHeader(fh) now = int( time.time() ) archives", "= lowerIntervalStart step = higher['secondsPerPoint'] for i in xrange(0,len(unpackedSeries),2): pointTime", "higher precision archives %s,%s\" % (archive,next) #Looks good, now we", "= archive[0] * archive[1] nextRetention = next[0] * next[1] assert", "pointSize myOffset = archive['offset'] + (byteDistance % archive['size']) fh.seek(myOffset) archiveEnd", "pointSize startInterval = previousInterval - (step * (numberOfPoints-1)) #debug('__archive_update_many was", "return info #startBlock('__readHeader') originalOffset = fh.tell() fh.seek(0) packedMetadata = fh.read(metadataSize)", "fh.read(metadataSize) (lastUpdate,maxRetention,xff,archiveCount) = struct.unpack(metadataFormat,packedMetadata) archives = [] for i in", "iterating points, point=%s age=%d' % (str(point),age)) while currentArchive['retention'] < age:", "< header['maxRetention'] and diff >= 0, \"Timestamp not covered by", "#in-place reassignment is faster than append() currentInterval += step fh.close()", "base, so we start at the start #debug('__archive_update_many baseInterval is", "pointSize untilOffset = archive['offset'] + (byteDistance % archive['size']) #Read all", "propagation!') #debug(' __archive_update_many propagateFurther=%s' % propagateFurther) if not propagateFurther: break", "+ (higherSize % higher['size']) fh.seek(higherFirstOffset) if higherFirstOffset < higherLastOffset: #we", "LOCK: fcntl.flock( fh.fileno(), fcntl.LOCK_EX ) header = __readHeader(fh) now =", "= struct.unpack(pointFormat,packedPoint) if baseInterval == 0: step = archive['secondsPerPoint'] points", "= open(path,'r+b') if LOCK: fcntl.flock( fh.fileno(), fcntl.LOCK_EX ) header =", "or implied. # See the License for the specific language", "previousInterval = interval else: numberOfPoints = len(currentString) / pointSize startInterval", "fh.seek(myOffset) fh.write(myPackedPoint) #Now we propagate the update to lower-precision archives", "chronological order __archive_update_many(fh,header,currentArchive,currentPoints) currentPoints = [] try: currentArchive = next(archives)", "def read(self,bytes): self.readCount += 1 debug('READ %d bytes #%d' %", "packedString=%d archiveEnd=%d bytesBeyond=%d' % (myOffset,len(packedString),archiveEnd,bytesBeyond)) if bytesBeyond > 0: fh.write(", "unpack?) byteOrder,pointTypes = pointFormat[0],pointFormat[1:] points = len(seriesString) / pointSize seriesFormat", "= fh.read(pointSize) (baseInterval,baseValue) = struct.unpack(pointFormat,packedPoint) if baseInterval == 0: step", "series data we just read byteOrder,pointTypes = pointFormat[0],pointFormat[1:] points =", "known points knownValues = [v for v in neighborValues if", "= archive['offset'] + archive['size'] seriesString = fh.read(archiveEnd - fromOffset) fh.seek(archive['offset'])", "float(value) fh = open(path,'r+b') if LOCK: fcntl.flock( fh.fileno(), fcntl.LOCK_EX )", "iterating alignedPoint at %s' % interval) if (not previousInterval) or", "intervals than higher precision archives %s,%s\" % (archive,next) #Looks good,", "points ] #Create a packed string for each contiguous sequence", "else: return False def update(path,value,timestamp=None): \"\"\"update(path,value,timestamp=None) path is a string", "not __propagate(fh,myInterval,header['xFilesFactor'],higher,lower): break higher = lower #endBlock('update propagation') __changeLastUpdate(fh) fh.close()", "wrap the archive seriesString = fh.read(higherLastOffset - higherFirstOffset) else: #We", "= int(timestamp) diff = now - timestamp assert diff <", "startInterval = previousInterval - (step * (numberOfPoints-1)) #debug('__archive_update_many was NOT", "cannot configure two archives with the same precision %s,%s\" %", "= open(path,'rb') header = __readHeader(fh) now = int( time.time() )", "#Determine fromOffset timeDistance = fromInterval - baseInterval pointDistance = timeDistance", "diff = now - fromTime for archive in header['archives']: if", "%s already exists!\" % path fh = open(path,'wb') if LOCK:", "pointSize myOffset = archive['offset'] + (byteDistance % archive['size']) fh.seek(myOffset) fh.write(myPackedPoint)", "first update fh.seek(archive['offset']) fh.write(myPackedPoint) baseInterval,baseValue = myInterval,value else: #Not our", "break #First we update the highest-precision archive myInterval = timestamp", "first string as the base, so we start at the", "== currentInterval: neighborValues[i/2] = unpackedSeries[i+1] currentInterval += step #Propagate aggregateValue", "a string fromTime is an epoch time untilTime is also", ") fh.write( packedString[-bytesBeyond:] ) #safe because it can't exceed the", "a list of archives, each of which is of the", "where our writes will start fh.seek(archive['offset']) packedBasePoint = fh.read(pointSize) (baseInterval,baseValue)", "the License. # # # This module is an implementation", "MC.set(self.name, self.getvalue(), min_compress_len = min_compress_len) StringIO.close(self) def exists(path): return MC.get(path)", "fromTime for archive in header['archives']: if archive['retention'] >= diff: break", "interval that must have known values for a propagation to", "+ step numberOfPoints = len(currentString) / pointSize startInterval = previousInterval", "\"You cannot configure two archives with the same precision %s,%s\"", "archiveOffsetPointer = headerSize for secondsPerPoint,points in archiveList: archiveInfo = struct.pack(archiveInfoFormat,", "fh.seek(fromOffset) if fromOffset < untilOffset: #If we don't wrap around", "archive['offset'] + (byteDistance % archive['size']) fh.seek(myOffset) archiveEnd = archive['offset'] +", "= unpackedSeries[i+1] currentInterval += step #Propagate aggregateValue to propagate from", "baseInterval pointDistance = timeDistance / archive['secondsPerPoint'] byteDistance = pointDistance *", "(interval,value) in alignedPoints: #debug('__archive_update_many iterating alignedPoint at %s' % interval)", "startInterval = previousInterval - (step * (numberOfPoints-1)) #debug('__archive_update_many done iterating", "struct.unpack(pointFormat,packedPoint) if higherBaseInterval == 0: higherFirstOffset = higher['offset'] else: timeDistance", "fromTime is an epoch time untilTime is also an epoch", "import os, struct, time try: import fcntl CAN_LOCK = True", "packing') packedStrings = [] previousInterval = None currentString = \"\"", "% len(currentPoints)) if currentPoints: #commit all the points we've found", "= higherFirstOffset + (higherSize % higher['size']) fh.seek(higherFirstOffset) if higherFirstOffset <", "= higher['offset'] else: timeDistance = lowerIntervalStart - higherBaseInterval pointDistance =", "points in chronological order __archive_update_many(fh,header,currentArchive,currentPoints) currentPoints = [] try: currentArchive", "baseInterval) #Write all of our packed strings in locations determined", "to now \"\"\" fh = open(path,'rb') header = __readHeader(fh) now", "fh.write(myPackedPoint) #Now we propagate the update to lower-precision archives #startBlock('update", "later break #First we update the highest-precision archive myInterval =", "% interval) if (not previousInterval) or (interval == previousInterval +", "propagation') #endBlock('__archive_update_many file=%s archive=%s points=%d' % (fh.name,step,len(points))) def info(path): \"\"\"info(path)", "= struct.pack(longFormat, len(archiveList)) packedMetadata = lastUpdate + maxRetention + xFilesFactor", "first update #debug('__archive_update_many first update') baseInterval = packedStrings[0][0] #use our", "open, debug, startBlock, endBlock class open(file): def __init__(self,*args,**kwargs): file.__init__(self,*args,**kwargs) self.writeCount", "This is a modified version of whisper.py For details on", "= __readHeader(fh) fh.close() return info def fetch(path,fromTime,untilTime=None): \"\"\"fetch(path,fromTime,untilTime=None) path is", "packedPoint = fh.read(pointSize) (higherBaseInterval,higherBaseValue) = struct.unpack(pointFormat,packedPoint) if higherBaseInterval == 0:", "# # This module is an implementation of the Whisper", "% (archive[0],next[0]) retention = archive[0] * archive[1] nextRetention = next[0]", "'lastUpdate' : lastUpdate, 'maxRetention' : maxRetention, 'xFilesFactor' : xff, 'archives'", "= fh.read(higherLastOffset - higherFirstOffset) else: #We do wrap the archive", "lower['secondsPerPoint']) lowerIntervals = [fit(p[0]) for p in alignedPoints] uniqueLowerIntervals =", "header assert not exists(path), \"File %s already exists!\" % path", "untilTime > now: untilTime = now if fromTime < (now", "struct.pack(timestampFormat,now) fh.write(packedTime) fh.seek(originalOffset) endBlock('__changeLastUpdate()') def create(path,archiveList,xFilesFactor=0.5): \"\"\"create(path,archiveList,xFilesFactor=0.5) path is a", "+ (byteDistance % archive['size']) fh.seek(myOffset) archiveEnd = archive['offset'] + archive['size']", "<filename>contrib/memcache_whisper.py #!/usr/bin/env python # Copyright 2008 Orbitz WorldWide # #", "of values neighborValues = [None] * points currentInterval = lowerIntervalStart", "(interval,packedString) in packedStrings: timeDistance = interval - baseInterval pointDistance =", "byteDistance = pointDistance * pointSize higherFirstOffset = higher['offset'] + (byteDistance", "but defaults to now \"\"\" fh = open(path,'rb') header =", "valueFormat = \"!d\" valueSize = struct.calcsize(valueFormat) pointFormat = \"!Ld\" pointSize", "not propagateFurther: break higher = lower #endBlock('__archive_update_many propagation') #endBlock('__archive_update_many file=%s", "archive['offset'] + (byteDistance % archive['size']) #Read all the points in", ": secondsPerPoint * points, 'size' : points * pointSize, }", "assert diff < header['maxRetention'] and diff >= 0, \"Timestamp not", "using next archive %s' % str(currentArchive)) except StopIteration: #debug(' update_many", "== \"rb\": StringIO.__init__(self, MC.get(self.name)) else: StringIO.__init__(self) def close(self): if self.mode", "packed strings in locations determined by the baseInterval #startBlock('__archive_update_many write()", "self.readCount += 1 debug('READ %d bytes #%d' % (bytes,self.readCount)) return", "Here is the basic layout of a whisper data file", ") if untilTime is None or untilTime > now: untilTime", "memcache.Client(servers) class open(StringIO): def __init__(self,*args,**kwargs): self.name = args[0] self.mode =", "it can fit currentPoints.reverse() #put points in chronological order __archive_update_many(fh,header,currentArchive,currentPoints)", "p: p[0],reverse=True) #order points by timestamp, newest first fh =", "fh.fileno(), fcntl.LOCK_EX ) header = __readHeader(fh) now = int( time.time()", "= [ (timestamp - (timestamp % step), value) for (timestamp,value)", "archives.append(archiveInfo) fh.seek(originalOffset) info = { 'lastUpdate' : lastUpdate, 'maxRetention' :", "== \"r+b\" or self.mode == \"wb\": MC.set(self.name, self.getvalue(), min_compress_len =", "precision archives later break #First we update the highest-precision archive", "not currentArchive: break #drop remaining points that don't fit in", "+ (byteDistance % archive['size']) #Read all the points in the", "else: StringIO.__init__(self) def close(self): if self.mode == \"r+b\" or self.mode", "__timingBlocks[name] = time.time() def endBlock(name): debug(\"%s took %.5f seconds\" %", "first fh = open(path,'r+b') if LOCK: fcntl.flock( fh.fileno(), fcntl.LOCK_EX )", "API # Here is the basic layout of a whisper", "don't fit in the database #debug(' update_many adding point=%s' %", "currentPoints.reverse() #put points in chronological order __archive_update_many(fh,header,currentArchive,currentPoints) currentPoints = []", "(lastUpdate,maxRetention,xff,archiveCount) = struct.unpack(metadataFormat,packedMetadata) archives = [] for i in xrange(archiveCount):", "= struct.calcsize(floatFormat) timestampFormat = \"!L\" timestampSize = struct.calcsize(timestampFormat) valueFormat =", "fh.seek(lower['offset']) packedPoint = fh.read(pointSize) (lowerBaseInterval,lowerBaseValue) = struct.unpack(pointFormat,packedPoint) if lowerBaseInterval ==", "#endBlock('__archive_update_many write() operations') #Now we propagate the updates to lower-precision", "checking logic above) else: fh.write(packedString) #endBlock('__archive_update_many write() operations') #Now we", "now - header['maxRetention'] assert fromTime < untilTime, \"Invalid time interval\"", "the baseInterval #startBlock('__archive_update_many write() operations') for (interval,packedString) in packedStrings: timeDistance", "- higherFirstOffset) fh.seek(higher['offset']) seriesString += fh.read(higherLastOffset - higher['offset']) #Now we", "next(archives) #debug(' update_many using next archive %s' % str(currentArchive)) except", "baseInterval == 0: #This file's first update #debug('__archive_update_many first update')", "currentPoints = [] for point in points: age = now", "% (len(alignedPoints),len(uniqueLowerIntervals))) propagateFurther = False for interval in uniqueLowerIntervals: #debug('", "= interval if currentString: #startInterval = previousInterval - (step *", "- fromInterval) / step timeInfo = (fromInterval,untilInterval,step) valueList = [None]", "packing onto currentString') currentString += struct.pack(pointFormat,interval,value) previousInterval = interval else:", "for (interval,value) in alignedPoints: #debug('__archive_update_many iterating alignedPoint at %s' %", "the archive, so we need two reads archiveEnd = archive['offset']", "(interval == previousInterval + step): #debug('__archive_update_many was expected, packing onto", "archives #startBlock('__archive_update_many propagation') higher = archive lowerArchives = [arc for", "in writing, software # distributed under the License is distributed", "governing permissions and # limitations under the License. # #", "if timestamp is None: timestamp = now timestamp = int(timestamp)", "__readHeader(fh) now = int( time.time() ) if untilTime is None", "propagation') higher = archive for lower in lowerArchives: if not", "archiveEnd=%d bytesBeyond=%d' % (myOffset,len(packedString),archiveEnd,bytesBeyond)) if bytesBeyond > 0: fh.write( packedString[:-bytesBeyond]", "previousInterval + step): #debug('__archive_update_many was expected, packing onto currentString') currentString", "value = float(value) fh = open(path,'r+b') if LOCK: fcntl.flock( fh.fileno(),", "all the points we've found that it can fit currentPoints.reverse()", "* pointSize higherFirstOffset = higher['offset'] + (byteDistance % higher['size']) higherPoints", "Copyright 2008 Orbitz WorldWide # # Licensed under the Apache", "in a propagation interval that must have known values for", "(i % lower['secondsPerPoint']) lowerIntervals = [fit(p[0]) for p in alignedPoints]", "self.mode = args[1] if self.mode == \"r+b\" or self.mode ==", "this lower archive timeDistance = lowerIntervalStart - lowerBaseInterval pointDistance =", "= struct.pack( floatFormat, float(xFilesFactor) ) archiveCount = struct.pack(longFormat, len(archiveList)) packedMetadata", "= fh.read(pointSize) (baseInterval,baseValue) = struct.unpack(pointFormat,packedBasePoint) if baseInterval == 0: #This", "archive['offset'] + archive['size'] bytesBeyond = (myOffset + len(packedString)) - archiveEnd", "timestamp,value \"\"\" NOTE: This is a modified version of whisper.py", "(numberOfPoints-1)) #debug('__archive_update_many was NOT expected, appending to packedStrings startInterval=%s currentString=%d", "= int( time.time() ) if timestamp is None: timestamp =", "point=%s' % str(point)) currentPoints.append(point) #debug(' update_many done iterating points') if", "License is distributed on an \"AS IS\" BASIS, # WITHOUT", "License, Version 2.0 (the \"License\"); # you may not use", "any archives in this database\" for i,archive in enumerate(header['archives']): #Find", "fromTime = now - header['maxRetention'] assert fromTime < untilTime, \"Invalid", "debug('READ %d bytes #%d' % (bytes,self.readCount)) return file.read(self,bytes) def debug(message):", "StringIO import StringIO import memcache global open, exists, drop MC", "points=%d' % (fh.name,step,len(points))) alignedPoints = [ (timestamp - (timestamp %", "configurations... assert archiveList, \"You must specify at least one archive", "#startBlock('complete update_many path=%s points=%d' % (path,len(points))) if not points: return", "points is a list of (timestamp,value) points \"\"\" #startBlock('complete update_many", "print('DEBUG :: %s' % message) __timingBlocks = {} def startBlock(name):", "%s,%s\" % (archive[0],next[0]) retention = archive[0] * archive[1] nextRetention =", "struct, time try: import fcntl CAN_LOCK = True except ImportError:", "(higherBaseInterval,higherBaseValue) = struct.unpack(pointFormat,packedPoint) if higherBaseInterval == 0: higherFirstOffset = higher['offset']", "archive['secondsPerPoint'] points = (untilInterval - fromInterval) / step timeInfo =", "{} def startBlock(name): __timingBlocks[name] = time.time() def endBlock(name): debug(\"%s took", "def enableMemcache(servers = ['127.0.0.1:11211'], min_compress_len = 0): from StringIO import", "longFormat, oldest ) xFilesFactor = struct.pack( floatFormat, float(xFilesFactor) ) archiveCount", "higher['offset'] else: timeDistance = lowerIntervalStart - higherBaseInterval pointDistance = timeDistance", "valueList = [None] * points #pre-allocate entire list for speed", "a string \"\"\" fh = open(path,'rb') info = __readHeader(fh) fh.close()", "the License for the specific language governing permissions and #", "path is a string points is a list of (timestamp,value)", "zeroes = '\\x00' * (archiveOffsetPointer - headerSize) fh.write(zeroes) fh.close() def", "currentPoints = [] try: currentArchive = next(archives) #debug(' update_many using", "previousInterval = interval if currentString: #startInterval = previousInterval - (step", "the highest-precision archive myInterval = timestamp - (timestamp % archive['secondsPerPoint'])", "lambda *a,**k: None def exists(path): return os.path.exists(path) def drop(path): os.remove(path)", "__archive_update_many myOffset=%d packedString=%d archiveEnd=%d bytesBeyond=%d' % (myOffset,len(packedString),archiveEnd,bytesBeyond)) if bytesBeyond >", "args[0] self.mode = args[1] if self.mode == \"r+b\" or self.mode", "iter( header['archives'] ) currentArchive = next(archives) #debug(' update_many currentArchive=%s' %", "True except ImportError: CAN_LOCK = False LOCK = False CACHE_HEADERS", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "archives, each of which is of the form (secondsPerPoint,numberOfPoints) xFilesFactor", "file.__init__(self,*args,**kwargs) self.writeCount = 0 self.readCount = 0 def write(self,data): self.writeCount", "archive[0]) == 0,\\ \"Higher precision archives' precision must evenly divide", "None break if not currentArchive: break #drop remaining points that", "previousInterval = None currentString = \"\" for (interval,value) in alignedPoints:", "diff: continue lowerArchives = header['archives'][i+1:] #We'll pass on the update", "timeInfo = (fromInterval,untilInterval,step) valueList = [None] * points return (timeInfo,valueList)", "%d lower archives' % len(lowerArchives)) for lower in lowerArchives: fit", "unpackedSeries[i+1] valueList[i/2] = pointValue #in-place reassignment is faster than append()", "v is not None] knownPercent = float(len(knownValues)) / float(len(neighborValues)) if", "string archiveList is a list of archives, each of which", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "= args[0] self.mode = args[1] if self.mode == \"r+b\" or", "None or untilTime > now: untilTime = now if fromTime", "#startBlock('__archive_update_many write() operations') for (interval,packedString) in packedStrings: timeDistance = interval", "step = archive['secondsPerPoint'] points = (untilInterval - fromInterval) / step", "'size' : points * pointSize, } archives.append(archiveInfo) fh.seek(originalOffset) info =", "timeDistance / archive['secondsPerPoint'] byteDistance = pointDistance * pointSize untilOffset =", "path is a string value is a float timestamp is", "- (step * (numberOfPoints-1)) #debug('__archive_update_many was NOT expected, appending to", "endBlock(name): debug(\"%s took %.5f seconds\" % (name,time.time() - __timingBlocks.pop(name))) def", "archive configuration!\" archiveList.sort(key=lambda a: a[0]) #sort by precision (secondsPerPoint) for", "valueList = [None] * points return (timeInfo,valueList) #Determine fromOffset timeDistance", "#debug(' update_many using next archive %s' % str(currentArchive)) except StopIteration:", "baseInterval = packedStrings[0][0] #use our first string as the base,", "#sort by precision (secondsPerPoint) for i,archive in enumerate(archiveList): if i", "fh.write(myPackedPoint) baseInterval,baseValue = myInterval,value else: #Not our first update timeDistance", "# distributed under the License is distributed on an \"AS", "struct.pack(pointFormat,myInterval,value) fh.seek(archive['offset']) packedPoint = fh.read(pointSize) (baseInterval,baseValue) = struct.unpack(pointFormat,packedPoint) if baseInterval", "time intervals than higher precision archives %s,%s\" % (archive,next) #Looks", "pointValue = unpackedSeries[i+1] valueList[i/2] = pointValue #in-place reassignment is faster", "# Unless required by applicable law or agreed to in", "lower in lowerArchives: if not __propagate(fh,myInterval,header['xFilesFactor'],higher,lower): break higher = lower", "archive['secondsPerPoint']] #debug('__archive_update_many I have %d lower archives' % len(lowerArchives)) for", "= fh.read(untilOffset - fromOffset) else: #We do wrap around the", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "= open(path,'wb') if LOCK: fcntl.flock( fh.fileno(), fcntl.LOCK_EX ) lastUpdate =", "= [None] * points return (timeInfo,valueList) #Determine fromOffset timeDistance =", "than append() currentInterval += step fh.close() timeInfo = (fromInterval,untilInterval,step) return", "= metadataSize + (archiveInfoSize * len(archiveList)) archiveOffsetPointer = headerSize for", "commit after we've checked all the archives currentPoints.reverse() __archive_update_many(fh,header,currentArchive,currentPoints) __changeLastUpdate(fh)", "i,archive in enumerate(archiveList): if i == len(archiveList) - 1: break", "% str(currentArchive)) except StopIteration: #debug(' update_many no more archives!') currentArchive", "#Now we propagate the updates to lower-precision archives #startBlock('__archive_update_many propagation')", "string packing') #Read base point and determine where our writes", ") currentArchive = next(archives) #debug(' update_many currentArchive=%s' % str(currentArchive)) currentPoints", "untilOffset = archive['offset'] + (byteDistance % archive['size']) #Read all the", "archiveOffsetPointer, secondsPerPoint, points) fh.write(archiveInfo) archiveOffsetPointer += (points * pointSize) zeroes", "__headerCache[fh.name] = info #endBlock('__readHeader') return info def __changeLastUpdate(fh): return #XXX", "the Apache License, Version 2.0 (the \"License\"); # you may", "floatFormat = \"!f\" floatSize = struct.calcsize(floatFormat) timestampFormat = \"!L\" timestampSize", "= \"!3L\" archiveInfoSize = struct.calcsize(archiveInfoFormat) debug = startBlock = endBlock", "packedMetadata = fh.read(metadataSize) (lastUpdate,maxRetention,xff,archiveCount) = struct.unpack(metadataFormat,packedMetadata) archives = [] for", "propagate the updates to lower-precision archives #startBlock('__archive_update_many propagation') higher =", "__archive_update_many Successful propagation!') #debug(' __archive_update_many propagateFurther=%s' % propagateFurther) if not", "(byteDistance % archive['size']) fh.seek(myOffset) fh.write(myPackedPoint) #Now we propagate the update", "now - point[0] #debug(' update_many iterating points, point=%s age=%d' %", "/ pointSize startInterval = previousInterval - (step * (numberOfPoints-1)) #debug('__archive_update_many", "#debug(' __archive_update_many myOffset=%d packedString=%d archiveEnd=%d bytesBeyond=%d' % (myOffset,len(packedString),archiveEnd,bytesBeyond)) if bytesBeyond", "will start fh.seek(archive['offset']) packedBasePoint = fh.read(pointSize) (baseInterval,baseValue) = struct.unpack(pointFormat,packedBasePoint) if", "= len(currentString) / pointSize startInterval = previousInterval - (step *", "== 0: #This file's first update #debug('__archive_update_many first update') baseInterval", "the file and write the header assert not exists(path), \"File", "archive=%s points=%d' % (fh.name,step,len(points))) def info(path): \"\"\"info(path) path is a", "higherFirstOffset) fh.seek(higher['offset']) seriesString += fh.read(higherLastOffset - higher['offset']) #Now we unpack", "enableDebug(): global open, debug, startBlock, endBlock class open(file): def __init__(self,*args,**kwargs):", "+= fh.read(higherLastOffset - higher['offset']) #Now we unpack the series data", ": archives, } if CACHE_HEADERS: __headerCache[fh.name] = info #endBlock('__readHeader') return", "(next[0] % archive[0]) == 0,\\ \"Higher precision archives' precision must", "higherFirstOffset + (higherSize % higher['size']) fh.seek(higherFirstOffset) if higherFirstOffset < higherLastOffset:", "myInterval = timestamp - (timestamp % archive['secondsPerPoint']) myPackedPoint = struct.pack(pointFormat,myInterval,value)", "is the basic layout of a whisper data file #", "return (timeInfo,valueList) #Determine fromOffset timeDistance = fromInterval - baseInterval pointDistance", "(not previousInterval) or (interval == previousInterval + step): #debug('__archive_update_many was", "timeDistance = myInterval - baseInterval pointDistance = timeDistance / archive['secondsPerPoint']", "= timeDistance / higher['secondsPerPoint'] byteDistance = pointDistance * pointSize higherFirstOffset", "update') baseInterval = packedStrings[0][0] #use our first string as the", "% str(currentArchive)) currentPoints = [] for point in points: age", "close(self): if self.mode == \"r+b\" or self.mode == \"wb\": MC.set(self.name,", "in lowerArchives: if not __propagate(fh,myInterval,header['xFilesFactor'],higher,lower): break higher = lower #endBlock('update", "points in a propagation interval that must have known values", "construct a list of values neighborValues = [None] * points", "higher['offset'] + higher['size'] seriesString = fh.read(higherEnd - higherFirstOffset) fh.seek(higher['offset']) seriesString", "- 1: break next = archiveList[i+1] assert archive[0] < next[0],\\", "covers timestamp if archive['retention'] < diff: continue lowerArchives = header['archives'][i+1:]", "myOffset = archive['offset'] + (byteDistance % archive['size']) fh.seek(myOffset) fh.write(myPackedPoint) #Now", "of our packed strings in locations determined by the baseInterval", "fh.seek(0) packedMetadata = fh.read(metadataSize) (lastUpdate,maxRetention,xff,archiveCount) = struct.unpack(metadataFormat,packedMetadata) archives = []", "os.path.exists(path) def drop(path): os.remove(path) def enableMemcache(servers = ['127.0.0.1:11211'], min_compress_len =", "points = len(seriesString) / pointSize seriesFormat = byteOrder + (pointTypes", "archive['size']) fh.seek(myOffset) archiveEnd = archive['offset'] + archive['size'] bytesBeyond = (myOffset", "in enumerate(archiveList): if i == len(archiveList) - 1: break next", "(baseInterval,baseValue) = struct.unpack(pointFormat,packedPoint) if baseInterval == 0: #This file's first", "#Not our first update timeDistance = myInterval - baseInterval pointDistance", "while currentArchive['retention'] < age: #we can't fit any more points", "(len(data),self.writeCount)) return file.write(self,data) def read(self,bytes): self.readCount += 1 debug('READ %d", "update the highest-precision archive myInterval = timestamp - (timestamp %", "higher['size']) higherPoints = lower['secondsPerPoint'] / higher['secondsPerPoint'] higherSize = higherPoints *", "series data we just read (anything faster than unpack?) byteOrder,pointTypes", "= Metadata,ArchiveInfo+ # Metadata = lastUpdate,maxRetention,xFilesFactor,archiveCount # ArchiveInfo = Offset,SecondsPerPoint,Points", "oldest = sorted([secondsPerPoint * points for secondsPerPoint,points in archiveList])[-1] maxRetention", "wrapped an archive!') assert fh.tell() == archiveEnd, \"archiveEnd=%d fh.tell=%d bytesBeyond=%d", "under the License is distributed on an \"AS IS\" BASIS,", "to propagate a value! aggregateValue = float(sum(knownValues)) / float(len(knownValues)) #TODO", "first update timeDistance = myInterval - baseInterval pointDistance = timeDistance", "% (fh.name,step,len(points))) alignedPoints = [ (timestamp - (timestamp % step),", "min_compress_len = min_compress_len) StringIO.close(self) def exists(path): return MC.get(path) != None", "next archive %s' % str(currentArchive)) except StopIteration: #debug(' update_many no", "it can't exceed the archive (retention checking logic above) else:", "[fit(p[0]) for p in alignedPoints] uniqueLowerIntervals = set(lowerIntervals) #debug(' __archive_update_many", "% (archive,next) assert (next[0] % archive[0]) == 0,\\ \"Higher precision", "\"\"\" NOTE: This is a modified version of whisper.py For", "struct.unpack(pointFormat,packedBasePoint) if baseInterval == 0: #This file's first update #debug('__archive_update_many", "1 debug('WRITE %d bytes #%d' % (len(data),self.writeCount)) return file.write(self,data) def", "open(StringIO): def __init__(self,*args,**kwargs): self.name = args[0] self.mode = args[1] if", "points=%d' % (fh.name,step,len(points))) def info(path): \"\"\"info(path) path is a string", "For details on the modification, read https://bugs.launchpad.net/graphite/+bug/245835 \"\"\" import os,", "i - (i % lower['secondsPerPoint']) lowerIntervals = [fit(p[0]) for p", "(len(currentString),startInterval)) packedStrings.append( (startInterval,currentString) ) #endBlock('__archive_update_many string packing') #Read base point", ": xff, 'archives' : archives, } if CACHE_HEADERS: __headerCache[fh.name] =", "xFilesFactor + archiveCount fh.write(packedMetadata) headerSize = metadataSize + (archiveInfoSize *", "to %d, interval=%d' % (higher['secondsPerPoint'],lower['secondsPerPoint'],interval)) if __propagate(fh,interval,header['xFilesFactor'],higher,lower): propagateFurther = True", "0,\\ \"Higher precision archives' precision must evenly divide all lower", "return False def update(path,value,timestamp=None): \"\"\"update(path,value,timestamp=None) path is a string value", "that don't fit in the database #debug(' update_many adding point=%s'", "self.mode == \"rb\": StringIO.__init__(self, MC.get(self.name)) else: StringIO.__init__(self) def close(self): if", "= fh.read(pointSize) (baseInterval,baseValue) = struct.unpack(pointFormat,packedPoint) if baseInterval == 0: #This", "in this archive #debug(' update_many this point is too old", "(timeInfo,valueList) #Determine fromOffset timeDistance = fromInterval - baseInterval pointDistance =", "startBlock('__changeLastUpdate()') originalOffset = fh.tell() fh.seek(0) #Based on assumption that first", "LOCK: fcntl.flock( fh.fileno(), fcntl.LOCK_EX ) lastUpdate = struct.pack( timestampFormat, int(time.time())", "points) unpackedSeries = struct.unpack(seriesFormat, seriesString) #And finally we construct a", "(startInterval,len(currentString))) packedStrings.append( (startInterval,currentString) ) currentString = struct.pack(pointFormat,interval,value) previousInterval = interval", "for lower in lowerArchives: if not __propagate(fh,myInterval,header['xFilesFactor'],higher,lower): break higher =", "#We do wrap around the archive, so we need two", "{ 'offset' : offset, 'secondsPerPoint' : secondsPerPoint, 'points' : points,", "the highest-precision archive that covers timestamp if archive['retention'] < diff:", "do wrap the archive higherEnd = higher['offset'] + higher['size'] seriesString", "= struct.unpack(pointFormat,packedPoint) if higherBaseInterval == 0: higherFirstOffset = higher['offset'] else:", "value! aggregateValue = float(sum(knownValues)) / float(len(knownValues)) #TODO another CF besides", "under the License. # # # This module is an", "% (path,len(points))) def __archive_update_many(fh,header,archive,points): step = archive['secondsPerPoint'] #startBlock('__archive_update_many file=%s archive=%s", "info #endBlock('__readHeader') return info def __changeLastUpdate(fh): return #XXX Make this", "fh.tell() == archiveEnd, \"archiveEnd=%d fh.tell=%d bytesBeyond=%d len(packedString)=%d\" % (archiveEnd,fh.tell(),bytesBeyond,len(packedString)) fh.seek(", "Header = Metadata,ArchiveInfo+ # Metadata = lastUpdate,maxRetention,xFilesFactor,archiveCount # ArchiveInfo =", "archive['size'] seriesString = fh.read(archiveEnd - fromOffset) fh.seek(archive['offset']) seriesString += fh.read(untilOffset", "modification, read https://bugs.launchpad.net/graphite/+bug/245835 \"\"\" import os, struct, time try: import", "0 def write(self,data): self.writeCount += 1 debug('WRITE %d bytes #%d'", "archive['offset']) #Now we unpack the series data we just read", "def exists(path): return os.path.exists(path) def drop(path): os.remove(path) def enableMemcache(servers =", "+ (pointTypes * points) unpackedSeries = struct.unpack(seriesFormat, seriesString) #And finally", "to propagate from neighborValues if we have enough known points", "\"!L\" longSize = struct.calcsize(longFormat) floatFormat = \"!f\" floatSize = struct.calcsize(floatFormat)", "currentString = struct.pack(pointFormat,interval,value) previousInterval = interval if currentString: #startInterval =", "pointDistance = timeDistance / higher['secondsPerPoint'] byteDistance = pointDistance * pointSize", "Archive = Point+ # Point = timestamp,value \"\"\" NOTE: This", "* (numberOfPoints-1)) #debug('__archive_update_many done iterating alignedPoints, remainder currentString of %d", "ANY KIND, either express or implied. # See the License", "break if not currentArchive: break #drop remaining points that don't", "#startInterval = previousInterval - (step * len(currentString) / pointSize) +", "wrap the archive higherEnd = higher['offset'] + higher['size'] seriesString =", "the License. # You may obtain a copy of the", "for (timestamp,value) in points ] #Create a packed string for", "% (str(point),age)) while currentArchive['retention'] < age: #we can't fit any", "def __archive_update_many(fh,header,archive,points): step = archive['secondsPerPoint'] #startBlock('__archive_update_many file=%s archive=%s points=%d' %", "database #debug(' update_many adding point=%s' % str(point)) currentPoints.append(point) #debug(' update_many", "(path,len(points))) def __archive_update_many(fh,header,archive,points): step = archive['secondsPerPoint'] #startBlock('__archive_update_many file=%s archive=%s points=%d'", "# See the License for the specific language governing permissions", "currentPoints: #don't forget to commit after we've checked all the", "fromTime - (fromTime % archive['secondsPerPoint']) ) untilInterval = int( untilTime", "len(lowerArchives)) for lower in lowerArchives: fit = lambda i: i", "any more points in this archive #debug(' update_many this point", "our first update timeDistance = myInterval - baseInterval pointDistance =", "covered by any archives in this database\" for i,archive in", "lastUpdate,maxRetention,xFilesFactor,archiveCount # ArchiveInfo = Offset,SecondsPerPoint,Points # Data = Archive+ #", "- lowerBaseInterval pointDistance = timeDistance / lower['secondsPerPoint'] byteDistance = pointDistance", "in the interval fh.seek(fromOffset) if fromOffset < untilOffset: #If we", "% (path,len(points))) if not points: return points = [ (int(t),float(v))", "packedString[:-bytesBeyond] ) #debug('We wrapped an archive!') assert fh.tell() == archiveEnd,", "self.mode == \"r+b\" or self.mode == \"rb\": StringIO.__init__(self, MC.get(self.name)) else:", "from %d to %d, interval=%d' % (higher['secondsPerPoint'],lower['secondsPerPoint'],interval)) if __propagate(fh,interval,header['xFilesFactor'],higher,lower): propagateFurther", "archive['offset'] + archive['size'] seriesString = fh.read(archiveEnd - fromOffset) fh.seek(archive['offset']) seriesString", "% len(lowerArchives)) for lower in lowerArchives: fit = lambda i:", "(archiveEnd,fh.tell(),bytesBeyond,len(packedString)) fh.seek( archive['offset'] ) fh.write( packedString[-bytesBeyond:] ) #safe because it", "timestamp - (timestamp % archive['secondsPerPoint']) myPackedPoint = struct.pack(pointFormat,myInterval,value) fh.seek(archive['offset']) packedPoint", "time.time() ) packedTime = struct.pack(timestampFormat,now) fh.write(packedTime) fh.seek(originalOffset) endBlock('__changeLastUpdate()') def create(path,archiveList,xFilesFactor=0.5):", "= min_compress_len) StringIO.close(self) def exists(path): return MC.get(path) != None def", "= struct.pack(pointFormat,interval,value) previousInterval = interval if currentString: #startInterval = previousInterval", "(optimize this!) valueList = [None] * points #pre-allocate entire list", "archive['size']) fh.seek(myOffset) fh.write(myPackedPoint) #Now we propagate the update to lower-precision", "\"\"\" #Validate archive configurations... assert archiveList, \"You must specify at", "interval - baseInterval pointDistance = timeDistance / step byteDistance =", "else: #We do wrap around the archive, so we need", "higher['size'] seriesString = fh.read(higherEnd - higherFirstOffset) fh.seek(higher['offset']) seriesString += fh.read(higherLastOffset", "in points: age = now - point[0] #debug(' update_many iterating", "this lower archive fh.seek(lower['offset']) fh.write(myPackedPoint) else: #Not our first propagated", "self.writeCount += 1 debug('WRITE %d bytes #%d' % (len(data),self.writeCount)) return", "limitations under the License. # # # This module is", "timeDistance = lowerIntervalStart - lowerBaseInterval pointDistance = timeDistance / lower['secondsPerPoint']", "pointSize higherFirstOffset = higher['offset'] + (byteDistance % higher['size']) higherPoints =", "+= struct.pack(pointFormat,interval,value) previousInterval = interval else: numberOfPoints = len(currentString) /", "NOTE: This is a modified version of whisper.py For details", "floatFormat, float(xFilesFactor) ) archiveCount = struct.pack(longFormat, len(archiveList)) packedMetadata = lastUpdate", "pointSize) + step numberOfPoints = len(currentString) / pointSize startInterval =", "#endBlock('__archive_update_many string packing') #Read base point and determine where our", "= archive['secondsPerPoint'] for i in xrange(0,len(unpackedSeries),2): pointTime = unpackedSeries[i] if", "% lower['secondsPerPoint']) lowerIntervalEnd = lowerIntervalStart + lower['secondsPerPoint'] fh.seek(higher['offset']) packedPoint =", "= myInterval - baseInterval pointDistance = timeDistance / archive['secondsPerPoint'] byteDistance", "permissions and # limitations under the License. # # #", "% archive['size']) fh.seek(myOffset) fh.write(myPackedPoint) #Now we propagate the update to", "= archiveList[i+1] assert archive[0] < next[0],\\ \"You cannot configure two", "Licensed under the Apache License, Version 2.0 (the \"License\"); #", "1: break next = archiveList[i+1] assert archive[0] < next[0],\\ \"You", "== 0: #First propagated update to this lower archive fh.seek(lower['offset'])", "file.read(self,bytes) def debug(message): print('DEBUG :: %s' % message) __timingBlocks =", "writing, software # distributed under the License is distributed on", "baseInterval,baseValue = myInterval,value else: #Not our first update timeDistance =", "(baseInterval,baseValue) = struct.unpack(pointFormat,packedBasePoint) if baseInterval == 0: #This file's first", "point=%s age=%d' % (str(point),age)) while currentArchive['retention'] < age: #we can't", "points = (untilInterval - fromInterval) / step timeInfo = (fromInterval,untilInterval,step)", "update_many path=%s points=%d' % (path,len(points))) def __archive_update_many(fh,header,archive,points): step = archive['secondsPerPoint']", "return file.read(self,bytes) def debug(message): print('DEBUG :: %s' % message) __timingBlocks", "was NOT expected, appending to packedStrings startInterval=%s currentString=%d bytes' %", "= headerSize for secondsPerPoint,points in archiveList: archiveInfo = struct.pack(archiveInfoFormat, archiveOffsetPointer,", "of which is of the form (secondsPerPoint,numberOfPoints) xFilesFactor specifies the", "fh.seek( archive['offset'] ) fh.write( packedString[-bytesBeyond:] ) #safe because it can't", "must specify at least one archive configuration!\" archiveList.sort(key=lambda a: a[0])", "(archive,next) assert (next[0] % archive[0]) == 0,\\ \"Higher precision archives'", "= [arc for arc in header['archives'] if arc['secondsPerPoint'] > archive['secondsPerPoint']]", "lower in lowerArchives: fit = lambda i: i - (i", "archive['size']) #Read all the points in the interval fh.seek(fromOffset) if", "= lowerIntervalStart + lower['secondsPerPoint'] fh.seek(higher['offset']) packedPoint = fh.read(pointSize) (higherBaseInterval,higherBaseValue) =", "self.writeCount = 0 self.readCount = 0 def write(self,data): self.writeCount +=", "\"!f\" floatSize = struct.calcsize(floatFormat) timestampFormat = \"!L\" timestampSize = struct.calcsize(timestampFormat)", "header = __readHeader(fh) now = int( time.time() ) if untilTime", "(timestamp % lower['secondsPerPoint']) lowerIntervalEnd = lowerIntervalStart + lower['secondsPerPoint'] fh.seek(higher['offset']) packedPoint", "point is too old to fit here, currentPoints=%d' % len(currentPoints))", "= fh.read(archiveInfoSize) (offset,secondsPerPoint,points) = struct.unpack(archiveInfoFormat,packedArchiveInfo) archiveInfo = { 'offset' :", "def write(self,data): self.writeCount += 1 debug('WRITE %d bytes #%d' %", "= struct.pack(timestampFormat,now) fh.write(packedTime) fh.seek(originalOffset) endBlock('__changeLastUpdate()') def create(path,archiveList,xFilesFactor=0.5): \"\"\"create(path,archiveList,xFilesFactor=0.5) path is", "min_compress_len) StringIO.close(self) def exists(path): return MC.get(path) != None def drop(path):", "(untilInterval - fromInterval) / step timeInfo = (fromInterval,untilInterval,step) valueList =", "+= (points * pointSize) zeroes = '\\x00' * (archiveOffsetPointer -", "% archive[0]) == 0,\\ \"Higher precision archives' precision must evenly", "Offset,SecondsPerPoint,Points # Data = Archive+ # Archive = Point+ #", "% (bytes,self.readCount)) return file.read(self,bytes) def debug(message): print('DEBUG :: %s' %", "points = [ (int(t),float(v)) for (t,v) in points] points.sort(key=lambda p:", "archives with the same precision %s,%s\" % (archive,next) assert (next[0]", "update_many this point is too old to fit here, currentPoints=%d'", "archive (retention checking logic above) else: fh.write(packedString) #endBlock('__archive_update_many write() operations')", "in locations determined by the baseInterval #startBlock('__archive_update_many write() operations') for", "* len(archiveList)) archiveOffsetPointer = headerSize for secondsPerPoint,points in archiveList: archiveInfo", "if currentString: #startInterval = previousInterval - (step * len(currentString) /", "memcache global open, exists, drop MC = memcache.Client(servers) class open(StringIO):", "update_many no more archives!') currentArchive = None break if not", "if archive['retention'] >= diff: break fromInterval = int( fromTime -", "% archive['secondsPerPoint']) ) untilInterval = int( untilTime - (untilTime %", "info #startBlock('__readHeader') originalOffset = fh.tell() fh.seek(0) packedMetadata = fh.read(metadataSize) (lastUpdate,maxRetention,xff,archiveCount)", "appending to packedStrings startInterval=%s currentString=%d bytes' % (startInterval,len(currentString))) packedStrings.append( (startInterval,currentString)", "#debug(' __archive_update_many propagateFurther=%s' % propagateFurther) if not propagateFurther: break higher", "(timestamp % step), value) for (timestamp,value) in points ] #Create", "currentPoints=%d' % len(currentPoints)) if currentPoints: #commit all the points we've", "#debug('__archive_update_many baseInterval is %s' % baseInterval) #Write all of our", "#Not our first propagated update to this lower archive timeDistance", "= fromInterval step = archive['secondsPerPoint'] for i in xrange(0,len(unpackedSeries),2): pointTime", "if knownPercent >= xff: #we have enough data to propagate", "the modification, read https://bugs.launchpad.net/graphite/+bug/245835 \"\"\" import os, struct, time try:", "def update(path,value,timestamp=None): \"\"\"update(path,value,timestamp=None) path is a string value is a", "archives' % len(lowerArchives)) for lower in lowerArchives: fit = lambda", "we construct a list of values (optimize this!) valueList =", "also an epoch time, but defaults to now \"\"\" fh", "is lastUpdate now = int( time.time() ) packedTime = struct.pack(timestampFormat,now)", "= lowerIntervalStart - higherBaseInterval pointDistance = timeDistance / higher['secondsPerPoint'] byteDistance", "exceed the archive (retention checking logic above) else: fh.write(packedString) #endBlock('__archive_update_many", "i in xrange(0,len(unpackedSeries),2): pointTime = unpackedSeries[i] if pointTime == currentInterval:", "- higher['offset']) #Now we unpack the series data we just", "packedPoint = fh.read(pointSize) (lowerBaseInterval,lowerBaseValue) = struct.unpack(pointFormat,packedPoint) if lowerBaseInterval == 0:", "time, but defaults to now \"\"\" fh = open(path,'rb') header", "to these lower precision archives later break #First we update", "pointSize seriesFormat = byteOrder + (pointTypes * points) unpackedSeries =", "def info(path): \"\"\"info(path) path is a string \"\"\" fh =", ":: %s' % message) __timingBlocks = {} def startBlock(name): __timingBlocks[name]", "#we have enough data to propagate a value! aggregateValue =", "old to fit here, currentPoints=%d' % len(currentPoints)) if currentPoints: #commit", "def __init__(self,*args,**kwargs): file.__init__(self,*args,**kwargs) self.writeCount = 0 self.readCount = 0 def", "update(path,value,timestamp=None): \"\"\"update(path,value,timestamp=None) path is a string value is a float", "currentPoints.reverse() __archive_update_many(fh,header,currentArchive,currentPoints) __changeLastUpdate(fh) fh.close() #endBlock('complete update_many path=%s points=%d' % (path,len(points)))", "WorldWide # # Licensed under the Apache License, Version 2.0", "archive for lower in lowerArchives: if not __propagate(fh,myInterval,header['xFilesFactor'],higher,lower): break higher", "#debug('__archive_update_many was NOT expected, appending to packedStrings startInterval=%s currentString=%d bytes'", "lower #endBlock('update propagation') __changeLastUpdate(fh) fh.close() #endBlock('complete update') def update_many(path,points): \"\"\"update_many(path,points)", "lower-precision archives #startBlock('update propagation') higher = archive for lower in", "occur \"\"\" #Validate archive configurations... assert archiveList, \"You must specify", "propagate a value! aggregateValue = float(sum(knownValues)) / float(len(knownValues)) #TODO another", "the interval fh.seek(fromOffset) if fromOffset < untilOffset: #If we don't", "fh.read(higherLastOffset - higher['offset']) #Now we unpack the series data we", "pointSize fromOffset = archive['offset'] + (byteDistance % archive['size']) #Determine untilOffset", "currentString') currentString += struct.pack(pointFormat,interval,value) previousInterval = interval else: numberOfPoints =", "of %d bytes, startInterval=%s' % (len(currentString),startInterval)) packedStrings.append( (startInterval,currentString) ) #endBlock('__archive_update_many", "#startBlock('__archive_update_many string packing') packedStrings = [] previousInterval = None currentString", "%d bytes #%d' % (len(data),self.writeCount)) return file.write(self,data) def read(self,bytes): self.readCount", "operations') #Now we propagate the updates to lower-precision archives #startBlock('__archive_update_many", "\"Higher precision archives' precision must evenly divide all lower precision", "the points we've found that it can fit currentPoints.reverse() #put", "now - fromTime for archive in header['archives']: if archive['retention'] >=", "string as the base, so we start at the start", "fh.fileno(), fcntl.LOCK_EX ) lastUpdate = struct.pack( timestampFormat, int(time.time()) ) oldest", "= 0): from StringIO import StringIO import memcache global open,", "= archive['offset'] + (byteDistance % archive['size']) #Read all the points", "is %s' % baseInterval) #Write all of our packed strings", "fh.seek(higher['offset']) seriesString += fh.read(higherLastOffset - higher['offset']) #Now we unpack the", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "propagation to occur \"\"\" #Validate archive configurations... assert archiveList, \"You", "for p in alignedPoints] uniqueLowerIntervals = set(lowerIntervals) #debug(' __archive_update_many points=%d", "struct.pack( longFormat, oldest ) xFilesFactor = struct.pack( floatFormat, float(xFilesFactor) )", "str(currentArchive)) currentPoints = [] for point in points: age =", "a NOP, use os.stat(filename).st_mtime instead startBlock('__changeLastUpdate()') originalOffset = fh.tell() fh.seek(0)", "the update to lower-precision archives #startBlock('update propagation') higher = archive", "pointDistance * pointSize myOffset = archive['offset'] + (byteDistance % archive['size'])", "found that it can fit currentPoints.reverse() #put points in chronological", "file # # File = Header,Data # Header = Metadata,ArchiveInfo+", "points: return points = [ (int(t),float(v)) for (t,v) in points]", "of archives, each of which is of the form (secondsPerPoint,numberOfPoints)", "fh.close() #endBlock('complete update_many path=%s points=%d' % (path,len(points))) def __archive_update_many(fh,header,archive,points): step", "https://bugs.launchpad.net/graphite/+bug/245835 \"\"\" import os, struct, time try: import fcntl CAN_LOCK", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "faster than append() currentInterval += step fh.close() timeInfo = (fromInterval,untilInterval,step)", "\"\"\"info(path) path is a string \"\"\" fh = open(path,'rb') info", "= timeDistance / archive['secondsPerPoint'] byteDistance = pointDistance * pointSize fromOffset", "seriesString) #And finally we construct a list of values (optimize", "path=%s points=%d' % (path,len(points))) if not points: return points =", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "neighborValues if v is not None] knownPercent = float(len(knownValues)) /", "points by timestamp, newest first fh = open(path,'r+b') if LOCK:", "0: #First propagated update to this lower archive fh.seek(lower['offset']) fh.write(myPackedPoint)", "update_many path=%s points=%d' % (path,len(points))) if not points: return points", "the archive seriesString = fh.read(untilOffset - fromOffset) else: #We do", "pointTime = unpackedSeries[i] if pointTime == currentInterval: pointValue = unpackedSeries[i+1]", "#startBlock('__archive_update_many file=%s archive=%s points=%d' % (fh.name,step,len(points))) alignedPoints = [ (timestamp", "we unpack the series data we just read byteOrder,pointTypes =", "\"\"\" #startBlock('complete update') value = float(value) fh = open(path,'r+b') if", "in xrange(0,len(unpackedSeries),2): pointTime = unpackedSeries[i] if pointTime == currentInterval: pointValue", "divide all lower precision archives' precision %s,%s\" % (archive[0],next[0]) retention", "(offset,secondsPerPoint,points) = struct.unpack(archiveInfoFormat,packedArchiveInfo) archiveInfo = { 'offset' : offset, 'secondsPerPoint'", "__init__(self,*args,**kwargs): self.name = args[0] self.mode = args[1] if self.mode ==", "- (timestamp % step), value) for (timestamp,value) in points ]", "points=%d unique=%d' % (len(alignedPoints),len(uniqueLowerIntervals))) propagateFurther = False for interval in", "{} longFormat = \"!L\" longSize = struct.calcsize(longFormat) floatFormat = \"!f\"", "- __timingBlocks.pop(name))) def __readHeader(fh): info = __headerCache.get(fh.name) if info: return", "info(path): \"\"\"info(path) path is a string \"\"\" fh = open(path,'rb')", "#debug(' update_many adding point=%s' % str(point)) currentPoints.append(point) #debug(' update_many done", "step): #debug('__archive_update_many was expected, packing onto currentString') currentString += struct.pack(pointFormat,interval,value)", "a[0]) #sort by precision (secondsPerPoint) for i,archive in enumerate(archiveList): if", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", ": offset, 'secondsPerPoint' : secondsPerPoint, 'points' : points, 'retention' :", "lowerIntervalStart - lowerBaseInterval pointDistance = timeDistance / lower['secondsPerPoint'] byteDistance =", "if lowerBaseInterval == 0: #First propagated update to this lower", "higher['secondsPerPoint'] higherSize = higherPoints * pointSize higherLastOffset = higherFirstOffset +", "with the same precision %s,%s\" % (archive,next) assert (next[0] %", "= len(seriesString) / pointSize seriesFormat = byteOrder + (pointTypes *", "open, exists, drop MC = memcache.Client(servers) class open(StringIO): def __init__(self,*args,**kwargs):", "__propagate(fh,myInterval,header['xFilesFactor'],higher,lower): break higher = lower #endBlock('update propagation') __changeLastUpdate(fh) fh.close() #endBlock('complete", "longSize = struct.calcsize(longFormat) floatFormat = \"!f\" floatSize = struct.calcsize(floatFormat) timestampFormat", "!= None def drop(path): MC.delete(path) def enableDebug(): global open, debug,", "specific language governing permissions and # limitations under the License.", "#If we don't wrap around the archive seriesString = fh.read(untilOffset", "bytesBeyond=%d' % (myOffset,len(packedString),archiveEnd,bytesBeyond)) if bytesBeyond > 0: fh.write( packedString[:-bytesBeyond] )", "path is a string \"\"\" fh = open(path,'rb') info =", "# Archive = Point+ # Point = timestamp,value \"\"\" NOTE:", "#TODO another CF besides average? myPackedPoint = struct.pack(pointFormat,lowerIntervalStart,aggregateValue) fh.seek(lower['offset']) packedPoint", "- (timestamp % archive['secondsPerPoint']) myPackedPoint = struct.pack(pointFormat,myInterval,value) fh.seek(archive['offset']) packedPoint =", "archive['secondsPerPoint'] #startBlock('__archive_update_many file=%s archive=%s points=%d' % (fh.name,step,len(points))) alignedPoints = [", "if currentArchive and currentPoints: #don't forget to commit after we've", "sorted([secondsPerPoint * points for secondsPerPoint,points in archiveList])[-1] maxRetention = struct.pack(", "int( time.time() ) if timestamp is None: timestamp = now", "step numberOfPoints = len(currentString) / pointSize startInterval = previousInterval -", "on the update to these lower precision archives later break", "lower['secondsPerPoint'] fh.seek(higher['offset']) packedPoint = fh.read(pointSize) (higherBaseInterval,higherBaseValue) = struct.unpack(pointFormat,packedPoint) if higherBaseInterval", "a propagation to occur \"\"\" #Validate archive configurations... assert archiveList,", "= fromInterval - baseInterval pointDistance = timeDistance / archive['secondsPerPoint'] byteDistance", "in enumerate(header['archives']): #Find the highest-precision archive that covers timestamp if", "[] for i in xrange(archiveCount): packedArchiveInfo = fh.read(archiveInfoSize) (offset,secondsPerPoint,points) =", "a propagation interval that must have known values for a", "metadataFormat = \"!2LfL\" metadataSize = struct.calcsize(metadataFormat) archiveInfoFormat = \"!3L\" archiveInfoSize", "currentArchive and currentPoints: #don't forget to commit after we've checked", "above) else: fh.write(packedString) #endBlock('__archive_update_many write() operations') #Now we propagate the", "# you may not use this file except in compliance", "next = archiveList[i+1] assert archive[0] < next[0],\\ \"You cannot configure", "#Propagate aggregateValue to propagate from neighborValues if we have enough", "higher = archive lowerArchives = [arc for arc in header['archives']", "* points return (timeInfo,valueList) #Determine fromOffset timeDistance = fromInterval -", "#endBlock('complete update_many path=%s points=%d' % (path,len(points))) def __archive_update_many(fh,header,archive,points): step =", ") #endBlock('__archive_update_many string packing') #Read base point and determine where", "= fh.read(pointSize) (higherBaseInterval,higherBaseValue) = struct.unpack(pointFormat,packedPoint) if higherBaseInterval == 0: higherFirstOffset", "= [None] * points currentInterval = lowerIntervalStart step = higher['secondsPerPoint']", "== 0: #This file's first update fh.seek(archive['offset']) fh.write(myPackedPoint) baseInterval,baseValue =", "just read byteOrder,pointTypes = pointFormat[0],pointFormat[1:] points = len(seriesString) / pointSize", "(int(t),float(v)) for (t,v) in points] points.sort(key=lambda p: p[0],reverse=True) #order points", "the archive (retention checking logic above) else: fh.write(packedString) #endBlock('__archive_update_many write()", "archiveEnd #debug(' __archive_update_many myOffset=%d packedString=%d archiveEnd=%d bytesBeyond=%d' % (myOffset,len(packedString),archiveEnd,bytesBeyond)) if", "= [] for point in points: age = now -", "timeDistance = fromInterval - baseInterval pointDistance = timeDistance / archive['secondsPerPoint']", "= struct.calcsize(longFormat) floatFormat = \"!f\" floatSize = struct.calcsize(floatFormat) timestampFormat =", "startInterval=%s' % (len(currentString),startInterval)) packedStrings.append( (startInterval,currentString) ) #endBlock('__archive_update_many string packing') #Read", "def __readHeader(fh): info = __headerCache.get(fh.name) if info: return info #startBlock('__readHeader')", "# limitations under the License. # # # This module", "< untilTime, \"Invalid time interval\" diff = now - fromTime", "don't wrap around the archive seriesString = fh.read(untilOffset - fromOffset)", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "I have %d lower archives' % len(lowerArchives)) for lower in", "we have enough known points knownValues = [v for v", "* (archiveOffsetPointer - headerSize) fh.write(zeroes) fh.close() def __propagate(fh,timestamp,xff,higher,lower): lowerIntervalStart =", "header['archives'] ) currentArchive = next(archives) #debug(' update_many currentArchive=%s' % str(currentArchive))", "pointDistance * pointSize fromOffset = archive['offset'] + (byteDistance % archive['size'])", "__changeLastUpdate(fh): return #XXX Make this a NOP, use os.stat(filename).st_mtime instead", "int( time.time() ) archives = iter( header['archives'] ) currentArchive =", "next[0],\\ \"You cannot configure two archives with the same precision", "update_many iterating points, point=%s age=%d' % (str(point),age)) while currentArchive['retention'] <", "read(self,bytes): self.readCount += 1 debug('READ %d bytes #%d' % (bytes,self.readCount))", "startBlock, endBlock class open(file): def __init__(self,*args,**kwargs): file.__init__(self,*args,**kwargs) self.writeCount = 0", "archive in header['archives']: if archive['retention'] >= diff: break fromInterval =", "archives = [] for i in xrange(archiveCount): packedArchiveInfo = fh.read(archiveInfoSize)", "#startBlock('__readHeader') originalOffset = fh.tell() fh.seek(0) packedMetadata = fh.read(metadataSize) (lastUpdate,maxRetention,xff,archiveCount) =", "nextRetention = next[0] * next[1] assert nextRetention > retention,\\ \"Lower", "under the Apache License, Version 2.0 (the \"License\"); # you", "xrange(archiveCount): packedArchiveInfo = fh.read(archiveInfoSize) (offset,secondsPerPoint,points) = struct.unpack(archiveInfoFormat,packedArchiveInfo) archiveInfo = {", "__propagate(fh,timestamp,xff,higher,lower): lowerIntervalStart = timestamp - (timestamp % lower['secondsPerPoint']) lowerIntervalEnd =", "in alignedPoints] uniqueLowerIntervals = set(lowerIntervals) #debug(' __archive_update_many points=%d unique=%d' %", "currentString: #startInterval = previousInterval - (step * len(currentString) / pointSize)", "- header['maxRetention']): fromTime = now - header['maxRetention'] assert fromTime <", "the update to these lower precision archives later break #First", "faster than unpack?) byteOrder,pointTypes = pointFormat[0],pointFormat[1:] points = len(seriesString) /", "\"Lower precision archives must cover larger time intervals than higher", "lowerIntervalStart step = higher['secondsPerPoint'] for i in xrange(0,len(unpackedSeries),2): pointTime =", "after we've checked all the archives currentPoints.reverse() __archive_update_many(fh,header,currentArchive,currentPoints) __changeLastUpdate(fh) fh.close()", "archiveOffsetPointer += (points * pointSize) zeroes = '\\x00' * (archiveOffsetPointer", "(byteDistance % archive['size']) #Determine untilOffset timeDistance = untilInterval - baseInterval", "determine where our writes will start fh.seek(archive['offset']) packedBasePoint = fh.read(pointSize)", "> retention,\\ \"Lower precision archives must cover larger time intervals", "python # Copyright 2008 Orbitz WorldWide # # Licensed under", "i == len(archiveList) - 1: break next = archiveList[i+1] assert", "was expected, packing onto currentString') currentString += struct.pack(pointFormat,interval,value) previousInterval =", ": points * pointSize, } archives.append(archiveInfo) fh.seek(originalOffset) info = {", "first update') baseInterval = packedStrings[0][0] #use our first string as", "reassignment is faster than append() currentInterval += step fh.close() timeInfo", "precision must evenly divide all lower precision archives' precision %s,%s\"", "- (step * (numberOfPoints-1)) #debug('__archive_update_many done iterating alignedPoints, remainder currentString", "locations determined by the baseInterval #startBlock('__archive_update_many write() operations') for (interval,packedString)", "[arc for arc in header['archives'] if arc['secondsPerPoint'] > archive['secondsPerPoint']] #debug('__archive_update_many", "os, struct, time try: import fcntl CAN_LOCK = True except", "MC.delete(path) def enableDebug(): global open, debug, startBlock, endBlock class open(file):", "= archive['offset'] + (byteDistance % archive['size']) #Determine untilOffset timeDistance =", "unpack the series data we just read (anything faster than", "archive['size']) #Determine untilOffset timeDistance = untilInterval - baseInterval pointDistance =", "an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "onto currentString') currentString += struct.pack(pointFormat,interval,value) previousInterval = interval else: numberOfPoints", "- baseInterval pointDistance = timeDistance / archive['secondsPerPoint'] byteDistance = pointDistance", "update fh.seek(archive['offset']) fh.write(myPackedPoint) baseInterval,baseValue = myInterval,value else: #Not our first", "if fromOffset < untilOffset: #If we don't wrap around the", "neighborValues = [None] * points currentInterval = lowerIntervalStart step =", "now = int( time.time() ) archives = iter( header['archives'] )", "fraction of data points in a propagation interval that must", "= now timestamp = int(timestamp) diff = now - timestamp", "untilInterval = int( untilTime - (untilTime % archive['secondsPerPoint']) ) fh.seek(archive['offset'])", "archiveCount fh.write(packedMetadata) headerSize = metadataSize + (archiveInfoSize * len(archiveList)) archiveOffsetPointer", "#debug(' update_many currentArchive=%s' % str(currentArchive)) currentPoints = [] for point", "points \"\"\" #startBlock('complete update_many path=%s points=%d' % (path,len(points))) if not", "return info def fetch(path,fromTime,untilTime=None): \"\"\"fetch(path,fromTime,untilTime=None) path is a string fromTime", "#debug('__archive_update_many I have %d lower archives' % len(lowerArchives)) for lower", "archive %s' % str(currentArchive)) except StopIteration: #debug(' update_many no more", "= \"!f\" floatSize = struct.calcsize(floatFormat) timestampFormat = \"!L\" timestampSize =", "= __headerCache.get(fh.name) if info: return info #startBlock('__readHeader') originalOffset = fh.tell()", "valueList[i/2] = pointValue #in-place reassignment is faster than append() currentInterval", "specifies the fraction of data points in a propagation interval", "do wrap around the archive, so we need two reads", "#This file's first update #debug('__archive_update_many first update') baseInterval = packedStrings[0][0]", "False for interval in uniqueLowerIntervals: #debug(' __archive_update_many propagating from %d", "- header['maxRetention'] assert fromTime < untilTime, \"Invalid time interval\" diff", "more points in this archive #debug(' update_many this point is", "is a float timestamp is either an int or float", "timestamp if archive['retention'] < diff: continue lowerArchives = header['archives'][i+1:] #We'll", "\"\" for (interval,value) in alignedPoints: #debug('__archive_update_many iterating alignedPoint at %s'", "archives in this database\" for i,archive in enumerate(header['archives']): #Find the", "path is a string fromTime is an epoch time untilTime", "0, \"Timestamp not covered by any archives in this database\"", "points, 'size' : points * pointSize, } archives.append(archiveInfo) fh.seek(originalOffset) info", "that first field is lastUpdate now = int( time.time() )", "now we create the file and write the header assert", "- point[0] #debug(' update_many iterating points, point=%s age=%d' % (str(point),age))", "archives' precision %s,%s\" % (archive[0],next[0]) retention = archive[0] * archive[1]", "(fh.name,step,len(points))) def info(path): \"\"\"info(path) path is a string \"\"\" fh", "ArchiveInfo = Offset,SecondsPerPoint,Points # Data = Archive+ # Archive =", "= struct.calcsize(valueFormat) pointFormat = \"!Ld\" pointSize = struct.calcsize(pointFormat) metadataFormat =", "* (numberOfPoints-1)) #debug('__archive_update_many was NOT expected, appending to packedStrings startInterval=%s", "return file.write(self,data) def read(self,bytes): self.readCount += 1 debug('READ %d bytes", "+ len(packedString)) - archiveEnd #debug(' __archive_update_many myOffset=%d packedString=%d archiveEnd=%d bytesBeyond=%d'", "== 0,\\ \"Higher precision archives' precision must evenly divide all", "done iterating points') if currentArchive and currentPoints: #don't forget to", "(str(point),age)) while currentArchive['retention'] < age: #we can't fit any more", "MC.get(self.name)) else: StringIO.__init__(self) def close(self): if self.mode == \"r+b\" or", "points.sort(key=lambda p: p[0],reverse=True) #order points by timestamp, newest first fh", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "in header['archives'] if arc['secondsPerPoint'] > archive['secondsPerPoint']] #debug('__archive_update_many I have %d", "} if CACHE_HEADERS: __headerCache[fh.name] = info #endBlock('__readHeader') return info def", "#debug(' update_many this point is too old to fit here,", "else: #Not our first propagated update to this lower archive", "fh.tell() fh.seek(0) #Based on assumption that first field is lastUpdate", "all lower precision archives' precision %s,%s\" % (archive[0],next[0]) retention =", "(untilTime % archive['secondsPerPoint']) ) fh.seek(archive['offset']) packedPoint = fh.read(pointSize) (baseInterval,baseValue) =", "def __changeLastUpdate(fh): return #XXX Make this a NOP, use os.stat(filename).st_mtime", "points #pre-allocate entire list for speed currentInterval = fromInterval step", "baseInterval == 0: step = archive['secondsPerPoint'] points = (untilInterval -", ": maxRetention, 'xFilesFactor' : xff, 'archives' : archives, } if", "debug('WRITE %d bytes #%d' % (len(data),self.writeCount)) return file.write(self,data) def read(self,bytes):", "Apache License, Version 2.0 (the \"License\"); # you may not", "= now - fromTime for archive in header['archives']: if archive['retention']", "either express or implied. # See the License for the", "i: i - (i % lower['secondsPerPoint']) lowerIntervals = [fit(p[0]) for", "'maxRetention' : maxRetention, 'xFilesFactor' : xff, 'archives' : archives, }", "+= 1 debug('READ %d bytes #%d' % (bytes,self.readCount)) return file.read(self,bytes)", "point in points: age = now - point[0] #debug(' update_many", "= lower #endBlock('__archive_update_many propagation') #endBlock('__archive_update_many file=%s archive=%s points=%d' % (fh.name,step,len(points)))", "pointValue #in-place reassignment is faster than append() currentInterval += step", "(byteDistance % higher['size']) higherPoints = lower['secondsPerPoint'] / higher['secondsPerPoint'] higherSize =", "> now: untilTime = now if fromTime < (now -", "all the points in the interval fh.seek(fromOffset) if fromOffset <", "= float(sum(knownValues)) / float(len(knownValues)) #TODO another CF besides average? myPackedPoint", "#endBlock('update propagation') __changeLastUpdate(fh) fh.close() #endBlock('complete update') def update_many(path,points): \"\"\"update_many(path,points) path", "points) fh.write(archiveInfo) archiveOffsetPointer += (points * pointSize) zeroes = '\\x00'", "than unpack?) byteOrder,pointTypes = pointFormat[0],pointFormat[1:] points = len(seriesString) / pointSize", "if not currentArchive: break #drop remaining points that don't fit", "= higher['offset'] + (byteDistance % higher['size']) higherPoints = lower['secondsPerPoint'] /", "fh.write( packedString[-bytesBeyond:] ) #safe because it can't exceed the archive", "alignedPoints: #debug('__archive_update_many iterating alignedPoint at %s' % interval) if (not", "fh.write(packedTime) fh.seek(originalOffset) endBlock('__changeLastUpdate()') def create(path,archiveList,xFilesFactor=0.5): \"\"\"create(path,archiveList,xFilesFactor=0.5) path is a string", "len(packedString)=%d\" % (archiveEnd,fh.tell(),bytesBeyond,len(packedString)) fh.seek( archive['offset'] ) fh.write( packedString[-bytesBeyond:] ) #safe", "archive seriesString = fh.read(untilOffset - fromOffset) else: #We do wrap", "here, currentPoints=%d' % len(currentPoints)) if currentPoints: #commit all the points", "cover larger time intervals than higher precision archives %s,%s\" %", ") #debug('We wrapped an archive!') assert fh.tell() == archiveEnd, \"archiveEnd=%d", "== archiveEnd, \"archiveEnd=%d fh.tell=%d bytesBeyond=%d len(packedString)=%d\" % (archiveEnd,fh.tell(),bytesBeyond,len(packedString)) fh.seek( archive['offset']", "interval=%d' % (higher['secondsPerPoint'],lower['secondsPerPoint'],interval)) if __propagate(fh,interval,header['xFilesFactor'],higher,lower): propagateFurther = True #debug(' __archive_update_many", "self.readCount = 0 def write(self,data): self.writeCount += 1 debug('WRITE %d", ") fh.seek(archive['offset']) packedPoint = fh.read(pointSize) (baseInterval,baseValue) = struct.unpack(pointFormat,packedPoint) if baseInterval", "an epoch time untilTime is also an epoch time, but", "higher['secondsPerPoint'] for i in xrange(0,len(unpackedSeries),2): pointTime = unpackedSeries[i] if pointTime", "#First we update the highest-precision archive myInterval = timestamp -", "% step), value) for (timestamp,value) in points ] #Create a", "struct.unpack(seriesFormat, seriesString) #And finally we construct a list of values", "startInterval=%s currentString=%d bytes' % (startInterval,len(currentString))) packedStrings.append( (startInterval,currentString) ) currentString =", "True #debug(' __archive_update_many Successful propagation!') #debug(' __archive_update_many propagateFurther=%s' % propagateFurther)", "[None] * points return (timeInfo,valueList) #Determine fromOffset timeDistance = fromInterval", "module is an implementation of the Whisper database API #", "specify at least one archive configuration!\" archiveList.sort(key=lambda a: a[0]) #sort", "not points: return points = [ (int(t),float(v)) for (t,v) in", "floatSize = struct.calcsize(floatFormat) timestampFormat = \"!L\" timestampSize = struct.calcsize(timestampFormat) valueFormat", "seriesString = fh.read(untilOffset - fromOffset) else: #We do wrap around", "currentInterval = fromInterval step = archive['secondsPerPoint'] for i in xrange(0,len(unpackedSeries),2):", "archiveInfoFormat = \"!3L\" archiveInfoSize = struct.calcsize(archiveInfoFormat) debug = startBlock =", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "* archive[1] nextRetention = next[0] * next[1] assert nextRetention >", "= \"!L\" longSize = struct.calcsize(longFormat) floatFormat = \"!f\" floatSize =", "higherFirstOffset = higher['offset'] else: timeDistance = lowerIntervalStart - higherBaseInterval pointDistance", "#First propagated update to this lower archive fh.seek(lower['offset']) fh.write(myPackedPoint) else:", "precision (secondsPerPoint) for i,archive in enumerate(archiveList): if i == len(archiveList)", "= next(archives) #debug(' update_many using next archive %s' % str(currentArchive))", "archive seriesString = fh.read(higherLastOffset - higherFirstOffset) else: #We do wrap", "for speed currentInterval = fromInterval step = archive['secondsPerPoint'] for i", "packedStrings[0][0] #use our first string as the base, so we", "untilTime, \"Invalid time interval\" diff = now - fromTime for", "timeDistance / archive['secondsPerPoint'] byteDistance = pointDistance * pointSize fromOffset =", "#debug(' __archive_update_many points=%d unique=%d' % (len(alignedPoints),len(uniqueLowerIntervals))) propagateFurther = False for", "archive['offset'] + (byteDistance % archive['size']) fh.seek(myOffset) fh.write(myPackedPoint) #Now we propagate", "points, 'retention' : secondsPerPoint * points, 'size' : points *", "#endBlock('__archive_update_many file=%s archive=%s points=%d' % (fh.name,step,len(points))) def info(path): \"\"\"info(path) path", "= archive for lower in lowerArchives: if not __propagate(fh,myInterval,header['xFilesFactor'],higher,lower): break", "0): from StringIO import StringIO import memcache global open, exists,", "info def fetch(path,fromTime,untilTime=None): \"\"\"fetch(path,fromTime,untilTime=None) path is a string fromTime is", "update to lower-precision archives #startBlock('update propagation') higher = archive for", "Header,Data # Header = Metadata,ArchiveInfo+ # Metadata = lastUpdate,maxRetention,xFilesFactor,archiveCount #", "timeDistance / higher['secondsPerPoint'] byteDistance = pointDistance * pointSize higherFirstOffset =", "= timeDistance / lower['secondsPerPoint'] byteDistance = pointDistance * pointSize lowerOffset", "__propagate(fh,interval,header['xFilesFactor'],higher,lower): propagateFurther = True #debug(' __archive_update_many Successful propagation!') #debug(' __archive_update_many", "- archiveEnd #debug(' __archive_update_many myOffset=%d packedString=%d archiveEnd=%d bytesBeyond=%d' % (myOffset,len(packedString),archiveEnd,bytesBeyond))", "lowerArchives = header['archives'][i+1:] #We'll pass on the update to these", "(timestamp % archive['secondsPerPoint']) myPackedPoint = struct.pack(pointFormat,myInterval,value) fh.seek(archive['offset']) packedPoint = fh.read(pointSize)", "'offset' : offset, 'secondsPerPoint' : secondsPerPoint, 'points' : points, 'retention'", "if higherBaseInterval == 0: higherFirstOffset = higher['offset'] else: timeDistance =", "+ maxRetention + xFilesFactor + archiveCount fh.write(packedMetadata) headerSize = metadataSize", "import StringIO import memcache global open, exists, drop MC =", "points knownValues = [v for v in neighborValues if v", "the basic layout of a whisper data file # #", "alignedPoints, remainder currentString of %d bytes, startInterval=%s' % (len(currentString),startInterval)) packedStrings.append(", "is a list of (timestamp,value) points \"\"\" #startBlock('complete update_many path=%s", "now if fromTime < (now - header['maxRetention']): fromTime = now", "path is a string archiveList is a list of archives,", "we've found that it can fit currentPoints.reverse() #put points in", "iterating points') if currentArchive and currentPoints: #don't forget to commit", "pointTime == currentInterval: pointValue = unpackedSeries[i+1] valueList[i/2] = pointValue #in-place", "fcntl.LOCK_EX ) header = __readHeader(fh) now = int( time.time() )", "untilOffset timeDistance = untilInterval - baseInterval pointDistance = timeDistance /", "is a string points is a list of (timestamp,value) points", "done iterating alignedPoints, remainder currentString of %d bytes, startInterval=%s' %", "precision %s,%s\" % (archive,next) assert (next[0] % archive[0]) == 0,\\", "= int( time.time() ) archives = iter( header['archives'] ) currentArchive", "we unpack the series data we just read (anything faster", "at the start #debug('__archive_update_many baseInterval is %s' % baseInterval) #Write", "(points * pointSize) zeroes = '\\x00' * (archiveOffsetPointer - headerSize)", "- (fromTime % archive['secondsPerPoint']) ) untilInterval = int( untilTime -", "% path fh = open(path,'wb') if LOCK: fcntl.flock( fh.fileno(), fcntl.LOCK_EX", "== len(archiveList) - 1: break next = archiveList[i+1] assert archive[0]", "= previousInterval - (step * (numberOfPoints-1)) #debug('__archive_update_many done iterating alignedPoints,", "headerSize) fh.write(zeroes) fh.close() def __propagate(fh,timestamp,xff,higher,lower): lowerIntervalStart = timestamp - (timestamp", "try: currentArchive = next(archives) #debug(' update_many using next archive %s'", "debug = startBlock = endBlock = lambda *a,**k: None def", "struct.calcsize(metadataFormat) archiveInfoFormat = \"!3L\" archiveInfoSize = struct.calcsize(archiveInfoFormat) debug = startBlock", "debug(\"%s took %.5f seconds\" % (name,time.time() - __timingBlocks.pop(name))) def __readHeader(fh):", "\"!Ld\" pointSize = struct.calcsize(pointFormat) metadataFormat = \"!2LfL\" metadataSize = struct.calcsize(metadataFormat)", "packed string for each contiguous sequence of points #startBlock('__archive_update_many string", "'retention' : secondsPerPoint * points, 'size' : points * pointSize,", "to fit here, currentPoints=%d' % len(currentPoints)) if currentPoints: #commit all", "return MC.get(path) != None def drop(path): MC.delete(path) def enableDebug(): global", "enableMemcache(servers = ['127.0.0.1:11211'], min_compress_len = 0): from StringIO import StringIO", "use this file except in compliance with the License. #", "#don't forget to commit after we've checked all the archives", "(lowerBaseInterval,lowerBaseValue) = struct.unpack(pointFormat,packedPoint) if lowerBaseInterval == 0: #First propagated update", "archiveList: archiveInfo = struct.pack(archiveInfoFormat, archiveOffsetPointer, secondsPerPoint, points) fh.write(archiveInfo) archiveOffsetPointer +=", "\"File %s already exists!\" % path fh = open(path,'wb') if", "= pointFormat[0],pointFormat[1:] points = len(seriesString) / pointSize seriesFormat = byteOrder", "- (step * len(currentString) / pointSize) + step numberOfPoints =", "struct.calcsize(longFormat) floatFormat = \"!f\" floatSize = struct.calcsize(floatFormat) timestampFormat = \"!L\"", "(step * (numberOfPoints-1)) #debug('__archive_update_many done iterating alignedPoints, remainder currentString of", "have enough data to propagate a value! aggregateValue = float(sum(knownValues))", "debug(message): print('DEBUG :: %s' % message) __timingBlocks = {} def", "our packed strings in locations determined by the baseInterval #startBlock('__archive_update_many", "because it can't exceed the archive (retention checking logic above)", "= struct.unpack(seriesFormat, seriesString) #And finally we construct a list of", "= False CACHE_HEADERS = False __headerCache = {} longFormat =", "int or float \"\"\" #startBlock('complete update') value = float(value) fh", "StringIO import memcache global open, exists, drop MC = memcache.Client(servers)", "(pointTypes * points) unpackedSeries = struct.unpack(seriesFormat, seriesString) #And finally we", "fh.close() return info def fetch(path,fromTime,untilTime=None): \"\"\"fetch(path,fromTime,untilTime=None) path is a string", "/ pointSize) + step numberOfPoints = len(currentString) / pointSize startInterval", "metadataSize = struct.calcsize(metadataFormat) archiveInfoFormat = \"!3L\" archiveInfoSize = struct.calcsize(archiveInfoFormat) debug", "= fh.read(higherEnd - higherFirstOffset) fh.seek(higher['offset']) seriesString += fh.read(higherLastOffset - higher['offset'])", "fcntl CAN_LOCK = True except ImportError: CAN_LOCK = False LOCK", "aggregateValue to propagate from neighborValues if we have enough known", "higher['size']) fh.seek(higherFirstOffset) if higherFirstOffset < higherLastOffset: #we don't wrap the", "startBlock = endBlock = lambda *a,**k: None def exists(path): return", "byteDistance = pointDistance * pointSize untilOffset = archive['offset'] + (byteDistance", "= struct.pack(pointFormat,myInterval,value) fh.seek(archive['offset']) packedPoint = fh.read(pointSize) (baseInterval,baseValue) = struct.unpack(pointFormat,packedPoint) if", "byteDistance = pointDistance * pointSize myOffset = archive['offset'] + (byteDistance", "= next(archives) #debug(' update_many currentArchive=%s' % str(currentArchive)) currentPoints = []", "= struct.unpack(archiveInfoFormat,packedArchiveInfo) archiveInfo = { 'offset' : offset, 'secondsPerPoint' :", "on the modification, read https://bugs.launchpad.net/graphite/+bug/245835 \"\"\" import os, struct, time", "read https://bugs.launchpad.net/graphite/+bug/245835 \"\"\" import os, struct, time try: import fcntl", "xFilesFactor specifies the fraction of data points in a propagation", "+ (archiveInfoSize * len(archiveList)) archiveOffsetPointer = headerSize for secondsPerPoint,points in", "time.time() def endBlock(name): debug(\"%s took %.5f seconds\" % (name,time.time() -", "use os.stat(filename).st_mtime instead startBlock('__changeLastUpdate()') originalOffset = fh.tell() fh.seek(0) #Based on", "packedPoint = fh.read(pointSize) (baseInterval,baseValue) = struct.unpack(pointFormat,packedPoint) if baseInterval == 0:", "os.stat(filename).st_mtime instead startBlock('__changeLastUpdate()') originalOffset = fh.tell() fh.seek(0) #Based on assumption", "two archives with the same precision %s,%s\" % (archive,next) assert", "%d to %d, interval=%d' % (higher['secondsPerPoint'],lower['secondsPerPoint'],interval)) if __propagate(fh,interval,header['xFilesFactor'],higher,lower): propagateFurther =", "step = archive['secondsPerPoint'] #startBlock('__archive_update_many file=%s archive=%s points=%d' % (fh.name,step,len(points))) alignedPoints", "__archive_update_many points=%d unique=%d' % (len(alignedPoints),len(uniqueLowerIntervals))) propagateFurther = False for interval", "and write the header assert not exists(path), \"File %s already", "in compliance with the License. # You may obtain a", "software # distributed under the License is distributed on an", "must evenly divide all lower precision archives' precision %s,%s\" %", "= lowerIntervalStart - lowerBaseInterval pointDistance = timeDistance / lower['secondsPerPoint'] byteDistance", "list for speed currentInterval = fromInterval step = archive['secondsPerPoint'] for", "bytes #%d' % (bytes,self.readCount)) return file.read(self,bytes) def debug(message): print('DEBUG ::", "fh.read(pointSize) (baseInterval,baseValue) = struct.unpack(pointFormat,packedPoint) if baseInterval == 0: step =", "/ higher['secondsPerPoint'] byteDistance = pointDistance * pointSize higherFirstOffset = higher['offset']", "lowerIntervalStart + lower['secondsPerPoint'] fh.seek(higher['offset']) packedPoint = fh.read(pointSize) (higherBaseInterval,higherBaseValue) = struct.unpack(pointFormat,packedPoint)", "exists, drop MC = memcache.Client(servers) class open(StringIO): def __init__(self,*args,**kwargs): self.name", "archive myInterval = timestamp - (timestamp % archive['secondsPerPoint']) myPackedPoint =", "# Metadata = lastUpdate,maxRetention,xFilesFactor,archiveCount # ArchiveInfo = Offset,SecondsPerPoint,Points # Data", "assert fromTime < untilTime, \"Invalid time interval\" diff = now", "header['archives'] if arc['secondsPerPoint'] > archive['secondsPerPoint']] #debug('__archive_update_many I have %d lower", "- archive['offset']) #Now we unpack the series data we just", "\"r+b\" or self.mode == \"rb\": StringIO.__init__(self, MC.get(self.name)) else: StringIO.__init__(self) def", "data points in a propagation interval that must have known", "def debug(message): print('DEBUG :: %s' % message) __timingBlocks = {}", "continue lowerArchives = header['archives'][i+1:] #We'll pass on the update to", "epoch time, but defaults to now \"\"\" fh = open(path,'rb')", "__archive_update_many(fh,header,currentArchive,currentPoints) __changeLastUpdate(fh) fh.close() #endBlock('complete update_many path=%s points=%d' % (path,len(points))) def", "step = archive['secondsPerPoint'] for i in xrange(0,len(unpackedSeries),2): pointTime = unpackedSeries[i]", "% archive['size']) #Read all the points in the interval fh.seek(fromOffset)", "points * pointSize, } archives.append(archiveInfo) fh.seek(originalOffset) info = { 'lastUpdate'", "in xrange(archiveCount): packedArchiveInfo = fh.read(archiveInfoSize) (offset,secondsPerPoint,points) = struct.unpack(archiveInfoFormat,packedArchiveInfo) archiveInfo =", "file's first update #debug('__archive_update_many first update') baseInterval = packedStrings[0][0] #use", "currentPoints.append(point) #debug(' update_many done iterating points') if currentArchive and currentPoints:", "each of which is of the form (secondsPerPoint,numberOfPoints) xFilesFactor specifies", "database\" for i,archive in enumerate(header['archives']): #Find the highest-precision archive that", "we propagate the updates to lower-precision archives #startBlock('__archive_update_many propagation') higher", "\"\"\"create(path,archiveList,xFilesFactor=0.5) path is a string archiveList is a list of", "point and determine where our writes will start fh.seek(archive['offset']) packedBasePoint", "reads archiveEnd = archive['offset'] + archive['size'] seriesString = fh.read(archiveEnd -", "self.getvalue(), min_compress_len = min_compress_len) StringIO.close(self) def exists(path): return MC.get(path) !=", "lastUpdate now = int( time.time() ) packedTime = struct.pack(timestampFormat,now) fh.write(packedTime)", "Orbitz WorldWide # # Licensed under the Apache License, Version", "path fh = open(path,'wb') if LOCK: fcntl.flock( fh.fileno(), fcntl.LOCK_EX )", "step = higher['secondsPerPoint'] for i in xrange(0,len(unpackedSeries),2): pointTime = unpackedSeries[i]", "= float(len(knownValues)) / float(len(neighborValues)) if knownPercent >= xff: #we have", "= [v for v in neighborValues if v is not", "lower precision archives' precision %s,%s\" % (archive[0],next[0]) retention = archive[0]", "archive['secondsPerPoint'] for i in xrange(0,len(unpackedSeries),2): pointTime = unpackedSeries[i] if pointTime", "= int( time.time() ) if untilTime is None or untilTime", "= archive['secondsPerPoint'] points = (untilInterval - fromInterval) / step timeInfo", "arc in header['archives'] if arc['secondsPerPoint'] > archive['secondsPerPoint']] #debug('__archive_update_many I have", "#debug(' __archive_update_many Successful propagation!') #debug(' __archive_update_many propagateFurther=%s' % propagateFurther) if", "#Read base point and determine where our writes will start", "if untilTime is None or untilTime > now: untilTime =", "% (len(data),self.writeCount)) return file.write(self,data) def read(self,bytes): self.readCount += 1 debug('READ", "% lower['secondsPerPoint']) lowerIntervals = [fit(p[0]) for p in alignedPoints] uniqueLowerIntervals", "unpackedSeries[i] if pointTime == currentInterval: pointValue = unpackedSeries[i+1] valueList[i/2] =", "* pointSize lowerOffset = lower['offset'] + (byteDistance % lower['size']) fh.seek(lowerOffset)", "data we just read (anything faster than unpack?) byteOrder,pointTypes =", "1 debug('READ %d bytes #%d' % (bytes,self.readCount)) return file.read(self,bytes) def", "message) __timingBlocks = {} def startBlock(name): __timingBlocks[name] = time.time() def", "with the License. # You may obtain a copy of", "= memcache.Client(servers) class open(StringIO): def __init__(self,*args,**kwargs): self.name = args[0] self.mode", "fh = open(path,'wb') if LOCK: fcntl.flock( fh.fileno(), fcntl.LOCK_EX ) lastUpdate", "#Determine untilOffset timeDistance = untilInterval - baseInterval pointDistance = timeDistance", "pointDistance * pointSize higherFirstOffset = higher['offset'] + (byteDistance % higher['size'])", "fh.seek(archive['offset']) packedPoint = fh.read(pointSize) (baseInterval,baseValue) = struct.unpack(pointFormat,packedPoint) if baseInterval ==", "and # limitations under the License. # # # This", ") currentString = struct.pack(pointFormat,interval,value) previousInterval = interval if currentString: #startInterval", "*a,**k: None def exists(path): return os.path.exists(path) def drop(path): os.remove(path) def", "= fh.tell() fh.seek(0) packedMetadata = fh.read(metadataSize) (lastUpdate,maxRetention,xff,archiveCount) = struct.unpack(metadataFormat,packedMetadata) archives", "= timeDistance / archive['secondsPerPoint'] byteDistance = pointDistance * pointSize myOffset", "currentArchive['retention'] < age: #we can't fit any more points in", "fcntl.flock( fh.fileno(), fcntl.LOCK_EX ) header = __readHeader(fh) now = int(", "open(path,'rb') info = __readHeader(fh) fh.close() return info def fetch(path,fromTime,untilTime=None): \"\"\"fetch(path,fromTime,untilTime=None)", "MC = memcache.Client(servers) class open(StringIO): def __init__(self,*args,**kwargs): self.name = args[0]", "exists(path): return os.path.exists(path) def drop(path): os.remove(path) def enableMemcache(servers = ['127.0.0.1:11211'],", "= False LOCK = False CACHE_HEADERS = False __headerCache =", "* points #pre-allocate entire list for speed currentInterval = fromInterval", "express or implied. # See the License for the specific", "+ (byteDistance % archive['size']) #Determine untilOffset timeDistance = untilInterval -", "except in compliance with the License. # You may obtain", "is a modified version of whisper.py For details on the", "StringIO.__init__(self) def close(self): if self.mode == \"r+b\" or self.mode ==", "maxRetention, 'xFilesFactor' : xff, 'archives' : archives, } if CACHE_HEADERS:", "(bytes,self.readCount)) return file.read(self,bytes) def debug(message): print('DEBUG :: %s' % message)", "#%d' % (bytes,self.readCount)) return file.read(self,bytes) def debug(message): print('DEBUG :: %s'", "= archive lowerArchives = [arc for arc in header['archives'] if", "first propagated update to this lower archive timeDistance = lowerIntervalStart", "fh.write(myPackedPoint) return True else: return False def update(path,value,timestamp=None): \"\"\"update(path,value,timestamp=None) path", "= lambda *a,**k: None def exists(path): return os.path.exists(path) def drop(path):", "False def update(path,value,timestamp=None): \"\"\"update(path,value,timestamp=None) path is a string value is", "struct.calcsize(valueFormat) pointFormat = \"!Ld\" pointSize = struct.calcsize(pointFormat) metadataFormat = \"!2LfL\"", "= sorted([secondsPerPoint * points for secondsPerPoint,points in archiveList])[-1] maxRetention =", "float(len(knownValues)) / float(len(neighborValues)) if knownPercent >= xff: #we have enough", "[ (int(t),float(v)) for (t,v) in points] points.sort(key=lambda p: p[0],reverse=True) #order", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "metadataSize + (archiveInfoSize * len(archiveList)) archiveOffsetPointer = headerSize for secondsPerPoint,points", ">= diff: break fromInterval = int( fromTime - (fromTime %", "header['maxRetention'] assert fromTime < untilTime, \"Invalid time interval\" diff =", "lower precision archives later break #First we update the highest-precision", "age = now - point[0] #debug(' update_many iterating points, point=%s", "header['maxRetention'] and diff >= 0, \"Timestamp not covered by any", "untilTime - (untilTime % archive['secondsPerPoint']) ) fh.seek(archive['offset']) packedPoint = fh.read(pointSize)", "StringIO.close(self) def exists(path): return MC.get(path) != None def drop(path): MC.delete(path)", "CONDITIONS OF ANY KIND, either express or implied. # See", "#endBlock('__archive_update_many propagation') #endBlock('__archive_update_many file=%s archive=%s points=%d' % (fh.name,step,len(points))) def info(path):", "data to propagate a value! aggregateValue = float(sum(knownValues)) / float(len(knownValues))", "archive, so we need two reads archiveEnd = archive['offset'] +", "we create the file and write the header assert not", "- fromOffset) fh.seek(archive['offset']) seriesString += fh.read(untilOffset - archive['offset']) #Now we", "currentInterval: neighborValues[i/2] = unpackedSeries[i+1] currentInterval += step #Propagate aggregateValue to", "one archive configuration!\" archiveList.sort(key=lambda a: a[0]) #sort by precision (secondsPerPoint)", "= struct.calcsize(archiveInfoFormat) debug = startBlock = endBlock = lambda *a,**k:", "else: #Not our first update timeDistance = myInterval - baseInterval", "newest first fh = open(path,'r+b') if LOCK: fcntl.flock( fh.fileno(), fcntl.LOCK_EX", "in neighborValues if v is not None] knownPercent = float(len(knownValues))", "lower['secondsPerPoint']) lowerIntervalEnd = lowerIntervalStart + lower['secondsPerPoint'] fh.seek(higher['offset']) packedPoint = fh.read(pointSize)", "this!) valueList = [None] * points #pre-allocate entire list for", "\"r+b\" or self.mode == \"wb\": MC.set(self.name, self.getvalue(), min_compress_len = min_compress_len)", "write the header assert not exists(path), \"File %s already exists!\"", "so we need two reads archiveEnd = archive['offset'] + archive['size']", "__headerCache.get(fh.name) if info: return info #startBlock('__readHeader') originalOffset = fh.tell() fh.seek(0)", "archive higherEnd = higher['offset'] + higher['size'] seriesString = fh.read(higherEnd -", "len(currentPoints)) if currentPoints: #commit all the points we've found that", "#put points in chronological order __archive_update_many(fh,header,currentArchive,currentPoints) currentPoints = [] try:", "Make this a NOP, use os.stat(filename).st_mtime instead startBlock('__changeLastUpdate()') originalOffset =", "= higherPoints * pointSize higherLastOffset = higherFirstOffset + (higherSize %", "CACHE_HEADERS: __headerCache[fh.name] = info #endBlock('__readHeader') return info def __changeLastUpdate(fh): return", "= True #debug(' __archive_update_many Successful propagation!') #debug(' __archive_update_many propagateFurther=%s' %", "the series data we just read byteOrder,pointTypes = pointFormat[0],pointFormat[1:] points", "higher['secondsPerPoint'] byteDistance = pointDistance * pointSize higherFirstOffset = higher['offset'] +", "of a whisper data file # # File = Header,Data", "next[1] assert nextRetention > retention,\\ \"Lower precision archives must cover", "return info def __changeLastUpdate(fh): return #XXX Make this a NOP,", "== 0: higherFirstOffset = higher['offset'] else: timeDistance = lowerIntervalStart -", "archive['secondsPerPoint'] byteDistance = pointDistance * pointSize myOffset = archive['offset'] +", "not covered by any archives in this database\" for i,archive", "% str(point)) currentPoints.append(point) #debug(' update_many done iterating points') if currentArchive", "neighborValues if we have enough known points knownValues = [v", "baseInterval #startBlock('__archive_update_many write() operations') for (interval,packedString) in packedStrings: timeDistance =", "'archives' : archives, } if CACHE_HEADERS: __headerCache[fh.name] = info #endBlock('__readHeader')", "file=%s archive=%s points=%d' % (fh.name,step,len(points))) def info(path): \"\"\"info(path) path is", "(myOffset,len(packedString),archiveEnd,bytesBeyond)) if bytesBeyond > 0: fh.write( packedString[:-bytesBeyond] ) #debug('We wrapped", "= now if fromTime < (now - header['maxRetention']): fromTime =", "\"\"\" fh = open(path,'rb') header = __readHeader(fh) now = int(", "secondsPerPoint,points in archiveList: archiveInfo = struct.pack(archiveInfoFormat, archiveOffsetPointer, secondsPerPoint, points) fh.write(archiveInfo)", "__init__(self,*args,**kwargs): file.__init__(self,*args,**kwargs) self.writeCount = 0 self.readCount = 0 def write(self,data):", "struct.unpack(archiveInfoFormat,packedArchiveInfo) archiveInfo = { 'offset' : offset, 'secondsPerPoint' : secondsPerPoint,", "% (name,time.time() - __timingBlocks.pop(name))) def __readHeader(fh): info = __headerCache.get(fh.name) if", "if pointTime == currentInterval: neighborValues[i/2] = unpackedSeries[i+1] currentInterval += step", "higher = lower #endBlock('__archive_update_many propagation') #endBlock('__archive_update_many file=%s archive=%s points=%d' %", "is an epoch time untilTime is also an epoch time,", "endBlock class open(file): def __init__(self,*args,**kwargs): file.__init__(self,*args,**kwargs) self.writeCount = 0 self.readCount", "% propagateFurther) if not propagateFurther: break higher = lower #endBlock('__archive_update_many", "of points #startBlock('__archive_update_many string packing') packedStrings = [] previousInterval =", "CF besides average? myPackedPoint = struct.pack(pointFormat,lowerIntervalStart,aggregateValue) fh.seek(lower['offset']) packedPoint = fh.read(pointSize)", "or self.mode == \"rb\": StringIO.__init__(self, MC.get(self.name)) else: StringIO.__init__(self) def close(self):", "[None] * points #pre-allocate entire list for speed currentInterval =", "struct.calcsize(floatFormat) timestampFormat = \"!L\" timestampSize = struct.calcsize(timestampFormat) valueFormat = \"!d\"", "if not __propagate(fh,myInterval,header['xFilesFactor'],higher,lower): break higher = lower #endBlock('update propagation') __changeLastUpdate(fh)", "* pointSize, } archives.append(archiveInfo) fh.seek(originalOffset) info = { 'lastUpdate' :", "= { 'offset' : offset, 'secondsPerPoint' : secondsPerPoint, 'points' :", "string value is a float timestamp is either an int", "contiguous sequence of points #startBlock('__archive_update_many string packing') packedStrings = []", "determined by the baseInterval #startBlock('__archive_update_many write() operations') for (interval,packedString) in", "fh.seek(myOffset) archiveEnd = archive['offset'] + archive['size'] bytesBeyond = (myOffset +", "archive!') assert fh.tell() == archiveEnd, \"archiveEnd=%d fh.tell=%d bytesBeyond=%d len(packedString)=%d\" %", "archiveCount = struct.pack(longFormat, len(archiveList)) packedMetadata = lastUpdate + maxRetention +", "values for a propagation to occur \"\"\" #Validate archive configurations...", "(archive,next) #Looks good, now we create the file and write", "enumerate(archiveList): if i == len(archiveList) - 1: break next =", "archive that covers timestamp if archive['retention'] < diff: continue lowerArchives", "bytes, startInterval=%s' % (len(currentString),startInterval)) packedStrings.append( (startInterval,currentString) ) #endBlock('__archive_update_many string packing')", "= \"!Ld\" pointSize = struct.calcsize(pointFormat) metadataFormat = \"!2LfL\" metadataSize =", "= lower['offset'] + (byteDistance % lower['size']) fh.seek(lowerOffset) fh.write(myPackedPoint) return True", "if v is not None] knownPercent = float(len(knownValues)) / float(len(neighborValues))", "\"archiveEnd=%d fh.tell=%d bytesBeyond=%d len(packedString)=%d\" % (archiveEnd,fh.tell(),bytesBeyond,len(packedString)) fh.seek( archive['offset'] ) fh.write(", "0: #This file's first update #debug('__archive_update_many first update') baseInterval =", "> archive['secondsPerPoint']] #debug('__archive_update_many I have %d lower archives' % len(lowerArchives))", "fromOffset) fh.seek(archive['offset']) seriesString += fh.read(untilOffset - archive['offset']) #Now we unpack", "if info: return info #startBlock('__readHeader') originalOffset = fh.tell() fh.seek(0) packedMetadata", "= Point+ # Point = timestamp,value \"\"\" NOTE: This is", "== currentInterval: pointValue = unpackedSeries[i+1] valueList[i/2] = pointValue #in-place reassignment", "#%d' % (len(data),self.writeCount)) return file.write(self,data) def read(self,bytes): self.readCount += 1", "archiveList is a list of archives, each of which is", "point[0] #debug(' update_many iterating points, point=%s age=%d' % (str(point),age)) while", "pointDistance * pointSize untilOffset = archive['offset'] + (byteDistance % archive['size'])", "than higher precision archives %s,%s\" % (archive,next) #Looks good, now", "\"\"\"fetch(path,fromTime,untilTime=None) path is a string fromTime is an epoch time", "fh.seek(originalOffset) info = { 'lastUpdate' : lastUpdate, 'maxRetention' : maxRetention,", "in this database\" for i,archive in enumerate(header['archives']): #Find the highest-precision", "import fcntl CAN_LOCK = True except ImportError: CAN_LOCK = False", "string points is a list of (timestamp,value) points \"\"\" #startBlock('complete", "% (archiveEnd,fh.tell(),bytesBeyond,len(packedString)) fh.seek( archive['offset'] ) fh.write( packedString[-bytesBeyond:] ) #safe because", "open(path,'wb') if LOCK: fcntl.flock( fh.fileno(), fcntl.LOCK_EX ) lastUpdate = struct.pack(", "checked all the archives currentPoints.reverse() __archive_update_many(fh,header,currentArchive,currentPoints) __changeLastUpdate(fh) fh.close() #endBlock('complete update_many", "Point = timestamp,value \"\"\" NOTE: This is a modified version", "= timestamp,value \"\"\" NOTE: This is a modified version of", "fh.read(archiveInfoSize) (offset,secondsPerPoint,points) = struct.unpack(archiveInfoFormat,packedArchiveInfo) archiveInfo = { 'offset' : offset,", "info = { 'lastUpdate' : lastUpdate, 'maxRetention' : maxRetention, 'xFilesFactor'", "lower['offset'] + (byteDistance % lower['size']) fh.seek(lowerOffset) fh.write(myPackedPoint) return True else:", "i,archive in enumerate(header['archives']): #Find the highest-precision archive that covers timestamp", "fh.seek(archive['offset']) packedBasePoint = fh.read(pointSize) (baseInterval,baseValue) = struct.unpack(pointFormat,packedBasePoint) if baseInterval ==", "have enough known points knownValues = [v for v in", "= struct.pack( longFormat, oldest ) xFilesFactor = struct.pack( floatFormat, float(xFilesFactor)", "fh.tell=%d bytesBeyond=%d len(packedString)=%d\" % (archiveEnd,fh.tell(),bytesBeyond,len(packedString)) fh.seek( archive['offset'] ) fh.write( packedString[-bytesBeyond:]", "string for each contiguous sequence of points #startBlock('__archive_update_many string packing')", "len(archiveList)) packedMetadata = lastUpdate + maxRetention + xFilesFactor + archiveCount", "untilTime = now if fromTime < (now - header['maxRetention']): fromTime", "archive[0] < next[0],\\ \"You cannot configure two archives with the", "None: timestamp = now timestamp = int(timestamp) diff = now", "struct.calcsize(timestampFormat) valueFormat = \"!d\" valueSize = struct.calcsize(valueFormat) pointFormat = \"!Ld\"", "archives must cover larger time intervals than higher precision archives", "myInterval - baseInterval pointDistance = timeDistance / archive['secondsPerPoint'] byteDistance =", "%d bytes #%d' % (bytes,self.readCount)) return file.read(self,bytes) def debug(message): print('DEBUG", "< age: #we can't fit any more points in this", "string \"\"\" fh = open(path,'rb') info = __readHeader(fh) fh.close() return", "archive['secondsPerPoint'] byteDistance = pointDistance * pointSize fromOffset = archive['offset'] +", "archive['secondsPerPoint'] byteDistance = pointDistance * pointSize untilOffset = archive['offset'] +", ") header = __readHeader(fh) now = int( time.time() ) if", "these lower precision archives later break #First we update the", "time try: import fcntl CAN_LOCK = True except ImportError: CAN_LOCK", "- higherBaseInterval pointDistance = timeDistance / higher['secondsPerPoint'] byteDistance = pointDistance", "propagated update to this lower archive timeDistance = lowerIntervalStart -", "0: higherFirstOffset = higher['offset'] else: timeDistance = lowerIntervalStart - higherBaseInterval", "'points' : points, 'retention' : secondsPerPoint * points, 'size' :", "alignedPoint at %s' % interval) if (not previousInterval) or (interval", "struct.unpack(pointFormat,packedPoint) if baseInterval == 0: step = archive['secondsPerPoint'] points =", "two reads archiveEnd = archive['offset'] + archive['size'] seriesString = fh.read(archiveEnd", "values (optimize this!) valueList = [None] * points #pre-allocate entire", "fcntl.flock( fh.fileno(), fcntl.LOCK_EX ) lastUpdate = struct.pack( timestampFormat, int(time.time()) )", "for v in neighborValues if v is not None] knownPercent", "* pointSize untilOffset = archive['offset'] + (byteDistance % archive['size']) #Read", "if currentPoints: #commit all the points we've found that it", "#we can't fit any more points in this archive #debug('", "is faster than append() currentInterval += step fh.close() timeInfo =", "float(len(neighborValues)) if knownPercent >= xff: #we have enough data to", "int( time.time() ) if untilTime is None or untilTime >", "None def exists(path): return os.path.exists(path) def drop(path): os.remove(path) def enableMemcache(servers", "__changeLastUpdate(fh) fh.close() #endBlock('complete update') def update_many(path,points): \"\"\"update_many(path,points) path is a", "write() operations') for (interval,packedString) in packedStrings: timeDistance = interval -", "%.5f seconds\" % (name,time.time() - __timingBlocks.pop(name))) def __readHeader(fh): info =", "archiveInfo = { 'offset' : offset, 'secondsPerPoint' : secondsPerPoint, 'points'", "/ archive['secondsPerPoint'] byteDistance = pointDistance * pointSize myOffset = archive['offset']", "/ step byteDistance = pointDistance * pointSize myOffset = archive['offset']", "order __archive_update_many(fh,header,currentArchive,currentPoints) currentPoints = [] try: currentArchive = next(archives) #debug('", "seriesString = fh.read(higherEnd - higherFirstOffset) fh.seek(higher['offset']) seriesString += fh.read(higherLastOffset -", "Successful propagation!') #debug(' __archive_update_many propagateFurther=%s' % propagateFurther) if not propagateFurther:", "def startBlock(name): __timingBlocks[name] = time.time() def endBlock(name): debug(\"%s took %.5f", "is a string fromTime is an epoch time untilTime is", "seriesString) #And finally we construct a list of values neighborValues", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "= struct.calcsize(pointFormat) metadataFormat = \"!2LfL\" metadataSize = struct.calcsize(metadataFormat) archiveInfoFormat =", "fit in the database #debug(' update_many adding point=%s' % str(point))", "fit any more points in this archive #debug(' update_many this", "assert archiveList, \"You must specify at least one archive configuration!\"", "in archiveList])[-1] maxRetention = struct.pack( longFormat, oldest ) xFilesFactor =", "to lower-precision archives #startBlock('__archive_update_many propagation') higher = archive lowerArchives =", "write() operations') #Now we propagate the updates to lower-precision archives", "if bytesBeyond > 0: fh.write( packedString[:-bytesBeyond] ) #debug('We wrapped an", "lower-precision archives #startBlock('__archive_update_many propagation') higher = archive lowerArchives = [arc", "%d bytes, startInterval=%s' % (len(currentString),startInterval)) packedStrings.append( (startInterval,currentString) ) #endBlock('__archive_update_many string", "\"You must specify at least one archive configuration!\" archiveList.sort(key=lambda a:", "(path,len(points))) if not points: return points = [ (int(t),float(v)) for", "= pointDistance * pointSize higherFirstOffset = higher['offset'] + (byteDistance %", "def fetch(path,fromTime,untilTime=None): \"\"\"fetch(path,fromTime,untilTime=None) path is a string fromTime is an", "lambda i: i - (i % lower['secondsPerPoint']) lowerIntervals = [fit(p[0])", "+ step): #debug('__archive_update_many was expected, packing onto currentString') currentString +=", "str(currentArchive)) except StopIteration: #debug(' update_many no more archives!') currentArchive =", "assert not exists(path), \"File %s already exists!\" % path fh", "if pointTime == currentInterval: pointValue = unpackedSeries[i+1] valueList[i/2] = pointValue", "is an implementation of the Whisper database API # Here", "+ (byteDistance % higher['size']) higherPoints = lower['secondsPerPoint'] / higher['secondsPerPoint'] higherSize", "this database\" for i,archive in enumerate(header['archives']): #Find the highest-precision archive", "\"!d\" valueSize = struct.calcsize(valueFormat) pointFormat = \"!Ld\" pointSize = struct.calcsize(pointFormat)", "+ xFilesFactor + archiveCount fh.write(packedMetadata) headerSize = metadataSize + (archiveInfoSize", "(numberOfPoints-1)) #debug('__archive_update_many done iterating alignedPoints, remainder currentString of %d bytes,", "xff: #we have enough data to propagate a value! aggregateValue", "Archive+ # Archive = Point+ # Point = timestamp,value \"\"\"", "pointSize) zeroes = '\\x00' * (archiveOffsetPointer - headerSize) fh.write(zeroes) fh.close()", "#pre-allocate entire list for speed currentInterval = fromInterval step =", "for i,archive in enumerate(archiveList): if i == len(archiveList) - 1:", "Version 2.0 (the \"License\"); # you may not use this", "archives #startBlock('update propagation') higher = archive for lower in lowerArchives:", "can't exceed the archive (retention checking logic above) else: fh.write(packedString)", "> 0: fh.write( packedString[:-bytesBeyond] ) #debug('We wrapped an archive!') assert", "around the archive seriesString = fh.read(untilOffset - fromOffset) else: #We", "assumption that first field is lastUpdate now = int( time.time()", "#This file's first update fh.seek(archive['offset']) fh.write(myPackedPoint) baseInterval,baseValue = myInterval,value else:", "= 0 def write(self,data): self.writeCount += 1 debug('WRITE %d bytes", "\"!2LfL\" metadataSize = struct.calcsize(metadataFormat) archiveInfoFormat = \"!3L\" archiveInfoSize = struct.calcsize(archiveInfoFormat)", "#safe because it can't exceed the archive (retention checking logic", "by any archives in this database\" for i,archive in enumerate(header['archives']):", "fh.write(packedMetadata) headerSize = metadataSize + (archiveInfoSize * len(archiveList)) archiveOffsetPointer =", "age=%d' % (str(point),age)) while currentArchive['retention'] < age: #we can't fit", "__readHeader(fh) now = int( time.time() ) if timestamp is None:", "info: return info #startBlock('__readHeader') originalOffset = fh.tell() fh.seek(0) packedMetadata =", "(fh.name,step,len(points))) alignedPoints = [ (timestamp - (timestamp % step), value)", "bytesBeyond > 0: fh.write( packedString[:-bytesBeyond] ) #debug('We wrapped an archive!')", "by applicable law or agreed to in writing, software #", "fromOffset timeDistance = fromInterval - baseInterval pointDistance = timeDistance /", "lower #endBlock('__archive_update_many propagation') #endBlock('__archive_update_many file=%s archive=%s points=%d' % (fh.name,step,len(points))) def", "exists(path), \"File %s already exists!\" % path fh = open(path,'wb')", "secondsPerPoint,points in archiveList])[-1] maxRetention = struct.pack( longFormat, oldest ) xFilesFactor", "is too old to fit here, currentPoints=%d' % len(currentPoints)) if", "least one archive configuration!\" archiveList.sort(key=lambda a: a[0]) #sort by precision", "0: #This file's first update fh.seek(archive['offset']) fh.write(myPackedPoint) baseInterval,baseValue = myInterval,value", "myInterval,value else: #Not our first update timeDistance = myInterval -", "read (anything faster than unpack?) byteOrder,pointTypes = pointFormat[0],pointFormat[1:] points =", "__readHeader(fh): info = __headerCache.get(fh.name) if info: return info #startBlock('__readHeader') originalOffset", "except StopIteration: #debug(' update_many no more archives!') currentArchive = None", "header['maxRetention']): fromTime = now - header['maxRetention'] assert fromTime < untilTime,", "%s' % interval) if (not previousInterval) or (interval == previousInterval", "return #XXX Make this a NOP, use os.stat(filename).st_mtime instead startBlock('__changeLastUpdate()')", "propagation interval that must have known values for a propagation", "arc['secondsPerPoint'] > archive['secondsPerPoint']] #debug('__archive_update_many I have %d lower archives' %", "a list of values (optimize this!) valueList = [None] *", "[None] * points currentInterval = lowerIntervalStart step = higher['secondsPerPoint'] for", "unpackedSeries = struct.unpack(seriesFormat, seriesString) #And finally we construct a list", "maxRetention + xFilesFactor + archiveCount fh.write(packedMetadata) headerSize = metadataSize +", "% (fh.name,step,len(points))) def info(path): \"\"\"info(path) path is a string \"\"\"", "- headerSize) fh.write(zeroes) fh.close() def __propagate(fh,timestamp,xff,higher,lower): lowerIntervalStart = timestamp -", "around the archive, so we need two reads archiveEnd =", "fh.read(untilOffset - fromOffset) else: #We do wrap around the archive,", "#debug('We wrapped an archive!') assert fh.tell() == archiveEnd, \"archiveEnd=%d fh.tell=%d", "endBlock = lambda *a,**k: None def exists(path): return os.path.exists(path) def", "archive['retention'] < diff: continue lowerArchives = header['archives'][i+1:] #We'll pass on", "\"\"\"update_many(path,points) path is a string points is a list of", "unpackedSeries[i] if pointTime == currentInterval: neighborValues[i/2] = unpackedSeries[i+1] currentInterval +=", "applicable law or agreed to in writing, software # distributed", "fh.write(myPackedPoint) else: #Not our first propagated update to this lower", "fit currentPoints.reverse() #put points in chronological order __archive_update_many(fh,header,currentArchive,currentPoints) currentPoints =", "+ archive['size'] bytesBeyond = (myOffset + len(packedString)) - archiveEnd #debug('", "len(currentString) / pointSize) + step numberOfPoints = len(currentString) / pointSize", "break #drop remaining points that don't fit in the database", "Metadata = lastUpdate,maxRetention,xFilesFactor,archiveCount # ArchiveInfo = Offset,SecondsPerPoint,Points # Data =", "valueSize = struct.calcsize(valueFormat) pointFormat = \"!Ld\" pointSize = struct.calcsize(pointFormat) metadataFormat", "__timingBlocks.pop(name))) def __readHeader(fh): info = __headerCache.get(fh.name) if info: return info", "for secondsPerPoint,points in archiveList: archiveInfo = struct.pack(archiveInfoFormat, archiveOffsetPointer, secondsPerPoint, points)", "fromInterval step = archive['secondsPerPoint'] for i in xrange(0,len(unpackedSeries),2): pointTime =", "archiveEnd = archive['offset'] + archive['size'] seriesString = fh.read(archiveEnd - fromOffset)", "+ archive['size'] seriesString = fh.read(archiveEnd - fromOffset) fh.seek(archive['offset']) seriesString +=", "File = Header,Data # Header = Metadata,ArchiveInfo+ # Metadata =", "== previousInterval + step): #debug('__archive_update_many was expected, packing onto currentString')", "#debug('__archive_update_many iterating alignedPoint at %s' % interval) if (not previousInterval)", "#order points by timestamp, newest first fh = open(path,'r+b') if", "currentArchive: break #drop remaining points that don't fit in the", "sequence of points #startBlock('__archive_update_many string packing') packedStrings = [] previousInterval", "endBlock('__changeLastUpdate()') def create(path,archiveList,xFilesFactor=0.5): \"\"\"create(path,archiveList,xFilesFactor=0.5) path is a string archiveList is", "= fh.read(pointSize) (lowerBaseInterval,lowerBaseValue) = struct.unpack(pointFormat,packedPoint) if lowerBaseInterval == 0: #First", "currentArchive = next(archives) #debug(' update_many currentArchive=%s' % str(currentArchive)) currentPoints =", "= lower['secondsPerPoint'] / higher['secondsPerPoint'] higherSize = higherPoints * pointSize higherLastOffset", "(startInterval,currentString) ) #endBlock('__archive_update_many string packing') #Read base point and determine", "break fromInterval = int( fromTime - (fromTime % archive['secondsPerPoint']) )", "highest-precision archive myInterval = timestamp - (timestamp % archive['secondsPerPoint']) myPackedPoint", "higherLastOffset = higherFirstOffset + (higherSize % higher['size']) fh.seek(higherFirstOffset) if higherFirstOffset", "def create(path,archiveList,xFilesFactor=0.5): \"\"\"create(path,archiveList,xFilesFactor=0.5) path is a string archiveList is a", "update #debug('__archive_update_many first update') baseInterval = packedStrings[0][0] #use our first", "float(xFilesFactor) ) archiveCount = struct.pack(longFormat, len(archiveList)) packedMetadata = lastUpdate +", "details on the modification, read https://bugs.launchpad.net/graphite/+bug/245835 \"\"\" import os, struct,", "update_many currentArchive=%s' % str(currentArchive)) currentPoints = [] for point in", "# You may obtain a copy of the License at", "start fh.seek(archive['offset']) packedBasePoint = fh.read(pointSize) (baseInterval,baseValue) = struct.unpack(pointFormat,packedBasePoint) if baseInterval", "% archive['secondsPerPoint']) ) fh.seek(archive['offset']) packedPoint = fh.read(pointSize) (baseInterval,baseValue) = struct.unpack(pointFormat,packedPoint)", "we need two reads archiveEnd = archive['offset'] + archive['size'] seriesString", "Metadata,ArchiveInfo+ # Metadata = lastUpdate,maxRetention,xFilesFactor,archiveCount # ArchiveInfo = Offset,SecondsPerPoint,Points #", "a list of (timestamp,value) points \"\"\" #startBlock('complete update_many path=%s points=%d'", "wrap around the archive, so we need two reads archiveEnd", "diff = now - timestamp assert diff < header['maxRetention'] and", "currentArchive=%s' % str(currentArchive)) currentPoints = [] for point in points:", "by the baseInterval #startBlock('__archive_update_many write() operations') for (interval,packedString) in packedStrings:", "which is of the form (secondsPerPoint,numberOfPoints) xFilesFactor specifies the fraction", "struct.calcsize(pointFormat) metadataFormat = \"!2LfL\" metadataSize = struct.calcsize(metadataFormat) archiveInfoFormat = \"!3L\"", "wrap around the archive seriesString = fh.read(untilOffset - fromOffset) else:", "this a NOP, use os.stat(filename).st_mtime instead startBlock('__changeLastUpdate()') originalOffset = fh.tell()", "previousInterval - (step * len(currentString) / pointSize) + step numberOfPoints", "update_many adding point=%s' % str(point)) currentPoints.append(point) #debug(' update_many done iterating", "+= step #Propagate aggregateValue to propagate from neighborValues if we", "bytes' % (startInterval,len(currentString))) packedStrings.append( (startInterval,currentString) ) currentString = struct.pack(pointFormat,interval,value) previousInterval", "a whisper data file # # File = Header,Data #", "header = __readHeader(fh) now = int( time.time() ) archives =", "myOffset=%d packedString=%d archiveEnd=%d bytesBeyond=%d' % (myOffset,len(packedString),archiveEnd,bytesBeyond)) if bytesBeyond > 0:", "points that don't fit in the database #debug(' update_many adding", "#debug(' __archive_update_many propagating from %d to %d, interval=%d' % (higher['secondsPerPoint'],lower['secondsPerPoint'],interval))", "fh.seek(archive['offset']) fh.write(myPackedPoint) baseInterval,baseValue = myInterval,value else: #Not our first update", "higherFirstOffset) else: #We do wrap the archive higherEnd = higher['offset']", "= now - point[0] #debug(' update_many iterating points, point=%s age=%d'", "lowerIntervalStart - higherBaseInterval pointDistance = timeDistance / higher['secondsPerPoint'] byteDistance =", "= previousInterval - (step * (numberOfPoints-1)) #debug('__archive_update_many was NOT expected,", "an archive!') assert fh.tell() == archiveEnd, \"archiveEnd=%d fh.tell=%d bytesBeyond=%d len(packedString)=%d\"", "the points in the interval fh.seek(fromOffset) if fromOffset < untilOffset:", "now \"\"\" fh = open(path,'rb') header = __readHeader(fh) now =", "myPackedPoint = struct.pack(pointFormat,myInterval,value) fh.seek(archive['offset']) packedPoint = fh.read(pointSize) (baseInterval,baseValue) = struct.unpack(pointFormat,packedPoint)", "True else: return False def update(path,value,timestamp=None): \"\"\"update(path,value,timestamp=None) path is a", "alignedPoints] uniqueLowerIntervals = set(lowerIntervals) #debug(' __archive_update_many points=%d unique=%d' % (len(alignedPoints),len(uniqueLowerIntervals)))", "seriesString += fh.read(higherLastOffset - higher['offset']) #Now we unpack the series", "currentString of %d bytes, startInterval=%s' % (len(currentString),startInterval)) packedStrings.append( (startInterval,currentString) )", "now: untilTime = now if fromTime < (now - header['maxRetention']):", "packing') #Read base point and determine where our writes will", "lowerArchives: if not __propagate(fh,myInterval,header['xFilesFactor'],higher,lower): break higher = lower #endBlock('update propagation')", "data file # # File = Header,Data # Header =", "implementation of the Whisper database API # Here is the", "= __readHeader(fh) now = int( time.time() ) if untilTime is", "speed currentInterval = fromInterval step = archive['secondsPerPoint'] for i in", "by precision (secondsPerPoint) for i,archive in enumerate(archiveList): if i ==", "currentInterval = lowerIntervalStart step = higher['secondsPerPoint'] for i in xrange(0,len(unpackedSeries),2):", "timeDistance / lower['secondsPerPoint'] byteDistance = pointDistance * pointSize lowerOffset =", "\"License\"); # you may not use this file except in", ") archives = iter( header['archives'] ) currentArchive = next(archives) #debug('", "__readHeader(fh) fh.close() return info def fetch(path,fromTime,untilTime=None): \"\"\"fetch(path,fromTime,untilTime=None) path is a", ") xFilesFactor = struct.pack( floatFormat, float(xFilesFactor) ) archiveCount = struct.pack(longFormat,", "% higher['size']) fh.seek(higherFirstOffset) if higherFirstOffset < higherLastOffset: #we don't wrap", "fh.read(pointSize) (lowerBaseInterval,lowerBaseValue) = struct.unpack(pointFormat,packedPoint) if lowerBaseInterval == 0: #First propagated", "= set(lowerIntervals) #debug(' __archive_update_many points=%d unique=%d' % (len(alignedPoints),len(uniqueLowerIntervals))) propagateFurther =", "archiveList, \"You must specify at least one archive configuration!\" archiveList.sort(key=lambda", "unique=%d' % (len(alignedPoints),len(uniqueLowerIntervals))) propagateFurther = False for interval in uniqueLowerIntervals:", "higherSize = higherPoints * pointSize higherLastOffset = higherFirstOffset + (higherSize", "need two reads archiveEnd = archive['offset'] + archive['size'] seriesString =", "# # File = Header,Data # Header = Metadata,ArchiveInfo+ #", "struct.unpack(pointFormat,packedPoint) if lowerBaseInterval == 0: #First propagated update to this", "struct.pack( timestampFormat, int(time.time()) ) oldest = sorted([secondsPerPoint * points for", "- fromOffset) else: #We do wrap around the archive, so", "* pointSize higherLastOffset = higherFirstOffset + (higherSize % higher['size']) fh.seek(higherFirstOffset)", "header['archives']: if archive['retention'] >= diff: break fromInterval = int( fromTime", "value is a float timestamp is either an int or", "open(path,'rb') header = __readHeader(fh) now = int( time.time() ) if", "must have known values for a propagation to occur \"\"\"", "#we don't wrap the archive seriesString = fh.read(higherLastOffset - higherFirstOffset)", "in the database #debug(' update_many adding point=%s' % str(point)) currentPoints.append(point)", "interval fh.seek(fromOffset) if fromOffset < untilOffset: #If we don't wrap", ") untilInterval = int( untilTime - (untilTime % archive['secondsPerPoint']) )", "uniqueLowerIntervals: #debug(' __archive_update_many propagating from %d to %d, interval=%d' %", "None def drop(path): MC.delete(path) def enableDebug(): global open, debug, startBlock,", "break higher = lower #endBlock('update propagation') __changeLastUpdate(fh) fh.close() #endBlock('complete update')" ]
[ "(2 + ((255 - red_mean) / 256)) * (blue **", "in range(0, size[0]): pixel = pix[x, y] best_delta = float('Inf')", "c_tuple2[0] green = c_tuple1[1] - c_tuple2[1] blue = c_tuple1[2] -", "# calculate the color distance between two rgb tuples red_mean", "pix = pix_data.load() emoji_grid = [] for y in range(0,", "reader = csv.reader(raw_list) raw_list = list(reader) for entry in raw_list:", "= list(reader) for entry in raw_list: emoji_list.append([entry[0], make_tuple(entry[1])]) image =", "in line: # TODO: ZWJ support if char is None:", "csv from ast import literal_eval as make_tuple from math import", "ZWJ support if char is None: line_out += '\\u2001\\u2006' else:", "return args if __name__ == '__main__': args = handle_arguments() path", "return im def color_distance(c_tuple1, c_tuple2): # calculate the color distance", "entry[0] best_delta = delta emoji_grid[-1].append(best) return emoji_grid def handle_arguments(): parser", "= csv.reader(raw_list) raw_list = list(reader) for entry in raw_list: emoji_list.append([entry[0],", "256)) * (red ** 2) delta += (4 * (green", "from ast import literal_eval as make_tuple from math import sqrt", "- red_mean) / 256)) * (blue ** 2) delta =", "in emoji_list: emoji_color = entry[1] if pixel[3] == 0: best", "using emoji' ) parser.add_argument('image', help='image to be processed') args =", "== 0: best = None else: delta = color_distance(emoji_color, pixel)", "open('proc.csv') as raw_list: emoji_list = [] reader = csv.reader(raw_list) raw_list", "blue = c_tuple1[2] - c_tuple2[2] delta = (2 + (red_mean", "if __name__ == '__main__': args = handle_arguments() path = args.image", "pixel = pix[x, y] best_delta = float('Inf') for entry in", "line: # TODO: ZWJ support if char is None: line_out", "float('Inf') for entry in emoji_list: emoji_color = entry[1] if pixel[3]", "c_tuple2): # calculate the color distance between two rgb tuples", "line_out += '\\u2001\\u2006' else: char_code = '0x' + char char_code", "emoji_list: emoji_color = entry[1] if pixel[3] == 0: best =", "line_out += chr(char_code) out.writelines(line_out + '\\n') def gen_matrix(pix_data): # generate", "import argparse import os.path def load_img(image): # load an image", "def handle_arguments(): parser = argparse.ArgumentParser( description='Represent an image using emoji'", "char_code = '0x' + char char_code = int(char_code, base=16) line_out", "as a PIL object im = Image.open(image).convert('RGBA') return im def", "encoding='utf-8') as out: for line in text_matrix: line_out = ''", "** 2) delta += (4 * (green ** 2)) delta", "return delta def write_out(text_matrix): # write out emoji grid to", "emoji_grid def handle_arguments(): parser = argparse.ArgumentParser( description='Represent an image using", "handle_arguments(): parser = argparse.ArgumentParser( description='Represent an image using emoji' )", "+= (2 + ((255 - red_mean) / 256)) * (blue", "return emoji_grid def handle_arguments(): parser = argparse.ArgumentParser( description='Represent an image", "raw_list = list(reader) for entry in raw_list: emoji_list.append([entry[0], make_tuple(entry[1])]) image", "+= '\\u2001\\u2006' else: char_code = '0x' + char char_code =", "argparse import os.path def load_img(image): # load an image as", "raw_list: emoji_list = [] reader = csv.reader(raw_list) raw_list = list(reader)", "parser.add_argument('image', help='image to be processed') args = parser.parse_args() return args", "import Image import csv from ast import literal_eval as make_tuple", "in range(0, size[1]): emoji_grid.append([]) for x in range(0, size[0]): pixel", "for entry in raw_list: emoji_list.append([entry[0], make_tuple(entry[1])]) image = load_img(path) size", "c_tuple2[2] delta = (2 + (red_mean / 256)) * (red", "'\\n') def gen_matrix(pix_data): # generate unicode data from colors pix", ") parser.add_argument('image', help='image to be processed') args = parser.parse_args() return", "im = Image.open(image).convert('RGBA') return im def color_distance(c_tuple1, c_tuple2): # calculate", "((255 - red_mean) / 256)) * (blue ** 2) delta", "= entry[0] best_delta = delta emoji_grid[-1].append(best) return emoji_grid def handle_arguments():", "green = c_tuple1[1] - c_tuple2[1] blue = c_tuple1[2] - c_tuple2[2]", "rgb tuples red_mean = (c_tuple1[0] + c_tuple2[0]) / 2 red", "import csv from ast import literal_eval as make_tuple from math", "import sqrt import argparse import os.path def load_img(image): # load", "as out: for line in text_matrix: line_out = '' for", "for char in line: # TODO: ZWJ support if char", "open('out.txt', '+w', encoding='utf-8') as out: for line in text_matrix: line_out", "data from colors pix = pix_data.load() emoji_grid = [] for", "entry[1] if pixel[3] == 0: best = None else: delta", "0: best = None else: delta = color_distance(emoji_color, pixel) if", "__name__ == '__main__': args = handle_arguments() path = args.image emoji_list", "red_mean) / 256)) * (blue ** 2) delta = sqrt(delta)", "grid to txt file with open('out.txt', '+w', encoding='utf-8') as out:", "# TODO: ZWJ support if char is None: line_out +=", "emoji_color = entry[1] if pixel[3] == 0: best = None", "= [] with open('proc.csv') as raw_list: emoji_list = [] reader", "in text_matrix: line_out = '' for char in line: #", "# write out emoji grid to txt file with open('out.txt',", "image using emoji' ) parser.add_argument('image', help='image to be processed') args", "'+w', encoding='utf-8') as out: for line in text_matrix: line_out =", "argparse.ArgumentParser( description='Represent an image using emoji' ) parser.add_argument('image', help='image to", "'0x' + char char_code = int(char_code, base=16) line_out += chr(char_code)", "for line in text_matrix: line_out = '' for char in", "delta def write_out(text_matrix): # write out emoji grid to txt", "if char is None: line_out += '\\u2001\\u2006' else: char_code =", "[] for y in range(0, size[1]): emoji_grid.append([]) for x in", "2) delta = sqrt(delta) return delta def write_out(text_matrix): # write", "= sqrt(delta) return delta def write_out(text_matrix): # write out emoji", "tuples red_mean = (c_tuple1[0] + c_tuple2[0]) / 2 red =", "text_matrix: line_out = '' for char in line: # TODO:", "from colors pix = pix_data.load() emoji_grid = [] for y", "= pix[x, y] best_delta = float('Inf') for entry in emoji_list:", "best_delta = delta emoji_grid[-1].append(best) return emoji_grid def handle_arguments(): parser =", "parser = argparse.ArgumentParser( description='Represent an image using emoji' ) parser.add_argument('image',", "out emoji grid to txt file with open('out.txt', '+w', encoding='utf-8')", "unicode data from colors pix = pix_data.load() emoji_grid = []", "out.writelines(line_out + '\\n') def gen_matrix(pix_data): # generate unicode data from", "from math import sqrt import argparse import os.path def load_img(image):", "2)) delta += (2 + ((255 - red_mean) / 256))", "best = None else: delta = color_distance(emoji_color, pixel) if delta", "help='image to be processed') args = parser.parse_args() return args if", "def color_distance(c_tuple1, c_tuple2): # calculate the color distance between two", "handle_arguments() path = args.image emoji_list = [] with open('proc.csv') as", "out: for line in text_matrix: line_out = '' for char", "with open('out.txt', '+w', encoding='utf-8') as out: for line in text_matrix:", "color_distance(c_tuple1, c_tuple2): # calculate the color distance between two rgb", "base=16) line_out += chr(char_code) out.writelines(line_out + '\\n') def gen_matrix(pix_data): #", "red_mean = (c_tuple1[0] + c_tuple2[0]) / 2 red = c_tuple1[0]", "- c_tuple2[2] delta = (2 + (red_mean / 256)) *", "= (2 + (red_mean / 256)) * (red ** 2)", "delta = sqrt(delta) return delta def write_out(text_matrix): # write out", "c_tuple1[2] - c_tuple2[2] delta = (2 + (red_mean / 256))", "write_out(text_matrix): # write out emoji grid to txt file with", "delta < best_delta: best = entry[0] best_delta = delta emoji_grid[-1].append(best)", "+ (red_mean / 256)) * (red ** 2) delta +=", "support if char is None: line_out += '\\u2001\\u2006' else: char_code", "c_tuple1[0] - c_tuple2[0] green = c_tuple1[1] - c_tuple2[1] blue =", "to txt file with open('out.txt', '+w', encoding='utf-8') as out: for", "* (green ** 2)) delta += (2 + ((255 -", "None: line_out += '\\u2001\\u2006' else: char_code = '0x' + char", "emoji_grid = [] for y in range(0, size[1]): emoji_grid.append([]) for", "an image using emoji' ) parser.add_argument('image', help='image to be processed')", "int(char_code, base=16) line_out += chr(char_code) out.writelines(line_out + '\\n') def gen_matrix(pix_data):", "# load an image as a PIL object im =", "txt file with open('out.txt', '+w', encoding='utf-8') as out: for line", "import os.path def load_img(image): # load an image as a", "def load_img(image): # load an image as a PIL object", "/ 256)) * (red ** 2) delta += (4 *", "== '__main__': args = handle_arguments() path = args.image emoji_list =", "range(0, size[1]): emoji_grid.append([]) for x in range(0, size[0]): pixel =", "for entry in emoji_list: emoji_color = entry[1] if pixel[3] ==", "= None else: delta = color_distance(emoji_color, pixel) if delta <", "= int(char_code, base=16) line_out += chr(char_code) out.writelines(line_out + '\\n') def", "= handle_arguments() path = args.image emoji_list = [] with open('proc.csv')", "line in text_matrix: line_out = '' for char in line:", "args if __name__ == '__main__': args = handle_arguments() path =", "if pixel[3] == 0: best = None else: delta =", "if delta < best_delta: best = entry[0] best_delta = delta", "2 red = c_tuple1[0] - c_tuple2[0] green = c_tuple1[1] -", "+= (4 * (green ** 2)) delta += (2 +", "sqrt(delta) return delta def write_out(text_matrix): # write out emoji grid", "[] reader = csv.reader(raw_list) raw_list = list(reader) for entry in", "'\\u2001\\u2006' else: char_code = '0x' + char char_code = int(char_code,", "* (blue ** 2) delta = sqrt(delta) return delta def", "entry in emoji_list: emoji_color = entry[1] if pixel[3] == 0:", "<gh_stars>0 from PIL import Image import csv from ast import", "make_tuple(entry[1])]) image = load_img(path) size = image.size emoji_grid = gen_matrix(image)", "emoji_grid[-1].append(best) return emoji_grid def handle_arguments(): parser = argparse.ArgumentParser( description='Represent an", "line_out = '' for char in line: # TODO: ZWJ", "distance between two rgb tuples red_mean = (c_tuple1[0] + c_tuple2[0])", "PIL import Image import csv from ast import literal_eval as", "entry in raw_list: emoji_list.append([entry[0], make_tuple(entry[1])]) image = load_img(path) size =", "None else: delta = color_distance(emoji_color, pixel) if delta < best_delta:", "(c_tuple1[0] + c_tuple2[0]) / 2 red = c_tuple1[0] - c_tuple2[0]", "range(0, size[0]): pixel = pix[x, y] best_delta = float('Inf') for", "char is None: line_out += '\\u2001\\u2006' else: char_code = '0x'", "pix_data.load() emoji_grid = [] for y in range(0, size[1]): emoji_grid.append([])", "literal_eval as make_tuple from math import sqrt import argparse import", "math import sqrt import argparse import os.path def load_img(image): #", "path = args.image emoji_list = [] with open('proc.csv') as raw_list:", "size[1]): emoji_grid.append([]) for x in range(0, size[0]): pixel = pix[x,", "two rgb tuples red_mean = (c_tuple1[0] + c_tuple2[0]) / 2", "make_tuple from math import sqrt import argparse import os.path def", "= pix_data.load() emoji_grid = [] for y in range(0, size[1]):", "args = handle_arguments() path = args.image emoji_list = [] with", "= argparse.ArgumentParser( description='Represent an image using emoji' ) parser.add_argument('image', help='image", "= entry[1] if pixel[3] == 0: best = None else:", "processed') args = parser.parse_args() return args if __name__ == '__main__':", "pix[x, y] best_delta = float('Inf') for entry in emoji_list: emoji_color", "char in line: # TODO: ZWJ support if char is", "= '0x' + char char_code = int(char_code, base=16) line_out +=", "between two rgb tuples red_mean = (c_tuple1[0] + c_tuple2[0]) /", "ast import literal_eval as make_tuple from math import sqrt import", "= color_distance(emoji_color, pixel) if delta < best_delta: best = entry[0]", "be processed') args = parser.parse_args() return args if __name__ ==", "= parser.parse_args() return args if __name__ == '__main__': args =", "Image import csv from ast import literal_eval as make_tuple from", "= c_tuple1[2] - c_tuple2[2] delta = (2 + (red_mean /", "** 2)) delta += (2 + ((255 - red_mean) /", "** 2) delta = sqrt(delta) return delta def write_out(text_matrix): #", "emoji grid to txt file with open('out.txt', '+w', encoding='utf-8') as", "in raw_list: emoji_list.append([entry[0], make_tuple(entry[1])]) image = load_img(path) size = image.size", "load an image as a PIL object im = Image.open(image).convert('RGBA')", "args.image emoji_list = [] with open('proc.csv') as raw_list: emoji_list =", "red = c_tuple1[0] - c_tuple2[0] green = c_tuple1[1] - c_tuple2[1]", "= Image.open(image).convert('RGBA') return im def color_distance(c_tuple1, c_tuple2): # calculate the", "args = parser.parse_args() return args if __name__ == '__main__': args", "+ ((255 - red_mean) / 256)) * (blue ** 2)", "for y in range(0, size[1]): emoji_grid.append([]) for x in range(0,", "parser.parse_args() return args if __name__ == '__main__': args = handle_arguments()", "= [] for y in range(0, size[1]): emoji_grid.append([]) for x", "delta = color_distance(emoji_color, pixel) if delta < best_delta: best =", "write out emoji grid to txt file with open('out.txt', '+w',", "= c_tuple1[0] - c_tuple2[0] green = c_tuple1[1] - c_tuple2[1] blue", "else: delta = color_distance(emoji_color, pixel) if delta < best_delta: best", "y in range(0, size[1]): emoji_grid.append([]) for x in range(0, size[0]):", "c_tuple2[0]) / 2 red = c_tuple1[0] - c_tuple2[0] green =", "for x in range(0, size[0]): pixel = pix[x, y] best_delta", "os.path def load_img(image): # load an image as a PIL", "= [] reader = csv.reader(raw_list) raw_list = list(reader) for entry", "emoji_list.append([entry[0], make_tuple(entry[1])]) image = load_img(path) size = image.size emoji_grid =", "256)) * (blue ** 2) delta = sqrt(delta) return delta", "+ '\\n') def gen_matrix(pix_data): # generate unicode data from colors", "c_tuple1[1] - c_tuple2[1] blue = c_tuple1[2] - c_tuple2[2] delta =", "PIL object im = Image.open(image).convert('RGBA') return im def color_distance(c_tuple1, c_tuple2):", "as raw_list: emoji_list = [] reader = csv.reader(raw_list) raw_list =", "def write_out(text_matrix): # write out emoji grid to txt file", "pixel) if delta < best_delta: best = entry[0] best_delta =", "load_img(path) size = image.size emoji_grid = gen_matrix(image) write_out(emoji_grid) print('Output in", "delta = (2 + (red_mean / 256)) * (red **", "(2 + (red_mean / 256)) * (red ** 2) delta", "image = load_img(path) size = image.size emoji_grid = gen_matrix(image) write_out(emoji_grid)", "= float('Inf') for entry in emoji_list: emoji_color = entry[1] if", "< best_delta: best = entry[0] best_delta = delta emoji_grid[-1].append(best) return", "+= chr(char_code) out.writelines(line_out + '\\n') def gen_matrix(pix_data): # generate unicode", "im def color_distance(c_tuple1, c_tuple2): # calculate the color distance between", "char char_code = int(char_code, base=16) line_out += chr(char_code) out.writelines(line_out +", "delta += (2 + ((255 - red_mean) / 256)) *", "size = image.size emoji_grid = gen_matrix(image) write_out(emoji_grid) print('Output in out.txt')", "emoji_list = [] reader = csv.reader(raw_list) raw_list = list(reader) for", "as make_tuple from math import sqrt import argparse import os.path", "'__main__': args = handle_arguments() path = args.image emoji_list = []", "+ c_tuple2[0]) / 2 red = c_tuple1[0] - c_tuple2[0] green", "gen_matrix(pix_data): # generate unicode data from colors pix = pix_data.load()", "= load_img(path) size = image.size emoji_grid = gen_matrix(image) write_out(emoji_grid) print('Output", "an image as a PIL object im = Image.open(image).convert('RGBA') return", "colors pix = pix_data.load() emoji_grid = [] for y in", "image as a PIL object im = Image.open(image).convert('RGBA') return im", "description='Represent an image using emoji' ) parser.add_argument('image', help='image to be", "with open('proc.csv') as raw_list: emoji_list = [] reader = csv.reader(raw_list)", "char_code = int(char_code, base=16) line_out += chr(char_code) out.writelines(line_out + '\\n')", "size[0]): pixel = pix[x, y] best_delta = float('Inf') for entry", "'' for char in line: # TODO: ZWJ support if", "emoji_grid.append([]) for x in range(0, size[0]): pixel = pix[x, y]", "csv.reader(raw_list) raw_list = list(reader) for entry in raw_list: emoji_list.append([entry[0], make_tuple(entry[1])])", "list(reader) for entry in raw_list: emoji_list.append([entry[0], make_tuple(entry[1])]) image = load_img(path)", "(blue ** 2) delta = sqrt(delta) return delta def write_out(text_matrix):", "chr(char_code) out.writelines(line_out + '\\n') def gen_matrix(pix_data): # generate unicode data", "- c_tuple2[0] green = c_tuple1[1] - c_tuple2[1] blue = c_tuple1[2]", "emoji_list = [] with open('proc.csv') as raw_list: emoji_list = []", "the color distance between two rgb tuples red_mean = (c_tuple1[0]", "(red_mean / 256)) * (red ** 2) delta += (4", "2) delta += (4 * (green ** 2)) delta +=", "from PIL import Image import csv from ast import literal_eval", "(red ** 2) delta += (4 * (green ** 2))", "file with open('out.txt', '+w', encoding='utf-8') as out: for line in", "= '' for char in line: # TODO: ZWJ support", "= (c_tuple1[0] + c_tuple2[0]) / 2 red = c_tuple1[0] -", "= args.image emoji_list = [] with open('proc.csv') as raw_list: emoji_list", "(green ** 2)) delta += (2 + ((255 - red_mean)", "* (red ** 2) delta += (4 * (green **", "# generate unicode data from colors pix = pix_data.load() emoji_grid", "/ 256)) * (blue ** 2) delta = sqrt(delta) return", "x in range(0, size[0]): pixel = pix[x, y] best_delta =", "= c_tuple1[1] - c_tuple2[1] blue = c_tuple1[2] - c_tuple2[2] delta", "generate unicode data from colors pix = pix_data.load() emoji_grid =", "load_img(image): # load an image as a PIL object im", "(4 * (green ** 2)) delta += (2 + ((255", "[] with open('proc.csv') as raw_list: emoji_list = [] reader =", "best_delta: best = entry[0] best_delta = delta emoji_grid[-1].append(best) return emoji_grid", "best_delta = float('Inf') for entry in emoji_list: emoji_color = entry[1]", "TODO: ZWJ support if char is None: line_out += '\\u2001\\u2006'", "/ 2 red = c_tuple1[0] - c_tuple2[0] green = c_tuple1[1]", "raw_list: emoji_list.append([entry[0], make_tuple(entry[1])]) image = load_img(path) size = image.size emoji_grid", "Image.open(image).convert('RGBA') return im def color_distance(c_tuple1, c_tuple2): # calculate the color", "y] best_delta = float('Inf') for entry in emoji_list: emoji_color =", "+ char char_code = int(char_code, base=16) line_out += chr(char_code) out.writelines(line_out", "calculate the color distance between two rgb tuples red_mean =", "is None: line_out += '\\u2001\\u2006' else: char_code = '0x' +", "else: char_code = '0x' + char char_code = int(char_code, base=16)", "object im = Image.open(image).convert('RGBA') return im def color_distance(c_tuple1, c_tuple2): #", "color_distance(emoji_color, pixel) if delta < best_delta: best = entry[0] best_delta", "pixel[3] == 0: best = None else: delta = color_distance(emoji_color,", "to be processed') args = parser.parse_args() return args if __name__", "import literal_eval as make_tuple from math import sqrt import argparse", "color distance between two rgb tuples red_mean = (c_tuple1[0] +", "= delta emoji_grid[-1].append(best) return emoji_grid def handle_arguments(): parser = argparse.ArgumentParser(", "- c_tuple2[1] blue = c_tuple1[2] - c_tuple2[2] delta = (2", "delta += (4 * (green ** 2)) delta += (2", "best = entry[0] best_delta = delta emoji_grid[-1].append(best) return emoji_grid def", "def gen_matrix(pix_data): # generate unicode data from colors pix =", "delta emoji_grid[-1].append(best) return emoji_grid def handle_arguments(): parser = argparse.ArgumentParser( description='Represent", "emoji' ) parser.add_argument('image', help='image to be processed') args = parser.parse_args()", "sqrt import argparse import os.path def load_img(image): # load an", "a PIL object im = Image.open(image).convert('RGBA') return im def color_distance(c_tuple1,", "c_tuple2[1] blue = c_tuple1[2] - c_tuple2[2] delta = (2 +" ]
[ "RawButtonPressMask = (1 << RawButtonPress) RawButtonReleaseMask = (1 << RawButtonRelease)", "import integer_types from Xlib.protocol import rq from Xlib import X", "rq.Card32), ) KeyInfo = rq.Struct( rq.Card16('type'), rq.Card16('length'), rq.Card16('sourceid'), rq.LengthOf('keycodes', 2),", "rq.Struct( rq.Card16('type'), rq.Card16('length'), rq.Card16('sourceid'), rq.Card16('number'), rq.Card16('scroll_type'), rq.Pad(2), rq.Card32('flags'), FP3232('increment'), )", "rq.LengthOf('modifiers', 2), rq.Pad(22), rq.List('modifiers', rq.Card32), ) def passive_grab_device(self, deviceid, time,", "length def __len__(self): return self._length def __getitem__(self, key): return self._value", "= (1 << RawButtonRelease) RawMotionMask = (1 << RawMotion) GrabModeSync", "else: raise AssertionError(sys.byteorder) while val: fun(val & 0xFFFFFFFF) val =", "encoded in native byte order from end to end. The", "= 9 FocusOut = 10 HierarchyChanged = 11 PropertyEvent =", "= (1 << ButtonRelease) MotionMask = (1 << Motion) EnterMask", "def __repr__(self): return '0b{value:0{width}b}'.format(value=self._value, width=self._length) class ButtonState(rq.ValueField): structcode = None", "= 0 PropertyCreated = 1 PropertyModified = 2 NotifyNormal =", "rq.Card16('length'), rq.Card16('sourceid'), rq.LengthOf(('state', 'labels'), 2), ButtonState('state'), rq.List('labels', rq.Card32), ) KeyInfo", "window=self, masks=event_masks, ) AnyInfo = rq.Struct( rq.Card16('type'), rq.Card16('length'), rq.Card16('sourceid'), rq.Pad(2),", "1, (GrabtypeButton, GrabtypeKeycode, GrabtypeEnter, GrabtypeFocusIn, GrabtypeTouchBegin)), rq.Pad(3), rq.List('modifiers', rq.Card32), )", "FP1616('event_x'), FP1616('event_y'), rq.LengthOf('buttons', 2), rq.Card16('valulators_len'), DEVICEID('sourceid'), rq.Pad(2), rq.Card32('flags'), rq.Object('mods', ModifierInfo),", "rq.Struct( rq.Card8('opcode'), rq.Opcode(46), rq.RequestLength(), rq.Window('window'), rq.LengthOf('masks', 2), rq.Pad(2), rq.List('masks', EventMask),", "= 0 for byte in reversed(struct.unpack('={0:d}B'.format(mask_len), mask_data)): mask_value <<= 8", "a copy of the GNU Lesser General Public # License", "5 Motion = 6 Enter = 7 Leave = 8", "# of the License, or (at your option) any later", "mask_seq = array.array(rq.struct_to_array_codes['L']) if isinstance(val, integer_types): # We need to", "rq.ReplyLength(), rq.LengthOf('modifiers', 2), rq.Pad(22), rq.List('modifiers', rq.Card32), ) def passive_grab_device(self, deviceid,", "rq.Card8('opcode'), rq.Opcode(47), rq.RequestLength(), rq.Card16('major_version'), rq.Card16('minor_version'), ) _reply = rq.Struct( rq.ReplyCode(),", "struct.unpack('=HH', data[:4]) class_struct = INFO_CLASSES.get(class_type, AnyInfo) class_data, _ = class_struct.parse_binary(data,", "rq.Card32), ) def passive_ungrab_device(self, deviceid, detail, grab_type, modifiers): return XIPassiveUngrabDevice(", "<< Leave) FocusInMask = (1 << FocusIn) FocusOutMask = (1", "time=time, deviceid=deviceid, ) class XIPassiveGrabDevice(rq.ReplyRequest): _request = rq.Struct( rq.Card8('opcode'), rq.Opcode(54),", "modifiers) HierarchyInfo = rq.Struct( DEVICEID('deviceid'), DEVICEID('attachment'), DEVICEUSE('type'), rq.Bool('enabled'), rq.Pad(2), rq.Card32('flags'),", "XIPassiveUngrabDevice( display=self.display, opcode=self.display.get_extension_major(extname), deviceid=deviceid, grab_window=self, detail=detail, grab_type=grab_type, modifiers=modifiers, ) def", "2 SlavePointer = 3 SlaveKeyboard = 4 FloatingSlave = 5", "= 3 DetachSlave = 4 AttachToMaster = 1 Floating =", "4:] return class_data, data ClassInfo = ClassInfoClass() DeviceInfo = rq.Struct(", "(1 << 2) SlaveRemoved = (1 << 3) SlaveAttached =", "2 GrabtypeFocusIn = 3 GrabtypeTouchBegin = 4 AnyModifier = (1", "= rq.Struct( rq.Card8('opcode'), rq.Opcode(51), rq.RequestLength(), rq.Window('grab_window'), rq.Card32('time'), rq.Cursor('cursor', (X.NONE, )),", "= data[length * 4:] return class_data, data ClassInfo = ClassInfoClass()", "rq.Card32('label'), FP3232('min'), FP3232('max'), FP3232('value'), rq.Card32('resolution'), rq.Card8('mode'), rq.Pad(3), ) ScrollInfo =", "= data[:mask_len] mask_value = 0 for byte in reversed(struct.unpack('={0:d}B'.format(mask_len), mask_data)):", "return passive_grab_device(self, deviceid, time, keycode, GrabtypeKeycode, grab_mode, paired_device_mode, owner_events, event_mask,", "= rq.Card16 DEVICEUSE = rq.Card8 class FP1616(rq.Int32): def check_value(self, value):", "(1 << ButtonPress) ButtonReleaseMask = (1 << ButtonRelease) MotionMask =", "simple case is # with a single unsigned 32-bit value,", ") class XIGrabDevice(rq.ReplyRequest): _request = rq.Struct( rq.Card8('opcode'), rq.Opcode(51), rq.RequestLength(), rq.Window('grab_window'),", "rq.LengthOf('name', 2), rq.Bool('enabled'), rq.Pad(1), rq.String8('name', 4), rq.List('classes', ClassInfo), ) class", "self._value = value self._length = length def __len__(self): return self._length", "rq.Card16('length'), rq.Card16('sourceid'), rq.Card16('number'), rq.Card32('label'), FP3232('min'), FP3232('max'), FP3232('value'), rq.Card32('resolution'), rq.Card8('mode'), rq.Pad(3),", "= struct.unpack('=HH', data[:4]) class_struct = INFO_CLASSES.get(class_type, AnyInfo) class_data, _ =", ">> 3) + 3) >> 2) mask_data = data[:mask_len] mask_value", "Enter) LeaveMask = (1 << Leave) FocusInMask = (1 <<", "= rq.Struct( rq.ReplyCode(), rq.Pad(1), rq.Card16('sequence_number'), rq.ReplyLength(), rq.LengthOf('modifiers', 2), rq.Pad(22), rq.List('modifiers',", "rq.Card32('flags'), rq.LengthOf('info', 2), rq.Pad(10), rq.List('info', HierarchyInfo), ) ModifierInfo = rq.Struct(", "(1 << HierarchyChanged) PropertyEventMask = (1 << PropertyEvent) RawKeyPressMask =", "parse_binary(self, data, display): class_type, length = struct.unpack('=HH', data[:4]) class_struct =", "# encoded in native byte order from end to end.", "info): disp.extension_add_method('display', 'xinput_query_version', query_version) disp.extension_add_method('window', 'xinput_select_events', select_events) disp.extension_add_method('display', 'xinput_query_device', query_device)", "XInput extension. ''' import sys import array import struct #", "32 else: mask_seq.extend(val) return mask_seq.tostring(), len(mask_seq), None EventMask = rq.Struct(", "data[:mask_len] mask_value = 0 for byte in reversed(struct.unpack('={0:d}B'.format(mask_len), mask_data)): mask_value", "= INFO_CLASSES.get(class_type, AnyInfo) class_data, _ = class_struct.parse_binary(data, display) data =", "across the entire set of values. if sys.byteorder == 'little':", "DEVICEID('sourceid'), rq.Card8('reason'), rq.Pad(11), rq.List('classes', ClassInfo), ) def init(disp, info): disp.extension_add_method('display',", "(1 << RawButtonRelease) RawMotionMask = (1 << RawMotion) GrabModeSync =", "4 ButtonRelease = 5 Motion = 6 Enter = 7", "grab_window=self, time=time, cursor=X.NONE, grab_mode=grab_mode, paired_device_mode=paired_device_mode, owner_events=owner_events, mask=event_mask, ) class XIUngrabDevice(rq.Request):", "= (1 << Enter) LeaveMask = (1 << Leave) FocusInMask", "2 AsyncPairedDevice = 3 AsyncPair = 4 SyncPair = 5", "= class_struct.parse_binary(data, display) data = data[length * 4:] return class_data,", "= 3 GrabtypeTouchBegin = 4 AnyModifier = (1 << 31)", "ButtonMask(mask_value >> 1, length), data ButtonInfo = rq.Struct( rq.Card16('type'), rq.Card16('length'),", "# with a single unsigned 32-bit value, for which we", "from end to end. The simple case is # with", "* 65536.0) def parse_value(self, value, display): return float(value) / float(1", "65536.0) def parse_value(self, value, display): return float(value) / float(1 <<", "_reply = rq.Struct( rq.ReplyCode(), rq.Pad(1), rq.Card16('sequence_number'), rq.ReplyLength(), rq.LengthOf('modifiers', 2), rq.Pad(22),", "modifiers=modifiers, ) def ungrab_keycode(self, deviceid, keycode, modifiers): return passive_ungrab_device(self, deviceid,", "mask_data)): mask_value <<= 8 mask_value |= byte data = data[mask_len:]", "= ClassInfoClass() DeviceInfo = rq.Struct( DEVICEID('deviceid'), rq.Card16('use'), rq.Card16('attachment'), rq.LengthOf('classes', 2),", "is # with a single unsigned 32-bit value, for which", "rq.Card16('use'), rq.Card16('attachment'), rq.LengthOf('classes', 2), rq.LengthOf('name', 2), rq.Bool('enabled'), rq.Pad(1), rq.String8('name', 4),", "rq.Struct( rq.Card8('opcode'), rq.Opcode(47), rq.RequestLength(), rq.Card16('major_version'), rq.Card16('minor_version'), ) _reply = rq.Struct(", "AnyModifier = (1 << 31) AnyButton = 0 AnyKeycode =", "rq.LengthOf('keycodes', 2), rq.List('keycodes', rq.Card32), ) ValuatorInfo = rq.Struct( rq.Card16('type'), rq.Card16('length'),", "rq.Opcode(51), rq.RequestLength(), rq.Window('grab_window'), rq.Card32('time'), rq.Cursor('cursor', (X.NONE, )), DEVICEID('deviceid'), rq.Set('grab_mode', 1,", "HierarchyInfo = rq.Struct( DEVICEID('deviceid'), DEVICEID('attachment'), DEVICEUSE('type'), rq.Bool('enabled'), rq.Pad(2), rq.Card32('flags'), )", "# 59 Temple Place, # Suite 330, # Boston, MA", "0 GrabModeAsync = 1 GrabModeTouch = 2 DEVICEID = rq.Card16", "pairs, where deviceid is a numerical device ID, or AllDevices", ") _reply = rq.Struct( rq.ReplyCode(), rq.Pad(1), rq.Card16('sequence_number'), rq.ReplyLength(), rq.Card16('major_version'), rq.Card16('minor_version'),", "PARTICULAR PURPOSE. # See the GNU Lesser General Public License", "Floating = 2 ModeRelative = 0 ModeAbsolute = 1 MasterPointer", "= 1 DeviceChange = 2 MasterAdded = (1 << 0)", "= 5 KeyClass = 0 ButtonClass = 1 ValuatorClass =", "<< RawButtonPress) RawButtonReleaseMask = (1 << RawButtonRelease) RawMotionMask = (1", "name) def parse_binary_value(self, data, display, length, fmt): # Mask: bitfield", "rq.Pad(2), ) _reply = rq.Struct( rq.ReplyCode(), rq.Pad(1), rq.Card16('sequence_number'), rq.ReplyLength(), rq.LengthOf('devices',", "cursor=X.NONE, detail=detail, grab_type=grab_type, grab_mode=grab_mode, paired_device_mode=paired_device_mode, owner_events=owner_events, mask=event_mask, modifiers=modifiers, ) def", "'xinput_select_events', select_events) disp.extension_add_method('display', 'xinput_query_device', query_device) disp.extension_add_method('window', 'xinput_grab_device', grab_device) disp.extension_add_method('display', 'xinput_ungrab_device',", "display=self.display, opcode=self.display.get_extension_major(extname), window=self, masks=event_masks, ) AnyInfo = rq.Struct( rq.Card16('type'), rq.Card16('length'),", "value ret = float(integral) # optimised math.ldexp(float(frac), -32) ret +=", ") ScrollInfo = rq.Struct( rq.Card16('type'), rq.Card16('length'), rq.Card16('sourceid'), rq.Card16('number'), rq.Card16('scroll_type'), rq.Pad(2),", "rq.Card16('number'), rq.Card16('scroll_type'), rq.Pad(2), rq.Card32('flags'), FP3232('increment'), ) TouchInfo = rq.Struct( rq.Card16('type'),", "GrabModeSync = 0 GrabModeAsync = 1 GrabModeTouch = 2 DEVICEID", "sequence of 32 bits unsigned values ''' return XISelectEvents( display=self.display,", "TouchInfo, } class ClassInfoClass(object): structcode = None def parse_binary(self, data,", "PropertyEvent) RawKeyPressMask = (1 << RawKeyPress) RawKeyReleaseMask = (1 <<", "ret = float(integral) # optimised math.ldexp(float(frac), -32) ret += float(frac)", "Boston, MA 02111-1307 USA ''' A very incomplete implementation of", "This library is distributed in the hope that it will", "= 8 KeyRepeat = (1 << 16) AllDevices = 0", "integer_types): # We need to build a \"binary mask\" that", "case is # with a single unsigned 32-bit value, for", "rq.LengthOf(('state', 'labels'), 2), ButtonState('state'), rq.List('labels', rq.Card32), ) KeyInfo = rq.Struct(", "rq.Card8('locked_group'), rq.Card8('effective_group'), ) DeviceEventData = rq.Struct( DEVICEID('deviceid'), rq.Card32('time'), rq.Card32('detail'), rq.Window('root'),", "rq.RequestLength(), rq.Card32('time'), DEVICEID('deviceid'), rq.Pad(2), ) def ungrab_device(self, deviceid, time): return", "# optimised math.ldexp(float(frac), -32) ret += float(frac) * (1.0 /", "<< DeviceChanged) KeyPressMask = (1 << KeyPress) KeyReleaseMask = (1", "'xinput_ungrab_keycode', ungrab_keycode) if hasattr(disp,\"ge_add_event_data\"): for device_event in (ButtonPress, ButtonRelease, KeyPress,", "__repr__(self): return '0b{value:0{width}b}'.format(value=self._value, width=self._length) class ButtonState(rq.ValueField): structcode = None def", "= rq.Struct( DEVICEID('deviceid'), rq.Card32('time'), rq.LengthOf('classes', 2), DEVICEID('sourceid'), rq.Card8('reason'), rq.Pad(11), rq.List('classes',", "either version 2.1 # of the License, or (at your", "# Suite 330, # Boston, MA 02111-1307 USA ''' A", "can tell) is # encoded in native byte order from", "0 AsyncDevice = 0 SyncDevice = 1 ReplayDevice = 2", "sys.byteorder == 'big': fun = mask_seq.append else: raise AssertionError(sys.byteorder) while", "name, rq.Card32, pad=0) def pack_value(self, val): mask_seq = array.array(rq.struct_to_array_codes['L']) if", "(1 << RawKeyPress) RawKeyReleaseMask = (1 << RawKeyRelease) RawButtonPressMask =", "= 2 DEVICEID = rq.Card16 DEVICE = rq.Card16 DEVICEUSE =", "def ungrab_device(self, deviceid, time): return XIUngrabDevice( display=self.display, opcode=self.display.get_extension_major(extname), time=time, deviceid=deviceid,", "val) elif sys.byteorder == 'big': fun = mask_seq.append else: raise", "should have received a copy of the GNU Lesser General", "= 4 NotifyPointer = 5 NotifyPointerRoot = 6 NotifyDetailNone =", "assert (mask_value & 1) == 0 return ButtonMask(mask_value >> 1,", "ButtonRelease = 5 Motion = 6 Enter = 7 Leave", "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # See the", "= 1 KeyPress = 2 KeyRelease = 3 ButtonPress =", "Foundation; either version 2.1 # of the License, or (at", "Motion) EnterMask = (1 << Enter) LeaveMask = (1 <<", "0xFFFFFFFF) val = val >> 32 else: mask_seq.extend(val) return mask_seq.tostring(),", "end. The simple case is # with a single unsigned", "RawKeyPress) RawKeyReleaseMask = (1 << RawKeyRelease) RawButtonPressMask = (1 <<", "deviceid, time, keycode, GrabtypeKeycode, grab_mode, paired_device_mode, owner_events, event_mask, modifiers) class", ") def ungrab_device(self, deviceid, time): return XIUngrabDevice( display=self.display, opcode=self.display.get_extension_major(extname), time=time,", "or (at your option) any later version. # # This", "5) DeviceEnabled = (1 << 6) DeviceDisabled = (1 <<", "# but WITHOUT ANY WARRANTY; without even the implied warranty", "4 # bytes we build a longer array, being careful", "class_type, length = struct.unpack('=HH', data[:4]) class_struct = INFO_CLASSES.get(class_type, AnyInfo) class_data,", "rq.RequestLength(), rq.Card32('time'), rq.Window('grab_window'), rq.Cursor('cursor', (X.NONE, )), rq.Card32('detail'), DEVICEID('deviceid'), rq.LengthOf('modifiers', 2),", "XIQueryVersion( display=self.display, opcode=self.display.get_extension_major(extname), major_version=2, minor_version=0, ) class Mask(rq.List): def __init__(self,", "rq.Bool('enabled'), rq.Pad(1), rq.String8('name', 4), rq.List('classes', ClassInfo), ) class XIQueryDevice(rq.ReplyRequest): _request", "elif sys.byteorder == 'big': fun = mask_seq.append else: raise AssertionError(sys.byteorder)", "2), rq.Pad(22), rq.List('modifiers', rq.Card32), ) def passive_grab_device(self, deviceid, time, detail,", "keycode, GrabtypeKeycode, grab_mode, paired_device_mode, owner_events, event_mask, modifiers) class XIPassiveUngrabDevice(rq.Request): _request", ") def ungrab_keycode(self, deviceid, keycode, modifiers): return passive_ungrab_device(self, deviceid, keycode,", "under the terms of the GNU Lesser General Public License", "# array with just one item. For values too big", "'labels'), 2), ButtonState('state'), rq.List('labels', rq.Card32), ) KeyInfo = rq.Struct( rq.Card16('type'),", "key) def __str__(self): return repr(self) def __repr__(self): return '0b{value:0{width}b}'.format(value=self._value, width=self._length)", "return repr(self) def __repr__(self): return '0b{value:0{width}b}'.format(value=self._value, width=self._length) class ButtonState(rq.ValueField): structcode", "rq.Card32('flags'), rq.Object('mods', ModifierInfo), rq.Object('groups', GroupInfo), ButtonState('buttons'), ) DeviceChangedEventData = rq.Struct(", "rq.Card16('major_version'), rq.Card16('minor_version'), rq.Pad(20), ) def query_version(self): return XIQueryVersion( display=self.display, opcode=self.display.get_extension_major(extname),", "ClassInfo = ClassInfoClass() DeviceInfo = rq.Struct( DEVICEID('deviceid'), rq.Card16('use'), rq.Card16('attachment'), rq.LengthOf('classes',", "ScrollClass: ScrollInfo, TouchClass: TouchInfo, } class ClassInfoClass(object): structcode = None", "rq.RequestLength(), rq.Window('grab_window'), rq.Card32('time'), rq.Cursor('cursor', (X.NONE, )), DEVICEID('deviceid'), rq.Set('grab_mode', 1, (GrabModeSync,", ") def query_device(self, deviceid): return XIQueryDevice( display=self.display, opcode=self.display.get_extension_major(extname), deviceid=deviceid, )", "1 RemoveMaster = 2 AttachSlave = 3 DetachSlave = 4", "array import struct # Python 2/3 compatibility. from six import", "opcode=self.display.get_extension_major(extname), deviceid=deviceid, grab_window=self, time=time, cursor=X.NONE, detail=detail, grab_type=grab_type, grab_mode=grab_mode, paired_device_mode=paired_device_mode, owner_events=owner_events,", "modifiers) class XIPassiveUngrabDevice(rq.Request): _request = rq.Struct( rq.Card8('opcode'), rq.Opcode(55), rq.RequestLength(), rq.Window('grab_window'),", "rq.Set('grab_mode', 1, (GrabModeSync, GrabModeAsync)), rq.Set('paired_device_mode', 1, (GrabModeSync, GrabModeAsync)), rq.Bool('owner_events'), rq.Pad(1),", "rq.RequestLength(), DEVICEID('deviceid'), rq.Pad(2), ) _reply = rq.Struct( rq.ReplyCode(), rq.Pad(1), rq.Card16('sequence_number'),", "4 * ((((length + 7) >> 3) + 3) >>", ") ValuatorInfo = rq.Struct( rq.Card16('type'), rq.Card16('length'), rq.Card16('sourceid'), rq.Card16('number'), rq.Card32('label'), FP3232('min'),", "Mask('mask'), ) _reply = rq.Struct( rq.ReplyCode(), rq.Pad(1), rq.Card16('sequence_number'), rq.ReplyLength(), rq.Card8('status'),", "deviceid=deviceid, grab_window=self, detail=detail, grab_type=grab_type, modifiers=modifiers, ) def ungrab_keycode(self, deviceid, keycode,", "NotifyNonlinear = 3 NotifyNonlinearVirtual = 4 NotifyPointer = 5 NotifyPointerRoot", "math.ldexp(float(frac), -32) ret += float(frac) * (1.0 / (1 <<", "= 0 ModeAbsolute = 1 MasterPointer = 1 MasterKeyboard =", "ClassInfoClass() DeviceInfo = rq.Struct( DEVICEID('deviceid'), rq.Card16('use'), rq.Card16('attachment'), rq.LengthOf('classes', 2), rq.LengthOf('name',", "return class_data, data ClassInfo = ClassInfoClass() DeviceInfo = rq.Struct( DEVICEID('deviceid'),", "2 KeyRelease = 3 ButtonPress = 4 ButtonRelease = 5", "= rq.Struct( rq.Card8('opcode'), rq.Opcode(46), rq.RequestLength(), rq.Window('window'), rq.LengthOf('masks', 2), rq.Pad(2), rq.List('masks',", "0 SyncDevice = 1 ReplayDevice = 2 AsyncPairedDevice = 3", "will be useful, # but WITHOUT ANY WARRANTY; without even", "KeyPress = 2 KeyRelease = 3 ButtonPress = 4 ButtonRelease", "mask_seq.append else: raise AssertionError(sys.byteorder) while val: fun(val & 0xFFFFFFFF) val", "|= byte data = data[mask_len:] assert (mask_value & 1) ==", "modifiers): return XIPassiveGrabDevice( display=self.display, opcode=self.display.get_extension_major(extname), deviceid=deviceid, grab_window=self, time=time, cursor=X.NONE, detail=detail,", "GrabModeAsync)), rq.Set('paired_device_mode', 1, (GrabModeSync, GrabModeAsync)), rq.Bool('owner_events'), rq.Pad(1), rq.LengthOf('mask', 2), Mask('mask'),", "<< HierarchyChanged) PropertyEventMask = (1 << PropertyEvent) RawKeyPressMask = (1", "rq.LengthOf('modifiers', 2), rq.Set('grab_type', 1, (GrabtypeButton, GrabtypeKeycode, GrabtypeEnter, GrabtypeFocusIn, GrabtypeTouchBegin)), rq.Pad(3),", "= (1 << 4) SlaveDetached = (1 << 5) DeviceEnabled", "ClassInfo), ) def init(disp, info): disp.extension_add_method('display', 'xinput_query_version', query_version) disp.extension_add_method('window', 'xinput_select_events',", "0 NotifyGrab = 1 NotifyUngrab = 2 NotifyWhileGrabbed = 3", "disp.extension_add_method('window', 'xinput_ungrab_keycode', ungrab_keycode) if hasattr(disp,\"ge_add_event_data\"): for device_event in (ButtonPress, ButtonRelease,", "<< 4) SlaveDetached = (1 << 5) DeviceEnabled = (1", "This library is free software; you can redistribute it and/or", "ValuatorInfo = rq.Struct( rq.Card16('type'), rq.Card16('length'), rq.Card16('sourceid'), rq.Card16('number'), rq.Card32('label'), FP3232('min'), FP3232('max'),", "byte in reversed(struct.unpack('={0:d}B'.format(mask_len), mask_data)): mask_value <<= 8 mask_value |= byte", "16) AllDevices = 0 AllMasterDevices = 1 DeviceChanged = 1", "just one item. For values too big to fit inside", "Leave) FocusInMask = (1 << FocusIn) FocusOutMask = (1 <<", "4 SyncPair = 5 SlaveSwitch = 1 DeviceChange = 2", "SlaveAdded = (1 << 2) SlaveRemoved = (1 << 3)", "1 KeyPress = 2 KeyRelease = 3 ButtonPress = 4", "NotifyPassiveGrab = 4 NotifyPassiveUngrab = 5 NotifyAncestor = 0 NotifyVirtual", "== 'big': fun = mask_seq.append else: raise AssertionError(sys.byteorder) while val:", "RawKeyPressMask = (1 << RawKeyPress) RawKeyReleaseMask = (1 << RawKeyRelease)", "free software; you can redistribute it and/or # modify it", "rq.Object('mods', ModifierInfo), rq.Object('groups', GroupInfo), ButtonState('buttons'), ) DeviceChangedEventData = rq.Struct( DEVICEID('deviceid'),", "XISelectEvents( display=self.display, opcode=self.display.get_extension_major(extname), window=self, masks=event_masks, ) AnyInfo = rq.Struct( rq.Card16('type'),", "= None def parse_binary(self, data, display): class_type, length = struct.unpack('=HH',", "RawKeyRelease = 14 RawButtonPress = 15 RawButtonRelease = 16 RawMotion", "return XIQueryDevice( display=self.display, opcode=self.display.get_extension_major(extname), deviceid=deviceid, ) class XIGrabDevice(rq.ReplyRequest): _request =", "<< KeyPress) KeyReleaseMask = (1 << KeyRelease) ButtonPressMask = (1", "array with just one item. For values too big to", "See the GNU Lesser General Public License for more details.", "0 for byte in reversed(struct.unpack('={0:d}B'.format(mask_len), mask_data)): mask_value <<= 8 mask_value", "= value ret = float(integral) # optimised math.ldexp(float(frac), -32) ret", "opcode=self.display.get_extension_major(extname), deviceid=deviceid, grab_window=self, detail=detail, grab_type=grab_type, modifiers=modifiers, ) def ungrab_keycode(self, deviceid,", "XIPassiveUngrabDevice(rq.Request): _request = rq.Struct( rq.Card8('opcode'), rq.Opcode(55), rq.RequestLength(), rq.Window('grab_window'), rq.Card32('detail'), DEVICEID('deviceid'),", "Leave = 8 FocusIn = 9 FocusOut = 10 HierarchyChanged", "that (as far as I can tell) is # encoded", "Free Software Foundation, Inc., # 59 Temple Place, # Suite", "0 PropertyCreated = 1 PropertyModified = 2 NotifyNormal = 0", "((((length + 7) >> 3) + 3) >> 2) mask_data", "major_version=2, minor_version=0, ) class Mask(rq.List): def __init__(self, name): rq.List.__init__(self, name,", "_request = rq.Struct( rq.Card8('opcode'), rq.Opcode(55), rq.RequestLength(), rq.Window('grab_window'), rq.Card32('detail'), DEVICEID('deviceid'), rq.LengthOf('modifiers',", "__str__(self): return repr(self) def __repr__(self): return '0b{value:0{width}b}'.format(value=self._value, width=self._length) class ButtonState(rq.ValueField):", "rq.Card8('status'), rq.Pad(23), ) def grab_device(self, deviceid, time, grab_mode, paired_device_mode, owner_events,", "GrabtypeKeycode, grab_mode, paired_device_mode, owner_events, event_mask, modifiers) class XIPassiveUngrabDevice(rq.Request): _request =", "RemoveMaster = 2 AttachSlave = 3 DetachSlave = 4 AttachToMaster", "12 RawKeyPress = 13 RawKeyRelease = 14 RawButtonPress = 15", "big to fit inside 4 # bytes we build a", "rq.Pad(10), rq.List('info', HierarchyInfo), ) ModifierInfo = rq.Struct( rq.Card32('base_mods'), rq.Card32('latched_mods'), rq.Card32('locked_mods'),", "_reply = rq.Struct( rq.ReplyCode(), rq.Pad(1), rq.Card16('sequence_number'), rq.ReplyLength(), rq.Card16('major_version'), rq.Card16('minor_version'), rq.Pad(20),", "You should have received a copy of the GNU Lesser", "class XIPassiveUngrabDevice(rq.Request): _request = rq.Struct( rq.Card8('opcode'), rq.Opcode(55), rq.RequestLength(), rq.Window('grab_window'), rq.Card32('detail'),", "AllMasterDevices = 1 DeviceChanged = 1 KeyPress = 2 KeyRelease", ") _reply = rq.Struct( rq.ReplyCode(), rq.Pad(1), rq.Card16('sequence_number'), rq.ReplyLength(), rq.Card8('status'), rq.Pad(23),", "= 0 NotifyVirtual = 1 NotifyInferior = 2 NotifyNonlinear =", "8 KeyRepeat = (1 << 16) AllDevices = 0 AllMasterDevices", "= rq.Struct( rq.ReplyCode(), rq.Pad(1), rq.Card16('sequence_number'), rq.ReplyLength(), rq.Card16('major_version'), rq.Card16('minor_version'), rq.Pad(20), )", "rq.Card8('opcode'), rq.Opcode(55), rq.RequestLength(), rq.Window('grab_window'), rq.Card32('detail'), DEVICEID('deviceid'), rq.LengthOf('modifiers', 2), rq.Set('grab_type', 1,", "for which we construct an # array with just one", "return float(value) / float(1 << 16) class FP3232(rq.ValueField): structcode =", "rq.List('classes', ClassInfo), ) def init(disp, info): disp.extension_add_method('display', 'xinput_query_version', query_version) disp.extension_add_method('window',", "paired_device_mode=paired_device_mode, owner_events=owner_events, mask=event_mask, modifiers=modifiers, ) def grab_keycode(self, deviceid, time, keycode,", "of the License, or (at your option) any later version.", "class Mask(rq.List): def __init__(self, name): rq.List.__init__(self, name, rq.Card32, pad=0) def", "rq.Pad(1), rq.Card16('sequence_number'), rq.ReplyLength(), rq.Card16('major_version'), rq.Card16('minor_version'), rq.Pad(20), ) def query_version(self): return", "<< 31) AnyButton = 0 AnyKeycode = 0 AsyncDevice =", "= rq.Struct( DEVICEID('deviceid'), rq.Card16('use'), rq.Card16('attachment'), rq.LengthOf('classes', 2), rq.LengthOf('name', 2), rq.Bool('enabled'),", "'xinput_query_version', query_version) disp.extension_add_method('window', 'xinput_select_events', select_events) disp.extension_add_method('display', 'xinput_query_device', query_device) disp.extension_add_method('window', 'xinput_grab_device',", "owner_events=owner_events, mask=event_mask, ) class XIUngrabDevice(rq.Request): _request = rq.Struct( rq.Card8('opcode'), rq.Opcode(52),", ") class Mask(rq.List): def __init__(self, name): rq.List.__init__(self, name, rq.Card32, pad=0)", "useful, # but WITHOUT ANY WARRANTY; without even the implied", "float(1 << 16) class FP3232(rq.ValueField): structcode = 'lL' structvalues =", "paired_device_mode, owner_events, event_mask, modifiers): return XIPassiveGrabDevice( display=self.display, opcode=self.display.get_extension_major(extname), deviceid=deviceid, grab_window=self,", "(deviceid, mask) pairs, where deviceid is a numerical device ID,", "ButtonRelease) MotionMask = (1 << Motion) EnterMask = (1 <<", "rq.Cursor('cursor', (X.NONE, )), DEVICEID('deviceid'), rq.Set('grab_mode', 1, (GrabModeSync, GrabModeAsync)), rq.Set('paired_device_mode', 1,", "rq.Window('grab_window'), rq.Cursor('cursor', (X.NONE, )), rq.Card32('detail'), DEVICEID('deviceid'), rq.LengthOf('modifiers', 2), rq.LengthOf('mask', 2),", "1) SlaveAdded = (1 << 2) SlaveRemoved = (1 <<", "6 NotifyDetailNone = 7 GrabtypeButton = 0 GrabtypeKeycode = 1", "= float(integral) # optimised math.ldexp(float(frac), -32) ret += float(frac) *", "# You should have received a copy of the GNU", "(1 << KeyPress) KeyReleaseMask = (1 << KeyRelease) ButtonPressMask =", "= rq.Struct( DEVICEID('deviceid'), rq.Card32('time'), rq.Card32('detail'), rq.Window('root'), rq.Window('event'), rq.Window('child'), FP1616('root_x'), FP1616('root_y'),", "end to end. The simple case is # with a", "DEVICEUSE = rq.Card8 class FP1616(rq.Int32): def check_value(self, value): return int(value", "length), data ButtonInfo = rq.Struct( rq.Card16('type'), rq.Card16('length'), rq.Card16('sourceid'), rq.LengthOf(('state', 'labels'),", "''' select_events(event_masks) event_masks: Sequence of (deviceid, mask) pairs, where deviceid", "_request = rq.Struct( rq.Card8('opcode'), rq.Opcode(52), rq.RequestLength(), rq.Card32('time'), DEVICEID('deviceid'), rq.Pad(2), )", "Enter = 7 Leave = 8 FocusIn = 9 FocusOut", "grab_mode, paired_device_mode, owner_events, event_mask, modifiers): return passive_grab_device(self, deviceid, time, keycode,", "RawButtonPress = 15 RawButtonRelease = 16 RawMotion = 17 DeviceChangedMask", "single unsigned 32-bit value, for which we construct an #", "class XIQueryDevice(rq.ReplyRequest): _request = rq.Struct( rq.Card8('opcode'), rq.Opcode(48), rq.RequestLength(), DEVICEID('deviceid'), rq.Pad(2),", "NotifyNonlinearVirtual = 4 NotifyPointer = 5 NotifyPointerRoot = 6 NotifyDetailNone", "4), rq.List('classes', ClassInfo), ) class XIQueryDevice(rq.ReplyRequest): _request = rq.Struct( rq.Card8('opcode'),", "data[:4]) class_struct = INFO_CLASSES.get(class_type, AnyInfo) class_data, _ = class_struct.parse_binary(data, display)", "ButtonPress) ButtonReleaseMask = (1 << ButtonRelease) MotionMask = (1 <<", "is a numerical device ID, or AllDevices or AllMasterDevices, and", "<< RawButtonRelease) RawMotionMask = (1 << RawMotion) GrabModeSync = 0", "SlaveAttached = (1 << 4) SlaveDetached = (1 << 5)", "integer_types from Xlib.protocol import rq from Xlib import X extname", "rq.LengthOf('modifiers', 2), rq.LengthOf('mask', 2), rq.Set('grab_type', 1, (GrabtypeButton, GrabtypeKeycode, GrabtypeEnter, GrabtypeFocusIn,", "RawMotion = 17 DeviceChangedMask = (1 << DeviceChanged) KeyPressMask =", "# # This library is distributed in the hope that", "select_events) disp.extension_add_method('display', 'xinput_query_device', query_device) disp.extension_add_method('window', 'xinput_grab_device', grab_device) disp.extension_add_method('display', 'xinput_ungrab_device', ungrab_device)", "= 0 ButtonClass = 1 ValuatorClass = 2 ScrollClass =", "(1 << 31) AnyButton = 0 AnyKeycode = 0 AsyncDevice", "opcode=self.display.get_extension_major(extname), time=time, deviceid=deviceid, ) class XIPassiveGrabDevice(rq.ReplyRequest): _request = rq.Struct( rq.Card8('opcode'),", "MA 02111-1307 USA ''' A very incomplete implementation of the", "it under the terms of the GNU Lesser General Public", "__init__(self, name): rq.ValueField.__init__(self, name) def parse_binary_value(self, data, display, length, fmt):", "= 5 SlaveSwitch = 1 DeviceChange = 2 MasterAdded =", "to end. The simple case is # with a single", "= (1 << 31) AnyButton = 0 AnyKeycode = 0", "rq.Card16('type'), rq.Card16('length'), rq.Card16('sourceid'), rq.LengthOf('keycodes', 2), rq.List('keycodes', rq.Card32), ) ValuatorInfo =", "GroupInfo = rq.Struct( rq.Card8('base_group'), rq.Card8('latched_group'), rq.Card8('locked_group'), rq.Card8('effective_group'), ) DeviceEventData =", "version. # # This library is distributed in the hope", "but WITHOUT ANY WARRANTY; without even the implied warranty of", "4 AnyModifier = (1 << 31) AnyButton = 0 AnyKeycode", "rq.Pad(11), rq.List('classes', ClassInfo), ) def init(disp, info): disp.extension_add_method('display', 'xinput_query_version', query_version)", "mask_len = 4 * ((((length + 7) >> 3) +", "DEVICEID('deviceid'), rq.Set('grab_mode', 1, (GrabModeSync, GrabModeAsync)), rq.Set('paired_device_mode', 1, (GrabModeSync, GrabModeAsync)), rq.Bool('owner_events'),", "modifiers): return XIPassiveUngrabDevice( display=self.display, opcode=self.display.get_extension_major(extname), deviceid=deviceid, grab_window=self, detail=detail, grab_type=grab_type, modifiers=modifiers,", "FITNESS FOR A PARTICULAR PURPOSE. # See the GNU Lesser", "(1 << RawMotion) GrabModeSync = 0 GrabModeAsync = 1 GrabModeTouch", "data[mask_len:] assert (mask_value & 1) == 0 return ButtonMask(mask_value >>", "to maintain native # byte order across the entire set", "ungrab_keycode) if hasattr(disp,\"ge_add_event_data\"): for device_event in (ButtonPress, ButtonRelease, KeyPress, KeyRelease,", "this library; if not, write to the # Free Software", "32-bit value, for which we construct an # array with", "rq.Pad(1), rq.Card16('sequence_number'), rq.ReplyLength(), rq.LengthOf('devices', 2), rq.Pad(22), rq.List('devices', DeviceInfo), ) def", "display=self.display, opcode=self.display.get_extension_major(extname), time=time, deviceid=deviceid, ) class XIPassiveGrabDevice(rq.ReplyRequest): _request = rq.Struct(", "= rq.Struct( rq.Card32('base_mods'), rq.Card32('latched_mods'), rq.Card32('locked_mods'), rq.Card32('effective_mods'), ) GroupInfo = rq.Struct(", "ButtonClass = 1 ValuatorClass = 2 ScrollClass = 3 TouchClass", "integral, frac = value ret = float(integral) # optimised math.ldexp(float(frac),", "== 0 return ButtonMask(mask_value >> 1, length), data ButtonInfo =", "display): class_type, length = struct.unpack('=HH', data[:4]) class_struct = INFO_CLASSES.get(class_type, AnyInfo)", "rq.Card32), ) _reply = rq.Struct( rq.ReplyCode(), rq.Pad(1), rq.Card16('sequence_number'), rq.ReplyLength(), rq.LengthOf('modifiers',", "fmt): # Mask: bitfield of <length> button states. mask_len =", "RawButtonReleaseMask = (1 << RawButtonRelease) RawMotionMask = (1 << RawMotion)", "grab_type=grab_type, grab_mode=grab_mode, paired_device_mode=paired_device_mode, owner_events=owner_events, mask=event_mask, modifiers=modifiers, ) def grab_keycode(self, deviceid,", "4 FloatingSlave = 5 KeyClass = 0 ButtonClass = 1", "ButtonInfo, ValuatorClass: ValuatorInfo, ScrollClass: ScrollInfo, TouchClass: TouchInfo, } class ClassInfoClass(object):", "= 4 SyncPair = 5 SlaveSwitch = 1 DeviceChange =", "rq.Card16('type'), rq.Card16('length'), rq.Card16('sourceid'), rq.LengthOf(('state', 'labels'), 2), ButtonState('state'), rq.List('labels', rq.Card32), )", "= 11 PropertyEvent = 12 RawKeyPress = 13 RawKeyRelease =", "def query_version(self): return XIQueryVersion( display=self.display, opcode=self.display.get_extension_major(extname), major_version=2, minor_version=0, ) class", "rq.Struct( DEVICEID('deviceid'), rq.Card32('time'), rq.Card32('flags'), rq.LengthOf('info', 2), rq.Pad(10), rq.List('info', HierarchyInfo), )", "rq.Set('paired_device_mode', 1, (GrabModeSync, GrabModeAsync)), rq.Bool('owner_events'), rq.Pad(1), rq.LengthOf('mask', 2), Mask('mask'), )", "(1 << 0) MasterRemoved = (1 << 1) SlaveAdded =", "order across the entire set of values. if sys.byteorder ==", "AssertionError(sys.byteorder) while val: fun(val & 0xFFFFFFFF) val = val >>", "XIPassiveGrabDevice(rq.ReplyRequest): _request = rq.Struct( rq.Card8('opcode'), rq.Opcode(54), rq.RequestLength(), rq.Card32('time'), rq.Window('grab_window'), rq.Cursor('cursor',", "HierarchyChanged) PropertyEventMask = (1 << PropertyEvent) RawKeyPressMask = (1 <<", "check_value(self, value): return int(value * 65536.0) def parse_value(self, value, display):", "owner_events, event_mask, modifiers): return XIPassiveGrabDevice( display=self.display, opcode=self.display.get_extension_major(extname), deviceid=deviceid, grab_window=self, time=time,", "= 1 MasterPointer = 1 MasterKeyboard = 2 SlavePointer =", "while val: fun(val & 0xFFFFFFFF) val = val >> 32", "= 1 GrabModeTouch = 2 DEVICEID = rq.Card16 DEVICE =", "rq.Card16('major_version'), rq.Card16('minor_version'), ) _reply = rq.Struct( rq.ReplyCode(), rq.Pad(1), rq.Card16('sequence_number'), rq.ReplyLength(),", "WARRANTY; without even the implied warranty of # MERCHANTABILITY or", "17 DeviceChangedMask = (1 << DeviceChanged) KeyPressMask = (1 <<", "FP3232('min'), FP3232('max'), FP3232('value'), rq.Card32('resolution'), rq.Card8('mode'), rq.Pad(3), ) ScrollInfo = rq.Struct(", "need to build a \"binary mask\" that (as far as", "rq.ReplyCode(), rq.Pad(1), rq.Card16('sequence_number'), rq.ReplyLength(), rq.Card8('status'), rq.Pad(23), ) def grab_device(self, deviceid,", "None def parse_binary(self, data, display): class_type, length = struct.unpack('=HH', data[:4])", "_reply = rq.Struct( rq.ReplyCode(), rq.Pad(1), rq.Card16('sequence_number'), rq.ReplyLength(), rq.Card8('status'), rq.Pad(23), )", "is distributed in the hope that it will be useful,", "8 mask_value |= byte data = data[mask_len:] assert (mask_value &", "2), rq.Set('grab_type', 1, (GrabtypeButton, GrabtypeKeycode, GrabtypeEnter, GrabtypeFocusIn, GrabtypeTouchBegin)), rq.Pad(3), rq.List('modifiers',", "grab_mode=grab_mode, paired_device_mode=paired_device_mode, owner_events=owner_events, mask=event_mask, ) class XIUngrabDevice(rq.Request): _request = rq.Struct(", "= 'lL' structvalues = 2 def check_value(self, value): return value", "AttachSlave = 3 DetachSlave = 4 AttachToMaster = 1 Floating", "<< key) def __str__(self): return repr(self) def __repr__(self): return '0b{value:0{width}b}'.format(value=self._value,", "HierarchyEventData = rq.Struct( DEVICEID('deviceid'), rq.Card32('time'), rq.Card32('flags'), rq.LengthOf('info', 2), rq.Pad(10), rq.List('info',", "time): return XIUngrabDevice( display=self.display, opcode=self.display.get_extension_major(extname), time=time, deviceid=deviceid, ) class XIPassiveGrabDevice(rq.ReplyRequest):", "KeyPressMask = (1 << KeyPress) KeyReleaseMask = (1 << KeyRelease)", "<< RawKeyRelease) RawButtonPressMask = (1 << RawButtonPress) RawButtonReleaseMask = (1", "from Xlib.protocol import rq from Xlib import X extname =", "ModifierInfo), rq.Object('groups', GroupInfo), ButtonState('buttons'), ) DeviceChangedEventData = rq.Struct( DEVICEID('deviceid'), rq.Card32('time'),", "return mask_seq.tostring(), len(mask_seq), None EventMask = rq.Struct( DEVICE('deviceid'), rq.LengthOf('mask', 2),", "# Mask: bitfield of <length> button states. mask_len = 4", "WITHOUT ANY WARRANTY; without even the implied warranty of #", "= 1 NotifyInferior = 2 NotifyNonlinear = 3 NotifyNonlinearVirtual =", "Free Software Foundation; either version 2.1 # of the License,", "rq.Card32('time'), DEVICEID('deviceid'), rq.Pad(2), ) def ungrab_device(self, deviceid, time): return XIUngrabDevice(", "= 15 RawButtonRelease = 16 RawMotion = 17 DeviceChangedMask =", "'0b{value:0{width}b}'.format(value=self._value, width=self._length) class ButtonState(rq.ValueField): structcode = None def __init__(self, name):", "length = struct.unpack('=HH', data[:4]) class_struct = INFO_CLASSES.get(class_type, AnyInfo) class_data, _", "display=self.display, opcode=self.display.get_extension_major(extname), deviceid=deviceid, ) class XIGrabDevice(rq.ReplyRequest): _request = rq.Struct( rq.Card8('opcode'),", "4 NotifyPointer = 5 NotifyPointerRoot = 6 NotifyDetailNone = 7", "fun(val & 0xFFFFFFFF) val = val >> 32 else: mask_seq.extend(val)", "DEVICEID('deviceid'), rq.Pad(2), ) def ungrab_device(self, deviceid, time): return XIUngrabDevice( display=self.display,", "= 2 KeyRelease = 3 ButtonPress = 4 ButtonRelease =", "too big to fit inside 4 # bytes we build", "integer or sequence of 32 bits unsigned values ''' return", "FP3232('increment'), ) TouchInfo = rq.Struct( rq.Card16('type'), rq.Card16('length'), rq.Card16('sourceid'), rq.Card8('mode'), rq.Card8('num_touches'),", "is either an unsigned integer or sequence of 32 bits", "4) SlaveDetached = (1 << 5) DeviceEnabled = (1 <<", "NotifyUngrab = 2 NotifyWhileGrabbed = 3 NotifyPassiveGrab = 4 NotifyPassiveUngrab", "rq.Window('root'), rq.Window('event'), rq.Window('child'), FP1616('root_x'), FP1616('root_y'), FP1616('event_x'), FP1616('event_y'), rq.LengthOf('buttons', 2), rq.Card16('valulators_len'),", "rq.Pad(2), ) class ButtonMask(object): def __init__(self, value, length): self._value =", "value): return int(value * 65536.0) def parse_value(self, value, display): return", "5 SlaveSwitch = 1 DeviceChange = 2 MasterAdded = (1", "(1 << 1) SlaveAdded = (1 << 2) SlaveRemoved =", "the GNU Lesser General Public License for more details. #", "2 def check_value(self, value): return value def parse_value(self, value, display):", "NotifyPointer = 5 NotifyPointerRoot = 6 NotifyDetailNone = 7 GrabtypeButton", "rq.Card16('sequence_number'), rq.ReplyLength(), rq.LengthOf('modifiers', 2), rq.Pad(22), rq.List('modifiers', rq.Card32), ) def passive_grab_device(self,", ") _reply = rq.Struct( rq.ReplyCode(), rq.Pad(1), rq.Card16('sequence_number'), rq.ReplyLength(), rq.LengthOf('modifiers', 2),", "deviceid=deviceid, grab_window=self, time=time, cursor=X.NONE, detail=detail, grab_type=grab_type, grab_mode=grab_mode, paired_device_mode=paired_device_mode, owner_events=owner_events, mask=event_mask,", "2 NotifyNormal = 0 NotifyGrab = 1 NotifyUngrab = 2", "'lL' structvalues = 2 def check_value(self, value): return value def", "optimised math.ldexp(float(frac), -32) ret += float(frac) * (1.0 / (1", "check_value(self, value): return value def parse_value(self, value, display): integral, frac", "return '0b{value:0{width}b}'.format(value=self._value, width=self._length) class ButtonState(rq.ValueField): structcode = None def __init__(self,", "= (1 << 6) DeviceDisabled = (1 << 7) AddMaster", "rq.Set('grab_type', 1, (GrabtypeButton, GrabtypeKeycode, GrabtypeEnter, GrabtypeFocusIn, GrabtypeTouchBegin)), rq.Set('grab_mode', 1, (GrabModeSync,", "rq.Card32('time'), rq.Card32('flags'), rq.LengthOf('info', 2), rq.Pad(10), rq.List('info', HierarchyInfo), ) ModifierInfo =", "# Python 2/3 compatibility. from six import integer_types from Xlib.protocol", "AttachToMaster = 1 Floating = 2 ModeRelative = 0 ModeAbsolute", "a single unsigned 32-bit value, for which we construct an", "= (1 << DeviceChanged) KeyPressMask = (1 << KeyPress) KeyReleaseMask", "'little': def fun(val): mask_seq.insert(0, val) elif sys.byteorder == 'big': fun", "ValuatorClass = 2 ScrollClass = 3 TouchClass = 8 KeyRepeat", "<<= 8 mask_value |= byte data = data[mask_len:] assert (mask_value", "rq.Card16('sourceid'), rq.Card16('number'), rq.Card16('scroll_type'), rq.Pad(2), rq.Card32('flags'), FP3232('increment'), ) TouchInfo = rq.Struct(", "keycode, modifiers): return passive_ungrab_device(self, deviceid, keycode, GrabtypeKeycode, modifiers) HierarchyInfo =", "of (deviceid, mask) pairs, where deviceid is a numerical device", "event_mask, modifiers) class XIPassiveUngrabDevice(rq.Request): _request = rq.Struct( rq.Card8('opcode'), rq.Opcode(55), rq.RequestLength(),", "ModifierInfo = rq.Struct( rq.Card32('base_mods'), rq.Card32('latched_mods'), rq.Card32('locked_mods'), rq.Card32('effective_mods'), ) GroupInfo =", ") def grab_keycode(self, deviceid, time, keycode, grab_mode, paired_device_mode, owner_events, event_mask,", "1) == 0 return ButtonMask(mask_value >> 1, length), data ButtonInfo", "/ (1 << 32)) return ret class XIQueryVersion(rq.ReplyRequest): _request =", "DeviceInfo), ) def query_device(self, deviceid): return XIQueryDevice( display=self.display, opcode=self.display.get_extension_major(extname), deviceid=deviceid,", "rq.Struct( DEVICEID('deviceid'), rq.Card32('time'), rq.LengthOf('classes', 2), DEVICEID('sourceid'), rq.Card8('reason'), rq.Pad(11), rq.List('classes', ClassInfo),", "values ''' return XISelectEvents( display=self.display, opcode=self.display.get_extension_major(extname), window=self, masks=event_masks, ) AnyInfo", "2012 Outpost Embedded, LLC # <NAME> <<EMAIL>> # # This", "SyncDevice = 1 ReplayDevice = 2 AsyncPairedDevice = 3 AsyncPair", "= 0 AllMasterDevices = 1 DeviceChanged = 1 KeyPress =", "FocusInMask = (1 << FocusIn) FocusOutMask = (1 << FocusOut)", "9 FocusOut = 10 HierarchyChanged = 11 PropertyEvent = 12", "PropertyEventMask = (1 << PropertyEvent) RawKeyPressMask = (1 << RawKeyPress)", "value self._length = length def __len__(self): return self._length def __getitem__(self,", "GrabtypeKeycode, modifiers) HierarchyInfo = rq.Struct( DEVICEID('deviceid'), DEVICEID('attachment'), DEVICEUSE('type'), rq.Bool('enabled'), rq.Pad(2),", "data ButtonInfo = rq.Struct( rq.Card16('type'), rq.Card16('length'), rq.Card16('sourceid'), rq.LengthOf(('state', 'labels'), 2),", "FP1616('root_x'), FP1616('root_y'), FP1616('event_x'), FP1616('event_y'), rq.LengthOf('buttons', 2), rq.Card16('valulators_len'), DEVICEID('sourceid'), rq.Pad(2), rq.Card32('flags'),", "15 RawButtonRelease = 16 RawMotion = 17 DeviceChangedMask = (1", "DEVICEID('deviceid'), rq.LengthOf('modifiers', 2), rq.Set('grab_type', 1, (GrabtypeButton, GrabtypeKeycode, GrabtypeEnter, GrabtypeFocusIn, GrabtypeTouchBegin)),", "rq.Bool('owner_events'), rq.Pad(1), rq.LengthOf('mask', 2), Mask('mask'), ) _reply = rq.Struct( rq.ReplyCode(),", "rq.Struct( DEVICE('deviceid'), rq.LengthOf('mask', 2), Mask('mask'), ) class XISelectEvents(rq.Request): _request =", "<< RawMotion) GrabModeSync = 0 GrabModeAsync = 1 GrabModeTouch =", "rq.Pad(1), rq.Card16('sequence_number'), rq.ReplyLength(), rq.Card8('status'), rq.Pad(23), ) def grab_device(self, deviceid, time,", "self._length = length def __len__(self): return self._length def __getitem__(self, key):", "reversed(struct.unpack('={0:d}B'.format(mask_len), mask_data)): mask_value <<= 8 mask_value |= byte data =", "2 NotifyNonlinear = 3 NotifyNonlinearVirtual = 4 NotifyPointer = 5", "the # Free Software Foundation, Inc., # 59 Temple Place,", "def grab_device(self, deviceid, time, grab_mode, paired_device_mode, owner_events, event_mask): return XIGrabDevice(", "extension module # # Copyright (C) 2012 Outpost Embedded, LLC", "3) + 3) >> 2) mask_data = data[:mask_len] mask_value =", "<NAME> <<EMAIL>> # # This library is free software; you", "(ButtonPress, ButtonRelease, KeyPress, KeyRelease, Motion): disp.ge_add_event_data(info.major_opcode, device_event, DeviceEventData) disp.ge_add_event_data(info.major_opcode, DeviceChanged,", "= (1 << HierarchyChanged) PropertyEventMask = (1 << PropertyEvent) RawKeyPressMask", "License for more details. # # You should have received", "= rq.Struct( rq.Card16('type'), rq.Card16('length'), rq.Card16('sourceid'), rq.Card16('number'), rq.Card32('label'), FP3232('min'), FP3232('max'), FP3232('value'),", "class_struct.parse_binary(data, display) data = data[length * 4:] return class_data, data", "ClassInfo), ) class XIQueryDevice(rq.ReplyRequest): _request = rq.Struct( rq.Card8('opcode'), rq.Opcode(48), rq.RequestLength(),", "7 Leave = 8 FocusIn = 9 FocusOut = 10", "rq.Struct( rq.Card16('type'), rq.Card16('length'), rq.Card16('sourceid'), rq.Card8('mode'), rq.Card8('num_touches'), ) INFO_CLASSES = {", "AllMasterDevices, and mask is either an unsigned integer or sequence", "passive_ungrab_device(self, deviceid, keycode, GrabtypeKeycode, modifiers) HierarchyInfo = rq.Struct( DEVICEID('deviceid'), DEVICEID('attachment'),", "= 2 MasterAdded = (1 << 0) MasterRemoved = (1", "# as published by the Free Software Foundation; either version", "return XIQueryVersion( display=self.display, opcode=self.display.get_extension_major(extname), major_version=2, minor_version=0, ) class Mask(rq.List): def", "rq.Card32), ) def passive_grab_device(self, deviceid, time, detail, grab_type, grab_mode, paired_device_mode,", "GrabModeAsync)), rq.Bool('owner_events'), rq.Pad(1), rq.LengthOf('mask', 2), Mask('mask'), ) _reply = rq.Struct(", "= 3 AsyncPair = 4 SyncPair = 5 SlaveSwitch =", "<< 0) MasterRemoved = (1 << 1) SlaveAdded = (1", "DEVICEID('deviceid'), rq.Card32('time'), rq.Card32('flags'), rq.LengthOf('info', 2), rq.Pad(10), rq.List('info', HierarchyInfo), ) ModifierInfo", "mask_seq.extend(val) return mask_seq.tostring(), len(mask_seq), None EventMask = rq.Struct( DEVICE('deviceid'), rq.LengthOf('mask',", "rq.Card8('effective_group'), ) DeviceEventData = rq.Struct( DEVICEID('deviceid'), rq.Card32('time'), rq.Card32('detail'), rq.Window('root'), rq.Window('event'),", "grab_window=self, time=time, cursor=X.NONE, detail=detail, grab_type=grab_type, grab_mode=grab_mode, paired_device_mode=paired_device_mode, owner_events=owner_events, mask=event_mask, modifiers=modifiers,", "<<EMAIL>> # # This library is free software; you can", "details. # # You should have received a copy of", "or sequence of 32 bits unsigned values ''' return XISelectEvents(", "in reversed(struct.unpack('={0:d}B'.format(mask_len), mask_data)): mask_value <<= 8 mask_value |= byte data", "FP3232('value'), rq.Card32('resolution'), rq.Card8('mode'), rq.Pad(3), ) ScrollInfo = rq.Struct( rq.Card16('type'), rq.Card16('length'),", "* 4:] return class_data, data ClassInfo = ClassInfoClass() DeviceInfo =", "rq.Card32('locked_mods'), rq.Card32('effective_mods'), ) GroupInfo = rq.Struct( rq.Card8('base_group'), rq.Card8('latched_group'), rq.Card8('locked_group'), rq.Card8('effective_group'),", "= 1 PropertyModified = 2 NotifyNormal = 0 NotifyGrab =", "= 1 ValuatorClass = 2 ScrollClass = 3 TouchClass =", "rq.List('labels', rq.Card32), ) KeyInfo = rq.Struct( rq.Card16('type'), rq.Card16('length'), rq.Card16('sourceid'), rq.LengthOf('keycodes',", "= 8 FocusIn = 9 FocusOut = 10 HierarchyChanged =", "(1 << FocusIn) FocusOutMask = (1 << FocusOut) HierarchyChangedMask =", "''' import sys import array import struct # Python 2/3", "ButtonReleaseMask = (1 << ButtonRelease) MotionMask = (1 << Motion)", "a longer array, being careful to maintain native # byte", "\"binary mask\" that (as far as I can tell) is", "General Public License # as published by the Free Software", "4 AttachToMaster = 1 Floating = 2 ModeRelative = 0", "minor_version=0, ) class Mask(rq.List): def __init__(self, name): rq.List.__init__(self, name, rq.Card32,", "rq.RequestLength(), rq.Window('window'), rq.LengthOf('masks', 2), rq.Pad(2), rq.List('masks', EventMask), ) def select_events(self,", "KeyClass = 0 ButtonClass = 1 ValuatorClass = 2 ScrollClass", "XIUngrabDevice( display=self.display, opcode=self.display.get_extension_major(extname), time=time, deviceid=deviceid, ) class XIPassiveGrabDevice(rq.ReplyRequest): _request =", "= (1 << FocusIn) FocusOutMask = (1 << FocusOut) HierarchyChangedMask", "rq.Struct( rq.Card16('type'), rq.Card16('length'), rq.Card16('sourceid'), rq.Card16('number'), rq.Card32('label'), FP3232('min'), FP3232('max'), FP3232('value'), rq.Card32('resolution'),", "= 1 NotifyUngrab = 2 NotifyWhileGrabbed = 3 NotifyPassiveGrab =", "values too big to fit inside 4 # bytes we", "or AllDevices or AllMasterDevices, and mask is either an unsigned", "ButtonPress = 4 ButtonRelease = 5 Motion = 6 Enter", "TouchInfo = rq.Struct( rq.Card16('type'), rq.Card16('length'), rq.Card16('sourceid'), rq.Card8('mode'), rq.Card8('num_touches'), ) INFO_CLASSES", "rq.Card32, pad=0) def pack_value(self, val): mask_seq = array.array(rq.struct_to_array_codes['L']) if isinstance(val,", "+ 7) >> 3) + 3) >> 2) mask_data =", "AnyInfo) class_data, _ = class_struct.parse_binary(data, display) data = data[length *", "raise AssertionError(sys.byteorder) while val: fun(val & 0xFFFFFFFF) val = val", "that it will be useful, # but WITHOUT ANY WARRANTY;", "= rq.Card16 DEVICE = rq.Card16 DEVICEUSE = rq.Card8 class FP1616(rq.Int32):", "def parse_binary_value(self, data, display, length, fmt): # Mask: bitfield of", "fun = mask_seq.append else: raise AssertionError(sys.byteorder) while val: fun(val &", "rq.RequestLength(), rq.Card16('major_version'), rq.Card16('minor_version'), ) _reply = rq.Struct( rq.ReplyCode(), rq.Pad(1), rq.Card16('sequence_number'),", ") class ButtonMask(object): def __init__(self, value, length): self._value = value", "rq.Struct( rq.ReplyCode(), rq.Pad(1), rq.Card16('sequence_number'), rq.ReplyLength(), rq.LengthOf('modifiers', 2), rq.Pad(22), rq.List('modifiers', rq.Card32),", "opcode=self.display.get_extension_major(extname), major_version=2, minor_version=0, ) class Mask(rq.List): def __init__(self, name): rq.List.__init__(self,", "= (1 << RawKeyRelease) RawButtonPressMask = (1 << RawButtonPress) RawButtonReleaseMask", "3 DetachSlave = 4 AttachToMaster = 1 Floating = 2", "= 3 ButtonPress = 4 ButtonRelease = 5 Motion =", "with this library; if not, write to the # Free", "rq.Card8('opcode'), rq.Opcode(46), rq.RequestLength(), rq.Window('window'), rq.LengthOf('masks', 2), rq.Pad(2), rq.List('masks', EventMask), )", "3) SlaveAttached = (1 << 4) SlaveDetached = (1 <<", "__getitem__(self, key): return self._value & (1 << key) def __str__(self):", "def __len__(self): return self._length def __getitem__(self, key): return self._value &", "software; you can redistribute it and/or # modify it under", "rq.Card16 DEVICE = rq.Card16 DEVICEUSE = rq.Card8 class FP1616(rq.Int32): def", "02111-1307 USA ''' A very incomplete implementation of the XInput", "of <length> button states. mask_len = 4 * ((((length +", "FloatingSlave = 5 KeyClass = 0 ButtonClass = 1 ValuatorClass", "def __init__(self, name): rq.ValueField.__init__(self, name) def parse_binary_value(self, data, display, length,", "def parse_value(self, value, display): integral, frac = value ret =", "# # This library is free software; you can redistribute", "# Boston, MA 02111-1307 USA ''' A very incomplete implementation", "pack_value(self, val): mask_seq = array.array(rq.struct_to_array_codes['L']) if isinstance(val, integer_types): # We", "(1 << Motion) EnterMask = (1 << Enter) LeaveMask =", "= { KeyClass: KeyInfo, ButtonClass: ButtonInfo, ValuatorClass: ValuatorInfo, ScrollClass: ScrollInfo,", ")), rq.Card32('detail'), DEVICEID('deviceid'), rq.LengthOf('modifiers', 2), rq.LengthOf('mask', 2), rq.Set('grab_type', 1, (GrabtypeButton,", "rq.Opcode(46), rq.RequestLength(), rq.Window('window'), rq.LengthOf('masks', 2), rq.Pad(2), rq.List('masks', EventMask), ) def", "def __getitem__(self, key): return self._value & (1 << key) def", "rq.Card16('sourceid'), rq.LengthOf('keycodes', 2), rq.List('keycodes', rq.Card32), ) ValuatorInfo = rq.Struct( rq.Card16('type'),", "the entire set of values. if sys.byteorder == 'little': def", "1 Floating = 2 ModeRelative = 0 ModeAbsolute = 1", "if sys.byteorder == 'little': def fun(val): mask_seq.insert(0, val) elif sys.byteorder", "to the # Free Software Foundation, Inc., # 59 Temple", "1, (GrabModeSync, GrabModeAsync)), rq.Set('paired_device_mode', 1, (GrabModeSync, GrabModeAsync)), rq.Bool('owner_events'), rq.Pad(1), rq.LengthOf('mask',", "7) >> 3) + 3) >> 2) mask_data = data[:mask_len]", "rq.Card16('type'), rq.Card16('length'), rq.Card16('sourceid'), rq.Pad(2), ) class ButtonMask(object): def __init__(self, value,", "implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR", "= data[mask_len:] assert (mask_value & 1) == 0 return ButtonMask(mask_value", "(1 << Leave) FocusInMask = (1 << FocusIn) FocusOutMask =", "2), rq.Set('grab_type', 1, (GrabtypeButton, GrabtypeKeycode, GrabtypeEnter, GrabtypeFocusIn, GrabtypeTouchBegin)), rq.Set('grab_mode', 1,", "return XIPassiveGrabDevice( display=self.display, opcode=self.display.get_extension_major(extname), deviceid=deviceid, grab_window=self, time=time, cursor=X.NONE, detail=detail, grab_type=grab_type,", "in (ButtonPress, ButtonRelease, KeyPress, KeyRelease, Motion): disp.ge_add_event_data(info.major_opcode, device_event, DeviceEventData) disp.ge_add_event_data(info.major_opcode,", "GrabtypeKeycode, GrabtypeEnter, GrabtypeFocusIn, GrabtypeTouchBegin)), rq.Set('grab_mode', 1, (GrabModeSync, GrabModeAsync)), rq.Set('paired_device_mode', 1,", "2), rq.Bool('enabled'), rq.Pad(1), rq.String8('name', 4), rq.List('classes', ClassInfo), ) class XIQueryDevice(rq.ReplyRequest):", "= length def __len__(self): return self._length def __getitem__(self, key): return", "query_device) disp.extension_add_method('window', 'xinput_grab_device', grab_device) disp.extension_add_method('display', 'xinput_ungrab_device', ungrab_device) disp.extension_add_method('window', 'xinput_grab_keycode', grab_keycode)", "redistribute it and/or # modify it under the terms of", "rq from Xlib import X extname = 'XInputExtension' PropertyDeleted =", "deviceid=deviceid, ) class XIPassiveGrabDevice(rq.ReplyRequest): _request = rq.Struct( rq.Card8('opcode'), rq.Opcode(54), rq.RequestLength(),", "KeyPress) KeyReleaseMask = (1 << KeyRelease) ButtonPressMask = (1 <<", "2) mask_data = data[:mask_len] mask_value = 0 for byte in", "native # byte order across the entire set of values.", "detail, grab_type, grab_mode, paired_device_mode, owner_events, event_mask, modifiers): return XIPassiveGrabDevice( display=self.display,", "rq.Opcode(54), rq.RequestLength(), rq.Card32('time'), rq.Window('grab_window'), rq.Cursor('cursor', (X.NONE, )), rq.Card32('detail'), DEVICEID('deviceid'), rq.LengthOf('modifiers',", "owner_events, event_mask, modifiers) class XIPassiveUngrabDevice(rq.Request): _request = rq.Struct( rq.Card8('opcode'), rq.Opcode(55),", "NotifyDetailNone = 7 GrabtypeButton = 0 GrabtypeKeycode = 1 GrabtypeEnter", "rq.Card16('minor_version'), rq.Pad(20), ) def query_version(self): return XIQueryVersion( display=self.display, opcode=self.display.get_extension_major(extname), major_version=2,", "0 AnyKeycode = 0 AsyncDevice = 0 SyncDevice = 1", "rq.Pad(1), rq.Card16('sequence_number'), rq.ReplyLength(), rq.LengthOf('modifiers', 2), rq.Pad(22), rq.List('modifiers', rq.Card32), ) def", "def grab_keycode(self, deviceid, time, keycode, grab_mode, paired_device_mode, owner_events, event_mask, modifiers):", "grab_keycode(self, deviceid, time, keycode, grab_mode, paired_device_mode, owner_events, event_mask, modifiers): return", "32 bits unsigned values ''' return XISelectEvents( display=self.display, opcode=self.display.get_extension_major(extname), window=self,", "rq.Struct( rq.Card8('base_group'), rq.Card8('latched_group'), rq.Card8('locked_group'), rq.Card8('effective_group'), ) DeviceEventData = rq.Struct( DEVICEID('deviceid'),", "The simple case is # with a single unsigned 32-bit", "GrabModeAsync)), rq.Set('paired_device_mode', 1, (GrabModeSync, GrabModeAsync)), rq.Bool('owner_events'), rq.Pad(2), Mask('mask'), rq.List('modifiers', rq.Card32),", "16 RawMotion = 17 DeviceChangedMask = (1 << DeviceChanged) KeyPressMask", "Place, # Suite 330, # Boston, MA 02111-1307 USA '''", ") class XIUngrabDevice(rq.Request): _request = rq.Struct( rq.Card8('opcode'), rq.Opcode(52), rq.RequestLength(), rq.Card32('time'),", "rq.ReplyLength(), rq.LengthOf('devices', 2), rq.Pad(22), rq.List('devices', DeviceInfo), ) def query_device(self, deviceid):", "= (1 << RawKeyPress) RawKeyReleaseMask = (1 << RawKeyRelease) RawButtonPressMask", "query_version(self): return XIQueryVersion( display=self.display, opcode=self.display.get_extension_major(extname), major_version=2, minor_version=0, ) class Mask(rq.List):", "int(value * 65536.0) def parse_value(self, value, display): return float(value) /", "= 4 AnyModifier = (1 << 31) AnyButton = 0", "disp.extension_add_method('window', 'xinput_select_events', select_events) disp.extension_add_method('display', 'xinput_query_device', query_device) disp.extension_add_method('window', 'xinput_grab_device', grab_device) disp.extension_add_method('display',", "mask_data = data[:mask_len] mask_value = 0 for byte in reversed(struct.unpack('={0:d}B'.format(mask_len),", "RawButtonRelease = 16 RawMotion = 17 DeviceChangedMask = (1 <<", "structvalues = 2 def check_value(self, value): return value def parse_value(self,", "GrabModeAsync = 1 GrabModeTouch = 2 DEVICEID = rq.Card16 DEVICE", "HierarchyInfo), ) ModifierInfo = rq.Struct( rq.Card32('base_mods'), rq.Card32('latched_mods'), rq.Card32('locked_mods'), rq.Card32('effective_mods'), )", "val >> 32 else: mask_seq.extend(val) return mask_seq.tostring(), len(mask_seq), None EventMask", "for more details. # # You should have received a", "rq.Card32('flags'), ) HierarchyEventData = rq.Struct( DEVICEID('deviceid'), rq.Card32('time'), rq.Card32('flags'), rq.LengthOf('info', 2),", "'xinput_grab_device', grab_device) disp.extension_add_method('display', 'xinput_ungrab_device', ungrab_device) disp.extension_add_method('window', 'xinput_grab_keycode', grab_keycode) disp.extension_add_method('window', 'xinput_ungrab_keycode',", "<< 7) AddMaster = 1 RemoveMaster = 2 AttachSlave =", "display=self.display, opcode=self.display.get_extension_major(extname), deviceid=deviceid, grab_window=self, time=time, cursor=X.NONE, detail=detail, grab_type=grab_type, grab_mode=grab_mode, paired_device_mode=paired_device_mode,", "opcode=self.display.get_extension_major(extname), deviceid=deviceid, ) class XIGrabDevice(rq.ReplyRequest): _request = rq.Struct( rq.Card8('opcode'), rq.Opcode(51),", "self._length def __getitem__(self, key): return self._value & (1 << key)", "XIQueryDevice(rq.ReplyRequest): _request = rq.Struct( rq.Card8('opcode'), rq.Opcode(48), rq.RequestLength(), DEVICEID('deviceid'), rq.Pad(2), )", "= rq.Struct( rq.Card8('base_group'), rq.Card8('latched_group'), rq.Card8('locked_group'), rq.Card8('effective_group'), ) DeviceEventData = rq.Struct(", "class XIGrabDevice(rq.ReplyRequest): _request = rq.Struct( rq.Card8('opcode'), rq.Opcode(51), rq.RequestLength(), rq.Window('grab_window'), rq.Card32('time'),", "(GrabModeSync, GrabModeAsync)), rq.Bool('owner_events'), rq.Pad(1), rq.LengthOf('mask', 2), Mask('mask'), ) _reply =", "class XIQueryVersion(rq.ReplyRequest): _request = rq.Struct( rq.Card8('opcode'), rq.Opcode(47), rq.RequestLength(), rq.Card16('major_version'), rq.Card16('minor_version'),", "ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY", "= 4 NotifyPassiveUngrab = 5 NotifyAncestor = 0 NotifyVirtual =", "GrabtypeTouchBegin = 4 AnyModifier = (1 << 31) AnyButton =", "bytes we build a longer array, being careful to maintain", "received a copy of the GNU Lesser General Public #", "FocusOut) HierarchyChangedMask = (1 << HierarchyChanged) PropertyEventMask = (1 <<", "disp.extension_add_method('window', 'xinput_grab_keycode', grab_keycode) disp.extension_add_method('window', 'xinput_ungrab_keycode', ungrab_keycode) if hasattr(disp,\"ge_add_event_data\"): for device_event", "(1 << 7) AddMaster = 1 RemoveMaster = 2 AttachSlave", "rq.Card16('type'), rq.Card16('length'), rq.Card16('sourceid'), rq.Card16('number'), rq.Card16('scroll_type'), rq.Pad(2), rq.Card32('flags'), FP3232('increment'), ) TouchInfo", "1 DeviceChange = 2 MasterAdded = (1 << 0) MasterRemoved", "= 12 RawKeyPress = 13 RawKeyRelease = 14 RawButtonPress =", "<< 32)) return ret class XIQueryVersion(rq.ReplyRequest): _request = rq.Struct( rq.Card8('opcode'),", "of the XInput extension. ''' import sys import array import", "TouchClass: TouchInfo, } class ClassInfoClass(object): structcode = None def parse_binary(self,", "RawButtonRelease) RawMotionMask = (1 << RawMotion) GrabModeSync = 0 GrabModeAsync", "DEVICEUSE('type'), rq.Bool('enabled'), rq.Pad(2), rq.Card32('flags'), ) HierarchyEventData = rq.Struct( DEVICEID('deviceid'), rq.Card32('time'),", "rq.Card16('length'), rq.Card16('sourceid'), rq.Card16('number'), rq.Card16('scroll_type'), rq.Pad(2), rq.Card32('flags'), FP3232('increment'), ) TouchInfo =", "rq.Card8('latched_group'), rq.Card8('locked_group'), rq.Card8('effective_group'), ) DeviceEventData = rq.Struct( DEVICEID('deviceid'), rq.Card32('time'), rq.Card32('detail'),", "byte order from end to end. The simple case is", "# bytes we build a longer array, being careful to", "longer array, being careful to maintain native # byte order", "rq.Card32('latched_mods'), rq.Card32('locked_mods'), rq.Card32('effective_mods'), ) GroupInfo = rq.Struct( rq.Card8('base_group'), rq.Card8('latched_group'), rq.Card8('locked_group'),", "= (1 << 16) AllDevices = 0 AllMasterDevices = 1", "2), rq.Card16('valulators_len'), DEVICEID('sourceid'), rq.Pad(2), rq.Card32('flags'), rq.Object('mods', ModifierInfo), rq.Object('groups', GroupInfo), ButtonState('buttons'),", "We need to build a \"binary mask\" that (as far", "rq.Card16('valulators_len'), DEVICEID('sourceid'), rq.Pad(2), rq.Card32('flags'), rq.Object('mods', ModifierInfo), rq.Object('groups', GroupInfo), ButtonState('buttons'), )", "2 ModeRelative = 0 ModeAbsolute = 1 MasterPointer = 1", "rq.Set('grab_type', 1, (GrabtypeButton, GrabtypeKeycode, GrabtypeEnter, GrabtypeFocusIn, GrabtypeTouchBegin)), rq.Pad(3), rq.List('modifiers', rq.Card32),", "(GrabtypeButton, GrabtypeKeycode, GrabtypeEnter, GrabtypeFocusIn, GrabtypeTouchBegin)), rq.Pad(3), rq.List('modifiers', rq.Card32), ) def", "value, display): return float(value) / float(1 << 16) class FP3232(rq.ValueField):", "rq.List('modifiers', rq.Card32), ) def passive_ungrab_device(self, deviceid, detail, grab_type, modifiers): return", "# # Copyright (C) 2012 Outpost Embedded, LLC # <NAME>", "<< 16) class FP3232(rq.ValueField): structcode = 'lL' structvalues = 2", "paired_device_mode, owner_events, event_mask): return XIGrabDevice( display=self.display, opcode=self.display.get_extension_major(extname), deviceid=deviceid, grab_window=self, time=time,", "modifiers): return passive_ungrab_device(self, deviceid, keycode, GrabtypeKeycode, modifiers) HierarchyInfo = rq.Struct(", "PropertyCreated = 1 PropertyModified = 2 NotifyNormal = 0 NotifyGrab", "= (1 << KeyRelease) ButtonPressMask = (1 << ButtonPress) ButtonReleaseMask", "= 6 NotifyDetailNone = 7 GrabtypeButton = 0 GrabtypeKeycode =", "select_events(self, event_masks): ''' select_events(event_masks) event_masks: Sequence of (deviceid, mask) pairs,", "data ClassInfo = ClassInfoClass() DeviceInfo = rq.Struct( DEVICEID('deviceid'), rq.Card16('use'), rq.Card16('attachment'),", "masks=event_masks, ) AnyInfo = rq.Struct( rq.Card16('type'), rq.Card16('length'), rq.Card16('sourceid'), rq.Pad(2), )", "<< 2) SlaveRemoved = (1 << 3) SlaveAttached = (1", "5 NotifyPointerRoot = 6 NotifyDetailNone = 7 GrabtypeButton = 0", "DeviceChangedMask = (1 << DeviceChanged) KeyPressMask = (1 << KeyPress)", "EventMask = rq.Struct( DEVICE('deviceid'), rq.LengthOf('mask', 2), Mask('mask'), ) class XISelectEvents(rq.Request):", "<< ButtonPress) ButtonReleaseMask = (1 << ButtonRelease) MotionMask = (1", "(1 << RawButtonPress) RawButtonReleaseMask = (1 << RawButtonRelease) RawMotionMask =", "AllDevices or AllMasterDevices, and mask is either an unsigned integer", "rq.Window('grab_window'), rq.Card32('detail'), DEVICEID('deviceid'), rq.LengthOf('modifiers', 2), rq.Set('grab_type', 1, (GrabtypeButton, GrabtypeKeycode, GrabtypeEnter,", "_ = class_struct.parse_binary(data, display) data = data[length * 4:] return", "2 ScrollClass = 3 TouchClass = 8 KeyRepeat = (1", "Embedded, LLC # <NAME> <<EMAIL>> # # This library is", "NotifyPointerRoot = 6 NotifyDetailNone = 7 GrabtypeButton = 0 GrabtypeKeycode", "value, display): integral, frac = value ret = float(integral) #", "= 5 NotifyAncestor = 0 NotifyVirtual = 1 NotifyInferior =", "(1 << KeyRelease) ButtonPressMask = (1 << ButtonPress) ButtonReleaseMask =", "cursor=X.NONE, grab_mode=grab_mode, paired_device_mode=paired_device_mode, owner_events=owner_events, mask=event_mask, ) class XIUngrabDevice(rq.Request): _request =", "for device_event in (ButtonPress, ButtonRelease, KeyPress, KeyRelease, Motion): disp.ge_add_event_data(info.major_opcode, device_event,", "rq.Card8('mode'), rq.Card8('num_touches'), ) INFO_CLASSES = { KeyClass: KeyInfo, ButtonClass: ButtonInfo,", "KeyInfo, ButtonClass: ButtonInfo, ValuatorClass: ValuatorInfo, ScrollClass: ScrollInfo, TouchClass: TouchInfo, }", "build a longer array, being careful to maintain native #", "<< 6) DeviceDisabled = (1 << 7) AddMaster = 1", "import struct # Python 2/3 compatibility. from six import integer_types", "ret class XIQueryVersion(rq.ReplyRequest): _request = rq.Struct( rq.Card8('opcode'), rq.Opcode(47), rq.RequestLength(), rq.Card16('major_version'),", "time, detail, grab_type, grab_mode, paired_device_mode, owner_events, event_mask, modifiers): return XIPassiveGrabDevice(", "bitfield of <length> button states. mask_len = 4 * ((((length", "maintain native # byte order across the entire set of", "DEVICEID('deviceid'), rq.Pad(2), ) _reply = rq.Struct( rq.ReplyCode(), rq.Pad(1), rq.Card16('sequence_number'), rq.ReplyLength(),", "14 RawButtonPress = 15 RawButtonRelease = 16 RawMotion = 17", "of the GNU Lesser General Public License # as published", "1, (GrabModeSync, GrabModeAsync)), rq.Bool('owner_events'), rq.Pad(2), Mask('mask'), rq.List('modifiers', rq.Card32), ) _reply", "owner_events=owner_events, mask=event_mask, modifiers=modifiers, ) def grab_keycode(self, deviceid, time, keycode, grab_mode,", "GrabModeTouch = 2 DEVICEID = rq.Card16 DEVICE = rq.Card16 DEVICEUSE", "2), Mask('mask'), ) class XISelectEvents(rq.Request): _request = rq.Struct( rq.Card8('opcode'), rq.Opcode(46),", "3 GrabtypeTouchBegin = 4 AnyModifier = (1 << 31) AnyButton", "val): mask_seq = array.array(rq.struct_to_array_codes['L']) if isinstance(val, integer_types): # We need", "build a \"binary mask\" that (as far as I can", "copy of the GNU Lesser General Public # License along", "+ 3) >> 2) mask_data = data[:mask_len] mask_value = 0", "Public License for more details. # # You should have", "def __init__(self, value, length): self._value = value self._length = length", "= rq.Struct( rq.Card8('opcode'), rq.Opcode(54), rq.RequestLength(), rq.Card32('time'), rq.Window('grab_window'), rq.Cursor('cursor', (X.NONE, )),", "<< 5) DeviceEnabled = (1 << 6) DeviceDisabled = (1", "GroupInfo), ButtonState('buttons'), ) DeviceChangedEventData = rq.Struct( DEVICEID('deviceid'), rq.Card32('time'), rq.LengthOf('classes', 2),", "<length> button states. mask_len = 4 * ((((length + 7)", "button states. mask_len = 4 * ((((length + 7) >>", "Public # License along with this library; if not, write", "3 SlaveKeyboard = 4 FloatingSlave = 5 KeyClass = 0", "we construct an # array with just one item. For", "rq.Struct( rq.Card32('base_mods'), rq.Card32('latched_mods'), rq.Card32('locked_mods'), rq.Card32('effective_mods'), ) GroupInfo = rq.Struct( rq.Card8('base_group'),", "mask is either an unsigned integer or sequence of 32", "PURPOSE. # See the GNU Lesser General Public License for", "rq.ReplyCode(), rq.Pad(1), rq.Card16('sequence_number'), rq.ReplyLength(), rq.Card16('major_version'), rq.Card16('minor_version'), rq.Pad(20), ) def query_version(self):", "rq.Bool('enabled'), rq.Pad(2), rq.Card32('flags'), ) HierarchyEventData = rq.Struct( DEVICEID('deviceid'), rq.Card32('time'), rq.Card32('flags'),", "License # as published by the Free Software Foundation; either", "NotifyInferior = 2 NotifyNonlinear = 3 NotifyNonlinearVirtual = 4 NotifyPointer", "rq.ReplyCode(), rq.Pad(1), rq.Card16('sequence_number'), rq.ReplyLength(), rq.LengthOf('devices', 2), rq.Pad(22), rq.List('devices', DeviceInfo), )", ") INFO_CLASSES = { KeyClass: KeyInfo, ButtonClass: ButtonInfo, ValuatorClass: ValuatorInfo,", "DEVICEID('deviceid'), rq.LengthOf('modifiers', 2), rq.LengthOf('mask', 2), rq.Set('grab_type', 1, (GrabtypeButton, GrabtypeKeycode, GrabtypeEnter,", "ButtonState(rq.ValueField): structcode = None def __init__(self, name): rq.ValueField.__init__(self, name) def", "rq.String8('name', 4), rq.List('classes', ClassInfo), ) class XIQueryDevice(rq.ReplyRequest): _request = rq.Struct(", "# Xlib.ext.xinput -- XInput extension module # # Copyright (C)", "2) SlaveRemoved = (1 << 3) SlaveAttached = (1 <<", "= (1 << 3) SlaveAttached = (1 << 4) SlaveDetached", "float(integral) # optimised math.ldexp(float(frac), -32) ret += float(frac) * (1.0", "= 2 AsyncPairedDevice = 3 AsyncPair = 4 SyncPair =", ") def passive_grab_device(self, deviceid, time, detail, grab_type, grab_mode, paired_device_mode, owner_events,", "AnyButton = 0 AnyKeycode = 0 AsyncDevice = 0 SyncDevice", "can redistribute it and/or # modify it under the terms", "KeyRepeat = (1 << 16) AllDevices = 0 AllMasterDevices =", "rq.Window('event'), rq.Window('child'), FP1616('root_x'), FP1616('root_y'), FP1616('event_x'), FP1616('event_y'), rq.LengthOf('buttons', 2), rq.Card16('valulators_len'), DEVICEID('sourceid'),", "Python 2/3 compatibility. from six import integer_types from Xlib.protocol import", "ButtonState('state'), rq.List('labels', rq.Card32), ) KeyInfo = rq.Struct( rq.Card16('type'), rq.Card16('length'), rq.Card16('sourceid'),", "6 Enter = 7 Leave = 8 FocusIn = 9", "= rq.Card8 class FP1616(rq.Int32): def check_value(self, value): return int(value *", "rq.Struct( DEVICEID('deviceid'), rq.Card16('use'), rq.Card16('attachment'), rq.LengthOf('classes', 2), rq.LengthOf('name', 2), rq.Bool('enabled'), rq.Pad(1),", "your option) any later version. # # This library is", "value): return value def parse_value(self, value, display): integral, frac =", "def __init__(self, name): rq.List.__init__(self, name, rq.Card32, pad=0) def pack_value(self, val):", "def parse_value(self, value, display): return float(value) / float(1 << 16)", ") class XIQueryDevice(rq.ReplyRequest): _request = rq.Struct( rq.Card8('opcode'), rq.Opcode(48), rq.RequestLength(), DEVICEID('deviceid'),", "<< FocusOut) HierarchyChangedMask = (1 << HierarchyChanged) PropertyEventMask = (1", "rq.Pad(1), rq.String8('name', 4), rq.List('classes', ClassInfo), ) class XIQueryDevice(rq.ReplyRequest): _request =", "very incomplete implementation of the XInput extension. ''' import sys", "= 2 GrabtypeFocusIn = 3 GrabtypeTouchBegin = 4 AnyModifier =", "Temple Place, # Suite 330, # Boston, MA 02111-1307 USA", "= 2 ScrollClass = 3 TouchClass = 8 KeyRepeat =", "XIPassiveGrabDevice( display=self.display, opcode=self.display.get_extension_major(extname), deviceid=deviceid, grab_window=self, time=time, cursor=X.NONE, detail=detail, grab_type=grab_type, grab_mode=grab_mode,", "2), ButtonState('state'), rq.List('labels', rq.Card32), ) KeyInfo = rq.Struct( rq.Card16('type'), rq.Card16('length'),", "3) >> 2) mask_data = data[:mask_len] mask_value = 0 for", "rq.Card8('opcode'), rq.Opcode(52), rq.RequestLength(), rq.Card32('time'), DEVICEID('deviceid'), rq.Pad(2), ) def ungrab_device(self, deviceid,", "with a single unsigned 32-bit value, for which we construct", "rq.ReplyLength(), rq.Card8('status'), rq.Pad(23), ) def grab_device(self, deviceid, time, grab_mode, paired_device_mode,", "= rq.Struct( DEVICEID('deviceid'), rq.Card32('time'), rq.Card32('flags'), rq.LengthOf('info', 2), rq.Pad(10), rq.List('info', HierarchyInfo),", "= 2 def check_value(self, value): return value def parse_value(self, value,", "byte order across the entire set of values. if sys.byteorder", "structcode = None def parse_binary(self, data, display): class_type, length =", "1 DeviceChanged = 1 KeyPress = 2 KeyRelease = 3", "0 GrabtypeKeycode = 1 GrabtypeEnter = 2 GrabtypeFocusIn = 3", "rq.LengthOf('masks', 2), rq.Pad(2), rq.List('masks', EventMask), ) def select_events(self, event_masks): '''", "if not, write to the # Free Software Foundation, Inc.,", "KeyInfo = rq.Struct( rq.Card16('type'), rq.Card16('length'), rq.Card16('sourceid'), rq.LengthOf('keycodes', 2), rq.List('keycodes', rq.Card32),", "FP1616('event_y'), rq.LengthOf('buttons', 2), rq.Card16('valulators_len'), DEVICEID('sourceid'), rq.Pad(2), rq.Card32('flags'), rq.Object('mods', ModifierInfo), rq.Object('groups',", "TouchClass = 8 KeyRepeat = (1 << 16) AllDevices =", "RawKeyReleaseMask = (1 << RawKeyRelease) RawButtonPressMask = (1 << RawButtonPress)", "MasterRemoved = (1 << 1) SlaveAdded = (1 << 2)", "Motion): disp.ge_add_event_data(info.major_opcode, device_event, DeviceEventData) disp.ge_add_event_data(info.major_opcode, DeviceChanged, DeviceEventData) disp.ge_add_event_data(info.major_opcode, HierarchyChanged, HierarchyEventData)", "rq.Card32), ) ValuatorInfo = rq.Struct( rq.Card16('type'), rq.Card16('length'), rq.Card16('sourceid'), rq.Card16('number'), rq.Card32('label'),", "rq.Struct( rq.ReplyCode(), rq.Pad(1), rq.Card16('sequence_number'), rq.ReplyLength(), rq.Card8('status'), rq.Pad(23), ) def grab_device(self,", "modifiers=modifiers, ) def grab_keycode(self, deviceid, time, keycode, grab_mode, paired_device_mode, owner_events,", "1, length), data ButtonInfo = rq.Struct( rq.Card16('type'), rq.Card16('length'), rq.Card16('sourceid'), rq.LengthOf(('state',", "rq.LengthOf('mask', 2), Mask('mask'), ) _reply = rq.Struct( rq.ReplyCode(), rq.Pad(1), rq.Card16('sequence_number'),", "= val >> 32 else: mask_seq.extend(val) return mask_seq.tostring(), len(mask_seq), None", "class XISelectEvents(rq.Request): _request = rq.Struct( rq.Card8('opcode'), rq.Opcode(46), rq.RequestLength(), rq.Window('window'), rq.LengthOf('masks',", "and mask is either an unsigned integer or sequence of", "DeviceInfo = rq.Struct( DEVICEID('deviceid'), rq.Card16('use'), rq.Card16('attachment'), rq.LengthOf('classes', 2), rq.LengthOf('name', 2),", "rq.Opcode(55), rq.RequestLength(), rq.Window('grab_window'), rq.Card32('detail'), DEVICEID('deviceid'), rq.LengthOf('modifiers', 2), rq.Set('grab_type', 1, (GrabtypeButton,", "A very incomplete implementation of the XInput extension. ''' import", "= rq.Struct( DEVICE('deviceid'), rq.LengthOf('mask', 2), Mask('mask'), ) class XISelectEvents(rq.Request): _request", "paired_device_mode, owner_events, event_mask, modifiers) class XIPassiveUngrabDevice(rq.Request): _request = rq.Struct( rq.Card8('opcode'),", "display) data = data[length * 4:] return class_data, data ClassInfo", "# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # See", "GrabtypeKeycode = 1 GrabtypeEnter = 2 GrabtypeFocusIn = 3 GrabtypeTouchBegin", "def parse_binary(self, data, display): class_type, length = struct.unpack('=HH', data[:4]) class_struct", "/ float(1 << 16) class FP3232(rq.ValueField): structcode = 'lL' structvalues", "you can redistribute it and/or # modify it under the", "* (1.0 / (1 << 32)) return ret class XIQueryVersion(rq.ReplyRequest):", "-- XInput extension module # # Copyright (C) 2012 Outpost", "<< 3) SlaveAttached = (1 << 4) SlaveDetached = (1", "passive_grab_device(self, deviceid, time, keycode, GrabtypeKeycode, grab_mode, paired_device_mode, owner_events, event_mask, modifiers)", "rq.Card16('sourceid'), rq.Card16('number'), rq.Card32('label'), FP3232('min'), FP3232('max'), FP3232('value'), rq.Card32('resolution'), rq.Card8('mode'), rq.Pad(3), )", "along with this library; if not, write to the #", "2.1 # of the License, or (at your option) any", "SlaveDetached = (1 << 5) DeviceEnabled = (1 << 6)", "ID, or AllDevices or AllMasterDevices, and mask is either an", "rq.Struct( DEVICEID('deviceid'), DEVICEID('attachment'), DEVICEUSE('type'), rq.Bool('enabled'), rq.Pad(2), rq.Card32('flags'), ) HierarchyEventData =", "= (1 << 1) SlaveAdded = (1 << 2) SlaveRemoved", "ret += float(frac) * (1.0 / (1 << 32)) return", "= (1 << FocusOut) HierarchyChangedMask = (1 << HierarchyChanged) PropertyEventMask", "AnyInfo = rq.Struct( rq.Card16('type'), rq.Card16('length'), rq.Card16('sourceid'), rq.Pad(2), ) class ButtonMask(object):", "General Public License for more details. # # You should", "11 PropertyEvent = 12 RawKeyPress = 13 RawKeyRelease = 14", "GNU Lesser General Public License # as published by the", "rq.Struct( rq.ReplyCode(), rq.Pad(1), rq.Card16('sequence_number'), rq.ReplyLength(), rq.Card16('major_version'), rq.Card16('minor_version'), rq.Pad(20), ) def", "ScrollClass = 3 TouchClass = 8 KeyRepeat = (1 <<", "even the implied warranty of # MERCHANTABILITY or FITNESS FOR", "to fit inside 4 # bytes we build a longer", "pad=0) def pack_value(self, val): mask_seq = array.array(rq.struct_to_array_codes['L']) if isinstance(val, integer_types):", "_request = rq.Struct( rq.Card8('opcode'), rq.Opcode(51), rq.RequestLength(), rq.Window('grab_window'), rq.Card32('time'), rq.Cursor('cursor', (X.NONE,", "Mask('mask'), ) class XISelectEvents(rq.Request): _request = rq.Struct( rq.Card8('opcode'), rq.Opcode(46), rq.RequestLength(),", "data, display): class_type, length = struct.unpack('=HH', data[:4]) class_struct = INFO_CLASSES.get(class_type,", "= 2 NotifyWhileGrabbed = 3 NotifyPassiveGrab = 4 NotifyPassiveUngrab =", "repr(self) def __repr__(self): return '0b{value:0{width}b}'.format(value=self._value, width=self._length) class ButtonState(rq.ValueField): structcode =", "= 2 AttachSlave = 3 DetachSlave = 4 AttachToMaster =", "DEVICEID = rq.Card16 DEVICE = rq.Card16 DEVICEUSE = rq.Card8 class", "& 0xFFFFFFFF) val = val >> 32 else: mask_seq.extend(val) return", "DEVICEID('attachment'), DEVICEUSE('type'), rq.Bool('enabled'), rq.Pad(2), rq.Card32('flags'), ) HierarchyEventData = rq.Struct( DEVICEID('deviceid'),", "rq.Card32('time'), rq.Card32('detail'), rq.Window('root'), rq.Window('event'), rq.Window('child'), FP1616('root_x'), FP1616('root_y'), FP1616('event_x'), FP1616('event_y'), rq.LengthOf('buttons',", "_request = rq.Struct( rq.Card8('opcode'), rq.Opcode(54), rq.RequestLength(), rq.Card32('time'), rq.Window('grab_window'), rq.Cursor('cursor', (X.NONE,", "1 NotifyUngrab = 2 NotifyWhileGrabbed = 3 NotifyPassiveGrab = 4", "paired_device_mode=paired_device_mode, owner_events=owner_events, mask=event_mask, ) class XIUngrabDevice(rq.Request): _request = rq.Struct( rq.Card8('opcode'),", "rq.Bool('owner_events'), rq.Pad(2), Mask('mask'), rq.List('modifiers', rq.Card32), ) _reply = rq.Struct( rq.ReplyCode(),", "tell) is # encoded in native byte order from end", "MasterAdded = (1 << 0) MasterRemoved = (1 << 1)", "deviceid, time, grab_mode, paired_device_mode, owner_events, event_mask): return XIGrabDevice( display=self.display, opcode=self.display.get_extension_major(extname),", "<< RawKeyPress) RawKeyReleaseMask = (1 << RawKeyRelease) RawButtonPressMask = (1", "= 3 TouchClass = 8 KeyRepeat = (1 << 16)", "ScrollInfo, TouchClass: TouchInfo, } class ClassInfoClass(object): structcode = None def", "have received a copy of the GNU Lesser General Public", "-32) ret += float(frac) * (1.0 / (1 << 32))", "rq.Card32('time'), rq.Window('grab_window'), rq.Cursor('cursor', (X.NONE, )), rq.Card32('detail'), DEVICEID('deviceid'), rq.LengthOf('modifiers', 2), rq.LengthOf('mask',", "ScrollInfo = rq.Struct( rq.Card16('type'), rq.Card16('length'), rq.Card16('sourceid'), rq.Card16('number'), rq.Card16('scroll_type'), rq.Pad(2), rq.Card32('flags'),", "ReplayDevice = 2 AsyncPairedDevice = 3 AsyncPair = 4 SyncPair", "mask=event_mask, modifiers=modifiers, ) def grab_keycode(self, deviceid, time, keycode, grab_mode, paired_device_mode,", ") def select_events(self, event_masks): ''' select_events(event_masks) event_masks: Sequence of (deviceid,", "GrabtypeFocusIn = 3 GrabtypeTouchBegin = 4 AnyModifier = (1 <<", "= 'XInputExtension' PropertyDeleted = 0 PropertyCreated = 1 PropertyModified =", "(1 << key) def __str__(self): return repr(self) def __repr__(self): return", "(X.NONE, )), rq.Card32('detail'), DEVICEID('deviceid'), rq.LengthOf('modifiers', 2), rq.LengthOf('mask', 2), rq.Set('grab_type', 1,", "= 2 NotifyNonlinear = 3 NotifyNonlinearVirtual = 4 NotifyPointer =", "rq.Pad(1), rq.LengthOf('mask', 2), Mask('mask'), ) _reply = rq.Struct( rq.ReplyCode(), rq.Pad(1),", "mask_value <<= 8 mask_value |= byte data = data[mask_len:] assert", "(C) 2012 Outpost Embedded, LLC # <NAME> <<EMAIL>> # #", "__init__(self, value, length): self._value = value self._length = length def", "+= float(frac) * (1.0 / (1 << 32)) return ret", "(X.NONE, )), DEVICEID('deviceid'), rq.Set('grab_mode', 1, (GrabModeSync, GrabModeAsync)), rq.Set('paired_device_mode', 1, (GrabModeSync,", "name): rq.List.__init__(self, name, rq.Card32, pad=0) def pack_value(self, val): mask_seq =", "rq.Card32('time'), rq.Cursor('cursor', (X.NONE, )), DEVICEID('deviceid'), rq.Set('grab_mode', 1, (GrabModeSync, GrabModeAsync)), rq.Set('paired_device_mode',", "modify it under the terms of the GNU Lesser General", "event_mask, modifiers): return passive_grab_device(self, deviceid, time, keycode, GrabtypeKeycode, grab_mode, paired_device_mode,", "'big': fun = mask_seq.append else: raise AssertionError(sys.byteorder) while val: fun(val", "= 5 NotifyPointerRoot = 6 NotifyDetailNone = 7 GrabtypeButton =", "class ButtonState(rq.ValueField): structcode = None def __init__(self, name): rq.ValueField.__init__(self, name)", "grab_device) disp.extension_add_method('display', 'xinput_ungrab_device', ungrab_device) disp.extension_add_method('window', 'xinput_grab_keycode', grab_keycode) disp.extension_add_method('window', 'xinput_ungrab_keycode', ungrab_keycode)", "value def parse_value(self, value, display): integral, frac = value ret", "query_version) disp.extension_add_method('window', 'xinput_select_events', select_events) disp.extension_add_method('display', 'xinput_query_device', query_device) disp.extension_add_method('window', 'xinput_grab_device', grab_device)", "library is free software; you can redistribute it and/or #", "display, length, fmt): # Mask: bitfield of <length> button states.", "mask_seq.insert(0, val) elif sys.byteorder == 'big': fun = mask_seq.append else:", "1 NotifyInferior = 2 NotifyNonlinear = 3 NotifyNonlinearVirtual = 4", "disp.extension_add_method('display', 'xinput_query_version', query_version) disp.extension_add_method('window', 'xinput_select_events', select_events) disp.extension_add_method('display', 'xinput_query_device', query_device) disp.extension_add_method('window',", "from six import integer_types from Xlib.protocol import rq from Xlib", "= 5 Motion = 6 Enter = 7 Leave =", "def __str__(self): return repr(self) def __repr__(self): return '0b{value:0{width}b}'.format(value=self._value, width=self._length) class", "import array import struct # Python 2/3 compatibility. from six", "the Free Software Foundation; either version 2.1 # of the", "RawButtonPress) RawButtonReleaseMask = (1 << RawButtonRelease) RawMotionMask = (1 <<", "2), Mask('mask'), ) _reply = rq.Struct( rq.ReplyCode(), rq.Pad(1), rq.Card16('sequence_number'), rq.ReplyLength(),", "modifiers): return passive_grab_device(self, deviceid, time, keycode, GrabtypeKeycode, grab_mode, paired_device_mode, owner_events,", "rq.Card16('number'), rq.Card32('label'), FP3232('min'), FP3232('max'), FP3232('value'), rq.Card32('resolution'), rq.Card8('mode'), rq.Pad(3), ) ScrollInfo", "rq.LengthOf('devices', 2), rq.Pad(22), rq.List('devices', DeviceInfo), ) def query_device(self, deviceid): return", "unsigned 32-bit value, for which we construct an # array", "def init(disp, info): disp.extension_add_method('display', 'xinput_query_version', query_version) disp.extension_add_method('window', 'xinput_select_events', select_events) disp.extension_add_method('display',", "= rq.Struct( rq.Card8('opcode'), rq.Opcode(52), rq.RequestLength(), rq.Card32('time'), DEVICEID('deviceid'), rq.Pad(2), ) def", "<< KeyRelease) ButtonPressMask = (1 << ButtonPress) ButtonReleaseMask = (1", "# modify it under the terms of the GNU Lesser", "KeyReleaseMask = (1 << KeyRelease) ButtonPressMask = (1 << ButtonPress)", "License along with this library; if not, write to the", "ungrab_device) disp.extension_add_method('window', 'xinput_grab_keycode', grab_keycode) disp.extension_add_method('window', 'xinput_ungrab_keycode', ungrab_keycode) if hasattr(disp,\"ge_add_event_data\"): for", ") KeyInfo = rq.Struct( rq.Card16('type'), rq.Card16('length'), rq.Card16('sourceid'), rq.LengthOf('keycodes', 2), rq.List('keycodes',", "return ButtonMask(mask_value >> 1, length), data ButtonInfo = rq.Struct( rq.Card16('type'),", "= 1 Floating = 2 ModeRelative = 0 ModeAbsolute =", "class ClassInfoClass(object): structcode = None def parse_binary(self, data, display): class_type,", "compatibility. from six import integer_types from Xlib.protocol import rq from", "rq.Card16('sequence_number'), rq.ReplyLength(), rq.Card16('major_version'), rq.Card16('minor_version'), rq.Pad(20), ) def query_version(self): return XIQueryVersion(", "XInput extension module # # Copyright (C) 2012 Outpost Embedded,", "isinstance(val, integer_types): # We need to build a \"binary mask\"", "# Free Software Foundation, Inc., # 59 Temple Place, #", "MasterKeyboard = 2 SlavePointer = 3 SlaveKeyboard = 4 FloatingSlave", "GrabtypeTouchBegin)), rq.Pad(3), rq.List('modifiers', rq.Card32), ) def passive_ungrab_device(self, deviceid, detail, grab_type,", "RawMotionMask = (1 << RawMotion) GrabModeSync = 0 GrabModeAsync =", "__init__(self, name): rq.List.__init__(self, name, rq.Card32, pad=0) def pack_value(self, val): mask_seq", "def select_events(self, event_masks): ''' select_events(event_masks) event_masks: Sequence of (deviceid, mask)", "Copyright (C) 2012 Outpost Embedded, LLC # <NAME> <<EMAIL>> #", "USA ''' A very incomplete implementation of the XInput extension.", "= (1 << 0) MasterRemoved = (1 << 1) SlaveAdded", "= 0 GrabtypeKeycode = 1 GrabtypeEnter = 2 GrabtypeFocusIn =", "deviceid, keycode, GrabtypeKeycode, modifiers) HierarchyInfo = rq.Struct( DEVICEID('deviceid'), DEVICEID('attachment'), DEVICEUSE('type'),", "= (1 << ButtonPress) ButtonReleaseMask = (1 << ButtonRelease) MotionMask", "rq.Struct( rq.Card16('type'), rq.Card16('length'), rq.Card16('sourceid'), rq.LengthOf(('state', 'labels'), 2), ButtonState('state'), rq.List('labels', rq.Card32),", "FocusIn = 9 FocusOut = 10 HierarchyChanged = 11 PropertyEvent", "(1 << DeviceChanged) KeyPressMask = (1 << KeyPress) KeyReleaseMask =", "<< PropertyEvent) RawKeyPressMask = (1 << RawKeyPress) RawKeyReleaseMask = (1", "rq.ValueField.__init__(self, name) def parse_binary_value(self, data, display, length, fmt): # Mask:", "rq.List('info', HierarchyInfo), ) ModifierInfo = rq.Struct( rq.Card32('base_mods'), rq.Card32('latched_mods'), rq.Card32('locked_mods'), rq.Card32('effective_mods'),", "= rq.Struct( rq.ReplyCode(), rq.Pad(1), rq.Card16('sequence_number'), rq.ReplyLength(), rq.Card8('status'), rq.Pad(23), ) def", "2), DEVICEID('sourceid'), rq.Card8('reason'), rq.Pad(11), rq.List('classes', ClassInfo), ) def init(disp, info):", "rq.Card8('base_group'), rq.Card8('latched_group'), rq.Card8('locked_group'), rq.Card8('effective_group'), ) DeviceEventData = rq.Struct( DEVICEID('deviceid'), rq.Card32('time'),", "GrabtypeEnter = 2 GrabtypeFocusIn = 3 GrabtypeTouchBegin = 4 AnyModifier", "owner_events, event_mask): return XIGrabDevice( display=self.display, opcode=self.display.get_extension_major(extname), deviceid=deviceid, grab_window=self, time=time, cursor=X.NONE,", "passive_grab_device(self, deviceid, time, detail, grab_type, grab_mode, paired_device_mode, owner_events, event_mask, modifiers):", "3 ButtonPress = 4 ButtonRelease = 5 Motion = 6", "class_data, _ = class_struct.parse_binary(data, display) data = data[length * 4:]", "display=self.display, opcode=self.display.get_extension_major(extname), deviceid=deviceid, grab_window=self, time=time, cursor=X.NONE, grab_mode=grab_mode, paired_device_mode=paired_device_mode, owner_events=owner_events, mask=event_mask,", "of the GNU Lesser General Public # License along with", "None def __init__(self, name): rq.ValueField.__init__(self, name) def parse_binary_value(self, data, display,", "(1 << 32)) return ret class XIQueryVersion(rq.ReplyRequest): _request = rq.Struct(", "GrabtypeKeycode, GrabtypeEnter, GrabtypeFocusIn, GrabtypeTouchBegin)), rq.Pad(3), rq.List('modifiers', rq.Card32), ) def passive_ungrab_device(self,", "For values too big to fit inside 4 # bytes", "array, being careful to maintain native # byte order across", "0 AllMasterDevices = 1 DeviceChanged = 1 KeyPress = 2", ") HierarchyEventData = rq.Struct( DEVICEID('deviceid'), rq.Card32('time'), rq.Card32('flags'), rq.LengthOf('info', 2), rq.Pad(10),", "it will be useful, # but WITHOUT ANY WARRANTY; without", "'XInputExtension' PropertyDeleted = 0 PropertyCreated = 1 PropertyModified = 2", "event_masks: Sequence of (deviceid, mask) pairs, where deviceid is a", "mask\" that (as far as I can tell) is #", "NotifyAncestor = 0 NotifyVirtual = 1 NotifyInferior = 2 NotifyNonlinear", "= rq.Struct( rq.Card8('opcode'), rq.Opcode(47), rq.RequestLength(), rq.Card16('major_version'), rq.Card16('minor_version'), ) _reply =", "return XISelectEvents( display=self.display, opcode=self.display.get_extension_major(extname), window=self, masks=event_masks, ) AnyInfo = rq.Struct(", "is # encoded in native byte order from end to", "SlavePointer = 3 SlaveKeyboard = 4 FloatingSlave = 5 KeyClass", "hope that it will be useful, # but WITHOUT ANY", "DeviceChangedEventData = rq.Struct( DEVICEID('deviceid'), rq.Card32('time'), rq.LengthOf('classes', 2), DEVICEID('sourceid'), rq.Card8('reason'), rq.Pad(11),", "Inc., # 59 Temple Place, # Suite 330, # Boston,", "rq.Pad(2), ) def ungrab_device(self, deviceid, time): return XIUngrabDevice( display=self.display, opcode=self.display.get_extension_major(extname),", "for byte in reversed(struct.unpack('={0:d}B'.format(mask_len), mask_data)): mask_value <<= 8 mask_value |=", "keycode, grab_mode, paired_device_mode, owner_events, event_mask, modifiers): return passive_grab_device(self, deviceid, time,", "GrabModeAsync)), rq.Bool('owner_events'), rq.Pad(2), Mask('mask'), rq.List('modifiers', rq.Card32), ) _reply = rq.Struct(", "the License, or (at your option) any later version. #", "name): rq.ValueField.__init__(self, name) def parse_binary_value(self, data, display, length, fmt): #", "frac = value ret = float(integral) # optimised math.ldexp(float(frac), -32)", "opcode=self.display.get_extension_major(extname), deviceid=deviceid, grab_window=self, time=time, cursor=X.NONE, grab_mode=grab_mode, paired_device_mode=paired_device_mode, owner_events=owner_events, mask=event_mask, )", "Software Foundation; either version 2.1 # of the License, or", "rq.Struct( rq.Card16('type'), rq.Card16('length'), rq.Card16('sourceid'), rq.LengthOf('keycodes', 2), rq.List('keycodes', rq.Card32), ) ValuatorInfo", "7) AddMaster = 1 RemoveMaster = 2 AttachSlave = 3", "deviceid): return XIQueryDevice( display=self.display, opcode=self.display.get_extension_major(extname), deviceid=deviceid, ) class XIGrabDevice(rq.ReplyRequest): _request", "ModeRelative = 0 ModeAbsolute = 1 MasterPointer = 1 MasterKeyboard", "XIQueryDevice( display=self.display, opcode=self.display.get_extension_major(extname), deviceid=deviceid, ) class XIGrabDevice(rq.ReplyRequest): _request = rq.Struct(", "330, # Boston, MA 02111-1307 USA ''' A very incomplete", "init(disp, info): disp.extension_add_method('display', 'xinput_query_version', query_version) disp.extension_add_method('window', 'xinput_select_events', select_events) disp.extension_add_method('display', 'xinput_query_device',", "GrabtypeTouchBegin)), rq.Set('grab_mode', 1, (GrabModeSync, GrabModeAsync)), rq.Set('paired_device_mode', 1, (GrabModeSync, GrabModeAsync)), rq.Bool('owner_events'),", "or AllMasterDevices, and mask is either an unsigned integer or", "class FP3232(rq.ValueField): structcode = 'lL' structvalues = 2 def check_value(self,", "ClassInfoClass(object): structcode = None def parse_binary(self, data, display): class_type, length", "2), rq.Pad(22), rq.List('devices', DeviceInfo), ) def query_device(self, deviceid): return XIQueryDevice(", "with just one item. For values too big to fit", "rq.Window('grab_window'), rq.Card32('time'), rq.Cursor('cursor', (X.NONE, )), DEVICEID('deviceid'), rq.Set('grab_mode', 1, (GrabModeSync, GrabModeAsync)),", "= 1 RemoveMaster = 2 AttachSlave = 3 DetachSlave =", "val: fun(val & 0xFFFFFFFF) val = val >> 32 else:", "1 GrabtypeEnter = 2 GrabtypeFocusIn = 3 GrabtypeTouchBegin = 4", "def passive_ungrab_device(self, deviceid, detail, grab_type, modifiers): return XIPassiveUngrabDevice( display=self.display, opcode=self.display.get_extension_major(extname),", "rq.Card16('type'), rq.Card16('length'), rq.Card16('sourceid'), rq.Card8('mode'), rq.Card8('num_touches'), ) INFO_CLASSES = { KeyClass:", "set of values. if sys.byteorder == 'little': def fun(val): mask_seq.insert(0,", "published by the Free Software Foundation; either version 2.1 #", "is free software; you can redistribute it and/or # modify", "rq.List.__init__(self, name, rq.Card32, pad=0) def pack_value(self, val): mask_seq = array.array(rq.struct_to_array_codes['L'])", "1, (GrabModeSync, GrabModeAsync)), rq.Set('paired_device_mode', 1, (GrabModeSync, GrabModeAsync)), rq.Bool('owner_events'), rq.Pad(2), Mask('mask'),", "KeyClass: KeyInfo, ButtonClass: ButtonInfo, ValuatorClass: ValuatorInfo, ScrollClass: ScrollInfo, TouchClass: TouchInfo,", "six import integer_types from Xlib.protocol import rq from Xlib import", "5 NotifyAncestor = 0 NotifyVirtual = 1 NotifyInferior = 2", "values. if sys.byteorder == 'little': def fun(val): mask_seq.insert(0, val) elif", "grab_type, grab_mode, paired_device_mode, owner_events, event_mask, modifiers): return XIPassiveGrabDevice( display=self.display, opcode=self.display.get_extension_major(extname),", "<< Motion) EnterMask = (1 << Enter) LeaveMask = (1", "disp.extension_add_method('display', 'xinput_ungrab_device', ungrab_device) disp.extension_add_method('window', 'xinput_grab_keycode', grab_keycode) disp.extension_add_method('window', 'xinput_ungrab_keycode', ungrab_keycode) if", "the hope that it will be useful, # but WITHOUT", "import X extname = 'XInputExtension' PropertyDeleted = 0 PropertyCreated =", "self._value & (1 << key) def __str__(self): return repr(self) def", "RawKeyRelease) RawButtonPressMask = (1 << RawButtonPress) RawButtonReleaseMask = (1 <<", "sys import array import struct # Python 2/3 compatibility. from", "extname = 'XInputExtension' PropertyDeleted = 0 PropertyCreated = 1 PropertyModified", "31) AnyButton = 0 AnyKeycode = 0 AsyncDevice = 0", "EnterMask = (1 << Enter) LeaveMask = (1 << Leave)", "DeviceChanged) KeyPressMask = (1 << KeyPress) KeyReleaseMask = (1 <<", "grab_mode, paired_device_mode, owner_events, event_mask, modifiers) class XIPassiveUngrabDevice(rq.Request): _request = rq.Struct(", "= 6 Enter = 7 Leave = 8 FocusIn =", "or FITNESS FOR A PARTICULAR PURPOSE. # See the GNU", "inside 4 # bytes we build a longer array, being", "display=self.display, opcode=self.display.get_extension_major(extname), deviceid=deviceid, grab_window=self, detail=detail, grab_type=grab_type, modifiers=modifiers, ) def ungrab_keycode(self,", "rq.Card32('base_mods'), rq.Card32('latched_mods'), rq.Card32('locked_mods'), rq.Card32('effective_mods'), ) GroupInfo = rq.Struct( rq.Card8('base_group'), rq.Card8('latched_group'),", "FOR A PARTICULAR PURPOSE. # See the GNU Lesser General", "KeyRelease = 3 ButtonPress = 4 ButtonRelease = 5 Motion", "2), rq.LengthOf('name', 2), rq.Bool('enabled'), rq.Pad(1), rq.String8('name', 4), rq.List('classes', ClassInfo), )", "struct # Python 2/3 compatibility. from six import integer_types from", "Xlib.ext.xinput -- XInput extension module # # Copyright (C) 2012", "def fun(val): mask_seq.insert(0, val) elif sys.byteorder == 'big': fun =", "DeviceChange = 2 MasterAdded = (1 << 0) MasterRemoved =", "rq.Struct( rq.ReplyCode(), rq.Pad(1), rq.Card16('sequence_number'), rq.ReplyLength(), rq.LengthOf('devices', 2), rq.Pad(22), rq.List('devices', DeviceInfo),", "not, write to the # Free Software Foundation, Inc., #", "time, grab_mode, paired_device_mode, owner_events, event_mask): return XIGrabDevice( display=self.display, opcode=self.display.get_extension_major(extname), deviceid=deviceid,", "deviceid, time, keycode, grab_mode, paired_device_mode, owner_events, event_mask, modifiers): return passive_grab_device(self,", "rq.Pad(2), rq.Card32('flags'), FP3232('increment'), ) TouchInfo = rq.Struct( rq.Card16('type'), rq.Card16('length'), rq.Card16('sourceid'),", "INFO_CLASSES.get(class_type, AnyInfo) class_data, _ = class_struct.parse_binary(data, display) data = data[length", "class XIPassiveGrabDevice(rq.ReplyRequest): _request = rq.Struct( rq.Card8('opcode'), rq.Opcode(54), rq.RequestLength(), rq.Card32('time'), rq.Window('grab_window'),", "= rq.Struct( rq.Card16('type'), rq.Card16('length'), rq.Card16('sourceid'), rq.Card8('mode'), rq.Card8('num_touches'), ) INFO_CLASSES =", "distributed in the hope that it will be useful, #", "rq.Card32('detail'), DEVICEID('deviceid'), rq.LengthOf('modifiers', 2), rq.LengthOf('mask', 2), rq.Set('grab_type', 1, (GrabtypeButton, GrabtypeKeycode,", "Suite 330, # Boston, MA 02111-1307 USA ''' A very", "rq.List('keycodes', rq.Card32), ) ValuatorInfo = rq.Struct( rq.Card16('type'), rq.Card16('length'), rq.Card16('sourceid'), rq.Card16('number'),", "rq.ReplyLength(), rq.Card16('major_version'), rq.Card16('minor_version'), rq.Pad(20), ) def query_version(self): return XIQueryVersion( display=self.display,", "2 DEVICEID = rq.Card16 DEVICE = rq.Card16 DEVICEUSE = rq.Card8", "1 ReplayDevice = 2 AsyncPairedDevice = 3 AsyncPair = 4", "as published by the Free Software Foundation; either version 2.1", "rq.Struct( rq.Card8('opcode'), rq.Opcode(48), rq.RequestLength(), DEVICEID('deviceid'), rq.Pad(2), ) _reply = rq.Struct(", "DEVICE = rq.Card16 DEVICEUSE = rq.Card8 class FP1616(rq.Int32): def check_value(self,", "float(frac) * (1.0 / (1 << 32)) return ret class", "Foundation, Inc., # 59 Temple Place, # Suite 330, #", "structcode = 'lL' structvalues = 2 def check_value(self, value): return", "we build a longer array, being careful to maintain native", ") TouchInfo = rq.Struct( rq.Card16('type'), rq.Card16('length'), rq.Card16('sourceid'), rq.Card8('mode'), rq.Card8('num_touches'), )", "= array.array(rq.struct_to_array_codes['L']) if isinstance(val, integer_types): # We need to build", "structcode = None def __init__(self, name): rq.ValueField.__init__(self, name) def parse_binary_value(self,", "= 17 DeviceChangedMask = (1 << DeviceChanged) KeyPressMask = (1", "GrabtypeButton = 0 GrabtypeKeycode = 1 GrabtypeEnter = 2 GrabtypeFocusIn", "FP3232(rq.ValueField): structcode = 'lL' structvalues = 2 def check_value(self, value):", "Lesser General Public License for more details. # # You", "def check_value(self, value): return value def parse_value(self, value, display): integral,", "AsyncPair = 4 SyncPair = 5 SlaveSwitch = 1 DeviceChange", "rq.Card8('opcode'), rq.Opcode(48), rq.RequestLength(), DEVICEID('deviceid'), rq.Pad(2), ) _reply = rq.Struct( rq.ReplyCode(),", "paired_device_mode, owner_events, event_mask, modifiers): return passive_grab_device(self, deviceid, time, keycode, GrabtypeKeycode,", "ModeAbsolute = 1 MasterPointer = 1 MasterKeyboard = 2 SlavePointer", "display): return float(value) / float(1 << 16) class FP3232(rq.ValueField): structcode", "FP1616('root_y'), FP1616('event_x'), FP1616('event_y'), rq.LengthOf('buttons', 2), rq.Card16('valulators_len'), DEVICEID('sourceid'), rq.Pad(2), rq.Card32('flags'), rq.Object('mods',", "KeyRelease) ButtonPressMask = (1 << ButtonPress) ButtonReleaseMask = (1 <<", "= rq.Struct( rq.Card16('type'), rq.Card16('length'), rq.Card16('sourceid'), rq.Card16('number'), rq.Card16('scroll_type'), rq.Pad(2), rq.Card32('flags'), FP3232('increment'),", "7 GrabtypeButton = 0 GrabtypeKeycode = 1 GrabtypeEnter = 2", "rq.Card32('flags'), FP3232('increment'), ) TouchInfo = rq.Struct( rq.Card16('type'), rq.Card16('length'), rq.Card16('sourceid'), rq.Card8('mode'),", "of 32 bits unsigned values ''' return XISelectEvents( display=self.display, opcode=self.display.get_extension_major(extname),", "HierarchyChangedMask = (1 << HierarchyChanged) PropertyEventMask = (1 << PropertyEvent)", "mask_value = 0 for byte in reversed(struct.unpack('={0:d}B'.format(mask_len), mask_data)): mask_value <<=", "the GNU Lesser General Public License # as published by", "as I can tell) is # encoded in native byte", "INFO_CLASSES = { KeyClass: KeyInfo, ButtonClass: ButtonInfo, ValuatorClass: ValuatorInfo, ScrollClass:", "FocusOutMask = (1 << FocusOut) HierarchyChangedMask = (1 << HierarchyChanged)", "construct an # array with just one item. For values", "rq.Card16('sourceid'), rq.LengthOf(('state', 'labels'), 2), ButtonState('state'), rq.List('labels', rq.Card32), ) KeyInfo =", "} class ClassInfoClass(object): structcode = None def parse_binary(self, data, display):", "<< Enter) LeaveMask = (1 << Leave) FocusInMask = (1", "= None def __init__(self, name): rq.ValueField.__init__(self, name) def parse_binary_value(self, data,", "rq.Card16('attachment'), rq.LengthOf('classes', 2), rq.LengthOf('name', 2), rq.Bool('enabled'), rq.Pad(1), rq.String8('name', 4), rq.List('classes',", "terms of the GNU Lesser General Public License # as", "AsyncDevice = 0 SyncDevice = 1 ReplayDevice = 2 AsyncPairedDevice", "rq.Card16('sourceid'), rq.Pad(2), ) class ButtonMask(object): def __init__(self, value, length): self._value", "(GrabModeSync, GrabModeAsync)), rq.Set('paired_device_mode', 1, (GrabModeSync, GrabModeAsync)), rq.Bool('owner_events'), rq.Pad(1), rq.LengthOf('mask', 2),", "hasattr(disp,\"ge_add_event_data\"): for device_event in (ButtonPress, ButtonRelease, KeyPress, KeyRelease, Motion): disp.ge_add_event_data(info.major_opcode,", "mask_seq.tostring(), len(mask_seq), None EventMask = rq.Struct( DEVICE('deviceid'), rq.LengthOf('mask', 2), Mask('mask'),", "DeviceDisabled = (1 << 7) AddMaster = 1 RemoveMaster =", "EventMask), ) def select_events(self, event_masks): ''' select_events(event_masks) event_masks: Sequence of", "= 4 * ((((length + 7) >> 3) + 3)", "byte data = data[mask_len:] assert (mask_value & 1) == 0", "either an unsigned integer or sequence of 32 bits unsigned", "(GrabModeSync, GrabModeAsync)), rq.Set('paired_device_mode', 1, (GrabModeSync, GrabModeAsync)), rq.Bool('owner_events'), rq.Pad(2), Mask('mask'), rq.List('modifiers',", "rq.Card32('time'), rq.LengthOf('classes', 2), DEVICEID('sourceid'), rq.Card8('reason'), rq.Pad(11), rq.List('classes', ClassInfo), ) def", "ValuatorClass: ValuatorInfo, ScrollClass: ScrollInfo, TouchClass: TouchInfo, } class ClassInfoClass(object): structcode", ") ModifierInfo = rq.Struct( rq.Card32('base_mods'), rq.Card32('latched_mods'), rq.Card32('locked_mods'), rq.Card32('effective_mods'), ) GroupInfo", "being careful to maintain native # byte order across the", "59 Temple Place, # Suite 330, # Boston, MA 02111-1307", "= (1 << KeyPress) KeyReleaseMask = (1 << KeyRelease) ButtonPressMask", "time, keycode, GrabtypeKeycode, grab_mode, paired_device_mode, owner_events, event_mask, modifiers) class XIPassiveUngrabDevice(rq.Request):", "return value def parse_value(self, value, display): integral, frac = value", ") DeviceChangedEventData = rq.Struct( DEVICEID('deviceid'), rq.Card32('time'), rq.LengthOf('classes', 2), DEVICEID('sourceid'), rq.Card8('reason'),", "return self._length def __getitem__(self, key): return self._value & (1 <<", "data, display, length, fmt): # Mask: bitfield of <length> button", "GNU Lesser General Public License for more details. # #", "2), rq.Pad(2), rq.List('masks', EventMask), ) def select_events(self, event_masks): ''' select_events(event_masks)", "LLC # <NAME> <<EMAIL>> # # This library is free", "# This library is free software; you can redistribute it", "ValuatorInfo, ScrollClass: ScrollInfo, TouchClass: TouchInfo, } class ClassInfoClass(object): structcode =", "fun(val): mask_seq.insert(0, val) elif sys.byteorder == 'big': fun = mask_seq.append", "DeviceEventData = rq.Struct( DEVICEID('deviceid'), rq.Card32('time'), rq.Card32('detail'), rq.Window('root'), rq.Window('event'), rq.Window('child'), FP1616('root_x'),", "else: mask_seq.extend(val) return mask_seq.tostring(), len(mask_seq), None EventMask = rq.Struct( DEVICE('deviceid'),", "= 1 ReplayDevice = 2 AsyncPairedDevice = 3 AsyncPair =", "detail, grab_type, modifiers): return XIPassiveUngrabDevice( display=self.display, opcode=self.display.get_extension_major(extname), deviceid=deviceid, grab_window=self, detail=detail,", "rq.List('modifiers', rq.Card32), ) def passive_grab_device(self, deviceid, time, detail, grab_type, grab_mode,", "time=time, cursor=X.NONE, grab_mode=grab_mode, paired_device_mode=paired_device_mode, owner_events=owner_events, mask=event_mask, ) class XIUngrabDevice(rq.Request): _request", "(mask_value & 1) == 0 return ButtonMask(mask_value >> 1, length),", "rq.Card8 class FP1616(rq.Int32): def check_value(self, value): return int(value * 65536.0)", "= rq.Struct( DEVICEID('deviceid'), DEVICEID('attachment'), DEVICEUSE('type'), rq.Bool('enabled'), rq.Pad(2), rq.Card32('flags'), ) HierarchyEventData", "def passive_grab_device(self, deviceid, time, detail, grab_type, grab_mode, paired_device_mode, owner_events, event_mask,", "grab_keycode) disp.extension_add_method('window', 'xinput_ungrab_keycode', ungrab_keycode) if hasattr(disp,\"ge_add_event_data\"): for device_event in (ButtonPress,", "& (1 << key) def __str__(self): return repr(self) def __repr__(self):", "5 KeyClass = 0 ButtonClass = 1 ValuatorClass = 2", "array.array(rq.struct_to_array_codes['L']) if isinstance(val, integer_types): # We need to build a", "rq.LengthOf('info', 2), rq.Pad(10), rq.List('info', HierarchyInfo), ) ModifierInfo = rq.Struct( rq.Card32('base_mods'),", "numerical device ID, or AllDevices or AllMasterDevices, and mask is", "= 1 MasterKeyboard = 2 SlavePointer = 3 SlaveKeyboard =", "rq.Card16('minor_version'), ) _reply = rq.Struct( rq.ReplyCode(), rq.Pad(1), rq.Card16('sequence_number'), rq.ReplyLength(), rq.Card16('major_version'),", "sys.byteorder == 'little': def fun(val): mask_seq.insert(0, val) elif sys.byteorder ==", "rq.Cursor('cursor', (X.NONE, )), rq.Card32('detail'), DEVICEID('deviceid'), rq.LengthOf('modifiers', 2), rq.LengthOf('mask', 2), rq.Set('grab_type',", "_request = rq.Struct( rq.Card8('opcode'), rq.Opcode(48), rq.RequestLength(), DEVICEID('deviceid'), rq.Pad(2), ) _reply", "= 2 ModeRelative = 0 ModeAbsolute = 1 MasterPointer =", "_reply = rq.Struct( rq.ReplyCode(), rq.Pad(1), rq.Card16('sequence_number'), rq.ReplyLength(), rq.LengthOf('devices', 2), rq.Pad(22),", "in the hope that it will be useful, # but", "in native byte order from end to end. The simple", "# <NAME> <<EMAIL>> # # This library is free software;", "display=self.display, opcode=self.display.get_extension_major(extname), major_version=2, minor_version=0, ) class Mask(rq.List): def __init__(self, name):", "ButtonInfo = rq.Struct( rq.Card16('type'), rq.Card16('length'), rq.Card16('sourceid'), rq.LengthOf(('state', 'labels'), 2), ButtonState('state'),", "3 AsyncPair = 4 SyncPair = 5 SlaveSwitch = 1", "device_event in (ButtonPress, ButtonRelease, KeyPress, KeyRelease, Motion): disp.ge_add_event_data(info.major_opcode, device_event, DeviceEventData)", "(GrabModeSync, GrabModeAsync)), rq.Bool('owner_events'), rq.Pad(2), Mask('mask'), rq.List('modifiers', rq.Card32), ) _reply =", "GNU Lesser General Public # License along with this library;", "rq.List('devices', DeviceInfo), ) def query_device(self, deviceid): return XIQueryDevice( display=self.display, opcode=self.display.get_extension_major(extname),", "deviceid is a numerical device ID, or AllDevices or AllMasterDevices,", "SlaveKeyboard = 4 FloatingSlave = 5 KeyClass = 0 ButtonClass", "# License along with this library; if not, write to", "the GNU Lesser General Public # License along with this", "grab_mode=grab_mode, paired_device_mode=paired_device_mode, owner_events=owner_events, mask=event_mask, modifiers=modifiers, ) def grab_keycode(self, deviceid, time,", "(at your option) any later version. # # This library", "data[length * 4:] return class_data, data ClassInfo = ClassInfoClass() DeviceInfo", "ButtonClass: ButtonInfo, ValuatorClass: ValuatorInfo, ScrollClass: ScrollInfo, TouchClass: TouchInfo, } class", "display): integral, frac = value ret = float(integral) # optimised", "NotifyGrab = 1 NotifyUngrab = 2 NotifyWhileGrabbed = 3 NotifyPassiveGrab", "''' A very incomplete implementation of the XInput extension. '''", "0 ModeAbsolute = 1 MasterPointer = 1 MasterKeyboard = 2", "rq.Pad(2), rq.Card32('flags'), rq.Object('mods', ModifierInfo), rq.Object('groups', GroupInfo), ButtonState('buttons'), ) DeviceChangedEventData =", "= 0 NotifyGrab = 1 NotifyUngrab = 2 NotifyWhileGrabbed =", "implementation of the XInput extension. ''' import sys import array", "(1 << 16) AllDevices = 0 AllMasterDevices = 1 DeviceChanged", ") class XISelectEvents(rq.Request): _request = rq.Struct( rq.Card8('opcode'), rq.Opcode(46), rq.RequestLength(), rq.Window('window'),", "2 MasterAdded = (1 << 0) MasterRemoved = (1 <<", "KeyRelease, Motion): disp.ge_add_event_data(info.major_opcode, device_event, DeviceEventData) disp.ge_add_event_data(info.major_opcode, DeviceChanged, DeviceEventData) disp.ge_add_event_data(info.major_opcode, HierarchyChanged,", "return self._value & (1 << key) def __str__(self): return repr(self)", "time, keycode, grab_mode, paired_device_mode, owner_events, event_mask, modifiers): return passive_grab_device(self, deviceid,", "grab_mode, paired_device_mode, owner_events, event_mask): return XIGrabDevice( display=self.display, opcode=self.display.get_extension_major(extname), deviceid=deviceid, grab_window=self,", "rq.Card16('length'), rq.Card16('sourceid'), rq.LengthOf('keycodes', 2), rq.List('keycodes', rq.Card32), ) ValuatorInfo = rq.Struct(", "rq.Pad(20), ) def query_version(self): return XIQueryVersion( display=self.display, opcode=self.display.get_extension_major(extname), major_version=2, minor_version=0,", "1 ValuatorClass = 2 ScrollClass = 3 TouchClass = 8", "Xlib import X extname = 'XInputExtension' PropertyDeleted = 0 PropertyCreated", "warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.", "SlaveRemoved = (1 << 3) SlaveAttached = (1 << 4)", "MasterPointer = 1 MasterKeyboard = 2 SlavePointer = 3 SlaveKeyboard", "1, (GrabtypeButton, GrabtypeKeycode, GrabtypeEnter, GrabtypeFocusIn, GrabtypeTouchBegin)), rq.Set('grab_mode', 1, (GrabModeSync, GrabModeAsync)),", "(GrabtypeButton, GrabtypeKeycode, GrabtypeEnter, GrabtypeFocusIn, GrabtypeTouchBegin)), rq.Set('grab_mode', 1, (GrabModeSync, GrabModeAsync)), rq.Set('paired_device_mode',", "rq.Set('grab_mode', 1, (GrabModeSync, GrabModeAsync)), rq.Set('paired_device_mode', 1, (GrabModeSync, GrabModeAsync)), rq.Bool('owner_events'), rq.Pad(2),", "4 NotifyPassiveUngrab = 5 NotifyAncestor = 0 NotifyVirtual = 1", "= 14 RawButtonPress = 15 RawButtonRelease = 16 RawMotion =", "rq.Pad(22), rq.List('devices', DeviceInfo), ) def query_device(self, deviceid): return XIQueryDevice( display=self.display,", "10 HierarchyChanged = 11 PropertyEvent = 12 RawKeyPress = 13", "rq.LengthOf('buttons', 2), rq.Card16('valulators_len'), DEVICEID('sourceid'), rq.Pad(2), rq.Card32('flags'), rq.Object('mods', ModifierInfo), rq.Object('groups', GroupInfo),", "rq.Set('paired_device_mode', 1, (GrabModeSync, GrabModeAsync)), rq.Bool('owner_events'), rq.Pad(2), Mask('mask'), rq.List('modifiers', rq.Card32), )", "return XIGrabDevice( display=self.display, opcode=self.display.get_extension_major(extname), deviceid=deviceid, grab_window=self, time=time, cursor=X.NONE, grab_mode=grab_mode, paired_device_mode=paired_device_mode,", "(1 << ButtonRelease) MotionMask = (1 << Motion) EnterMask =", "rq.Card32('detail'), rq.Window('root'), rq.Window('event'), rq.Window('child'), FP1616('root_x'), FP1616('root_y'), FP1616('event_x'), FP1616('event_y'), rq.LengthOf('buttons', 2),", "AllDevices = 0 AllMasterDevices = 1 DeviceChanged = 1 KeyPress", "Mask: bitfield of <length> button states. mask_len = 4 *", "_request = rq.Struct( rq.Card8('opcode'), rq.Opcode(47), rq.RequestLength(), rq.Card16('major_version'), rq.Card16('minor_version'), ) _reply", "NotifyWhileGrabbed = 3 NotifyPassiveGrab = 4 NotifyPassiveUngrab = 5 NotifyAncestor", "rq.Card16('length'), rq.Card16('sourceid'), rq.Pad(2), ) class ButtonMask(object): def __init__(self, value, length):", "NotifyPassiveUngrab = 5 NotifyAncestor = 0 NotifyVirtual = 1 NotifyInferior", "rq.Pad(3), rq.List('modifiers', rq.Card32), ) def passive_ungrab_device(self, deviceid, detail, grab_type, modifiers):", "GrabtypeEnter, GrabtypeFocusIn, GrabtypeTouchBegin)), rq.Pad(3), rq.List('modifiers', rq.Card32), ) def passive_ungrab_device(self, deviceid,", "order from end to end. The simple case is #", "rq.ReplyCode(), rq.Pad(1), rq.Card16('sequence_number'), rq.ReplyLength(), rq.LengthOf('modifiers', 2), rq.Pad(22), rq.List('modifiers', rq.Card32), )", "2), rq.List('keycodes', rq.Card32), ) ValuatorInfo = rq.Struct( rq.Card16('type'), rq.Card16('length'), rq.Card16('sourceid'),", "module # # Copyright (C) 2012 Outpost Embedded, LLC #", "the implied warranty of # MERCHANTABILITY or FITNESS FOR A", "data = data[length * 4:] return class_data, data ClassInfo =", "return XIUngrabDevice( display=self.display, opcode=self.display.get_extension_major(extname), time=time, deviceid=deviceid, ) class XIPassiveGrabDevice(rq.ReplyRequest): _request", "rq.List('masks', EventMask), ) def select_events(self, event_masks): ''' select_events(event_masks) event_masks: Sequence", "of values. if sys.byteorder == 'little': def fun(val): mask_seq.insert(0, val)", "unsigned values ''' return XISelectEvents( display=self.display, opcode=self.display.get_extension_major(extname), window=self, masks=event_masks, )", "# See the GNU Lesser General Public License for more", "rq.Card16 DEVICEUSE = rq.Card8 class FP1616(rq.Int32): def check_value(self, value): return", "= 10 HierarchyChanged = 11 PropertyEvent = 12 RawKeyPress =", "1 MasterKeyboard = 2 SlavePointer = 3 SlaveKeyboard = 4", "ButtonPressMask = (1 << ButtonPress) ButtonReleaseMask = (1 << ButtonRelease)", "2/3 compatibility. from six import integer_types from Xlib.protocol import rq", "= rq.Struct( rq.ReplyCode(), rq.Pad(1), rq.Card16('sequence_number'), rq.ReplyLength(), rq.LengthOf('devices', 2), rq.Pad(22), rq.List('devices',", "__len__(self): return self._length def __getitem__(self, key): return self._value & (1", "_request = rq.Struct( rq.Card8('opcode'), rq.Opcode(46), rq.RequestLength(), rq.Window('window'), rq.LengthOf('masks', 2), rq.Pad(2),", "DEVICEID('deviceid'), rq.Card32('time'), rq.Card32('detail'), rq.Window('root'), rq.Window('event'), rq.Window('child'), FP1616('root_x'), FP1616('root_y'), FP1616('event_x'), FP1616('event_y'),", "deviceid, detail, grab_type, modifiers): return XIPassiveUngrabDevice( display=self.display, opcode=self.display.get_extension_major(extname), deviceid=deviceid, grab_window=self,", "13 RawKeyRelease = 14 RawButtonPress = 15 RawButtonRelease = 16", "= 0 GrabModeAsync = 1 GrabModeTouch = 2 DEVICEID =", "if isinstance(val, integer_types): # We need to build a \"binary", "native byte order from end to end. The simple case", "rq.Card8('mode'), rq.Pad(3), ) ScrollInfo = rq.Struct( rq.Card16('type'), rq.Card16('length'), rq.Card16('sourceid'), rq.Card16('number'),", "# We need to build a \"binary mask\" that (as", "query_device(self, deviceid): return XIQueryDevice( display=self.display, opcode=self.display.get_extension_major(extname), deviceid=deviceid, ) class XIGrabDevice(rq.ReplyRequest):", "= (1 << PropertyEvent) RawKeyPressMask = (1 << RawKeyPress) RawKeyReleaseMask", "= 16 RawMotion = 17 DeviceChangedMask = (1 << DeviceChanged)", "GrabtypeFocusIn, GrabtypeTouchBegin)), rq.Pad(3), rq.List('modifiers', rq.Card32), ) def passive_ungrab_device(self, deviceid, detail,", "float(value) / float(1 << 16) class FP3232(rq.ValueField): structcode = 'lL'", "2), rq.Pad(10), rq.List('info', HierarchyInfo), ) ModifierInfo = rq.Struct( rq.Card32('base_mods'), rq.Card32('latched_mods'),", "(1 << 4) SlaveDetached = (1 << 5) DeviceEnabled =", "the terms of the GNU Lesser General Public License #", "rq.Struct( rq.Card8('opcode'), rq.Opcode(51), rq.RequestLength(), rq.Window('grab_window'), rq.Card32('time'), rq.Cursor('cursor', (X.NONE, )), DEVICEID('deviceid'),", "PropertyModified = 2 NotifyNormal = 0 NotifyGrab = 1 NotifyUngrab", "grab_mode, paired_device_mode, owner_events, event_mask, modifiers): return XIPassiveGrabDevice( display=self.display, opcode=self.display.get_extension_major(extname), deviceid=deviceid,", "1 MasterPointer = 1 MasterKeyboard = 2 SlavePointer = 3", "detail=detail, grab_type=grab_type, modifiers=modifiers, ) def ungrab_keycode(self, deviceid, keycode, modifiers): return", "= 7 Leave = 8 FocusIn = 9 FocusOut =", "rq.Card32('detail'), DEVICEID('deviceid'), rq.LengthOf('modifiers', 2), rq.Set('grab_type', 1, (GrabtypeButton, GrabtypeKeycode, GrabtypeEnter, GrabtypeFocusIn,", "deviceid=deviceid, grab_window=self, time=time, cursor=X.NONE, grab_mode=grab_mode, paired_device_mode=paired_device_mode, owner_events=owner_events, mask=event_mask, ) class", "= 3 NotifyNonlinearVirtual = 4 NotifyPointer = 5 NotifyPointerRoot =", "0 NotifyVirtual = 1 NotifyInferior = 2 NotifyNonlinear = 3", "class FP1616(rq.Int32): def check_value(self, value): return int(value * 65536.0) def", "Outpost Embedded, LLC # <NAME> <<EMAIL>> # # This library", "16) class FP3232(rq.ValueField): structcode = 'lL' structvalues = 2 def", "rq.Pad(2), rq.Card32('flags'), ) HierarchyEventData = rq.Struct( DEVICEID('deviceid'), rq.Card32('time'), rq.Card32('flags'), rq.LengthOf('info',", "GrabtypeFocusIn, GrabtypeTouchBegin)), rq.Set('grab_mode', 1, (GrabModeSync, GrabModeAsync)), rq.Set('paired_device_mode', 1, (GrabModeSync, GrabModeAsync)),", "Mask('mask'), rq.List('modifiers', rq.Card32), ) _reply = rq.Struct( rq.ReplyCode(), rq.Pad(1), rq.Card16('sequence_number'),", "2 AttachSlave = 3 DetachSlave = 4 AttachToMaster = 1", "rq.Pad(2), Mask('mask'), rq.List('modifiers', rq.Card32), ) _reply = rq.Struct( rq.ReplyCode(), rq.Pad(1),", "Motion = 6 Enter = 7 Leave = 8 FocusIn", "length): self._value = value self._length = length def __len__(self): return", "data = data[mask_len:] assert (mask_value & 1) == 0 return", "rq.LengthOf('mask', 2), Mask('mask'), ) class XISelectEvents(rq.Request): _request = rq.Struct( rq.Card8('opcode'),", "(1.0 / (1 << 32)) return ret class XIQueryVersion(rq.ReplyRequest): _request", "rq.Opcode(52), rq.RequestLength(), rq.Card32('time'), DEVICEID('deviceid'), rq.Pad(2), ) def ungrab_device(self, deviceid, time):", "unsigned integer or sequence of 32 bits unsigned values '''", "key): return self._value & (1 << key) def __str__(self): return", "device ID, or AllDevices or AllMasterDevices, and mask is either", "grab_type=grab_type, modifiers=modifiers, ) def ungrab_keycode(self, deviceid, keycode, modifiers): return passive_ungrab_device(self,", "1, (GrabModeSync, GrabModeAsync)), rq.Bool('owner_events'), rq.Pad(1), rq.LengthOf('mask', 2), Mask('mask'), ) _reply", "DeviceChanged = 1 KeyPress = 2 KeyRelease = 3 ButtonPress", "it and/or # modify it under the terms of the", "incomplete implementation of the XInput extension. ''' import sys import", "mask) pairs, where deviceid is a numerical device ID, or", "NotifyVirtual = 1 NotifyInferior = 2 NotifyNonlinear = 3 NotifyNonlinearVirtual", "bits unsigned values ''' return XISelectEvents( display=self.display, opcode=self.display.get_extension_major(extname), window=self, masks=event_masks,", "more details. # # You should have received a copy", "passive_ungrab_device(self, deviceid, detail, grab_type, modifiers): return XIPassiveUngrabDevice( display=self.display, opcode=self.display.get_extension_major(extname), deviceid=deviceid,", "rq.Opcode(48), rq.RequestLength(), DEVICEID('deviceid'), rq.Pad(2), ) _reply = rq.Struct( rq.ReplyCode(), rq.Pad(1),", "XIGrabDevice( display=self.display, opcode=self.display.get_extension_major(extname), deviceid=deviceid, grab_window=self, time=time, cursor=X.NONE, grab_mode=grab_mode, paired_device_mode=paired_device_mode, owner_events=owner_events,", "be useful, # but WITHOUT ANY WARRANTY; without even the", "DEVICEID('deviceid'), rq.Card32('time'), rq.LengthOf('classes', 2), DEVICEID('sourceid'), rq.Card8('reason'), rq.Pad(11), rq.List('classes', ClassInfo), )", "and/or # modify it under the terms of the GNU", "disp.extension_add_method('window', 'xinput_grab_device', grab_device) disp.extension_add_method('display', 'xinput_ungrab_device', ungrab_device) disp.extension_add_method('window', 'xinput_grab_keycode', grab_keycode) disp.extension_add_method('window',", "KeyPress, KeyRelease, Motion): disp.ge_add_event_data(info.major_opcode, device_event, DeviceEventData) disp.ge_add_event_data(info.major_opcode, DeviceChanged, DeviceEventData) disp.ge_add_event_data(info.major_opcode,", "return int(value * 65536.0) def parse_value(self, value, display): return float(value)", "FocusIn) FocusOutMask = (1 << FocusOut) HierarchyChangedMask = (1 <<", "= rq.Struct( rq.Card16('type'), rq.Card16('length'), rq.Card16('sourceid'), rq.LengthOf(('state', 'labels'), 2), ButtonState('state'), rq.List('labels',", "0 return ButtonMask(mask_value >> 1, length), data ButtonInfo = rq.Struct(", "rq.Card8('opcode'), rq.Opcode(54), rq.RequestLength(), rq.Card32('time'), rq.Window('grab_window'), rq.Cursor('cursor', (X.NONE, )), rq.Card32('detail'), DEVICEID('deviceid'),", "'xinput_grab_keycode', grab_keycode) disp.extension_add_method('window', 'xinput_ungrab_keycode', ungrab_keycode) if hasattr(disp,\"ge_add_event_data\"): for device_event in", "3 NotifyPassiveGrab = 4 NotifyPassiveUngrab = 5 NotifyAncestor = 0", "write to the # Free Software Foundation, Inc., # 59", "def ungrab_keycode(self, deviceid, keycode, modifiers): return passive_ungrab_device(self, deviceid, keycode, GrabtypeKeycode,", "later version. # # This library is distributed in the", "(1 << FocusOut) HierarchyChangedMask = (1 << HierarchyChanged) PropertyEventMask =", "= rq.Struct( rq.Card16('type'), rq.Card16('length'), rq.Card16('sourceid'), rq.LengthOf('keycodes', 2), rq.List('keycodes', rq.Card32), )", "= rq.Struct( rq.Card8('opcode'), rq.Opcode(48), rq.RequestLength(), DEVICEID('deviceid'), rq.Pad(2), ) _reply =", "SlaveSwitch = 1 DeviceChange = 2 MasterAdded = (1 <<", "# byte order across the entire set of values. if", "owner_events, event_mask, modifiers): return passive_grab_device(self, deviceid, time, keycode, GrabtypeKeycode, grab_mode,", ") def passive_ungrab_device(self, deviceid, detail, grab_type, modifiers): return XIPassiveUngrabDevice( display=self.display,", "= 0 SyncDevice = 1 ReplayDevice = 2 AsyncPairedDevice =", "XIUngrabDevice(rq.Request): _request = rq.Struct( rq.Card8('opcode'), rq.Opcode(52), rq.RequestLength(), rq.Card32('time'), DEVICEID('deviceid'), rq.Pad(2),", "rq.Card16('sequence_number'), rq.ReplyLength(), rq.Card8('status'), rq.Pad(23), ) def grab_device(self, deviceid, time, grab_mode,", "AnyKeycode = 0 AsyncDevice = 0 SyncDevice = 1 ReplayDevice", "DeviceEnabled = (1 << 6) DeviceDisabled = (1 << 7)", "ButtonRelease, KeyPress, KeyRelease, Motion): disp.ge_add_event_data(info.major_opcode, device_event, DeviceEventData) disp.ge_add_event_data(info.major_opcode, DeviceChanged, DeviceEventData)", "GrabtypeEnter, GrabtypeFocusIn, GrabtypeTouchBegin)), rq.Set('grab_mode', 1, (GrabModeSync, GrabModeAsync)), rq.Set('paired_device_mode', 1, (GrabModeSync,", "= (1 << RawMotion) GrabModeSync = 0 GrabModeAsync = 1", "rq.LengthOf('mask', 2), rq.Set('grab_type', 1, (GrabtypeButton, GrabtypeKeycode, GrabtypeEnter, GrabtypeFocusIn, GrabtypeTouchBegin)), rq.Set('grab_mode',", ") _reply = rq.Struct( rq.ReplyCode(), rq.Pad(1), rq.Card16('sequence_number'), rq.ReplyLength(), rq.LengthOf('devices', 2),", "rq.Card8('opcode'), rq.Opcode(51), rq.RequestLength(), rq.Window('grab_window'), rq.Card32('time'), rq.Cursor('cursor', (X.NONE, )), DEVICEID('deviceid'), rq.Set('grab_mode',", "far as I can tell) is # encoded in native", "select_events(event_masks) event_masks: Sequence of (deviceid, mask) pairs, where deviceid is", "rq.Card16('sequence_number'), rq.ReplyLength(), rq.LengthOf('devices', 2), rq.Pad(22), rq.List('devices', DeviceInfo), ) def query_device(self,", "RawMotion) GrabModeSync = 0 GrabModeAsync = 1 GrabModeTouch = 2", "rq.Struct( rq.Card8('opcode'), rq.Opcode(52), rq.RequestLength(), rq.Card32('time'), DEVICEID('deviceid'), rq.Pad(2), ) def ungrab_device(self,", "by the Free Software Foundation; either version 2.1 # of", "value, length): self._value = value self._length = length def __len__(self):", "DEVICEID('deviceid'), rq.Card16('use'), rq.Card16('attachment'), rq.LengthOf('classes', 2), rq.LengthOf('name', 2), rq.Bool('enabled'), rq.Pad(1), rq.String8('name',", "AddMaster = 1 RemoveMaster = 2 AttachSlave = 3 DetachSlave", "rq.Pad(2), rq.List('masks', EventMask), ) def select_events(self, event_masks): ''' select_events(event_masks) event_masks:", "(as far as I can tell) is # encoded in", "ButtonState('buttons'), ) DeviceChangedEventData = rq.Struct( DEVICEID('deviceid'), rq.Card32('time'), rq.LengthOf('classes', 2), DEVICEID('sourceid'),", "states. mask_len = 4 * ((((length + 7) >> 3)", "== 'little': def fun(val): mask_seq.insert(0, val) elif sys.byteorder == 'big':", "rq.Pad(3), ) ScrollInfo = rq.Struct( rq.Card16('type'), rq.Card16('length'), rq.Card16('sourceid'), rq.Card16('number'), rq.Card16('scroll_type'),", "from Xlib import X extname = 'XInputExtension' PropertyDeleted = 0", "event_mask): return XIGrabDevice( display=self.display, opcode=self.display.get_extension_major(extname), deviceid=deviceid, grab_window=self, time=time, cursor=X.NONE, grab_mode=grab_mode,", "library is distributed in the hope that it will be", "def pack_value(self, val): mask_seq = array.array(rq.struct_to_array_codes['L']) if isinstance(val, integer_types): #", "rq.Window('window'), rq.LengthOf('masks', 2), rq.Pad(2), rq.List('masks', EventMask), ) def select_events(self, event_masks):", "rq.Object('groups', GroupInfo), ButtonState('buttons'), ) DeviceChangedEventData = rq.Struct( DEVICEID('deviceid'), rq.Card32('time'), rq.LengthOf('classes',", "detail=detail, grab_type=grab_type, grab_mode=grab_mode, paired_device_mode=paired_device_mode, owner_events=owner_events, mask=event_mask, modifiers=modifiers, ) def grab_keycode(self,", "& 1) == 0 return ButtonMask(mask_value >> 1, length), data", "deviceid, keycode, modifiers): return passive_ungrab_device(self, deviceid, keycode, GrabtypeKeycode, modifiers) HierarchyInfo", "deviceid, time): return XIUngrabDevice( display=self.display, opcode=self.display.get_extension_major(extname), time=time, deviceid=deviceid, ) class", "= (1 << Motion) EnterMask = (1 << Enter) LeaveMask", "1 PropertyModified = 2 NotifyNormal = 0 NotifyGrab = 1", "(1 << 5) DeviceEnabled = (1 << 6) DeviceDisabled =", "= 3 SlaveKeyboard = 4 FloatingSlave = 5 KeyClass =", "= (1 << Leave) FocusInMask = (1 << FocusIn) FocusOutMask", "= 1 GrabtypeEnter = 2 GrabtypeFocusIn = 3 GrabtypeTouchBegin =", "# This library is distributed in the hope that it", "(1 << 6) DeviceDisabled = (1 << 7) AddMaster =", "= mask_seq.append else: raise AssertionError(sys.byteorder) while val: fun(val & 0xFFFFFFFF)", "import sys import array import struct # Python 2/3 compatibility.", "event_masks): ''' select_events(event_masks) event_masks: Sequence of (deviceid, mask) pairs, where", "rq.Struct( DEVICEID('deviceid'), rq.Card32('time'), rq.Card32('detail'), rq.Window('root'), rq.Window('event'), rq.Window('child'), FP1616('root_x'), FP1616('root_y'), FP1616('event_x'),", "Software Foundation, Inc., # 59 Temple Place, # Suite 330,", "= 4 AttachToMaster = 1 Floating = 2 ModeRelative =", "(1 << PropertyEvent) RawKeyPressMask = (1 << RawKeyPress) RawKeyReleaseMask =", "rq.Opcode(47), rq.RequestLength(), rq.Card16('major_version'), rq.Card16('minor_version'), ) _reply = rq.Struct( rq.ReplyCode(), rq.Pad(1),", "= (1 << RawButtonPress) RawButtonReleaseMask = (1 << RawButtonRelease) RawMotionMask", "= 13 RawKeyRelease = 14 RawButtonPress = 15 RawButtonRelease =", "HierarchyChanged = 11 PropertyEvent = 12 RawKeyPress = 13 RawKeyRelease", "FocusOut = 10 HierarchyChanged = 11 PropertyEvent = 12 RawKeyPress", "option) any later version. # # This library is distributed", "(1 << RawKeyRelease) RawButtonPressMask = (1 << RawButtonPress) RawButtonReleaseMask =", "License, or (at your option) any later version. # #", "DEVICEID('sourceid'), rq.Pad(2), rq.Card32('flags'), rq.Object('mods', ModifierInfo), rq.Object('groups', GroupInfo), ButtonState('buttons'), ) DeviceChangedEventData", "<< 16) AllDevices = 0 AllMasterDevices = 1 DeviceChanged =", "Lesser General Public License # as published by the Free", "def check_value(self, value): return int(value * 65536.0) def parse_value(self, value,", "<< 1) SlaveAdded = (1 << 2) SlaveRemoved = (1", "version 2.1 # of the License, or (at your option)", "6) DeviceDisabled = (1 << 7) AddMaster = 1 RemoveMaster", "= 7 GrabtypeButton = 0 GrabtypeKeycode = 1 GrabtypeEnter =", "library; if not, write to the # Free Software Foundation,", "1 GrabModeTouch = 2 DEVICEID = rq.Card16 DEVICE = rq.Card16", "a numerical device ID, or AllDevices or AllMasterDevices, and mask", "return XIPassiveUngrabDevice( display=self.display, opcode=self.display.get_extension_major(extname), deviceid=deviceid, grab_window=self, detail=detail, grab_type=grab_type, modifiers=modifiers, )", "'xinput_ungrab_device', ungrab_device) disp.extension_add_method('window', 'xinput_grab_keycode', grab_keycode) disp.extension_add_method('window', 'xinput_ungrab_keycode', ungrab_keycode) if hasattr(disp,\"ge_add_event_data\"):", "careful to maintain native # byte order across the entire", "MotionMask = (1 << Motion) EnterMask = (1 << Enter)", "def query_device(self, deviceid): return XIQueryDevice( display=self.display, opcode=self.display.get_extension_major(extname), deviceid=deviceid, ) class", "X extname = 'XInputExtension' PropertyDeleted = 0 PropertyCreated = 1", "val = val >> 32 else: mask_seq.extend(val) return mask_seq.tostring(), len(mask_seq),", "SyncPair = 5 SlaveSwitch = 1 DeviceChange = 2 MasterAdded", "NotifyNormal = 0 NotifyGrab = 1 NotifyUngrab = 2 NotifyWhileGrabbed", ") def query_version(self): return XIQueryVersion( display=self.display, opcode=self.display.get_extension_major(extname), major_version=2, minor_version=0, )", ") def grab_device(self, deviceid, time, grab_mode, paired_device_mode, owner_events, event_mask): return", "rq.Pad(22), rq.List('modifiers', rq.Card32), ) def passive_grab_device(self, deviceid, time, detail, grab_type,", "class ButtonMask(object): def __init__(self, value, length): self._value = value self._length", "time=time, cursor=X.NONE, detail=detail, grab_type=grab_type, grab_mode=grab_mode, paired_device_mode=paired_device_mode, owner_events=owner_events, mask=event_mask, modifiers=modifiers, )", "= 0 AsyncDevice = 0 SyncDevice = 1 ReplayDevice =", "rq.Card32('resolution'), rq.Card8('mode'), rq.Pad(3), ) ScrollInfo = rq.Struct( rq.Card16('type'), rq.Card16('length'), rq.Card16('sourceid'),", "class XIUngrabDevice(rq.Request): _request = rq.Struct( rq.Card8('opcode'), rq.Opcode(52), rq.RequestLength(), rq.Card32('time'), DEVICEID('deviceid'),", "RawKeyPress = 13 RawKeyRelease = 14 RawButtonPress = 15 RawButtonRelease", "rq.Pad(23), ) def grab_device(self, deviceid, time, grab_mode, paired_device_mode, owner_events, event_mask):", "rq.Card16('length'), rq.Card16('sourceid'), rq.Card8('mode'), rq.Card8('num_touches'), ) INFO_CLASSES = { KeyClass: KeyInfo,", "fit inside 4 # bytes we build a longer array,", "ButtonMask(object): def __init__(self, value, length): self._value = value self._length =", "deviceid, time, detail, grab_type, grab_mode, paired_device_mode, owner_events, event_mask, modifiers): return", "of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. #", "8 FocusIn = 9 FocusOut = 10 HierarchyChanged = 11", "None EventMask = rq.Struct( DEVICE('deviceid'), rq.LengthOf('mask', 2), Mask('mask'), ) class", "rq.Window('child'), FP1616('root_x'), FP1616('root_y'), FP1616('event_x'), FP1616('event_y'), rq.LengthOf('buttons', 2), rq.Card16('valulators_len'), DEVICEID('sourceid'), rq.Pad(2),", "0) MasterRemoved = (1 << 1) SlaveAdded = (1 <<", ") DeviceEventData = rq.Struct( DEVICEID('deviceid'), rq.Card32('time'), rq.Card32('detail'), rq.Window('root'), rq.Window('event'), rq.Window('child'),", "0 ButtonClass = 1 ValuatorClass = 2 ScrollClass = 3", "= (1 << 2) SlaveRemoved = (1 << 3) SlaveAttached", "3 NotifyNonlinearVirtual = 4 NotifyPointer = 5 NotifyPointerRoot = 6", "disp.extension_add_method('display', 'xinput_query_device', query_device) disp.extension_add_method('window', 'xinput_grab_device', grab_device) disp.extension_add_method('display', 'xinput_ungrab_device', ungrab_device) disp.extension_add_method('window',", "Mask(rq.List): def __init__(self, name): rq.List.__init__(self, name, rq.Card32, pad=0) def pack_value(self,", "ungrab_device(self, deviceid, time): return XIUngrabDevice( display=self.display, opcode=self.display.get_extension_major(extname), time=time, deviceid=deviceid, )", "parse_value(self, value, display): integral, frac = value ret = float(integral)", "XIQueryVersion(rq.ReplyRequest): _request = rq.Struct( rq.Card8('opcode'), rq.Opcode(47), rq.RequestLength(), rq.Card16('major_version'), rq.Card16('minor_version'), )", "mask_value |= byte data = data[mask_len:] assert (mask_value & 1)", "XIGrabDevice(rq.ReplyRequest): _request = rq.Struct( rq.Card8('opcode'), rq.Opcode(51), rq.RequestLength(), rq.Window('grab_window'), rq.Card32('time'), rq.Cursor('cursor',", "rq.Card16('sourceid'), rq.Card8('mode'), rq.Card8('num_touches'), ) INFO_CLASSES = { KeyClass: KeyInfo, ButtonClass:", "<< ButtonRelease) MotionMask = (1 << Motion) EnterMask = (1", "rq.List('modifiers', rq.Card32), ) _reply = rq.Struct( rq.ReplyCode(), rq.Pad(1), rq.Card16('sequence_number'), rq.ReplyLength(),", ") def init(disp, info): disp.extension_add_method('display', 'xinput_query_version', query_version) disp.extension_add_method('window', 'xinput_select_events', select_events)", "= (1 << 7) AddMaster = 1 RemoveMaster = 2", "rq.Card16('scroll_type'), rq.Pad(2), rq.Card32('flags'), FP3232('increment'), ) TouchInfo = rq.Struct( rq.Card16('type'), rq.Card16('length'),", "= (1 << 5) DeviceEnabled = (1 << 6) DeviceDisabled", "rq.Card8('num_touches'), ) INFO_CLASSES = { KeyClass: KeyInfo, ButtonClass: ButtonInfo, ValuatorClass:", "if hasattr(disp,\"ge_add_event_data\"): for device_event in (ButtonPress, ButtonRelease, KeyPress, KeyRelease, Motion):", ")), DEVICEID('deviceid'), rq.Set('grab_mode', 1, (GrabModeSync, GrabModeAsync)), rq.Set('paired_device_mode', 1, (GrabModeSync, GrabModeAsync)),", "3 TouchClass = 8 KeyRepeat = (1 << 16) AllDevices", "I can tell) is # encoded in native byte order", "= 2 SlavePointer = 3 SlaveKeyboard = 4 FloatingSlave =", "the XInput extension. ''' import sys import array import struct", ">> 32 else: mask_seq.extend(val) return mask_seq.tostring(), len(mask_seq), None EventMask =", "parse_binary_value(self, data, display, length, fmt): # Mask: bitfield of <length>", "mask=event_mask, ) class XIUngrabDevice(rq.Request): _request = rq.Struct( rq.Card8('opcode'), rq.Opcode(52), rq.RequestLength(),", "DEVICE('deviceid'), rq.LengthOf('mask', 2), Mask('mask'), ) class XISelectEvents(rq.Request): _request = rq.Struct(", "'xinput_query_device', query_device) disp.extension_add_method('window', 'xinput_grab_device', grab_device) disp.extension_add_method('display', 'xinput_ungrab_device', ungrab_device) disp.extension_add_method('window', 'xinput_grab_keycode',", "* ((((length + 7) >> 3) + 3) >> 2)", "rq.Struct( rq.Card8('opcode'), rq.Opcode(54), rq.RequestLength(), rq.Card32('time'), rq.Window('grab_window'), rq.Cursor('cursor', (X.NONE, )), rq.Card32('detail'),", "opcode=self.display.get_extension_major(extname), window=self, masks=event_masks, ) AnyInfo = rq.Struct( rq.Card16('type'), rq.Card16('length'), rq.Card16('sourceid'),", "= 4 FloatingSlave = 5 KeyClass = 0 ButtonClass =", "to build a \"binary mask\" that (as far as I", "return passive_ungrab_device(self, deviceid, keycode, GrabtypeKeycode, modifiers) HierarchyInfo = rq.Struct( DEVICEID('deviceid'),", "grab_device(self, deviceid, time, grab_mode, paired_device_mode, owner_events, event_mask): return XIGrabDevice( display=self.display,", "import rq from Xlib import X extname = 'XInputExtension' PropertyDeleted", "(1 << Enter) LeaveMask = (1 << Leave) FocusInMask =", "an # array with just one item. For values too", "LeaveMask = (1 << Leave) FocusInMask = (1 << FocusIn)", "rq.Struct( rq.Card16('type'), rq.Card16('length'), rq.Card16('sourceid'), rq.Pad(2), ) class ButtonMask(object): def __init__(self,", "one item. For values too big to fit inside 4", "class_struct = INFO_CLASSES.get(class_type, AnyInfo) class_data, _ = class_struct.parse_binary(data, display) data", "Public License # as published by the Free Software Foundation;", "keycode, GrabtypeKeycode, modifiers) HierarchyInfo = rq.Struct( DEVICEID('deviceid'), DEVICEID('attachment'), DEVICEUSE('type'), rq.Bool('enabled'),", "PropertyEvent = 12 RawKeyPress = 13 RawKeyRelease = 14 RawButtonPress", "rq.LengthOf('classes', 2), rq.LengthOf('name', 2), rq.Bool('enabled'), rq.Pad(1), rq.String8('name', 4), rq.List('classes', ClassInfo),", "32)) return ret class XIQueryVersion(rq.ReplyRequest): _request = rq.Struct( rq.Card8('opcode'), rq.Opcode(47),", "rq.Card16('type'), rq.Card16('length'), rq.Card16('sourceid'), rq.Card16('number'), rq.Card32('label'), FP3232('min'), FP3232('max'), FP3232('value'), rq.Card32('resolution'), rq.Card8('mode'),", "{ KeyClass: KeyInfo, ButtonClass: ButtonInfo, ValuatorClass: ValuatorInfo, ScrollClass: ScrollInfo, TouchClass:", "any later version. # # This library is distributed in", "ungrab_keycode(self, deviceid, keycode, modifiers): return passive_ungrab_device(self, deviceid, keycode, GrabtypeKeycode, modifiers)", "grab_type, modifiers): return XIPassiveUngrabDevice( display=self.display, opcode=self.display.get_extension_major(extname), deviceid=deviceid, grab_window=self, detail=detail, grab_type=grab_type,", ">> 2) mask_data = data[:mask_len] mask_value = 0 for byte", "Sequence of (deviceid, mask) pairs, where deviceid is a numerical", ") AnyInfo = rq.Struct( rq.Card16('type'), rq.Card16('length'), rq.Card16('sourceid'), rq.Pad(2), ) class", "extension. ''' import sys import array import struct # Python", "len(mask_seq), None EventMask = rq.Struct( DEVICE('deviceid'), rq.LengthOf('mask', 2), Mask('mask'), )", "grab_window=self, detail=detail, grab_type=grab_type, modifiers=modifiers, ) def ungrab_keycode(self, deviceid, keycode, modifiers):", "= rq.Struct( rq.Card16('type'), rq.Card16('length'), rq.Card16('sourceid'), rq.Pad(2), ) class ButtonMask(object): def", "General Public # License along with this library; if not,", "length, fmt): # Mask: bitfield of <length> button states. mask_len", "FP1616(rq.Int32): def check_value(self, value): return int(value * 65536.0) def parse_value(self,", "rq.RequestLength(), rq.Window('grab_window'), rq.Card32('detail'), DEVICEID('deviceid'), rq.LengthOf('modifiers', 2), rq.Set('grab_type', 1, (GrabtypeButton, GrabtypeKeycode,", "an unsigned integer or sequence of 32 bits unsigned values", "return ret class XIQueryVersion(rq.ReplyRequest): _request = rq.Struct( rq.Card8('opcode'), rq.Opcode(47), rq.RequestLength(),", "AsyncPairedDevice = 3 AsyncPair = 4 SyncPair = 5 SlaveSwitch", "Xlib.protocol import rq from Xlib import X extname = 'XInputExtension'", "= 1 DeviceChanged = 1 KeyPress = 2 KeyRelease =", "<< FocusIn) FocusOutMask = (1 << FocusOut) HierarchyChangedMask = (1", "rq.LengthOf('classes', 2), DEVICEID('sourceid'), rq.Card8('reason'), rq.Pad(11), rq.List('classes', ClassInfo), ) def init(disp,", "event_mask, modifiers): return XIPassiveGrabDevice( display=self.display, opcode=self.display.get_extension_major(extname), deviceid=deviceid, grab_window=self, time=time, cursor=X.NONE,", "a \"binary mask\" that (as far as I can tell)", "which we construct an # array with just one item.", "class_data, data ClassInfo = ClassInfoClass() DeviceInfo = rq.Struct( DEVICEID('deviceid'), rq.Card16('use'),", "FP3232('max'), FP3232('value'), rq.Card32('resolution'), rq.Card8('mode'), rq.Pad(3), ) ScrollInfo = rq.Struct( rq.Card16('type'),", "# Copyright (C) 2012 Outpost Embedded, LLC # <NAME> <<EMAIL>>", "rq.List('classes', ClassInfo), ) class XIQueryDevice(rq.ReplyRequest): _request = rq.Struct( rq.Card8('opcode'), rq.Opcode(48),", ">> 1, length), data ButtonInfo = rq.Struct( rq.Card16('type'), rq.Card16('length'), rq.Card16('sourceid'),", "PropertyDeleted = 0 PropertyCreated = 1 PropertyModified = 2 NotifyNormal", "where deviceid is a numerical device ID, or AllDevices or", "rq.Card8('reason'), rq.Pad(11), rq.List('classes', ClassInfo), ) def init(disp, info): disp.extension_add_method('display', 'xinput_query_version',", "= 4 ButtonRelease = 5 Motion = 6 Enter =", "(1 << 3) SlaveAttached = (1 << 4) SlaveDetached =", "''' return XISelectEvents( display=self.display, opcode=self.display.get_extension_major(extname), window=self, masks=event_masks, ) AnyInfo =", "= 3 NotifyPassiveGrab = 4 NotifyPassiveUngrab = 5 NotifyAncestor =", "XISelectEvents(rq.Request): _request = rq.Struct( rq.Card8('opcode'), rq.Opcode(46), rq.RequestLength(), rq.Window('window'), rq.LengthOf('masks', 2),", "= rq.Struct( rq.Card8('opcode'), rq.Opcode(55), rq.RequestLength(), rq.Window('grab_window'), rq.Card32('detail'), DEVICEID('deviceid'), rq.LengthOf('modifiers', 2),", "DetachSlave = 4 AttachToMaster = 1 Floating = 2 ModeRelative", "= 2 NotifyNormal = 0 NotifyGrab = 1 NotifyUngrab =", "= value self._length = length def __len__(self): return self._length def", ") class XIPassiveGrabDevice(rq.ReplyRequest): _request = rq.Struct( rq.Card8('opcode'), rq.Opcode(54), rq.RequestLength(), rq.Card32('time'),", "item. For values too big to fit inside 4 #", "2 NotifyWhileGrabbed = 3 NotifyPassiveGrab = 4 NotifyPassiveUngrab = 5", "deviceid=deviceid, ) class XIGrabDevice(rq.ReplyRequest): _request = rq.Struct( rq.Card8('opcode'), rq.Opcode(51), rq.RequestLength(),", "value, for which we construct an # array with just", "A PARTICULAR PURPOSE. # See the GNU Lesser General Public", "parse_value(self, value, display): return float(value) / float(1 << 16) class", "rq.Card32('effective_mods'), ) GroupInfo = rq.Struct( rq.Card8('base_group'), rq.Card8('latched_group'), rq.Card8('locked_group'), rq.Card8('effective_group'), )", "entire set of values. if sys.byteorder == 'little': def fun(val):", "width=self._length) class ButtonState(rq.ValueField): structcode = None def __init__(self, name): rq.ValueField.__init__(self,", "Lesser General Public # License along with this library; if", "rq.Struct( rq.Card8('opcode'), rq.Opcode(55), rq.RequestLength(), rq.Window('grab_window'), rq.Card32('detail'), DEVICEID('deviceid'), rq.LengthOf('modifiers', 2), rq.Set('grab_type',", "= 0 AnyKeycode = 0 AsyncDevice = 0 SyncDevice =", "2), rq.LengthOf('mask', 2), rq.Set('grab_type', 1, (GrabtypeButton, GrabtypeKeycode, GrabtypeEnter, GrabtypeFocusIn, GrabtypeTouchBegin)),", ") GroupInfo = rq.Struct( rq.Card8('base_group'), rq.Card8('latched_group'), rq.Card8('locked_group'), rq.Card8('effective_group'), ) DeviceEventData", "# # You should have received a copy of the", "DEVICEID('deviceid'), DEVICEID('attachment'), DEVICEUSE('type'), rq.Bool('enabled'), rq.Pad(2), rq.Card32('flags'), ) HierarchyEventData = rq.Struct(", "without even the implied warranty of # MERCHANTABILITY or FITNESS" ]
[]
[ "django.db import migrations class Migration(migrations.Migration): dependencies = [ ('YourJobAidApi', '0018_category_count_post'),", "dependencies = [ ('YourJobAidApi', '0018_category_count_post'), ] operations = [ migrations.RemoveField(", "3.0.4 on 2020-04-16 23:10 from django.db import migrations class Migration(migrations.Migration):", "2020-04-16 23:10 from django.db import migrations class Migration(migrations.Migration): dependencies =", "Django 3.0.4 on 2020-04-16 23:10 from django.db import migrations class", "from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('YourJobAidApi',", "= [ ('YourJobAidApi', '0018_category_count_post'), ] operations = [ migrations.RemoveField( model_name='category',", "by Django 3.0.4 on 2020-04-16 23:10 from django.db import migrations", "[ ('YourJobAidApi', '0018_category_count_post'), ] operations = [ migrations.RemoveField( model_name='category', name='count_post',", "<reponame>rayhanrock/django-yourjobaid-api # Generated by Django 3.0.4 on 2020-04-16 23:10 from", "Migration(migrations.Migration): dependencies = [ ('YourJobAidApi', '0018_category_count_post'), ] operations = [", "class Migration(migrations.Migration): dependencies = [ ('YourJobAidApi', '0018_category_count_post'), ] operations =", "migrations class Migration(migrations.Migration): dependencies = [ ('YourJobAidApi', '0018_category_count_post'), ] operations", "Generated by Django 3.0.4 on 2020-04-16 23:10 from django.db import", "23:10 from django.db import migrations class Migration(migrations.Migration): dependencies = [", "# Generated by Django 3.0.4 on 2020-04-16 23:10 from django.db", "import migrations class Migration(migrations.Migration): dependencies = [ ('YourJobAidApi', '0018_category_count_post'), ]", "'0018_category_count_post'), ] operations = [ migrations.RemoveField( model_name='category', name='count_post', ), ]", "('YourJobAidApi', '0018_category_count_post'), ] operations = [ migrations.RemoveField( model_name='category', name='count_post', ),", "on 2020-04-16 23:10 from django.db import migrations class Migration(migrations.Migration): dependencies" ]
[ "@File : __init__.py.py # @Software: PyCharm # @Note : xx", ": 2022/1/26 23:07 # @Author : zhaoyu # @Site :", "@Site : # @File : __init__.py.py # @Software: PyCharm #", "# @Author : zhaoyu # @Site : # @File :", "2022/1/26 23:07 # @Author : zhaoyu # @Site : #", "# @Time : 2022/1/26 23:07 # @Author : zhaoyu #", "zhaoyu # @Site : # @File : __init__.py.py # @Software:", "@Author : zhaoyu # @Site : # @File : __init__.py.py", ": zhaoyu # @Site : # @File : __init__.py.py #", ": # @File : __init__.py.py # @Software: PyCharm # @Note", "# @File : __init__.py.py # @Software: PyCharm # @Note :", "23:07 # @Author : zhaoyu # @Site : # @File", "# @Site : # @File : __init__.py.py # @Software: PyCharm", "@Time : 2022/1/26 23:07 # @Author : zhaoyu # @Site" ]
[ "} } errors { field message } } } \"\"\"", "attributes assert Attribute.objects.get_visible_to_user(staff_api_client.user).count() == 1 # The user should now", "@pytest.mark.parametrize(\"test_deprecated_filter\", [True, False]) @pytest.mark.parametrize(\"tested_field\", [\"inCategory\", \"inCollection\"]) def test_attributes_in_collection_query( user_api_client, product_type,", "for attr, expected_pk in zip(gql_attributes, expected_order): gql_type, gql_attr_id = graphene.Node.from_global_id(attr[\"id\"])", "expected_pk ATTRIBUTE_VALUES_RESORT_QUERY = \"\"\" mutation attributeReorderValues($attributeId: ID!, $moves: [ReorderInput]!) {", "\"\"\" qs = Attribute.objects.all() assert filter_attributes_by_product_types(qs, \"...\", \"\") is qs", "associated to it. \"\"\" # Retrieve the product's variant variant", "( (AttributeTypeEnum.PRODUCT, AttributeTypeEnum.VARIANT), (AttributeTypeEnum.VARIANT, AttributeTypeEnum.PRODUCT), (AttributeTypeEnum.PRODUCT, AttributeTypeEnum.PRODUCT), (AttributeTypeEnum.VARIANT, AttributeTypeEnum.VARIANT), ),", "== 3 variables = { \"type\": attribute_type, \"productTypeId\": product_type_id, \"moves\":", "for attr in attributes_data] expected_flat_attributes_data = list(expected_qs.values_list(\"slug\", flat=True)) assert flat_attributes_data", "= { \"type\": attribute_type, \"productTypeId\": product_type_id, \"moves\": [ { \"id\":", "m2m_rel_other_attr.sort_order = 0 m2m_rel_other_attr.save(update_fields=[\"sort_order\"]) # Assign attributes to the product", "{ node { attributes { values { type inputType }", "assert attr_data[\"name\"] == name assert attr_data[\"slug\"] == slugify(name) assert attr_data[\"type\"]", "= \"Yellow Color\" node_id = graphene.Node.to_global_id(\"Attribute\", attribute.id) variables = {", "the ones we are testing assert len(products) == 1 assert", "sortBy: $sortBy) { edges { node { slug } }", "{ id } } } } \"\"\" # Create a", "\"Non-assigned attr from the PT may be missing\" assert len(variant_attributes)", "\"in_space\", \"a-value\") assert exc.value.args == (\"Filtering by in_space is unsupported\",)", "errors[0][\"message\"] == error_msg product_errors = content[\"data\"][\"attributeUpdate\"][\"productErrors\"] assert product_errors[0][\"code\"] == error_code.name", "as a variant attribute when the product type doesn't support", "{\"filters\": {\"ids\": global_ids}} expected_slugs = sorted([attribute_list[0].slug, attribute_list[1].slug]) attributes = get_graphql_content(", "product.variants.first() assert product.attributes.count() == 1 assert variant.attributes.count() == 1 product_attribute_values", "the product type if is_variant: product.product_type.variant_attributes.set([color_attribute, other_attribute]) else: product.product_type.product_attributes.set([color_attribute, other_attribute])", ") m2m_model.objects.create( product_type=product_type, attribute=size_attribute, sort_order=1 ) variables = {\"sortBy\": {\"field\":", "False attribute.save(update_fields=[\"visible_in_storefront\"]) product = get_graphql_content(api_client.post_graphql(query))[\"data\"][\"products\"][ \"edges\" ][0][\"node\"] assert len(product[\"attributes\"]) ==", "sorted([attribute_list[0].slug, attribute_list[1].slug]) attributes = get_graphql_content( api_client.post_graphql(ATTRIBUTES_FILTER_QUERY, variables) )[\"data\"][\"attributes\"][\"edges\"] assert len(attributes)", "django.template.defaultfilters import slugify from graphene.utils.str_converters import to_camel_case from saleor.core.taxes import", "m2m_model.objects.create( product_type=product_type, attribute=color_attribute, sort_order=0 ) m2m_model.objects.create( product_type=product_type, attribute=size_attribute, sort_order=1 )", "variant_attributes[0][\"attribute\"][\"slug\"] == \"size\" assert variant_attributes[0][\"values\"][0][\"slug\"] == variant_attribute_values[0] assert variant_attributes[0][\"value\"][\"slug\"] ==", "operations.append( {\"type\": \"PRODUCT\", \"id\": graphene.Node.to_global_id(\"Attribute\", attr_id)} ) for attr_id in", "expected_product_attribute_count = product.attributes.count() - 1 expected_variant_attribute_count = variant.attributes.count() - 1", "api_client.user = staff_user expected_product_attribute_count += 1 expected_variant_attribute_count += 1 staff_user.user_permissions.add(permission_manage_products)", "values[2].pk), \"sortOrder\": -1, }, ], } expected_order = [values[1].pk, values[2].pk,", "size_attribute, permission_manage_products ): query = UPDATE_ATTRIBUTE_QUERY attribute = color_attribute node_id", "def test_create_attribute_and_attribute_values_errors( staff_api_client, name_1, name_2, error_msg, error_code, permission_manage_products, product_type, ):", "push them at the top # through a sort_order=0 as", "attributes[0].pk] content = get_graphql_content( staff_api_client.post_graphql(ATTRIBUTES_RESORT_QUERY, variables) )[\"data\"][\"productTypeReorderAttributes\"] assert not content[\"errors\"]", "assert attributes[0][\"node\"][\"slug\"] == \"size\" def test_filter_attributes_by_global_id_list(api_client, attribute_list): global_ids = [", "AttributeProduct), ), ) def test_sort_attributes_by_position_in_product_type( api_client, color_attribute, size_attribute, sort_field: str,", "variantAttributes { id } } } } \"\"\" def test_assign_attributes_to_product_type(", "{ slug } values { slug } value { slug", "# a new value with a new slug should pass", "the attributes assigned to a product type are resolved even", "{ attributes { attribute { slug } values { name", "should raise an error when trying to add an attribute", "message } attribute { slug } } } \"\"\" attribute_name", "graphene.Node.to_global_id(\"Attribute\", attribute.pk), } ] variables = {\"productTypeId\": product_type_global_id, \"operations\": operations}", "product_type_global_id, \"attributeIds\": [ graphene.Node.to_global_id(\"Attribute\", product_attributes[0].pk) ], } content = get_graphql_content(", "that is not/no longer in the product type.\"\"\" staff_api_client.user.user_permissions.add(permission_manage_products) product_type", "1 assert gql_attr[\"values\"][0][\"type\"] == \"STRING\" assert gql_attr[\"values\"][0][\"inputType\"] == \"DROPDOWN\" @pytest.mark.parametrize(", "(AttributeTypeEnum.PRODUCT, AttributeTypeEnum.VARIANT), (AttributeTypeEnum.VARIANT, AttributeTypeEnum.PRODUCT), (AttributeTypeEnum.PRODUCT, AttributeTypeEnum.PRODUCT), (AttributeTypeEnum.VARIANT, AttributeTypeEnum.VARIANT), ), )", "# Check if the slug was correctly set if no", "= \"\"\" query($filters: AttributeFilterInput!) { attributes(first: 10, filter: $filters) {", "variables)) # Check if the error is as expected: null", ") query = \"\"\" query($id: ID!) { attribute(id: $id) {", "def test_create_attribute_with_given_slug( staff_api_client, permission_manage_products, input_slug, expected_slug, expected_error, ): staff_api_client.user.user_permissions.add(permission_manage_products) query", "len(attributes_data) == attribute_count def test_attributes_query_hidden_attribute_as_staff_user( staff_api_client, product, color_attribute, permission_manage_products ):", "as the other attributes have sort_order=null AttributeProduct.objects.create( attribute=unassigned_product_attribute, product_type=product_type, sort_order=0", "are sorted.\"\"\" variant = product.variants.first() if is_variant: query = \"\"\"", "else product # type: Union[Product, ProductVariant] node.attributesrelated.clear() associate_attribute_values_to_instance( node, color_attribute,", "} \"\"\" else: query = \"\"\" query($id: ID!) { product(id:", "name == attribute.name assert not attribute.values.filter(pk=attribute_value_id).exists() assert attribute.values.filter(name=attribute_value_name).exists() def test_update_empty_attribute_and_add_values(", "get_graphql_content(staff_api_client.post_graphql(query, variables))[ \"data\" ][\"attributeAssign\"] assert content[\"errors\"] == [ { \"field\":", "== 1 assert attributes[0][\"node\"][\"slug\"] == \"size\" def test_filter_attributes_by_global_id_list(api_client, attribute_list): global_ids", "resolve to a product type: {product_type_id}\", } ] def test_sort_attributes_within_product_type_invalid_id(", "{ \"attributeId\": attribute_id, \"moves\": [{\"id\": value_id, \"sortOrder\": 1}], } content", "{ \"type\": gql_attribute_type.value, \"id\": graphene.Node.to_global_id(\"Attribute\", attribute.pk), } ] variables =", "graphene.Node.to_global_id(\"Attribute\", attributes[2].pk), \"sortOrder\": -1, }, ], } expected_order = [attributes[1].pk,", "attribute.values m2m_values.set(values) assert values == sorted( values, key=lambda o: o.sort_order", "$attributeId: ID!, $name: String!) { attributeValueCreate( attribute: $attributeId, input: {name:", "staff_api_client.user.user_permissions.add(permission_manage_products) response = staff_api_client.post_graphql(query) content = get_graphql_content(response) attributes_data = content[\"data\"][\"attributes\"][\"edges\"]", "mutation assign($productTypeId: ID!, $operations: [AttributeAssignInput]!) { attributeAssign(productTypeId: $productTypeId, operations: $operations)", "attributeValueCreate( attribute: $attributeId, input: {name: $name}) { productErrors { field", "backref_field, ): attributes = attribute_list assert len(attributes) == 3 staff_api_client.user.user_permissions.add(permission_manage_products)", "code } attribute { values { name } } attributeValue", "the permission yet to manage products, # the user shouldn't", "\"attributeId\", \"message\": f\"Couldn't resolve to an attribute: {attribute_id}\", } ]", "= \"\"\" query($nodeID: ID!) { attributes(first: 20, %(filter_input)s) { edges", "name_1}, {\"name\": name_2}]} response = staff_api_client.post_graphql( query, variables, permissions=[permission_manage_products] )", "\"DROPDOWN\" @pytest.mark.parametrize( \"attribute, expected_value\", ( (\"filterable_in_storefront\", True), (\"filterable_in_dashboard\", True), (\"visible_in_storefront\",", "graphene.Node.to_global_id(\"Attribute\", -1) value_id = graphene.Node.to_global_id(\"AttributeValue\", -1) variables = { \"attributeId\":", "exc: filter_attributes_by_product_types(qs, \"in_space\", \"a-value\") assert exc.value.args == (\"Filtering by in_space", "query = UPDATE_ATTRIBUTE_QUERY attribute = color_attribute node_id = graphene.Node.to_global_id(\"Attribute\", attribute.id)", "content[\"errors\"] == [ { \"field\": \"operations\", \"message\": \"Color (color) have", "mock.MagicMock() qs = filter_attributes_by_product_types(mocked_qs, \"in_category\", category_id) assert qs == mocked_qs.none.return_value", "== err_msg product_errors = content[\"data\"][\"attributeUpdate\"][\"productErrors\"] assert product_errors[0][\"code\"] == ProductErrorCode.INVALID.name def", "product_type=product_type, sort_order=0 ) assert product.attributes.count() == 1 assert variant.attributes.count() ==", "ID).\"\"\" product_type_id = graphene.Node.to_global_id(\"ProductType\", -1) attribute_id = graphene.Node.to_global_id(\"Attribute\", -1) variables", "Assign the dummy attributes to the product type and push", "product_attributes_ids ) assert len(content[\"productType\"][\"variantAttributes\"]) == len( variant_attributes_ids ) found_product_attrs_ids =", "graphene.Node.to_global_id(\"Attribute\", attribute.pk) for attribute in attribute_list[:2] ] variables = {\"filters\":", "\"as variant attributes\" ), } ] @pytest.mark.parametrize( \"product_type_attribute_type, gql_attribute_type\", (", "else \"product\"][\"attributes\"] actual_order = [ int(graphene.Node.from_global_id(attr[\"attribute\"][\"id\"])[1]) for attr in attributes", "color_attribute node_id = graphene.Node.to_global_id(\"Attribute\", attribute.id) variables = { \"name\": \"Example", "\"\"\" content = get_graphql_content( user_api_client.post_graphql(query, {\"id\": attribute_gql_id}) ) assert content[\"data\"][\"attribute\"],", "ProductType.objects.create(name=\"Dummy Type\") product_type_id = graphene.Node.to_global_id(\"ProductType\", product_type.id) attribute_id = graphene.Node.to_global_id(\"Attribute\", color_attribute.id)", "Ensure we are only working on one product and variant,", "} productAttributes { id } } } } \"\"\" def", "permissions=[permission_manage_products] ) content = get_graphql_content(response) assert not content[\"data\"][\"attributeCreate\"][\"errors\"] data =", "{ attributeCreate(input: {name: $name, slug: $slug}) { errors { field", "= get_graphql_content(staff_api_client.post_graphql(query, variables))[ \"data\" ][\"attributeUnassign\"] assert not content[\"errors\"] assert content[\"productType\"][\"id\"]", "= [ { \"type\": gql_attribute_type.value, \"id\": graphene.Node.to_global_id(\"Attribute\", attribute.pk), } ]", "ID!) { attributeDelete(id: $id) { errors { field message }", "attributes = get_graphql_content( api_client.post_graphql(ATTRIBUTES_FILTER_QUERY, variables) )[\"data\"][\"attributes\"][\"edges\"] assert len(attributes) == 2", "{ field message } attribute { id } } }", "\"...\", None) is qs def test_attributes_filter_by_product_type_with_unsupported_field(): \"\"\"Ensure using an unknown", "$addValues, removeValues: $removeValues}) { errors { field message } productErrors", "(\"VARIANT\", \"variant_attributes\", \"attributevariant\"), (\"PRODUCT\", \"product_attributes\", \"attributeproduct\"), ), ) def test_sort_attributes_within_product_type(", "productErrors { field message code } attribute { values {", "{\"field\": sort_field, \"direction\": \"DESC\"}} attributes = get_graphql_content( api_client.post_graphql(ATTRIBUTES_SORT_QUERY, variables) )[\"data\"][\"attributes\"][\"edges\"]", "for the attribute vs the product type if is_variant: m2m_rel_other_attr", "correctly created assert data[\"attribute\"][\"name\"] == attribute_name assert data[\"attribute\"][\"slug\"] == slugify(", "$productTypeId: ID! $moves: [ReorderInput]! $type: AttributeTypeEnum! ) { productTypeReorderAttributes( productTypeId:", "attributeUnassign(productTypeId: $productTypeId, attributeIds: $attributeIds) { errors { field message }", "graphene.Node.to_global_id(\"Attribute\", attribute.id) variables = { \"name\": name, \"id\": node_id, \"addValues\":", "in_space is unsupported\",) def test_attributes_filter_by_non_existing_category_id(): \"\"\"Ensure using a non-existing category", "} } } } } \"\"\" found_products = get_graphql_content( staff_api_client.post_graphql(query,", "][\"attributeAssign\"] assert content[\"errors\"] == [ { \"field\": \"operations\", \"message\": \"Color", "[] assert variant_attributes[0][\"value\"] is None def test_attributes_filter_by_product_type_with_empty_value(): \"\"\"Ensure passing an", "filter_attributes_by_product_types(qs, \"in_space\", \"a-value\") assert exc.value.args == (\"Filtering by in_space is", "PT may be missing\" assert len(variant_attributes) == 2, \"Non-assigned attr", "attributes = list(sort_method()) assert len(attributes) == 3 variables = {", "attribute_list): global_ids = [ graphene.Node.to_global_id(\"Attribute\", attribute.pk) for attribute in attribute_list[:2]", "} } } } } \"\"\" def test_update_attribute_name( staff_api_client, color_attribute,", "variables = {\"filters\": {\"filterableInDashboard\": True}} attributes = get_graphql_content( api_client.post_graphql(ATTRIBUTES_FILTER_QUERY, variables)", "product_type.pk) query = UNASSIGN_ATTR_QUERY variables = { \"productTypeId\": product_type_global_id, \"attributeIds\":", "user should now be able to see the attributes staff_api_client.user.user_permissions.add(permission_manage_products)", "== \"addValues\" assert errors[0][\"message\"] == error_msg product_errors = content[\"data\"][\"attributeUpdate\"][\"productErrors\"] assert", "name\", \"id\": node_id, \"slug\": \"example-slug\", \"addValues\": [], \"removeValues\": [attr_id], }", "node_id} staff_api_client.post_graphql( query, variables, permissions=[permission_manage_products] ) with pytest.raises(value._meta.model.DoesNotExist): value.refresh_from_db() @pytest.mark.parametrize(", "value_id, \"sortOrder\": 1}], } content = get_graphql_content( staff_api_client.post_graphql( ATTRIBUTE_VALUES_RESORT_QUERY, variables,", "test_delete_attribute_value( staff_api_client, color_attribute, pink_attribute_value, permission_manage_products ): value = color_attribute.values.get(name=\"Red\") query", "= QUERY_PRODUCT_AND_VARIANTS_ATTRIBUTES api_client = user_api_client variant = product.variants.first() product_type =", "} } } \"\"\" def test_create_attribute_and_attribute_values( staff_api_client, permission_manage_products ): query", "permissions=[permission_manage_products], ) )[\"data\"][\"attributeReorderValues\"] assert content[\"errors\"] == [ { \"field\": \"moves\",", "} } \"\"\" def test_unassign_attributes_from_product_type( staff_api_client, permission_manage_products, attribute_list ): product_type", "def test_attributes_of_products_are_sorted( staff_api_client, product, color_attribute, is_variant ): \"\"\"Ensures the attributes", "def test_validate_value_is_unique(color_attribute): value = color_attribute.values.first() # a new value but", "1) { edges { node { attributes { attribute {", "= get_graphql_content(response) data = content[\"data\"][\"attributeValueCreate\"] assert data[\"productErrors\"] assert data[\"productErrors\"][0][\"code\"] ==", "False), (\"storefront_search_position\", 0), ), ) def test_retrieving_the_restricted_attributes_restricted( staff_api_client, color_attribute, permission_manage_products,", "def test_update_attribute_and_add_attribute_values_errors( staff_api_client, name_1, name_2, error_msg, error_code, color_attribute, permission_manage_products, ):", "is part of the product type but not of the", "} found_variant_attrs_ids = { int(graphene.Node.from_global_id(attr[\"id\"])[1]) for attr in content[\"productType\"][\"variantAttributes\"] }", "values are properly resolved when an attribute is part of", "attributes[1][\"node\"][\"slug\"] == \"color\" def test_sort_attributes_by_default_sorting(api_client): \"\"\"Don't provide any sorting, this", "attributes(first: 10, sortBy: $sortBy) { edges { node { slug", "content[\"data\"][\"attributeUpdate\"][\"productErrors\"] assert product_errors[0][\"code\"] == ProductErrorCode.INVALID.name def test_delete_attribute( staff_api_client, color_attribute, permission_manage_products,", "= get_graphql_content(response) errors = content[\"data\"][\"attributeUpdate\"][\"errors\"] assert errors assert errors[0][\"field\"] ==", "\"\"\"Try to reorder an invalid product type (invalid ID).\"\"\" product_type_id", "assert errors[0][\"field\"] == \"values\" assert errors[0][\"message\"] == error_msg product_errors =", "in the product type.\"\"\" staff_api_client.user.user_permissions.add(permission_manage_products) product_type = ProductType.objects.create(name=\"Type\") product_type_global_id =", "} attributeValue { name slug } attribute { values {", "ID (when None) expected_order = [other_attribute.pk, color_attribute.pk] # Make the", "assert variant_attributes[0][\"value\"] is None assert variant_attributes[0][\"attribute\"][\"slug\"] == \"variant\" assert variant_attributes[0][\"values\"]", "( (\"filterable_in_storefront\", True), (\"filterable_in_dashboard\", True), (\"visible_in_storefront\", True), (\"available_in_grid\", True), (\"value_required\",", "assert len(variant_attributes) == len(variant_attribute_values) assert product_attributes[0][\"attribute\"][\"slug\"] == \"color\" assert product_attributes[0][\"values\"][0][\"slug\"]", "assert not content[\"errors\"], \"Should have succeeded\" assert content[\"productType\"][\"id\"] == product_type_global_id", "product_type_id, \"moves\": [{\"id\": attribute_id, \"sortOrder\": 1}], } content = get_graphql_content(", "assert errors[0][\"message\"] == error_msg product_errors = content[\"data\"][\"attributeUpdate\"][\"productErrors\"] assert product_errors[0][\"code\"] ==", "import get_graphql_content def test_validate_value_is_unique(color_attribute): value = color_attribute.values.first() # a new", "[ AttributeValue(slug=\"a\", name=\"A\", attribute=unassigned_product_attribute), AttributeValue(slug=\"b\", name=\"B\", attribute=unassigned_product_attribute), ] ) #", "in tested_field: filtered_by_node_id = graphene.Node.to_global_id(\"Category\", category.pk) else: raise AssertionError(tested_field) expected_qs", "100%, 50%)\", AttributeValueType.COLOR), (\"hsla(120, 60%, 70%, 0.3)\", AttributeValueType.COLOR), (\"rgba(100%, 255,", "attributes_data] expected_flat_attributes_data = list(expected_qs.values_list(\"slug\", flat=True)) assert flat_attributes_data == expected_flat_attributes_data CREATE_ATTRIBUTES_QUERY", "value for each dummy attribute to ensure they are not", "in content[\"productType\"][\"variantAttributes\"] } assert found_product_attrs_ids == product_attributes_ids assert found_variant_attrs_ids ==", "is None def test_attributes_filter_by_product_type_with_empty_value(): \"\"\"Ensure passing an empty or null", "permissions=[permission_manage_products] ) )[\"data\"][\"productTypeReorderAttributes\"] assert content[\"errors\"] == [ { \"field\": \"productTypeId\",", "\"\"\" mutation updateChoice( $id: ID!, $name: String!) { attributeValueUpdate( id:", "= graphene.Node.to_global_id(\"Attribute\", color_attribute.id) variables = { \"type\": \"VARIANT\", \"productTypeId\": product_type_id,", "product and variant's attributes products = get_graphql_content( api_client.post_graphql( \"\"\" {", "the product or variant as they are not associated to", "attr_data = data[\"attributeValue\"] assert attr_data[\"name\"] == name assert attr_data[\"slug\"] ==", "$nodeID }\" % tested_field} variables = {\"nodeID\": filtered_by_node_id} content =", "add an attribute already contained in the product type.\"\"\" product_type", "attribute { id values { id } } errors {", "to the given attribute.\"\"\" attribute_id = graphene.Node.to_global_id(\"Attribute\", color_attribute.id) value_id =", "raise an error with pytest.raises(ValidationError): validate_value_is_unique(color_attribute, AttributeValue(slug=value.slug)) # a new", "is_variant: m2m_rel_other_attr = other_attribute.attributevariant.last() else: m2m_rel_other_attr = other_attribute.attributeproduct.last() # Push", "{ productType { id variantAttributes { id slug } productAttributes", "$name, values: $values}) { errors { field message } productErrors", "} } } } } \"\"\" @pytest.mark.parametrize(\"is_staff\", (False, True)) def", ") AttributeVariant.objects.create( attribute=unassigned_variant_attribute, product_type=product_type, sort_order=0 ) assert product.attributes.count() == 1", "# Remove all attributes and values from the product and", "size_attribute expected_product_attribute_count = product.attributes.count() - 1 expected_variant_attribute_count = variant.attributes.count() -", "empty query set.\"\"\" category_id = graphene.Node.to_global_id(\"Category\", -1) mocked_qs = mock.MagicMock()", "\"productTypeId\": product_type_global_id, \"attributeIds\": [ graphene.Node.to_global_id(\"Attribute\", color_attribute_without_values.pk) ], } content =", "we are sure the query is actually passing the test.", "product.variants.first() product_type = product.product_type # Create dummy attributes unassigned_product_attribute =", "== variables[\"id\"] with pytest.raises(attribute._meta.model.DoesNotExist): attribute.refresh_from_db() CREATE_ATTRIBUTE_VALUE_QUERY = \"\"\" mutation createAttributeValue(", "input: {name: $name}) { productErrors { field message code }", "attribute values were correctly created assert len(data[\"attribute\"][\"values\"]) == 1 assert", "values { slug } value { slug } } }", "test_create_attribute_value( staff_api_client, color_attribute, permission_manage_products ): attribute = color_attribute query =", "{ \"name\": \"Example name\", \"id\": node_id, \"removeValues\": [], \"addValues\": [{\"name\":", "response = staff_api_client.post_graphql(query) content = get_graphql_content(response) attributes_data = content[\"data\"][\"attributes\"][\"edges\"] assert", "} content = get_graphql_content( staff_api_client.post_graphql( ATTRIBUTE_VALUES_RESORT_QUERY, variables, permissions=[permission_manage_products], ) )[\"data\"][\"attributeReorderValues\"]", "ID. Thus, we are sure the query is actually passing", "query = CREATE_ATTRIBUTES_QUERY variables = {\"name\": \"Example name\", \"values\": [{\"name\":", "Attribute.objects.all().count() # The user doesn't have the permission yet to", "{\"name\": name, \"id\": node_id, \"addValues\": [], \"removeValues\": []} response =", "to add an attribute already contained in the product type.\"\"\"", "assign($productTypeId: ID!, $operations: [AttributeAssignInput]!) { attributeAssign(productTypeId: $productTypeId, operations: $operations) {", "\"size\" def test_filter_attributes_by_global_id_list(api_client, attribute_list): global_ids = [ graphene.Node.to_global_id(\"Attribute\", attribute.pk) for", "\"Provided values are not unique.\", ProductErrorCode.UNIQUE, ), ( \"Red color\",", "product_type_attribute_type, gql_attribute_type, ): \"\"\"The assignAttribute mutation should raise an error", "permission_manage_products ): query = UPDATE_ATTRIBUTE_QUERY attribute = color_attribute name =", "permissions=[permission_manage_products] ) with pytest.raises(value._meta.model.DoesNotExist): value.refresh_from_db() @pytest.mark.parametrize( \"raw_value, expected_type\", [ (\"#0000\",", "= { \"attributeId\": attribute_id, \"moves\": [ { \"id\": graphene.Node.to_global_id(\"AttributeValue\", values[0].pk),", "$productTypeId, operations: $operations) { errors { field message } productType", "expected_flat_attributes_data CREATE_ATTRIBUTES_QUERY = \"\"\" mutation createAttribute($name: String!, $values: [AttributeValueCreateInput]) {", "name=\"Green\", slug=\"green\") values = list(attribute.values.all()) assert len(values) == 3 staff_api_client.user.user_permissions.add(permission_manage_products)", "assert content[\"errors\"] == [ { \"field\": \"operations\", \"message\": \"Variants are", "\"sortOrder\": -1, }, ], } expected_order = [attributes[1].pk, attributes[2].pk, attributes[0].pk]", "raise an error when trying to use an attribute as", "attribute to ensure they are not returned # by the", "user shouldn't be able to see the hidden attributes assert", "data[\"productErrors\"] attr_data = data[\"attributeValue\"] assert attr_data[\"name\"] == name assert attr_data[\"slug\"]", "graphene.Node.to_global_id(\"Product\", product.pk) # Retrieve the attributes data = get_graphql_content(staff_api_client.post_graphql(query, {\"id\":", "name: $name, addValues: $addValues, removeValues: $removeValues}) { errors { field", "the product type.\"\"\" staff_api_client.user.user_permissions.add(permission_manage_products) product_type = ProductType.objects.create(name=\"Type\") product_type_global_id = graphene.Node.to_global_id(\"ProductType\",", "attribute.id) m2m_values = attribute.values m2m_values.set(values) assert values == sorted( values,", "{ node { id name slug values { id name", "returned # by the product or variant as they are", "CREATE_ATTRIBUTES_QUERY attribute_name = \"<NAME>\" name = \"Value name\" variables =", "= Attribute.objects.create(name=\"P\", slug=\"product\") unassigned_variant_attribute = Attribute.objects.create(name=\"V\", slug=\"variant\") # Create a", "always the last attribute # when sorted by ID. Thus,", "variables = {\"name\": value_name.upper(), \"attributeId\": attribute_id} response = staff_api_client.post_graphql( query,", "ASSIGN_ATTR_QUERY operations = [ {\"type\": \"VARIANT\", \"id\": graphene.Node.to_global_id(\"Attribute\", attribute.pk)} ]", "{\"name\": name_2}]} response = staff_api_client.post_graphql( query, variables, permissions=[permission_manage_products] ) content", "content[\"errors\"] assert content[\"productType\"][\"id\"] == product_type_global_id assert len(content[\"productType\"][\"productAttributes\"]) == 0 assert", "a product type are resolved even if the product doesn't", "3 variables = { \"type\": attribute_type, \"productTypeId\": product_type_id, \"moves\": [", "from django.core.exceptions import ValidationError from django.db.models import Q from django.template.defaultfilters", "import Q from django.template.defaultfilters import slugify from graphene.utils.str_converters import to_camel_case", "} } } } \"\"\" if test_deprecated_filter: query = query", "staff_api_client.user.user_permissions.add(permission_manage_products) product_type = ProductType.objects.create(name=\"Dummy Type\") product_type_id = graphene.Node.to_global_id(\"ProductType\", product_type.id) m2m_attributes", "attribute should not have been assigned to a product type\"", "size_attribute = size_attribute.values.first() attr_id = graphene.Node.to_global_id(\"AttributeValue\", size_attribute.pk) variables = {", "{\"filters\": {\"availableInGrid\": True}} attributes = get_graphql_content( api_client.post_graphql(ATTRIBUTES_FILTER_QUERY, variables) )[\"data\"][\"attributes\"][\"edges\"] assert", "= ProductType.objects.create(name=\"Default Type\", has_variants=True) product_type_global_id = graphene.Node.to_global_id(\"ProductType\", product_type.pk) query =", "content[\"attribute\"][\"values\"] assert len(gql_values) == len(expected_order) actual_order = [] for attr,", "[ { \"id\": graphene.Node.to_global_id(\"AttributeValue\", values[0].pk), \"sortOrder\": +1, }, { \"id\":", "actual_order = [ int(graphene.Node.from_global_id(attr[\"attribute\"][\"id\"])[1]) for attr in attributes ] #", "node_id = graphene.Node.to_global_id(\"Attribute\", attribute.id) variables = { \"name\": \"Example name\",", "[] variables = {\"productTypeId\": product_type_global_id, \"operations\": operations} product_attributes_ids = {attr.pk", "= ProductType.objects.create(name=\"Type\") product_type_global_id = graphene.Node.to_global_id(\"ProductType\", product_type.pk) variant_attribute, *product_attributes = attribute_list", "{ errors { field message } productType { id variantAttributes", "variant.attributes.first().values.values_list(\"slug\", flat=True) ) assert len(product_attribute_values) == 1 assert len(variant_attribute_values) ==", "(\"DASHBOARD_VARIANT_POSITION\", AttributeVariant), (\"DASHBOARD_PRODUCT_POSITION\", AttributeProduct), ), ) def test_sort_attributes_by_position_in_product_type( api_client, color_attribute,", "} } } } \"\"\" def test_search_attributes(api_client, color_attribute, size_attribute): variables", "in zip(gql_values, expected_order): gql_type, gql_attr_id = graphene.Node.from_global_id(attr[\"id\"]) assert gql_type ==", ") def test_sort_attributes_by_position_in_product_type( api_client, color_attribute, size_attribute, sort_field: str, m2m_model: Union[AttributeVariant,", "attribute = color_attribute node_id = graphene.Node.to_global_id(\"Attribute\", attribute.id) variables = {", "len(attributes) == 2 received_slugs = sorted( [attributes[0][\"node\"][\"slug\"], attributes[1][\"node\"][\"slug\"]] ) assert", "description=\"Description\", ) other_collection.products.add(other_product) query = \"\"\" query($nodeID: ID!) { attributes(first:", "} content = get_graphql_content( staff_api_client.post_graphql( ATTRIBUTES_RESORT_QUERY, variables, permissions=[permission_manage_products] ) )[\"data\"][\"productTypeReorderAttributes\"]", "id } productAttributes { id } } } } \"\"\"", "[ graphene.Node.to_global_id(\"Attribute\", product_attributes[0].pk) ], } content = get_graphql_content( staff_api_client.post_graphql( query,", "assert ( content[\"productType\"][\"productAttributes\"][0][\"id\"] == remaining_attribute_global_id ) def test_unassign_attributes_not_in_product_type( staff_api_client, permission_manage_products,", "len(attributes) == 3 variables = { \"type\": attribute_type, \"productTypeId\": product_type_id,", "= False color_attribute.save(update_fields=[\"available_in_grid\"]) variables = {\"filters\": {\"availableInGrid\": True}} attributes =", "{ attribute { slug } values { slug } value", "were correctly created assert len(data[\"attribute\"][\"values\"]) == 1 assert data[\"attribute\"][\"values\"][0][\"name\"] ==", "color_attribute_without_values ): \"\"\"The unAssignAttribute mutation should not raise any error", "= graphene.Node.to_global_id(\"Product\", product.pk) # Retrieve the attributes data = get_graphql_content(staff_api_client.post_graphql(query,", "test_assign_attributes_to_product_type( staff_api_client, permission_manage_products, attribute_list ): product_type = ProductType.objects.create(name=\"Default Type\", has_variants=True)", "assert variant_attributes[0][\"values\"][0][\"slug\"] == variant_attribute_values[0] assert variant_attributes[0][\"value\"][\"slug\"] == variant_attribute_values[0] def test_resolve_attribute_values_non_assigned_to_node(", "with a higher ID # This will allow us to", "\"\"\" def test_update_attribute_value( staff_api_client, pink_attribute_value, permission_manage_products ): query = UPDATE_ATTRIBUTE_VALUE_QUERY", "QUERY_ATTRIBUTES response = user_api_client.post_graphql(query) content = get_graphql_content(response) attributes_data = content[\"data\"][\"attributes\"][\"edges\"]", "variant_attributes[0][\"value\"][\"slug\"] == variant_attribute_values[0] def test_resolve_attribute_values_non_assigned_to_node( user_api_client, product, staff_user ): \"\"\"Ensure", "{\"nodeID\": filtered_by_node_id} content = get_graphql_content(user_api_client.post_graphql(query, variables)) attributes_data = content[\"data\"][\"attributes\"][\"edges\"] flat_attributes_data", "== [] assert variant_attributes[0][\"value\"] is None def test_attributes_filter_by_product_type_with_empty_value(): \"\"\"Ensure passing", "errors assert errors[0][\"field\"] == \"removeValues\" err_msg = \"Value %s does", "\"Attributes having for input types ['multiselect'] cannot be assigned \"", "= QUERY_PRODUCT_AND_VARIANTS_ATTRIBUTES api_client = user_api_client variant = product.variants.first() product_attribute =", "] def test_assign_variant_attribute_having_unsupported_input_type( staff_api_client, permission_manage_products, product_type, size_attribute ): \"\"\"The assignAttribute", "graphene.Node.to_global_id(\"Attribute\", attribute.id) attribute_value_id = attribute.values.first().id value_id = graphene.Node.to_global_id(\"AttributeValue\", attribute_value_id) variables", "None assert variant_attributes[0][\"attribute\"][\"slug\"] == \"variant\" assert variant_attributes[0][\"values\"] == [] assert", "expected_value ATTRIBUTES_RESORT_QUERY = \"\"\" mutation ProductTypeReorderAttributes( $productTypeId: ID! $moves: [ReorderInput]!", "m2m_rel_other_attr.save(update_fields=[\"sort_order\"]) # Assign attributes to the product node = variant", "# Retrieve the attributes data = get_graphql_content(staff_api_client.post_graphql(query, {\"id\": node_id}))[ \"data\"", "get_graphql_content def test_validate_value_is_unique(color_attribute): value = color_attribute.values.first() # a new value", "attributes = get_graphql_content( api_client.post_graphql(ATTRIBUTES_FILTER_QUERY, variables) )[\"data\"][\"attributes\"][\"edges\"] assert len(attributes) == 1", "variables = { \"productTypeId\": product_type_global_id, \"attributeIds\": [ graphene.Node.to_global_id(\"Attribute\", product_attributes[0].pk) ],", "django.db.models import Q from django.template.defaultfilters import slugify from graphene.utils.str_converters import", "assert product_attributes[0][\"attribute\"][\"slug\"] == \"color\" assert product_attributes[0][\"values\"][0][\"slug\"] == product_attribute_values[0] assert product_attributes[0][\"value\"][\"slug\"]", "variant, the ones we are testing assert len(products) == 1", "variables = {\"id\": node_id} response = staff_api_client.post_graphql( query, variables, permissions=[permission_manage_products]", "values { id } } errors { field message }", "staff_api_client, product, color_attribute, is_variant ): \"\"\"Ensures the attributes of products", "assert product.attributes.count() == 1 assert variant.attributes.count() == 1 product =", "== slugify(name) assert attr_data[\"type\"] == \"STRING\" assert name in [value[\"name\"]", "errors assert errors[0][\"field\"] == \"addValues\" assert errors[0][\"message\"] == error_msg product_errors", "product and variant, the ones we are testing assert len(products)", "= attribute_list product_type.product_attributes.add(*product_attributes) product_type.variant_attributes.add(variant_attribute) remaining_attribute_global_id = graphene.Node.to_global_id( \"Attribute\", product_attributes[1].pk )", "0)\", AttributeValueType.COLOR), (\"http://example.com\", AttributeValueType.URL), (\"https://example.com\", AttributeValueType.URL), (\"ftp://example.com\", AttributeValueType.URL), (\"example.com\", AttributeValueType.STRING),", "len(attributes) == 1 assert attributes[0][\"node\"][\"slug\"] == \"size\" def test_filter_attributes_if_available_in_grid( api_client,", "# type: Union[Product, ProductVariant] node.attributesrelated.clear() associate_attribute_values_to_instance( node, color_attribute, color_attribute.values.first() )", "attribute value: {value_id}\", } ] def test_sort_values_within_attribute( staff_api_client, color_attribute, permission_manage_products", "slug } attribute { values { name } } }", "staff_api_client, permission_manage_products, product_type, size_attribute ): \"\"\"The assignAttribute mutation should raise", "None def test_attributes_filter_by_product_type_with_empty_value(): \"\"\"Ensure passing an empty or null value", "# the user shouldn't be able to see the hidden", "{ attribute(id: $id) { id slug } } \"\"\" content", "without any modification. \"\"\" qs = Attribute.objects.all() assert filter_attributes_by_product_types(qs, \"...\",", "assert len(product[\"variants\"][0][\"attributes\"]) == expected_variant_attribute_count def test_resolve_attribute_values(user_api_client, product, staff_user): \"\"\"Ensure the", "get_graphql_content( staff_api_client.post_graphql( ATTRIBUTES_RESORT_QUERY, variables, permissions=[permission_manage_products] ) )[\"data\"][\"productTypeReorderAttributes\"] assert content[\"errors\"] ==", "to see the attributes staff_api_client.user.user_permissions.add(permission_manage_products) response = staff_api_client.post_graphql(query) content =", "assert len(variant_attribute_values) == 1 product = get_graphql_content(api_client.post_graphql(query))[\"data\"][\"products\"][ \"edges\" ][0][\"node\"] product_attributes", "\"Category\" in tested_field: filtered_by_node_id = graphene.Node.to_global_id(\"Category\", category.pk) else: raise AssertionError(tested_field)", "\"STRING\" assert gql_attr[\"values\"][0][\"inputType\"] == \"DROPDOWN\" @pytest.mark.parametrize( \"attribute, expected_value\", ( (\"filterable_in_storefront\",", "slug was correctly set if no error was expected if", "= color_attribute query = CREATE_ATTRIBUTE_VALUE_QUERY attribute_id = graphene.Node.to_global_id(\"Attribute\", attribute.id) name", "$productTypeId moves: $moves type: $type ) { productType { id", "testing assert len(products) == 1 assert len(products[0][\"node\"][\"variants\"]) == 1 #", "assert len(attributes) == 3 staff_api_client.user.user_permissions.add(permission_manage_products) product_type = ProductType.objects.create(name=\"Dummy Type\") product_type_id", "variables = { \"name\": name, \"id\": node_id, \"addValues\": [{\"name\": attribute_value_name}],", "get_graphql_content(staff_api_client.post_graphql(query, variables)) # Check if the error is as expected:", "expected: null or something else assert content[\"data\"][\"attributeCreate\"][\"errors\"] == expected_error #", "= {\"sortBy\": {\"field\": sort_field, \"direction\": \"DESC\"}} attributes = get_graphql_content( api_client.post_graphql(ATTRIBUTES_SORT_QUERY,", "this other collection other_collection = Collection.objects.create( name=\"Other Collection\", slug=\"other-collection\", is_published=True,", "0, 0)\", AttributeValueType.COLOR), (\"hsl(0, 100%, 50%)\", AttributeValueType.COLOR), (\"hsla(120, 60%, 70%,", "for attr_id in product_attributes_ids: operations.append( {\"type\": \"PRODUCT\", \"id\": graphene.Node.to_global_id(\"Attribute\", attr_id)}", "assigned to this product type.\", } ] UNASSIGN_ATTR_QUERY = \"\"\"", "data[\"productErrors\"] assert data[\"productErrors\"][0][\"code\"] == ProductErrorCode.ALREADY_EXISTS.name assert data[\"productErrors\"][0][\"field\"] == \"name\" UPDATE_ATTRIBUTE_VALUE_QUERY", "assert errors assert errors[0][\"field\"] == \"values\" assert errors[0][\"message\"] == error_msg", "\"<NAME>\" attribute_value_name = \"Yellow Color\" node_id = graphene.Node.to_global_id(\"Attribute\", attribute.id) variables", "product_errors[0][\"code\"] == ProductErrorCode.INVALID.name def test_delete_attribute( staff_api_client, color_attribute, permission_manage_products, product_type ):", "hide the attribute color_attribute.visible_in_storefront = False color_attribute.save(update_fields=[\"visible_in_storefront\"]) attribute_count = Attribute.objects.get_visible_to_user(", "1 assert variant.attributes.count() == 1 product = get_graphql_content(api_client.post_graphql(query))[\"data\"][\"products\"][ \"edges\" ][0][\"node\"]", "product_type.pk) variant_attribute, *product_attributes = attribute_list product_type.product_attributes.add(*product_attributes) product_type.variant_attributes.add(variant_attribute) remaining_attribute_global_id = graphene.Node.to_global_id(", "graphene.Node.to_global_id(\"ProductType\", product_type.pk) variant_attribute, *product_attributes = attribute_list product_type.product_attributes.add(*product_attributes) product_type.variant_attributes.add(variant_attribute) remaining_attribute_global_id =", "\"...\", \"\") is qs assert filter_attributes_by_product_types(qs, \"...\", None) is qs", "content[\"data\"][\"attributeUpdate\"][\"errors\"] assert errors assert errors[0][\"field\"] == \"addValues\" assert errors[0][\"message\"] ==", "\"\"\" if test_deprecated_filter: query = query % {\"filter_input\": f\"{tested_field}: $nodeID\"}", "assert content[\"errors\"] == [ { \"field\": \"operations\", \"message\": ( \"Attributes", "should be the slugified name\" assert ( data[\"attribute\"][\"productTypes\"][\"edges\"] == []", "name=\"<NAME>\", slug=\"example-name\", value=\"#RED\" ) node_id = graphene.Node.to_global_id(\"AttributeValue\", value.id) variables =", "*product_attributes = attribute_list product_type.product_attributes.add(*product_attributes) product_type.variant_attributes.add(variant_attribute) remaining_attribute_global_id = graphene.Node.to_global_id( \"Attribute\", product_attributes[1].pk", "[ graphene.Node.to_global_id(\"Attribute\", color_attribute_without_values.pk) ], } content = get_graphql_content(staff_api_client.post_graphql(query, variables))[ \"data\"", "this product type.\", } ] UNASSIGN_ATTR_QUERY = \"\"\" mutation unAssignAttribute(", "{ productErrors { field message code } attribute { values", "actual_order = [] for attr, expected_pk in zip(gql_values, expected_order): gql_type,", "unAssignAttribute mutation should not raise any error when trying to", "node.attributesrelated.clear() associate_attribute_values_to_instance( node, color_attribute, color_attribute.values.first() ) # Sort the database", "\"data\" ] attributes = data[\"productVariant\" if is_variant else \"product\"][\"attributes\"] actual_order", "o: o.sort_order if o.sort_order is not None else o.pk ),", "\"color\" def test_filter_attributes_if_filterable_in_dashboard( api_client, color_attribute, size_attribute ): color_attribute.filterable_in_dashboard = False", "type and push them at the top # through a", "\"Value %s does not belong to this attribute.\" % str(size_attribute)", "len(content[\"productType\"][\"variantAttributes\"]) == len( variant_attributes_ids ) found_product_attrs_ids = { int(graphene.Node.from_global_id(attr[\"id\"])[1]) for", "} \"\"\" % attribute ) found_attributes = get_graphql_content( staff_api_client.post_graphql(query, permissions=[permission_manage_products])", "if no error was expected if expected_error is None: assert", "name slug } } } } } \"\"\" def test_attributes_query(user_api_client,", "= get_graphql_content( staff_api_client.post_graphql( ATTRIBUTE_VALUES_RESORT_QUERY, variables, permissions=[permission_manage_products], ) )[\"data\"][\"attributeReorderValues\"] assert content[\"errors\"]", ") def test_assign_attribute_to_product_type_having_already_that_attribute( staff_api_client, permission_manage_products, color_attribute_without_values, product_type_attribute_type, gql_attribute_type, ): \"\"\"The", "product_type_id, \"moves\": [ { \"id\": graphene.Node.to_global_id(\"Attribute\", attributes[0].pk), \"sortOrder\": +1, },", "$name, slug: $slug}) { errors { field message } attribute", "found_product_attrs_ids == product_attributes_ids assert found_variant_attrs_ids == variant_attributes_ids def test_assign_variant_attribute_to_product_type_with_disabled_variants( staff_api_client,", "[{\"name\": attribute_value_name}], \"removeValues\": [], } response = staff_api_client.post_graphql( query, variables,", "use an attribute as a variant attribute when the attribute's", "for gql_attr in found_products[0][\"node\"][\"attributes\"]: assert len(gql_attr[\"values\"]) == 1 assert gql_attr[\"values\"][0][\"type\"]", "get_graphql_content( user_api_client.post_graphql(query, {\"id\": attribute_gql_id}) ) assert content[\"data\"][\"attribute\"], \"Should have found", "moves: $moves) { attribute { id values { id }", "something else assert content[\"data\"][\"attributeCreate\"][\"errors\"] == expected_error # Check if the", "assert attribute.values.count() == 1 assert attribute.values.filter(name=attribute_value_name).exists() @pytest.mark.parametrize( \"name_1, name_2, error_msg,", "doesn't have the permission yet to manage products, # the", "a sort_order=0 as the other attributes have sort_order=null AttributeProduct.objects.create( attribute=unassigned_product_attribute,", "name=\"A\", attribute=unassigned_product_attribute), AttributeValue(slug=\"b\", name=\"B\", attribute=unassigned_product_attribute), ] ) # Assign the", "should sort by name by default.\"\"\" Attribute.objects.bulk_create( [Attribute(name=\"A\", slug=\"b\"), Attribute(name=\"B\",", "slug } value { slug } } } } }", "returns an empty query set.\"\"\" category_id = graphene.Node.to_global_id(\"Category\", -1) mocked_qs", "\"<NAME>\" variables = {\"name\": name, \"attributeId\": attribute_id} response = staff_api_client.post_graphql(", "slug } } \"\"\" content = get_graphql_content( user_api_client.post_graphql(query, {\"id\": attribute_gql_id})", "value = pink_attribute_value node_id = graphene.Node.to_global_id(\"AttributeValue\", value.id) name = \"Crimson", "= UPDATE_ATTRIBUTE_VALUE_QUERY value = pink_attribute_value.attribute.values.create( name=\"<NAME>\", slug=\"example-name\", value=\"#RED\" ) node_id", ") node_id = graphene.Node.to_global_id(\"AttributeValue\", value.id) variables = {\"name\": pink_attribute_value.name, \"id\":", "test_assign_variant_attribute_having_unsupported_input_type( staff_api_client, permission_manage_products, product_type, size_attribute ): \"\"\"The assignAttribute mutation should", "= [attributes[1].pk, attributes[2].pk, attributes[0].pk] content = get_graphql_content( staff_api_client.post_graphql(ATTRIBUTES_RESORT_QUERY, variables) )[\"data\"][\"productTypeReorderAttributes\"]", "type and attribute that shouldn't get matched other_category = Category.objects.create(name=\"Other", ") )[\"data\"][\"products\"][\"edges\"] # Ensure we are only working on one", "Create another collection with products but shouldn't get matched #", "unsupported\",) def test_attributes_filter_by_non_existing_category_id(): \"\"\"Ensure using a non-existing category ID returns", "} errors { field message } } } \"\"\" def", "\"message\": f\"Couldn't resolve to a product type: {product_type_id}\", } ]", "= Attribute.objects.all().count() # The user doesn't have the permission yet", "data[\"productErrors\"][0][\"field\"] == \"name\" def test_create_attribute_value_capitalized_name( staff_api_client, color_attribute, permission_manage_products ): attribute", "variant_attributes_ids: operations.append( {\"type\": \"VARIANT\", \"id\": graphene.Node.to_global_id(\"Attribute\", attr_id)} ) content =", "sort by name by default.\"\"\" Attribute.objects.bulk_create( [Attribute(name=\"A\", slug=\"b\"), Attribute(name=\"B\", slug=\"a\")]", "field message } } } \"\"\" def test_sort_values_within_attribute_invalid_product_type( staff_api_client, permission_manage_products", "assert int(gql_attr_id) == expected_pk ATTRIBUTE_VALUES_RESORT_QUERY = \"\"\" mutation attributeReorderValues($attributeId: ID!,", "{ id } } } } } } \"\"\" def", "the top and let the others to None m2m_rel_other_attr.sort_order =", "== 1 assert len(content[\"productType\"][\"variantAttributes\"]) == 1 assert ( content[\"productType\"][\"productAttributes\"][0][\"id\"] ==", "type.\"\"\" staff_api_client.user.user_permissions.add(permission_manage_products) product_type = ProductType.objects.create(name=\"Type\") product_type_global_id = graphene.Node.to_global_id(\"ProductType\", product_type.pk) query", "variables, permissions=[permission_manage_products] ) get_graphql_content(response) attribute.refresh_from_db() assert attribute.values.count() == 1 assert", "product = get_graphql_content(api_client.post_graphql(query))[\"data\"][\"products\"][ \"edges\" ][0][\"node\"] assert len(product[\"attributes\"]) == expected_product_attribute_count assert", "is ignored and the queryset is simply returned without any", "test_update_attribute_value( staff_api_client, pink_attribute_value, permission_manage_products ): query = UPDATE_ATTRIBUTE_VALUE_QUERY value =", ") )[\"data\"][\"productTypeReorderAttributes\"] assert content[\"errors\"] == [ { \"field\": \"productTypeId\", \"message\":", "id name slug } } } } } \"\"\" def", "): query = UPDATE_ATTRIBUTE_VALUE_QUERY value = pink_attribute_value.attribute.values.create( name=\"<NAME>\", slug=\"example-name\", value=\"#RED\"", "attribute as a variant attribute when the product type doesn't", "{ id name slug values { id name slug }", "} \"\"\" ) )[\"data\"][\"products\"][\"edges\"] # Ensure we are only working", "def test_filter_attributes_by_global_id_list(api_client, attribute_list): global_ids = [ graphene.Node.to_global_id(\"Attribute\", attribute.pk) for attribute", "error_code.name UPDATE_ATTRIBUTE_QUERY = \"\"\" mutation updateAttribute( $id: ID!, $name: String!,", "{\"name\": value_name.upper(), \"attributeId\": attribute_id} response = staff_api_client.post_graphql( query, variables, permissions=[permission_manage_products]", "} \"\"\" if test_deprecated_filter: query = query % {\"filter_input\": f\"{tested_field}:", "- 1 expected_variant_attribute_count = variant.attributes.count() - 1 if is_staff: api_client.user", ") assert len(product_attribute_values) == 1 assert len(variant_attribute_values) == 1 product", "as expected: null or something else assert content[\"data\"][\"attributeCreate\"][\"errors\"] == expected_error", "variables = {\"name\": attribute_name, \"slug\": input_slug} content = get_graphql_content(staff_api_client.post_graphql(query, variables))", "= graphene.Node.to_global_id(\"Attribute\", attribute.id) variables = {\"id\": node_id} response = staff_api_client.post_graphql(", "== \"name\" UPDATE_ATTRIBUTE_VALUE_QUERY = \"\"\" mutation updateChoice( $id: ID!, $name:", "variant_attributes_ids def test_assign_variant_attribute_to_product_type_with_disabled_variants( staff_api_client, permission_manage_products, product_type_without_variant, color_attribute_without_values, ): \"\"\"The assignAttribute", "{ \"id\": graphene.Node.to_global_id(\"Attribute\", attributes[2].pk), \"sortOrder\": -1, }, ], } expected_order", "product_type_global_id assert len(content[\"productType\"][\"productAttributes\"]) == 1 assert len(content[\"productType\"][\"variantAttributes\"]) == 1 assert", "assert data[\"attribute\"][\"values\"][0][\"slug\"] == slugify(name) @pytest.mark.parametrize( \"input_slug, expected_slug, expected_error\", ( (\"my-slug\",", "test_filter_attributes_if_filterable_in_dashboard( api_client, color_attribute, size_attribute ): color_attribute.filterable_in_dashboard = False color_attribute.save(update_fields=[\"filterable_in_dashboard\"]) variables", "= product.variants.first() if is_variant: query = \"\"\" query($id: ID!) {", "get matched other_category = Category.objects.create(name=\"Other Category\", slug=\"other-cat\") other_attribute = Attribute.objects.create(name=\"Other\",", "pink_attribute_value.attribute.values.create( name=\"<NAME>\", slug=\"example-name\", value=\"#RED\" ) node_id = graphene.Node.to_global_id(\"AttributeValue\", value.id) variables", "permission_manage_products, product_type ): attribute = color_attribute query = \"\"\" mutation", "= { \"type\": \"VARIANT\", \"productTypeId\": product_type_id, \"moves\": [{\"id\": attribute_id, \"sortOrder\":", "pink_attribute_value.name, \"id\": node_id} response = staff_api_client.post_graphql( query, variables, permissions=[permission_manage_products] )", "{ errors { field message } attributeValue { name slug", "attribute_value_name}], \"removeValues\": [value_id], } response = staff_api_client.post_graphql( query, variables, permissions=[permission_manage_products]", "assert not content[\"errors\"] assert ( content[\"productType\"][\"id\"] == product_type_id ), \"Did", "a higher ID # This will allow us to make", "product.pk) # Retrieve the attributes data = get_graphql_content(staff_api_client.post_graphql(query, {\"id\": node_id}))[", "from saleor.product.models import ( Attribute, AttributeProduct, AttributeValue, AttributeVariant, Category, Collection,", "} response = staff_api_client.post_graphql( query, variables, permissions=[permission_manage_products] ) get_graphql_content(response) attribute.refresh_from_db()", "} } } \"\"\" found_products = get_graphql_content( staff_api_client.post_graphql(query, permissions=[permission_manage_products]) )[\"data\"][\"products\"][\"edges\"]", "value.refresh_from_db() @pytest.mark.parametrize( \"raw_value, expected_type\", [ (\"#0000\", AttributeValueType.COLOR), (\"#FF69B4\", AttributeValueType.COLOR), (\"rgb(255,", "== 1 assert gql_attr[\"values\"][0][\"type\"] == \"STRING\" assert gql_attr[\"values\"][0][\"inputType\"] == \"DROPDOWN\"", "# a new value but with existing slug should raise", "== \"b\" assert attributes[1][\"node\"][\"slug\"] == \"a\" @pytest.mark.parametrize(\"is_variant\", (True, False)) def", "expected_order = [values[1].pk, values[2].pk, values[0].pk] content = get_graphql_content( staff_api_client.post_graphql(ATTRIBUTE_VALUES_RESORT_QUERY, variables)", "= Attribute.objects.create(name=\"Other\", slug=\"other\") other_product_type = ProductType.objects.create( name=\"Other type\", has_variants=True, is_shipping_required=True", "Q from django.template.defaultfilters import slugify from graphene.utils.str_converters import to_camel_case from", "product attributes values are all None assert len(product[\"attributes\"]) == 1", "AttributeInputType.MULTISELECT attribute.save(update_fields=[\"input_type\"]) product_type.variant_attributes.clear() staff_api_client.user.user_permissions.add(permission_manage_products) product_type_global_id = graphene.Node.to_global_id(\"ProductType\", product_type.pk) query =", "( \"\"\" { attributes(first: 10) { edges { node {", "Make the node ID if is_variant: node_id = graphene.Node.to_global_id(\"ProductVariant\", variant.pk)", "\" \"as variant attributes\" ), } ] @pytest.mark.parametrize( \"product_type_attribute_type, gql_attribute_type\",", "id } } } } \"\"\" # Create a dummy", "edges { node { name slug } } } }", "variables = {\"name\": name, \"attributeId\": attribute_id} response = staff_api_client.post_graphql( query,", "{ edges { node { id name slug values {", "$productTypeId: ID!, $attributeIds: [ID]! ) { attributeUnassign(productTypeId: $productTypeId, attributeIds: $attributeIds)", "{\"filters\": {\"search\": \"color\"}} attributes = get_graphql_content( api_client.post_graphql(ATTRIBUTES_FILTER_QUERY, variables) )[\"data\"][\"attributes\"][\"edges\"] assert", "UPDATE_ATTRIBUTE_QUERY attribute = color_attribute name = \"<NAME>\" node_id = graphene.Node.to_global_id(\"Attribute\",", "attribute # when sorted by ID. Thus, we are sure", "staff_user ): \"\"\"Ensure the attribute values are properly resolved when", "add an attribute as a variant attribute when the product", "graphene.Node.to_global_id(\"Attribute\", color_attribute.id) value_id = graphene.Node.to_global_id(\"AttributeValue\", -1) variables = { \"type\":", "attribute = color_attribute_without_values staff_api_client.user.user_permissions.add(permission_manage_products) product_type_global_id = graphene.Node.to_global_id(\"ProductType\", product_type.pk) query =", "value=\"#RED\" ) node_id = graphene.Node.to_global_id(\"AttributeValue\", value.id) variables = {\"name\": pink_attribute_value.name,", "product = products[0][\"node\"] variant = product[\"variants\"][0] # Ensure the product", "AttributeValueType.URL), (\"ftp://example.com\", AttributeValueType.URL), (\"example.com\", AttributeValueType.STRING), (\"Foo\", AttributeValueType.STRING), (\"linear-gradient(red, yellow)\", AttributeValueType.GRADIENT),", "UNASSIGN_ATTR_QUERY = \"\"\" mutation unAssignAttribute( $productTypeId: ID!, $attributeIds: [ID]! )", "attribute's input type doesn't support variants\"\"\" attribute = size_attribute attribute.input_type", "id variantAttributes { id } productAttributes { id } }", "object for the attribute vs the product type if is_variant:", "type (invalid ID).\"\"\" product_type_id = graphene.Node.to_global_id(\"ProductType\", -1) attribute_id = graphene.Node.to_global_id(\"Attribute\",", "assert filter_attributes_by_product_types(qs, \"...\", \"\") is qs assert filter_attributes_by_product_types(qs, \"...\", None)", ") for attr_id in variant_attributes_ids: operations.append( {\"type\": \"VARIANT\", \"id\": graphene.Node.to_global_id(\"Attribute\",", "ATTRIBUTE_VALUES_RESORT_QUERY, variables, permissions=[permission_manage_products], ) )[\"data\"][\"attributeReorderValues\"] assert content[\"errors\"] == [ {", "-1, }, ], } expected_order = [values[1].pk, values[2].pk, values[0].pk] content", "should raise an error when trying to use an attribute", "test_update_attribute_remove_and_add_values( staff_api_client, color_attribute, permission_manage_products ): query = UPDATE_ATTRIBUTE_QUERY attribute =", "test_unassign_attributes_from_product_type( staff_api_client, permission_manage_products, attribute_list ): product_type = ProductType.objects.create(name=\"Type\") product_type_global_id =", "hide the attribute color_attribute.visible_in_storefront = False color_attribute.save(update_fields=[\"visible_in_storefront\"]) attribute_count = Attribute.objects.all().count()", "data = content[\"data\"][\"attributeUpdate\"] assert not data[\"errors\"] assert data[\"attribute\"][\"name\"] == name", "not content[\"errors\"] assert ( content[\"productType\"][\"id\"] == product_type_id ), \"Did not", "assert actual_order == expected_order ATTRIBUTES_FILTER_QUERY = \"\"\" query($filters: AttributeFilterInput!) {", "Push the last attribute to the top and let the", "value.id) variables = {\"name\": pink_attribute_value.name, \"id\": node_id} response = staff_api_client.post_graphql(", "data[\"productErrors\"][0][\"code\"] == ProductErrorCode.ALREADY_EXISTS.name assert data[\"productErrors\"][0][\"field\"] == \"name\" def test_create_attribute_value_capitalized_name( staff_api_client,", "value) def test_get_single_attribute_by_pk(user_api_client, color_attribute_without_values): attribute_gql_id = graphene.Node.to_global_id( \"Attribute\", color_attribute_without_values.id )", "( \"Red color\", \"red color\", \"Provided values are not unique.\",", "{ slug } } } } } } } \"\"\"", "ID!, $name: String!) { attributeValueUpdate( id: $id, input: {name: $name})", "Attribute.objects.create(name=\"P\", slug=\"product\") unassigned_variant_attribute = Attribute.objects.create(name=\"V\", slug=\"variant\") # Create a value", "= content[\"data\"][\"attributeValueUpdate\"] assert data[\"errors\"] assert data[\"errors\"][0][\"message\"] assert data[\"errors\"][0][\"field\"] == \"name\"", "data[\"attribute\"][\"values\"][0][\"name\"] == name assert data[\"attribute\"][\"values\"][0][\"slug\"] == slugify(name) @pytest.mark.parametrize( \"input_slug, expected_slug,", "product_type, category, collection, collection_with_products, test_deprecated_filter, tested_field, ): if \"Collection\" in", "} \"\"\" def test_sort_values_within_attribute_invalid_product_type( staff_api_client, permission_manage_products ): \"\"\"Try to reorder", "get_graphql_content(api_client.post_graphql(query))[\"data\"][\"products\"][ \"edges\" ][0][\"node\"] product_attributes = product[\"attributes\"] variant_attributes = product[\"variants\"][0][\"attributes\"] assert", "{ field message code } attribute { name slug values", "= \"Value name\" variables = {\"name\": attribute_name, \"values\": [{\"name\": name}]}", "to an attribute value: {value_id}\", } ] def test_sort_values_within_attribute( staff_api_client,", "staff_api_client, product, color_attribute, permission_manage_products ): query = QUERY_ATTRIBUTES # hide", "last attribute to the top and let the others to", "= content[\"data\"][\"attributeUpdate\"] assert not data[\"errors\"] assert data[\"attribute\"][\"name\"] == name ==", "\"attributevariant\"), (\"PRODUCT\", \"product_attributes\", \"attributeproduct\"), ), ) def test_sort_attributes_within_product_type( staff_api_client, attribute_list,", "f\"Couldn't resolve to an attribute: {attribute_id}\", } ] def test_sort_values_within_attribute_invalid_id(", "= attribute_list assert len(attributes) == 3 staff_api_client.user.user_permissions.add(permission_manage_products) product_type = ProductType.objects.create(name=\"Dummy", "have found an attribute\" assert content[\"data\"][\"attribute\"][\"id\"] == attribute_gql_id assert content[\"data\"][\"attribute\"][\"slug\"]", "all None assert len(product[\"attributes\"]) == 1 assert product[\"attributes\"][0][\"attribute\"][\"slug\"] == \"color\"", "\"\"\" mutation unAssignAttribute( $productTypeId: ID!, $attributeIds: [ID]! ) { attributeUnassign(productTypeId:", "= get_graphql_content(response) data = content[\"data\"][\"attributeDelete\"] assert data[\"attribute\"][\"id\"] == variables[\"id\"] with", "assert len(attributes) == 1 assert attributes[0][\"node\"][\"slug\"] == \"size\" def test_filter_attributes_if_available_in_grid(", "type slug } } } \"\"\" def test_create_attribute_value( staff_api_client, color_attribute,", "{ \"field\": \"moves\", \"message\": f\"Couldn't resolve to an attribute: {attribute_id}\",", "expected_variant_attribute_count = variant.attributes.count() - 1 if is_staff: api_client.user = staff_user", ")[\"data\"][\"attributes\"][\"edges\"] assert len(attributes) == 1 assert attributes[0][\"node\"][\"slug\"] == \"size\" def", "expected_qs = Attribute.objects.filter( Q(attributeproduct__product_type_id=product_type.pk) | Q(attributevariant__product_type_id=product_type.pk) ) # Create another", "\"name\" def test_create_attribute_value_capitalized_name( staff_api_client, color_attribute, permission_manage_products ): attribute = color_attribute", "3 staff_api_client.user.user_permissions.add(permission_manage_products) attribute_id = graphene.Node.to_global_id(\"Attribute\", attribute.id) m2m_values = attribute.values m2m_values.set(values)", "assert data[\"attribute\"][\"id\"] == variables[\"id\"] with pytest.raises(attribute._meta.model.DoesNotExist): attribute.refresh_from_db() CREATE_ATTRIBUTE_VALUE_QUERY = \"\"\"", "\"field\": \"operations\", \"message\": \"Variants are disabled in this product type.\",", "to None m2m_rel_other_attr.sort_order = 0 m2m_rel_other_attr.save(update_fields=[\"sort_order\"]) # Assign attributes to", "assert errors[0][\"field\"] == \"removeValues\" err_msg = \"Value %s does not", "= data[\"attributeValue\"] assert attr_data[\"name\"] == name assert attr_data[\"slug\"] == slugify(name)", "# Retrieve the nodes data product = products[0][\"node\"] variant =", "\"\"\" query($sortBy: AttributeSortingInput) { attributes(first: 10, sortBy: $sortBy) { edges", "{ errors { field message } attribute { id }", "} } } \"\"\" def test_create_attribute_value( staff_api_client, color_attribute, permission_manage_products ):", "assert attributes[0][\"node\"][\"slug\"] == \"a\" assert attributes[1][\"node\"][\"slug\"] == \"b\" @pytest.mark.parametrize( \"sort_field,", "ID # This will allow us to make sure it", "= \"\"\" query($id: ID!) { attribute(id: $id) { id slug", "= product.variants.first() product_attribute = color_attribute variant_attribute = size_attribute expected_product_attribute_count =", "attribute = color_attribute name = \"<NAME>\" attribute_value_name = \"Red Color\"", "Attribute.objects.all() with pytest.raises(NotImplementedError) as exc: filter_attributes_by_product_types(qs, \"in_space\", \"a-value\") assert exc.value.args", "attribute_name ), \"The default slug should be the slugified name\"", "= get_graphql_content( staff_api_client.post_graphql( ATTRIBUTES_RESORT_QUERY, variables, permissions=[permission_manage_products] ) )[\"data\"][\"productTypeReorderAttributes\"] assert content[\"errors\"]", "attribute when the attribute's input type doesn't support variants\"\"\" attribute", "@pytest.mark.parametrize( \"sort_field, m2m_model\", ( (\"DASHBOARD_VARIANT_POSITION\", AttributeVariant), (\"DASHBOARD_PRODUCT_POSITION\", AttributeProduct), ), )", "def test_sort_attributes_by_position_in_product_type( api_client, color_attribute, size_attribute, sort_field: str, m2m_model: Union[AttributeVariant, AttributeProduct],", "user_api_client.post_graphql(query, {\"id\": attribute_gql_id}) ) assert content[\"data\"][\"attribute\"], \"Should have found an", "another collection with products but shouldn't get matched # as", "an error with pytest.raises(ValidationError): validate_value_is_unique(color_attribute, AttributeValue(slug=value.slug)) # a new value", "[], \"removeValues\": []} response = staff_api_client.post_graphql( query, variables, permissions=[permission_manage_products] )", "attribute, expected_value, ): \"\"\"Checks if the attributes are restricted and", "} } } \"\"\" def test_search_attributes(api_client, color_attribute, size_attribute): variables =", "product_attributes[0][\"values\"] == [] assert variant_attributes[0][\"value\"] is None assert variant_attributes[0][\"attribute\"][\"slug\"] ==", "is not directly associated to it. \"\"\" # Retrieve the", "\"\"\"Ensure passing an empty or null value is ignored and", "shouldn't get matched # as we don't look for this", "} } } } } } \"\"\" ) )[\"data\"][\"products\"][\"edges\"] #", "( data[\"attribute\"][\"productTypes\"][\"edges\"] == [] ), \"The attribute should not have", "received_slugs = sorted( [attributes[0][\"node\"][\"slug\"], attributes[1][\"node\"][\"slug\"]] ) assert received_slugs == expected_slugs", "[ int(graphene.Node.from_global_id(attr[\"attribute\"][\"id\"])[1]) for attr in attributes ] # Compare the", "ID!, $name: String!, $addValues: [AttributeValueCreateInput]!, $removeValues: [ID]!) { attributeUpdate( id:", "content[\"productType\"][\"id\"] == product_type_global_id assert len(content[\"productType\"][\"productAttributes\"]) == len( product_attributes_ids ) assert", "\"The attribute should not have been assigned to a product", "correct product type\" gql_attributes = content[\"productType\"][snake_to_camel_case(relation_field)] assert len(gql_attributes) == len(expected_order)", "else: m2m_rel_other_attr = other_attribute.attributeproduct.last() # Push the last attribute to", "\"size\" assert attributes[1][\"node\"][\"slug\"] == \"color\" def test_sort_attributes_by_default_sorting(api_client): \"\"\"Don't provide any", "== slugify( attribute_name ), \"The default slug should be the", "): attribute = color_attribute AttributeValue.objects.create(attribute=attribute, name=\"Green\", slug=\"green\") values = list(attribute.values.all())", "= graphene.Node.to_global_id( \"Attribute\", color_attribute_without_values.id ) query = \"\"\" query($id: ID!)", "a new value but with existing slug should raise an", "} } } } } \"\"\" def test_attributes_query(user_api_client, product): attributes", "== slugify(name) @pytest.mark.parametrize( \"input_slug, expected_slug, expected_error\", ( (\"my-slug\", \"my-slug\", []),", "1 expected_variant_attribute_count += 1 staff_user.user_permissions.add(permission_manage_products) # Hide one product and", "{ attribute { slug } values { name } }", "category.pk) else: raise AssertionError(tested_field) expected_qs = Attribute.objects.filter( Q(attributeproduct__product_type_id=product_type.pk) | Q(attributevariant__product_type_id=product_type.pk)", "), \"The attribute should not have been assigned to a", "found_variant_attrs_ids == variant_attributes_ids def test_assign_variant_attribute_to_product_type_with_disabled_variants( staff_api_client, permission_manage_products, product_type_without_variant, color_attribute_without_values, ):", "for attr in attributes ] # Compare the received data", "attribute was correctly created assert data[\"attribute\"][\"name\"] == attribute_name assert data[\"attribute\"][\"slug\"]", "type but not of the node (product/variant), thus no values", "variables))[ \"data\" ][\"attributeAssign\"] assert content[\"errors\"] == [ { \"field\": \"operations\",", "{ name slug values { name slug } productTypes(first: 10)", "product_type.pk) query = ASSIGN_ATTR_QUERY operations = [] variables = {\"productTypeId\":", "exception. \"\"\" qs = Attribute.objects.all() with pytest.raises(NotImplementedError) as exc: filter_attributes_by_product_types(qs,", "= staff_api_client.post_graphql(query) content = get_graphql_content(response) attributes_data = content[\"data\"][\"attributes\"][\"edges\"] assert len(attributes_data)", "\"b\" @pytest.mark.parametrize( \"sort_field, m2m_model\", ( (\"DASHBOARD_VARIANT_POSITION\", AttributeVariant), (\"DASHBOARD_PRODUCT_POSITION\", AttributeProduct), ),", "with pytest.raises(ValidationError): validate_value_is_unique(color_attribute, AttributeValue(slug=value.slug)) # a new value with a", "} } } \"\"\" def test_unassign_attributes_from_product_type( staff_api_client, permission_manage_products, attribute_list ):", "\"values\": [{\"name\": name}]} response = staff_api_client.post_graphql( query, variables, permissions=[permission_manage_products] )", "no error was expected if expected_error is None: assert content[\"data\"][\"attributeCreate\"][\"attribute\"][\"slug\"]", "} ] UNASSIGN_ATTR_QUERY = \"\"\" mutation unAssignAttribute( $productTypeId: ID!, $attributeIds:", "= content[\"data\"][\"attributeValueCreate\"] assert not data[\"productErrors\"] attr_data = data[\"attributeValue\"] assert attr_data[\"name\"]", "attr_data[\"slug\"] == slugify(name) assert attr_data[\"type\"] == \"STRING\" assert name in", "{ \"type\": \"VARIANT\", \"productTypeId\": product_type_id, \"moves\": [{\"id\": attribute_id, \"sortOrder\": 1}],", "size_attribute.values.first() attr_id = graphene.Node.to_global_id(\"AttributeValue\", size_attribute.pk) variables = { \"name\": \"Example", "== 2, \"Non-assigned attr from the PT may be missing\"", "from the product and its variant product.attributesrelated.clear() variant.attributesrelated.clear() # Retrieve", "# Create a dummy attribute with a higher ID #", "= False color_attribute.save(update_fields=[\"visible_in_storefront\"]) attribute_count = Attribute.objects.get_visible_to_user( user_api_client.user ).count() assert attribute_count", "if the attribute was correctly created assert data[\"attribute\"][\"name\"] == attribute_name", "node_id, \"addValues\": [], \"removeValues\": []} response = staff_api_client.post_graphql( query, variables,", "UPDATE_ATTRIBUTE_VALUE_QUERY = \"\"\" mutation updateChoice( $id: ID!, $name: String!) {", "not raise any error when trying to remove an attribute", "staff_api_client.post_graphql( ATTRIBUTES_RESORT_QUERY, variables, permissions=[permission_manage_products] ) )[\"data\"][\"productTypeReorderAttributes\"] assert content[\"errors\"] == [", "product type.\"\"\" product_type = ProductType.objects.create(name=\"Dummy Type\") product_type_id = graphene.Node.to_global_id(\"ProductType\", product_type.id)", "\"sortOrder\": 1}], } content = get_graphql_content( staff_api_client.post_graphql( ATTRIBUTE_VALUES_RESORT_QUERY, variables, permissions=[permission_manage_products],", "1 response = user_api_client.post_graphql(query) content = get_graphql_content(response) attributes_data = content[\"data\"][\"attributes\"][\"edges\"]", "variables = {\"name\": \"Example name\", \"values\": [{\"name\": name_1}, {\"name\": name_2}]}", "attribute { slug } values { name } } variants", "expected_slugs = sorted([attribute_list[0].slug, attribute_list[1].slug]) attributes = get_graphql_content( api_client.post_graphql(ATTRIBUTES_FILTER_QUERY, variables) )[\"data\"][\"attributes\"][\"edges\"]", "{\"productTypeId\": product_type_global_id, \"operations\": operations} product_attributes_ids = {attr.pk for attr in", "get_graphql_content(response) errors = content[\"data\"][\"attributeUpdate\"][\"errors\"] assert errors assert errors[0][\"field\"] == \"addValues\"", "is not None else o.pk ), \"The values are not", "assert product[\"attributes\"][0][\"attribute\"][\"slug\"] == \"color\" assert product[\"attributes\"][0][\"values\"] == [] # Ensure", "be blank.\"}], ), ), ) def test_create_attribute_with_given_slug( staff_api_client, permission_manage_products, input_slug,", "content[\"data\"][\"attributes\"][\"edges\"] assert len(attributes_data) == attribute_count def test_attributes_query_hidden_attribute_as_staff_user( staff_api_client, product, color_attribute,", "attribute_count QUERY_PRODUCT_AND_VARIANTS_ATTRIBUTES = \"\"\" { products(first: 1) { edges {", "AttributeVariant), (\"DASHBOARD_PRODUCT_POSITION\", AttributeProduct), ), ) def test_sort_attributes_by_position_in_product_type( api_client, color_attribute, size_attribute,", "attributes unassigned_product_attribute = Attribute.objects.create(name=\"P\", slug=\"product\") unassigned_variant_attribute = Attribute.objects.create(name=\"V\", slug=\"variant\") #", "attributes(first: 10, filter: $filters) { edges { node { name", "attributes[0][\"node\"][\"slug\"] == \"size\" def test_filter_attributes_if_available_in_grid( api_client, color_attribute, size_attribute ): color_attribute.available_in_grid", "graphene.Node.to_global_id(\"Attribute\", attributes[0].pk), \"sortOrder\": +1, }, { \"id\": graphene.Node.to_global_id(\"Attribute\", attributes[2].pk), \"sortOrder\":", "permission_manage_products, product_type_without_variant, color_attribute_without_values, ): \"\"\"The assignAttribute mutation should raise an", "): \"\"\"The assignAttribute mutation should raise an error when trying", "\"DESC\"}} attributes = get_graphql_content( api_client.post_graphql(ATTRIBUTES_SORT_QUERY, variables) )[\"data\"][\"attributes\"][\"edges\"] assert len(attributes) ==", "\"addValues\": [], \"removeValues\": [attr_id], } response = staff_api_client.post_graphql( query, variables,", "id: $id, input: { name: $name, addValues: $addValues, removeValues: $removeValues})", "variant_attributes[0][\"values\"][0][\"slug\"] == variant_attribute_values[0] assert variant_attributes[0][\"value\"][\"slug\"] == variant_attribute_values[0] def test_resolve_attribute_values_non_assigned_to_node( user_api_client,", "the product attributes values are all None assert len(product[\"attributes\"]) ==", "== 2 assert attributes[0][\"node\"][\"slug\"] == \"size\" assert attributes[1][\"node\"][\"slug\"] == \"color\"", "} } } \"\"\" if test_deprecated_filter: query = query %", ") variant_attribute_values = list( variant.attributes.first().values.values_list(\"slug\", flat=True) ) assert len(product_attribute_values) ==", "error_msg, error_code\", ( ( \"Red color\", \"Red color\", \"Provided values", "\"moves\": [ { \"id\": graphene.Node.to_global_id(\"AttributeValue\", values[0].pk), \"sortOrder\": +1, }, {", "for attribute in (product_attribute, variant_attribute): attribute.visible_in_storefront = False attribute.save(update_fields=[\"visible_in_storefront\"]) product", "\"name\": name, \"id\": node_id, \"addValues\": [{\"name\": attribute_value_name}], \"removeValues\": [value_id], }", "staff_api_client, color_attribute, permission_manage_products ): attribute = color_attribute query = CREATE_ATTRIBUTE_VALUE_QUERY", "trying to remove an attribute that is not/no longer in", "not properly ordered\" variables = { \"attributeId\": attribute_id, \"moves\": [", "get_graphql_content( api_client.post_graphql(ATTRIBUTES_FILTER_QUERY, variables) )[\"data\"][\"attributes\"][\"edges\"] assert len(attributes) == 1 assert attributes[0][\"node\"][\"slug\"]", "the M2M object for the attribute vs the product type", "node, color_attribute, color_attribute.values.first() ) # Sort the database attributes by", "[ {\"type\": \"VARIANT\", \"id\": graphene.Node.to_global_id(\"Attribute\", attribute.pk)} ] variables = {\"productTypeId\":", "get_graphql_content( staff_api_client.post_graphql(ATTRIBUTES_RESORT_QUERY, variables) )[\"data\"][\"productTypeReorderAttributes\"] assert not content[\"errors\"] assert ( content[\"productType\"][\"id\"]", ") assert received_slugs == expected_slugs ATTRIBUTES_SORT_QUERY = \"\"\" query($sortBy: AttributeSortingInput)", "= pink_attribute_value node_id = graphene.Node.to_global_id(\"AttributeValue\", value.id) name = \"Crimson name\"", "if o.sort_order is not None else o.pk ), \"The values", "{ field message } } } \"\"\" def test_sort_attributes_within_product_type_invalid_product_type( staff_api_client,", "product[\"variants\"][0][\"attributes\"] assert len(product_attributes) == len(product_attribute_values) assert len(variant_attributes) == len(variant_attribute_values) assert", "raises a NotImplemented exception. \"\"\" qs = Attribute.objects.all() with pytest.raises(NotImplementedError)", "String!) { attributeValueUpdate( id: $id, input: {name: $name}) { errors", "node_id}))[ \"data\" ] attributes = data[\"productVariant\" if is_variant else \"product\"][\"attributes\"]", "-1) mocked_qs = mock.MagicMock() qs = filter_attributes_by_product_types(mocked_qs, \"in_category\", category_id) assert", "attribute = color_attribute_without_values staff_api_client.user.user_permissions.add(permission_manage_products) product_type_global_id = graphene.Node.to_global_id(\"ProductType\", product_type.pk) if product_type_attribute_type", "} ] def test_sort_values_within_attribute_invalid_id( staff_api_client, permission_manage_products, color_attribute ): \"\"\"Try to", "of the product type but not of the node (product/variant),", "} response = staff_api_client.post_graphql( query, variables, permissions=[permission_manage_products] ) content =", "remaining_attribute_global_id = graphene.Node.to_global_id( \"Attribute\", product_attributes[1].pk ) query = UNASSIGN_ATTR_QUERY variables", "== len( product_attributes_ids ) assert len(content[\"productType\"][\"variantAttributes\"]) == len( variant_attributes_ids )", "variables, permissions=[permission_manage_products] ) )[\"data\"][\"productTypeReorderAttributes\"] assert content[\"errors\"] == [ { \"field\":", "attributes[1][\"node\"][\"slug\"]] ) assert received_slugs == expected_slugs ATTRIBUTES_SORT_QUERY = \"\"\" query($sortBy:", "variables = { \"productTypeId\": product_type_global_id, \"attributeIds\": [ graphene.Node.to_global_id(\"Attribute\", color_attribute_without_values.pk) ],", "variables) )[\"data\"][\"attributes\"][\"edges\"] assert len(attributes) == 2 assert attributes[0][\"node\"][\"slug\"] == \"size\"", "dummy attribute with a higher ID # This will allow", "not associated to the given product type.\"\"\" product_type = ProductType.objects.create(name=\"Dummy", "color_attribute.save(update_fields=[\"visible_in_storefront\"]) attribute_count = Attribute.objects.get_visible_to_user( user_api_client.user ).count() assert attribute_count == 1", "to reorder an attribute not associated to the given product", "get_graphql_content(response) data = content[\"data\"][\"attributeDelete\"] assert data[\"attribute\"][\"id\"] == variables[\"id\"] with pytest.raises(attribute._meta.model.DoesNotExist):", "variables = {\"name\": value_name, \"attributeId\": attribute_id} response = staff_api_client.post_graphql( query,", "$id) { attributeValue { name slug } } } \"\"\"", "(\"#FF69B4\", AttributeValueType.COLOR), (\"rgb(255, 0, 0)\", AttributeValueType.COLOR), (\"hsl(0, 100%, 50%)\", AttributeValueType.COLOR),", "variant's attributes products = get_graphql_content( api_client.post_graphql( \"\"\" { products(first: 10)", "thus no values should be resolved. \"\"\" query = QUERY_PRODUCT_AND_VARIANTS_ATTRIBUTES", "== \"color\" def test_filter_attributes_if_filterable_in_dashboard( api_client, color_attribute, size_attribute ): color_attribute.filterable_in_dashboard =", "Retrieve the M2M object for the attribute vs the product", "belong to this attribute.\" % str(size_attribute) assert errors[0][\"message\"] == err_msg", "content[\"data\"][\"attributeValueUpdate\"] value.refresh_from_db() assert data[\"attributeValue\"][\"name\"] == name == value.name assert data[\"attributeValue\"][\"slug\"]", "product type.\", } ] def test_assign_variant_attribute_having_unsupported_input_type( staff_api_client, permission_manage_products, product_type, size_attribute", "message } } } \"\"\" def test_sort_attributes_within_product_type_invalid_product_type( staff_api_client, permission_manage_products ):", "attribute { id } } } } \"\"\" else: query", "slug=\"product\") unassigned_variant_attribute = Attribute.objects.create(name=\"V\", slug=\"variant\") # Create a value for", "staff_api_client, color_attribute_without_values, permission_manage_products ): query = UPDATE_ATTRIBUTE_QUERY attribute = color_attribute_without_values", "ProductErrorCode.ALREADY_EXISTS.name assert data[\"productErrors\"][0][\"field\"] == \"name\" UPDATE_ATTRIBUTE_VALUE_QUERY = \"\"\" mutation updateChoice(", "{name: $name}) { errors { field message } attributeValue {", "), \"Did not return the correct product type\" gql_attributes =", "product' permission can. \"\"\" query = QUERY_PRODUCT_AND_VARIANTS_ATTRIBUTES api_client = user_api_client", "= content[\"productType\"][snake_to_camel_case(relation_field)] assert len(gql_attributes) == len(expected_order) for attr, expected_pk in", "are not unique.\", ProductErrorCode.UNIQUE, ), ), ) def test_create_attribute_and_attribute_values_errors( staff_api_client,", "ID if is_variant: node_id = graphene.Node.to_global_id(\"ProductVariant\", variant.pk) else: node_id =", "(invalid ID).\"\"\" attribute_id = graphene.Node.to_global_id(\"Attribute\", -1) value_id = graphene.Node.to_global_id(\"AttributeValue\", -1)", "to it. \"\"\" # Retrieve the product's variant variant =", "import Union from unittest import mock import graphene import pytest", "= size_attribute expected_product_attribute_count = product.attributes.count() - 1 expected_variant_attribute_count = variant.attributes.count()", "Check if the attribute was correctly created assert data[\"attribute\"][\"name\"] ==", "= graphene.Node.to_global_id(\"Attribute\", attribute.id) name = \"<NAME>\" variables = {\"name\": name,", "{ name } } variants { attributes { attribute {", "to add an attribute as a variant attribute when the", "} } } } \"\"\" ) )[\"data\"][\"products\"][\"edges\"] # Ensure we", "input type doesn't support variants\"\"\" attribute = size_attribute attribute.input_type =", "unAssignAttribute( $productTypeId: ID!, $attributeIds: [ID]! ) { attributeUnassign(productTypeId: $productTypeId, attributeIds:", "actual_order.append(int(gql_attr_id)) assert actual_order == expected_order ATTRIBUTES_FILTER_QUERY = \"\"\" query($filters: AttributeFilterInput!)", "QUERY_PRODUCT_AND_VARIANTS_ATTRIBUTES = \"\"\" { products(first: 1) { edges { node", "assert not content[\"data\"][\"attributeCreate\"][\"errors\"] data = content[\"data\"][\"attributeCreate\"] # Check if the", "} } attributeValue { name type slug } } }", "trying to use an attribute as a variant attribute when", "= color_attribute name = \"<NAME>\" node_id = graphene.Node.to_global_id(\"Attribute\", attribute.id) variables", "# Make the node ID if is_variant: node_id = graphene.Node.to_global_id(\"ProductVariant\",", "{ id values { id } } errors { field", "shouldn't be able to see the hidden attributes assert Attribute.objects.get_visible_to_user(staff_api_client.user).count()", "] ) # Assign the dummy attributes to the product", "be missing\" assert product_attributes[0][\"attribute\"][\"slug\"] == \"product\" assert product_attributes[0][\"values\"] == []", "= Attribute.objects.filter( Q(attributeproduct__product_type_id=product_type.pk) | Q(attributevariant__product_type_id=product_type.pk) ) # Create another product", ")[\"data\"][\"products\"][\"edges\"] # Ensure we are only working on one product", "2, \"Non-assigned attr from the PT may be missing\" assert", "to the top and let the others to None m2m_rel_other_attr.sort_order", "error_msg, error_code, permission_manage_products, product_type, ): query = CREATE_ATTRIBUTES_QUERY variables =", "to manage products, # the user shouldn't be able to", "assert errors assert errors[0][\"field\"] == \"addValues\" assert errors[0][\"message\"] == error_msg", "color_attribute name = \"<NAME>\" attribute_value_name = \"Red Color\" node_id =", "\"\"\"Ensure the attributes assigned to a product type are resolved", "a dummy attribute with a higher ID # This will", "UPDATE_ATTRIBUTE_QUERY attribute = color_attribute node_id = graphene.Node.to_global_id(\"Attribute\", attribute.id) variables =", "user_api_client.post_graphql(query) content = get_graphql_content(response) attributes_data = content[\"data\"][\"attributes\"][\"edges\"] assert attributes_data assert", "attributeCreate(input: {name: $name, values: $values}) { errors { field message", "= {attr.pk for attr in attribute_list[2:]} for attr_id in product_attributes_ids:", "product_type.variant_attributes.add(attribute) else: raise ValueError(f\"Unknown: {product_type}\") query = ASSIGN_ATTR_QUERY operations =", "and values from the product and its variant product.attributesrelated.clear() variant.attributesrelated.clear()", "assert variant_attributes[0][\"values\"] == [] assert variant_attributes[0][\"value\"] is None def test_attributes_filter_by_product_type_with_empty_value():", "attribute shouldn't be taken into account validate_value_is_unique(color_attribute, value) def test_get_single_attribute_by_pk(user_api_client,", "permission_manage_products, attribute, expected_value, ): \"\"\"Checks if the attributes are restricted", "associated to the given product type.\"\"\" product_type = ProductType.objects.create(name=\"Dummy Type\")", "query = query % {\"filter_input\": f\"{tested_field}: $nodeID\"} else: query =", "$slug}) { errors { field message } attribute { slug", "other_collection = Collection.objects.create( name=\"Other Collection\", slug=\"other-collection\", is_published=True, description=\"Description\", ) other_collection.products.add(other_product)", "non-existing category ID returns an empty query set.\"\"\" category_id =", "product type: {product_type_id}\", } ] def test_sort_attributes_within_product_type_invalid_id( staff_api_client, permission_manage_products, color_attribute", "\"product\"][\"attributes\"] actual_order = [ int(graphene.Node.from_global_id(attr[\"attribute\"][\"id\"])[1]) for attr in attributes ]", "gql_attr_id = graphene.Node.from_global_id(attr[\"id\"]) assert gql_type == \"AttributeValue\" actual_order.append(int(gql_attr_id)) assert actual_order", "import resolve_attribute_value_type from saleor.product import AttributeInputType from saleor.product.error_codes import ProductErrorCode", "when the attribute's input type doesn't support variants\"\"\" attribute =", "was expected if expected_error is None: assert content[\"data\"][\"attributeCreate\"][\"attribute\"][\"slug\"] == expected_slug", "data[\"attribute\"][\"id\"] == variables[\"id\"] with pytest.raises(attribute._meta.model.DoesNotExist): attribute.refresh_from_db() CREATE_ATTRIBUTE_VALUE_QUERY = \"\"\" mutation", "graphene.Node.to_global_id(\"ProductType\", product_type.pk) query = UNASSIGN_ATTR_QUERY variables = { \"productTypeId\": product_type_global_id,", "attribute { slug } values { slug } value {", "Create a dummy attribute with a higher ID # This", "{ attributes(first: 10, sortBy: $sortBy) { edges { node {", "= graphene.Node.to_global_id(\"Attribute\", attribute.id) size_attribute = size_attribute.values.first() attr_id = graphene.Node.to_global_id(\"AttributeValue\", size_attribute.pk)", "ValueError(f\"Unknown: {product_type}\") query = ASSIGN_ATTR_QUERY operations = [ { \"type\":", "\"Attribute\" assert int(gql_attr_id) == expected_pk ATTRIBUTE_VALUES_RESORT_QUERY = \"\"\" mutation attributeReorderValues($attributeId:", "edges { node { id } } } } }", "for this other collection other_collection = Collection.objects.create( name=\"Other Collection\", slug=\"other-collection\",", "data[\"errors\"][0][\"message\"] assert data[\"errors\"][0][\"field\"] == \"name\" def test_delete_attribute_value( staff_api_client, color_attribute, pink_attribute_value,", "field message } productType { id productAttributes { id }", "doesn't provide any value for it or is not directly", ") content = get_graphql_content( staff_api_client.post_graphql( query, variables, permissions=[permission_manage_products] ) )[\"data\"][\"attributeAssign\"]", "slug } value { slug } } variants { attributes", "product_type_global_id, \"operations\": operations} content = get_graphql_content(staff_api_client.post_graphql(query, variables))[ \"data\" ][\"attributeAssign\"] assert", "error when trying to add an attribute as a variant", "size_attribute, sort_field: str, m2m_model: Union[AttributeVariant, AttributeProduct], ): \"\"\"Sorts attributes for", "variables = { \"name\": \"Example name\", \"id\": node_id, \"slug\": \"example-slug\",", "variant.attributes.count() - 1 if is_staff: api_client.user = staff_user expected_product_attribute_count +=", "Attribute.objects.create(name=\"Other\", slug=\"other\") # Add the attribute to the product type", "== 1 response = user_api_client.post_graphql(query) content = get_graphql_content(response) attributes_data =", "content[\"errors\"] assert ( content[\"productType\"][\"id\"] == product_type_id ), \"Did not return", "} } \"\"\" def test_create_attribute_value( staff_api_client, color_attribute, permission_manage_products ): attribute", "= pink_attribute_value.attribute.values.create( name=\"<NAME>\", slug=\"example-name\", value=\"#RED\" ) node_id = graphene.Node.to_global_id(\"AttributeValue\", value.id)", "query = ASSIGN_ATTR_QUERY operations = [ { \"type\": gql_attribute_type.value, \"id\":", "attribute = to_camel_case(attribute) query = ( \"\"\" { attributes(first: 10)", "== expected_order ATTRIBUTES_FILTER_QUERY = \"\"\" query($filters: AttributeFilterInput!) { attributes(first: 10,", "the received data against our expectations assert actual_order == expected_order", "field message } attribute { id } } } \"\"\"", "field message code } attribute { name slug values {", "slug } } } \"\"\" node_id = graphene.Node.to_global_id(\"AttributeValue\", value.id) variables", "\"\"\" { products(first: 1) { edges { node { attributes", "{ \"field\": \"operations\", \"message\": \"Color (color) have already been assigned", "field message } productErrors { field message code } attribute", "= color_attribute variant_attribute = size_attribute expected_product_attribute_count = product.attributes.count() - 1", "len(data[\"attribute\"][\"values\"]) == 1 assert data[\"attribute\"][\"values\"][0][\"name\"] == name assert data[\"attribute\"][\"values\"][0][\"slug\"] ==", "slug } productAttributes { id } } errors { field", "see the hidden attributes assert Attribute.objects.get_visible_to_user(staff_api_client.user).count() == 1 # The", "= graphene.Node.to_global_id(\"Category\", category.pk) else: raise AssertionError(tested_field) expected_qs = Attribute.objects.filter( Q(attributeproduct__product_type_id=product_type.pk)", "data[\"attribute\"][\"values\"][0][\"slug\"] == slugify(name) @pytest.mark.parametrize( \"input_slug, expected_slug, expected_error\", ( (\"my-slug\", \"my-slug\",", "{ edges { node { name slug } } }", "} } \"\"\" else: query = \"\"\" query($id: ID!) {", "assert attribute.values.filter(name=attribute_value_name).exists() @pytest.mark.parametrize( \"name_1, name_2, error_msg, error_code\", ( ( \"Red", "graphene.Node.to_global_id(\"AttributeValue\", size_attribute.pk) variables = { \"name\": \"Example name\", \"id\": node_id,", "expected_pk in zip(gql_values, expected_order): gql_type, gql_attr_id = graphene.Node.from_global_id(attr[\"id\"]) assert gql_type", "def test_filter_attributes_if_available_in_grid( api_client, color_attribute, size_attribute ): color_attribute.available_in_grid = False color_attribute.save(update_fields=[\"available_in_grid\"])", "= \"<NAME>\" node_id = graphene.Node.to_global_id(\"Attribute\", attribute.id) variables = {\"name\": name,", "import ProductErrorCode from saleor.product.models import ( Attribute, AttributeProduct, AttributeValue, AttributeVariant,", "AttributeVariant.objects.create( attribute=unassigned_variant_attribute, product_type=product_type, sort_order=0 ) assert product.attributes.count() == 1 assert", "\"\"\" mutation deleteAttribute($id: ID!) { attributeDelete(id: $id) { errors {", "$name}) { productErrors { field message code } attribute {", "= get_graphql_content( staff_api_client.post_graphql(ATTRIBUTE_VALUES_RESORT_QUERY, variables) )[\"data\"][\"attributeReorderValues\"] assert not content[\"errors\"] assert content[\"attribute\"][\"id\"]", "color_attribute_without_values staff_api_client.user.user_permissions.add(permission_manage_products) product_type_global_id = graphene.Node.to_global_id(\"ProductType\", product_type.pk) query = ASSIGN_ATTR_QUERY operations", "{ name } } attributeValue { name type slug }", "= \"Value %s does not belong to this attribute.\" %", "attributes.count() def test_attributes_query_hidden_attribute(user_api_client, product, color_attribute): query = QUERY_ATTRIBUTES # hide", "product_type_attribute_type == AttributeTypeEnum.VARIANT: product_type.variant_attributes.add(attribute) else: raise ValueError(f\"Unknown: {product_type}\") query =", "test_update_attribute_and_add_attribute_values_errors( staff_api_client, name_1, name_2, error_msg, error_code, color_attribute, permission_manage_products, ): query", "the attributes of products and variants are sorted.\"\"\" variant =", "snake_to_camel_case from saleor.graphql.product.enums import AttributeTypeEnum, AttributeValueType from saleor.graphql.product.filters import filter_attributes_by_product_types", "== [] assert variant_attributes[0][\"value\"] is None assert variant_attributes[0][\"attribute\"][\"slug\"] == \"variant\"", "assert len(content[\"productType\"][\"productAttributes\"]) == len( product_attributes_ids ) assert len(content[\"productType\"][\"variantAttributes\"]) == len(", "Union[Product, ProductVariant] node.attributesrelated.clear() associate_attribute_values_to_instance( node, color_attribute, color_attribute.values.first() ) # Sort", "variables = { \"name\": \"Example name\", \"id\": node_id, \"removeValues\": [],", "expected_error is None: assert content[\"data\"][\"attributeCreate\"][\"attribute\"][\"slug\"] == expected_slug @pytest.mark.parametrize( \"name_1, name_2,", "attributes { attribute { slug } values { name }", "== [] # Ensure the variant attributes values are all", "assert attributes[1][\"node\"][\"slug\"] == \"a\" @pytest.mark.parametrize(\"is_variant\", (True, False)) def test_attributes_of_products_are_sorted( staff_api_client,", "is simply returned without any modification. \"\"\" qs = Attribute.objects.all()", "= UPDATE_ATTRIBUTE_QUERY attribute = color_attribute node_id = graphene.Node.to_global_id(\"Attribute\", attribute.id) size_attribute", "name } } variants { attributes { attribute { slug", "data = content[\"data\"][\"attributeDelete\"] assert data[\"attribute\"][\"id\"] == variables[\"id\"] with pytest.raises(attribute._meta.model.DoesNotExist): attribute.refresh_from_db()", "= False color_attribute.save(update_fields=[\"visible_in_storefront\"]) attribute_count = Attribute.objects.all().count() # The user doesn't", "attribute=unassigned_product_attribute), ] ) # Assign the dummy attributes to the", "get_graphql_content(response) attributes_data = content[\"data\"][\"attributes\"][\"edges\"] assert attributes_data assert len(attributes_data) == attributes.count()", "else: product.product_type.product_attributes.set([color_attribute, other_attribute]) # Retrieve the M2M object for the", "mutation should raise an error when trying to add an", "assigned \" \"as variant attributes\" ), } ] @pytest.mark.parametrize( \"product_type_attribute_type,", "\"\"\" query($filters: AttributeFilterInput!) { attributes(first: 10, filter: $filters) { edges", "slug=\"variant\") # Create a value for each dummy attribute to", "): attributes = attribute_list assert len(attributes) == 3 staff_api_client.user.user_permissions.add(permission_manage_products) product_type", "{ field message } productType { id variantAttributes { id", "attributeReorderValues($attributeId: ID!, $moves: [ReorderInput]!) { attributeReorderValues(attributeId: $attributeId, moves: $moves) {", "query($filters: AttributeFilterInput!) { attributes(first: 10, filter: $filters) { edges {", "staff_api_client, attribute_list, permission_manage_products, attribute_type, relation_field, backref_field, ): attributes = attribute_list", "through a sort_order=0 as the other attributes have sort_order=null AttributeProduct.objects.create(", "\"slug\": input_slug} content = get_graphql_content(staff_api_client.post_graphql(query, variables)) # Check if the", "them at the top # through a sort_order=0 as the", "AttributeProduct.objects.create( attribute=unassigned_product_attribute, product_type=product_type, sort_order=0 ) AttributeVariant.objects.create( attribute=unassigned_variant_attribute, product_type=product_type, sort_order=0 )", "'manage product' permission can. \"\"\" query = QUERY_PRODUCT_AND_VARIANTS_ATTRIBUTES api_client =", "assert len(content[\"productType\"][\"productAttributes\"]) == 1 assert len(content[\"productType\"][\"variantAttributes\"]) == 1 assert (", "staff_api_client, permission_manage_products ): query = CREATE_ATTRIBUTES_QUERY attribute_name = \"<NAME>\" name", "Attribute(name=\"MyAttribute\", slug=\"b\"), Attribute(name=\"MyAttribute\", slug=\"a\"), ] ) variables = {\"sortBy\": {\"field\":", "api_client = user_api_client variant = product.variants.first() product_type = product.product_type #", "the nodes data product = products[0][\"node\"] variant = product[\"variants\"][0] #", "attributeCreate(input: {name: $name, slug: $slug}) { errors { field message", "{ field message } attribute { slug } } }", "graphene.Node.from_global_id(attr[\"id\"]) assert gql_type == \"AttributeValue\" actual_order.append(int(gql_attr_id)) assert actual_order == expected_order", "product.variants.first() product_attribute = color_attribute variant_attribute = size_attribute expected_product_attribute_count = product.attributes.count()", "from saleor.graphql.product.enums import AttributeTypeEnum, AttributeValueType from saleor.graphql.product.filters import filter_attributes_by_product_types from", "variant.pk) else: node_id = graphene.Node.to_global_id(\"Product\", product.pk) # Retrieve the attributes", "} } \"\"\" def test_sort_values_within_attribute_invalid_product_type( staff_api_client, permission_manage_products ): \"\"\"Try to", "size_attribute attribute.input_type = AttributeInputType.MULTISELECT attribute.save(update_fields=[\"input_type\"]) product_type.variant_attributes.clear() staff_api_client.user.user_permissions.add(permission_manage_products) product_type_global_id = graphene.Node.to_global_id(\"ProductType\",", "value.id) variables = {\"id\": node_id} staff_api_client.post_graphql( query, variables, permissions=[permission_manage_products] )", "== len( variant_attributes_ids ) found_product_attrs_ids = { int(graphene.Node.from_global_id(attr[\"id\"])[1]) for attr", "): if \"Collection\" in tested_field: filtered_by_node_id = graphene.Node.to_global_id(\"Collection\", collection.pk) elif", "error when trying to use an attribute as a variant", "== (\"Filtering by in_space is unsupported\",) def test_attributes_filter_by_non_existing_category_id(): \"\"\"Ensure using", "else o.pk ), \"The values are not properly ordered\" variables", "\"id\": node_id, \"slug\": \"example-slug\", \"addValues\": [], \"removeValues\": [attr_id], } response", "graphene.Node.to_global_id(\"Attribute\", attribute.id) variables = { \"name\": \"Example name\", \"id\": node_id,", "from the storefront for attribute in (product_attribute, variant_attribute): attribute.visible_in_storefront =", "assert product_attributes[0][\"value\"][\"slug\"] == product_attribute_values[0] assert variant_attributes[0][\"attribute\"][\"slug\"] == \"size\" assert variant_attributes[0][\"values\"][0][\"slug\"]", "belongs to the attribute shouldn't be taken into account validate_value_is_unique(color_attribute,", "CREATE_ATTRIBUTE_VALUE_QUERY attribute_id = graphene.Node.to_global_id(\"Attribute\", attribute.id) name = \"<NAME>\" variables =", "query = \"\"\" { products(first: 10) { edges { node", ") content = get_graphql_content(response) data = content[\"data\"][\"attributeDelete\"] assert data[\"attribute\"][\"id\"] ==", "== product_attribute_values[0] assert variant_attributes[0][\"attribute\"][\"slug\"] == \"size\" assert variant_attributes[0][\"values\"][0][\"slug\"] == variant_attribute_values[0]", "AssertionError(tested_field) expected_qs = Attribute.objects.filter( Q(attributeproduct__product_type_id=product_type.pk) | Q(attributevariant__product_type_id=product_type.pk) ) # Create", "variant_attribute): attribute.visible_in_storefront = False attribute.save(update_fields=[\"visible_in_storefront\"]) product = get_graphql_content(api_client.post_graphql(query))[\"data\"][\"products\"][ \"edges\" ][0][\"node\"]", "an error when trying to use an attribute as a", "to ensure they are not returned # by the product", "\"The attribute's slug cannot be blank.\"}], ), ), ) def", "\"type\": \"VARIANT\", \"attributeId\": attribute_id, \"moves\": [{\"id\": value_id, \"sortOrder\": 1}], }", "{ edges { node { attributes { values { type", "id } } errors { field message } } }", "= color_attribute_without_values staff_api_client.user.user_permissions.add(permission_manage_products) product_type_global_id = graphene.Node.to_global_id(\"ProductType\", product_type.pk) if product_type_attribute_type ==", "\"\"\" mutation updateAttribute( $id: ID!, $name: String!, $addValues: [AttributeValueCreateInput]!, $removeValues:", "Product.objects.create( name=f\"Another Product\", product_type=other_product_type, category=other_category, price=zero_money(), is_published=True, ) # Create", "== name == attribute.name assert not attribute.values.filter(pk=attribute_value_id).exists() assert attribute.values.filter(name=attribute_value_name).exists() def", "== 1 assert product[\"attributes\"][0][\"attribute\"][\"slug\"] == \"color\" assert product[\"attributes\"][0][\"values\"] == []", "list(expected_qs.values_list(\"slug\", flat=True)) assert flat_attributes_data == expected_flat_attributes_data CREATE_ATTRIBUTES_QUERY = \"\"\" mutation", "resolve_attribute_value_type from saleor.product import AttributeInputType from saleor.product.error_codes import ProductErrorCode from", "== 1 assert len(variant_attribute_values) == 1 product = get_graphql_content(api_client.post_graphql(query))[\"data\"][\"products\"][ \"edges\"", "filter_attributes_by_product_types from saleor.graphql.product.mutations.attributes import validate_value_is_unique from saleor.graphql.product.types.attributes import resolve_attribute_value_type from", "): product_type = ProductType.objects.create(name=\"Default Type\", has_variants=True) product_type_global_id = graphene.Node.to_global_id(\"ProductType\", product_type.pk)", "from tests.api.utils import get_graphql_content def test_validate_value_is_unique(color_attribute): value = color_attribute.values.first() #", "} ] variables = {\"productTypeId\": product_type_global_id, \"operations\": operations} content =", "name_1, name_2, error_msg, error_code, permission_manage_products, product_type, ): query = CREATE_ATTRIBUTES_QUERY", "reorder a value not associated to the given attribute.\"\"\" attribute_id", "\"moves\", \"message\": f\"Couldn't resolve to an attribute value: {value_id}\", }", "(\"storefront_search_position\", 0), ), ) def test_retrieving_the_restricted_attributes_restricted( staff_api_client, color_attribute, permission_manage_products, attribute,", "import mock import graphene import pytest from django.core.exceptions import ValidationError", "ProductType.objects.create(name=\"Type\") product_type_global_id = graphene.Node.to_global_id(\"ProductType\", product_type.pk) query = UNASSIGN_ATTR_QUERY variables =", "# Ensure we are only working on one product and", "it. \"\"\" # Retrieve the product's variant variant = product.variants.get()", "are sure the query is actually passing the test. other_attribute", "staff_api_client.user.user_permissions.add(permission_manage_products) attribute_id = graphene.Node.to_global_id(\"Attribute\", attribute.id) m2m_values = attribute.values m2m_values.set(values) assert", "= getattr(product_type, relation_field) m2m_attributes.set(attributes) sort_method = getattr(m2m_attributes, f\"{relation_field}_sorted\") attributes =", "product node = variant if is_variant else product # type:", "None m2m_rel_other_attr.sort_order = 0 m2m_rel_other_attr.save(update_fields=[\"sort_order\"]) # Assign attributes to the", "\"Example name\", \"id\": node_id, \"slug\": \"example-slug\", \"addValues\": [], \"removeValues\": [attr_id],", "data[\"attribute\"][\"productTypes\"][\"edges\"] == [] def test_update_attribute_remove_and_add_values( staff_api_client, color_attribute, permission_manage_products ): query", "assert len(found_attributes) == 1 assert found_attributes[0][\"node\"][attribute] == expected_value ATTRIBUTES_RESORT_QUERY =", "= \"\"\" mutation updateChoice($id: ID!) { attributeValueDelete(id: $id) { attributeValue", "query($sortBy: AttributeSortingInput) { attributes(first: 10, sortBy: $sortBy) { edges {", "== variant_attribute_values[0] def test_resolve_attribute_values_non_assigned_to_node( user_api_client, product, staff_user ): \"\"\"Ensure the", "query, variables, permissions=[permission_manage_products] ) content = get_graphql_content(response) assert not content[\"data\"][\"attributeCreate\"][\"errors\"]", "} attribute { id } } } \"\"\" node_id =", "they are not associated to them AttributeValue.objects.bulk_create( [ AttributeValue(slug=\"a\", name=\"A\",", "the other attributes have sort_order=null AttributeProduct.objects.create( attribute=unassigned_product_attribute, product_type=product_type, sort_order=0 )", "product_attributes_ids = {attr.pk for attr in attribute_list[:2]} variant_attributes_ids = {attr.pk", "productAttributes { id } } } } \"\"\" def test_unassign_attributes_from_product_type(", "} content = get_graphql_content(staff_api_client.post_graphql(query, variables))[ \"data\" ][\"attributeUnassign\"] assert not content[\"errors\"]", "1 assert attributes[0][\"node\"][\"slug\"] == \"size\" def test_filter_attributes_if_available_in_grid( api_client, color_attribute, size_attribute", "other attributes have sort_order=null AttributeProduct.objects.create( attribute=unassigned_product_attribute, product_type=product_type, sort_order=0 ) AttributeVariant.objects.create(", "content[\"productType\"][\"id\"] == product_type_id ), \"Did not return the correct product", "query = CREATE_ATTRIBUTE_VALUE_QUERY attribute_id = graphene.Node.to_global_id(\"Attribute\", attribute.id) name = \"<NAME>\"", "color_attribute.visible_in_storefront = False color_attribute.save(update_fields=[\"visible_in_storefront\"]) attribute_count = Attribute.objects.all().count() # The user", "name == value.name assert data[\"attributeValue\"][\"slug\"] == slugify(name) assert name in", "api_client, color_attribute, size_attribute ): color_attribute.available_in_grid = False color_attribute.save(update_fields=[\"available_in_grid\"]) variables =", "{ edges { node { attributes { attribute { slug", "== 2 assert attributes[0][\"node\"][\"slug\"] == \"a\" assert attributes[1][\"node\"][\"slug\"] == \"b\"", "the queryset is simply returned without any modification. \"\"\" qs", "get_graphql_content(user_api_client.post_graphql(query, variables)) attributes_data = content[\"data\"][\"attributes\"][\"edges\"] flat_attributes_data = [attr[\"node\"][\"slug\"] for attr", ") # value that already belongs to the attribute shouldn't", "no values should be resolved. \"\"\" query = QUERY_PRODUCT_AND_VARIANTS_ATTRIBUTES api_client", "variables)) attributes_data = content[\"data\"][\"attributes\"][\"edges\"] flat_attributes_data = [attr[\"node\"][\"slug\"] for attr in", "the attribute values were correctly created assert len(data[\"attribute\"][\"values\"]) == 1", "id: $id, input: {name: $name}) { errors { field message", "$name}) { errors { field message } attributeValue { name", "product_type_global_id = graphene.Node.to_global_id(\"ProductType\", product_type.pk) query = ASSIGN_ATTR_QUERY operations = [", "= content[\"data\"][\"attributes\"][\"edges\"] flat_attributes_data = [attr[\"node\"][\"slug\"] for attr in attributes_data] expected_flat_attributes_data", "attribute_id gql_values = content[\"attribute\"][\"values\"] assert len(gql_values) == len(expected_order) actual_order =", "variant attribute from the storefront for attribute in (product_attribute, variant_attribute):", "% {\"filter_input\": \"filter: { %s: $nodeID }\" % tested_field} variables", "field message } productType { id variantAttributes { id }", "assert len(attributes) == 3 variables = { \"type\": attribute_type, \"productTypeId\":", "api_client, color_attribute, size_attribute ): color_attribute.filterable_in_dashboard = False color_attribute.save(update_fields=[\"filterable_in_dashboard\"]) variables =", "gql_attribute_type, ): \"\"\"The assignAttribute mutation should raise an error when", "], } content = get_graphql_content( staff_api_client.post_graphql( query, variables, permissions=[permission_manage_products] )", "if their default value is the expected one.\"\"\" attribute =", "= size_attribute attribute.input_type = AttributeInputType.MULTISELECT attribute.save(update_fields=[\"input_type\"]) product_type.variant_attributes.clear() staff_api_client.user.user_permissions.add(permission_manage_products) product_type_global_id =", "taken into account validate_value_is_unique(color_attribute, value) def test_get_single_attribute_by_pk(user_api_client, color_attribute_without_values): attribute_gql_id =", "assert len(content[\"productType\"][\"variantAttributes\"]) == 0 def test_retrieve_product_attributes_input_type( staff_api_client, product, permission_manage_products ):", "1 assert attributes[0][\"node\"][\"slug\"] == \"color\" def test_filter_attributes_if_filterable_in_dashboard( api_client, color_attribute, size_attribute", "= get_graphql_content(response) attribute.refresh_from_db() data = content[\"data\"][\"attributeUpdate\"] assert data[\"attribute\"][\"name\"] == name", "AttributeValueType from saleor.graphql.product.filters import filter_attributes_by_product_types from saleor.graphql.product.mutations.attributes import validate_value_is_unique from", "= list(sort_method()) assert len(attributes) == 3 variables = { \"type\":", "color_attribute.values.get(name=\"Red\") query = \"\"\" mutation updateChoice($id: ID!) { attributeValueDelete(id: $id)", "{ node { id } } } } } }", "node_id = graphene.Node.to_global_id(\"AttributeValue\", value.id) variables = {\"name\": pink_attribute_value.name, \"id\": node_id}", "\"field\": \"operations\", \"message\": ( \"Attributes having for input types ['multiselect']", "mutation updateChoice($id: ID!) { attributeValueDelete(id: $id) { attributeValue { name", "True), (\"value_required\", False), (\"storefront_search_position\", 0), ), ) def test_retrieving_the_restricted_attributes_restricted( staff_api_client,", "variables, permissions=[permission_manage_products] ) content = get_graphql_content(response) assert not content[\"data\"][\"attributeCreate\"][\"errors\"] data", "expected_order = [other_attribute.pk, color_attribute.pk] # Make the node ID if", "name\" variables = {\"name\": name, \"id\": node_id} response = staff_api_client.post_graphql(", "UPDATE_ATTRIBUTE_QUERY = \"\"\" mutation updateAttribute( $id: ID!, $name: String!, $addValues:", "= graphene.Node.to_global_id(\"Attribute\", color_attribute.id) value_id = graphene.Node.to_global_id(\"AttributeValue\", -1) variables = {", "[] for attr, expected_pk in zip(gql_values, expected_order): gql_type, gql_attr_id =", "m2m_model\", ( (\"DASHBOARD_VARIANT_POSITION\", AttributeVariant), (\"DASHBOARD_PRODUCT_POSITION\", AttributeProduct), ), ) def test_sort_attributes_by_position_in_product_type(", "= graphene.Node.to_global_id(\"Attribute\", attribute.id) value_name = attribute.values.first().name variables = {\"name\": value_name,", "values { name } } variants { attributes { attribute", "is unsupported\",) def test_attributes_filter_by_non_existing_category_id(): \"\"\"Ensure using a non-existing category ID", "permissions=[permission_manage_products]) )[\"data\"][\"attributes\"][\"edges\"] assert len(found_attributes) == 1 assert found_attributes[0][\"node\"][attribute] == expected_value", "values are all None assert len(product[\"attributes\"]) == 1 assert product[\"attributes\"][0][\"attribute\"][\"slug\"]", "len(gql_attr[\"values\"]) == 1 assert gql_attr[\"values\"][0][\"type\"] == \"STRING\" assert gql_attr[\"values\"][0][\"inputType\"] ==", "[]), ( \"\", None, [{\"field\": \"slug\", \"message\": \"The attribute's slug", "resolved when an attribute is part of the product type", "): attribute = color_attribute query = CREATE_ATTRIBUTE_VALUE_QUERY attribute_id = graphene.Node.to_global_id(\"Attribute\",", "if the product doesn't provide any value for it or", "not unique.\", ProductErrorCode.UNIQUE, ), ), ) def test_create_attribute_and_attribute_values_errors( staff_api_client, name_1,", "product type.\", } ] UNASSIGN_ATTR_QUERY = \"\"\" mutation unAssignAttribute( $productTypeId:", "} } variants { attributes { attribute { slug }", "product_type_global_id = graphene.Node.to_global_id(\"ProductType\", product_type.pk) query = UNASSIGN_ATTR_QUERY variables = {", "{ \"id\": graphene.Node.to_global_id(\"Attribute\", attributes[0].pk), \"sortOrder\": +1, }, { \"id\": graphene.Node.to_global_id(\"Attribute\",", "already been assigned to this product type.\", } ] UNASSIGN_ATTR_QUERY", "ATTRIBUTES_RESORT_QUERY = \"\"\" mutation ProductTypeReorderAttributes( $productTypeId: ID! $moves: [ReorderInput]! $type:", "variantAttributes { id } productAttributes { id } } }", "def test_attributes_query(user_api_client, product): attributes = Attribute.objects query = QUERY_ATTRIBUTES response", "product_attributes = product[\"attributes\"] variant_attributes = product[\"variants\"][0][\"attributes\"] assert len(product_attributes) == len(product_attribute_values)", "its variant product.attributesrelated.clear() variant.attributesrelated.clear() # Retrieve the product and variant's", "permission_manage_products ): attribute = color_attribute query = CREATE_ATTRIBUTE_VALUE_QUERY attribute_id =", "attributes assigned to a product type are resolved even if", "{\"type\": \"VARIANT\", \"id\": graphene.Node.to_global_id(\"Attribute\", attribute.pk)} ] variables = {\"productTypeId\": product_type_global_id,", "product_attributes[0][\"values\"][0][\"slug\"] == product_attribute_values[0] assert product_attributes[0][\"value\"][\"slug\"] == product_attribute_values[0] assert variant_attributes[0][\"attribute\"][\"slug\"] ==", "} } \"\"\" node_id = graphene.Node.to_global_id(\"Attribute\", attribute.id) variables = {\"id\":", "\"\"\" mutation createAttribute($name: String!, $values: [AttributeValueCreateInput]) { attributeCreate(input: {name: $name,", "and variant's attributes products = get_graphql_content( api_client.post_graphql( \"\"\" { products(first:", "the PT may be missing\" assert len(variant_attributes) == 2, \"Non-assigned", "staff_api_client.post_graphql( query, variables, permissions=[permission_manage_products] ) content = get_graphql_content(response) errors =", "test_deprecated_filter, tested_field, ): if \"Collection\" in tested_field: filtered_by_node_id = graphene.Node.to_global_id(\"Collection\",", "saleor.core.taxes import zero_money from saleor.graphql.core.utils import snake_to_camel_case from saleor.graphql.product.enums import", "assert data[\"productErrors\"] assert data[\"productErrors\"][0][\"code\"] == ProductErrorCode.ALREADY_EXISTS.name assert data[\"productErrors\"][0][\"field\"] == \"name\"", "to a product type are resolved even if the product", "permission_manage_products, ): \"\"\"Ensure non-staff users don't see hidden attributes, and", "values[0].pk] content = get_graphql_content( staff_api_client.post_graphql(ATTRIBUTE_VALUES_RESORT_QUERY, variables) )[\"data\"][\"attributeReorderValues\"] assert not content[\"errors\"]", "attribute=size_attribute, sort_order=1 ) variables = {\"sortBy\": {\"field\": sort_field, \"direction\": \"DESC\"}}", "an attribute: {attribute_id}\", } ] def test_sort_values_within_attribute_invalid_id( staff_api_client, permission_manage_products, color_attribute", "attribute_id = graphene.Node.to_global_id(\"Attribute\", color_attribute.id) value_id = graphene.Node.to_global_id(\"AttributeValue\", -1) variables =", "m2m_model.objects.create( product_type=product_type, attribute=size_attribute, sort_order=1 ) variables = {\"sortBy\": {\"field\": sort_field,", "ASSIGN_ATTR_QUERY operations = [] variables = {\"productTypeId\": product_type_global_id, \"operations\": operations}", "[ { \"field\": \"attributeId\", \"message\": f\"Couldn't resolve to an attribute:", "variables) )[\"data\"][\"attributes\"][\"edges\"] assert len(attributes) == 2 assert attributes[0][\"node\"][\"slug\"] == \"a\"", "mutation unAssignAttribute( $productTypeId: ID!, $attributeIds: [ID]! ) { attributeUnassign(productTypeId: $productTypeId,", "dummy attribute to ensure they are not returned # by", "pytest.raises(value._meta.model.DoesNotExist): value.refresh_from_db() @pytest.mark.parametrize( \"raw_value, expected_type\", [ (\"#0000\", AttributeValueType.COLOR), (\"#FF69B4\", AttributeValueType.COLOR),", "not content[\"data\"][\"attributeCreate\"][\"errors\"] data = content[\"data\"][\"attributeCreate\"] # Check if the attribute", "\"id\": node_id, \"addValues\": [], \"removeValues\": []} response = staff_api_client.post_graphql( query,", "= staff_api_client.post_graphql( query, variables, permissions=[permission_manage_products] ) content = get_graphql_content(response) attribute.refresh_from_db()", "value_name.upper(), \"attributeId\": attribute_id} response = staff_api_client.post_graphql( query, variables, permissions=[permission_manage_products] )", "} } } } \"\"\" def test_unassign_attributes_from_product_type( staff_api_client, permission_manage_products, attribute_list", "sorting, this should sort by name by default.\"\"\" Attribute.objects.bulk_create( [Attribute(name=\"A\",", "ProductType.objects.create( name=\"Other type\", has_variants=True, is_shipping_required=True ) other_product_type.product_attributes.add(other_attribute) other_product = Product.objects.create(", "mutation updateAttribute( $id: ID!, $name: String!, $addValues: [AttributeValueCreateInput]!, $removeValues: [ID]!)", "== variant_attributes_ids def test_assign_variant_attribute_to_product_type_with_disabled_variants( staff_api_client, permission_manage_products, product_type_without_variant, color_attribute_without_values, ): \"\"\"The", "type.\"\"\" product_type = ProductType.objects.create(name=\"My Product Type\") m2m_model.objects.create( product_type=product_type, attribute=color_attribute, sort_order=0", "should not have been assigned to a product type\" #", "= ASSIGN_ATTR_QUERY operations = [ {\"type\": \"VARIANT\", \"id\": graphene.Node.to_global_id(\"Attribute\", attribute.pk)}", "content = get_graphql_content(staff_api_client.post_graphql(query, variables))[ \"data\" ][\"attributeUnassign\"] assert not content[\"errors\"] assert", "Attribute.objects.bulk_create( [ Attribute(name=\"MyAttribute\", slug=\"b\"), Attribute(name=\"MyAttribute\", slug=\"a\"), ] ) variables =", "attribute { id } } } \"\"\" node_id = graphene.Node.to_global_id(\"Attribute\",", "Create another product type and attribute that shouldn't get matched", "\"Crimson name\" variables = {\"name\": name, \"id\": node_id} response =", "assert product_attributes[0][\"values\"] == [] assert variant_attributes[0][\"value\"] is None assert variant_attributes[0][\"attribute\"][\"slug\"]", "gql_attribute_type\", ( (AttributeTypeEnum.PRODUCT, AttributeTypeEnum.VARIANT), (AttributeTypeEnum.VARIANT, AttributeTypeEnum.PRODUCT), (AttributeTypeEnum.PRODUCT, AttributeTypeEnum.PRODUCT), (AttributeTypeEnum.VARIANT, AttributeTypeEnum.VARIANT),", "staff_api_client, name_1, name_2, error_msg, error_code, color_attribute, permission_manage_products, ): query =", "][0][\"node\"] assert len(product[\"attributes\"]) == expected_product_attribute_count assert len(product[\"variants\"][0][\"attributes\"]) == expected_variant_attribute_count def", "other_attribute]) else: product.product_type.product_attributes.set([color_attribute, other_attribute]) # Retrieve the M2M object for", "{ id slug } productAttributes { id } } errors", "is_shipping_required=True ) other_product_type.product_attributes.add(other_attribute) other_product = Product.objects.create( name=f\"Another Product\", product_type=other_product_type, category=other_category,", "\"message\": f\"Couldn't resolve to an attribute: {attribute_id}\", } ] def", "global_ids}} expected_slugs = sorted([attribute_list[0].slug, attribute_list[1].slug]) attributes = get_graphql_content( api_client.post_graphql(ATTRIBUTES_FILTER_QUERY, variables)", "can. \"\"\" query = QUERY_PRODUCT_AND_VARIANTS_ATTRIBUTES api_client = user_api_client variant =", "= getattr(m2m_attributes, f\"{relation_field}_sorted\") attributes = list(sort_method()) assert len(attributes) == 3", "attr from the PT may be missing\" assert product_attributes[0][\"attribute\"][\"slug\"] ==", "error when trying to remove an attribute that is not/no", "Attribute(name=\"B\", slug=\"a\")] ) attributes = get_graphql_content( api_client.post_graphql(ATTRIBUTES_SORT_QUERY, {}) )[\"data\"][\"attributes\"][\"edges\"] assert", "color_attribute, permission_manage_products ): query = UPDATE_ATTRIBUTE_QUERY attribute = color_attribute name", "== [] def test_update_attribute_remove_and_add_values( staff_api_client, color_attribute, permission_manage_products ): query =", "@pytest.mark.parametrize( \"product_type_attribute_type, gql_attribute_type\", ( (AttributeTypeEnum.PRODUCT, AttributeTypeEnum.VARIANT), (AttributeTypeEnum.VARIANT, AttributeTypeEnum.PRODUCT), (AttributeTypeEnum.PRODUCT, AttributeTypeEnum.PRODUCT),", "dummy attributes unassigned_product_attribute = Attribute.objects.create(name=\"P\", slug=\"product\") unassigned_variant_attribute = Attribute.objects.create(name=\"V\", slug=\"variant\")", "field message } attributeValue { name slug } attribute {", "query = QUERY_PRODUCT_AND_VARIANTS_ATTRIBUTES api_client = user_api_client variant = product.variants.first() assert", "assert len(data[\"attribute\"][\"values\"]) == 1 assert data[\"attribute\"][\"values\"][0][\"name\"] == name assert data[\"attribute\"][\"values\"][0][\"slug\"]", "{ \"productTypeId\": product_type_global_id, \"attributeIds\": [ graphene.Node.to_global_id(\"Attribute\", product_attributes[0].pk) ], } content", "new slug should pass validate_value_is_unique( color_attribute, AttributeValue(slug=\"spanish-inquisition\") ) # value", "new value but with existing slug should raise an error", "\"<NAME>\" attribute_value_name = \"Red Color\" node_id = graphene.Node.to_global_id(\"Attribute\", attribute.id) attribute_value_id", "ProductType.objects.create(name=\"Type\") product_type_global_id = graphene.Node.to_global_id(\"ProductType\", product_type.pk) variant_attribute, *product_attributes = attribute_list product_type.product_attributes.add(*product_attributes)", "10) { edges { node { %s } } }", "color_attribute.filterable_in_dashboard = False color_attribute.save(update_fields=[\"filterable_in_dashboard\"]) variables = {\"filters\": {\"filterableInDashboard\": True}} attributes", "} ] @pytest.mark.parametrize( \"product_type_attribute_type, gql_attribute_type\", ( (AttributeTypeEnum.PRODUCT, AttributeTypeEnum.VARIANT), (AttributeTypeEnum.VARIANT, AttributeTypeEnum.PRODUCT),", "gql_attr_id = graphene.Node.from_global_id(attr[\"id\"]) assert gql_type == \"Attribute\" assert int(gql_attr_id) ==", "= graphene.Node.to_global_id(\"ProductType\", product_type.id) m2m_attributes = getattr(product_type, relation_field) m2m_attributes.set(attributes) sort_method =", "properly ordered\" variables = { \"attributeId\": attribute_id, \"moves\": [ {", "int(gql_attr_id) == expected_pk ATTRIBUTE_VALUES_RESORT_QUERY = \"\"\" mutation attributeReorderValues($attributeId: ID!, $moves:", "message } attributeValue { name slug } attribute { values", "products[0][\"node\"] variant = product[\"variants\"][0] # Ensure the product attributes values", "@pytest.mark.parametrize( \"name_1, name_2, error_msg, error_code\", ( ( \"Red color\", \"Red", "assert name in [value[\"name\"] for value in data[\"attribute\"][\"values\"]] def test_create_attribute_value_not_unique_name(", "list( product.attributes.first().values.values_list(\"slug\", flat=True) ) variant_attribute_values = list( variant.attributes.first().values.values_list(\"slug\", flat=True) )", "== \"name\" def test_delete_attribute_value( staff_api_client, color_attribute, pink_attribute_value, permission_manage_products ): value", ") def test_unassign_attributes_not_in_product_type( staff_api_client, permission_manage_products, color_attribute_without_values ): \"\"\"The unAssignAttribute mutation", "\"Red color\", \"Red color\", \"Provided values are not unique.\", ProductErrorCode.UNIQUE,", "$sortBy) { edges { node { slug } } }", "attribute_count def test_attributes_query_hidden_attribute_as_staff_user( staff_api_client, product, color_attribute, permission_manage_products ): query =", "} content = get_graphql_content( staff_api_client.post_graphql( query, variables, permissions=[permission_manage_products] ) )[\"data\"][\"attributeUnassign\"]", "gql_attr in found_products[0][\"node\"][\"attributes\"]: assert len(gql_attr[\"values\"]) == 1 assert gql_attr[\"values\"][0][\"type\"] ==", "color_attribute_without_values, permission_manage_products ): query = UPDATE_ATTRIBUTE_QUERY attribute = color_attribute_without_values name", "ProductTypeReorderAttributes( $productTypeId: ID! $moves: [ReorderInput]! $type: AttributeTypeEnum! ) { productTypeReorderAttributes(", "test_validate_value_is_unique(color_attribute): value = color_attribute.values.first() # a new value but with", "collection, collection_with_products, test_deprecated_filter, tested_field, ): if \"Collection\" in tested_field: filtered_by_node_id", "if product_type_attribute_type == AttributeTypeEnum.PRODUCT: product_type.product_attributes.add(attribute) elif product_type_attribute_type == AttributeTypeEnum.VARIANT: product_type.variant_attributes.add(attribute)", "$removeValues: [ID]!) { attributeUpdate( id: $id, input: { name: $name,", "None) is qs def test_attributes_filter_by_product_type_with_unsupported_field(): \"\"\"Ensure using an unknown field", "node { name slug } } } } \"\"\" def", "{product_type_id}\", } ] def test_sort_attributes_within_product_type_invalid_id( staff_api_client, permission_manage_products, color_attribute ): \"\"\"Try", "query, variables, permissions=[permission_manage_products] ) content = get_graphql_content(response) errors = content[\"data\"][\"attributeCreate\"][\"errors\"]", "other_collection.products.add(other_product) query = \"\"\" query($nodeID: ID!) { attributes(first: 20, %(filter_input)s)", "response = staff_api_client.post_graphql( query, variables, permissions=[permission_manage_products] ) get_graphql_content(response) attribute.refresh_from_db() assert", "graphene.Node.to_global_id(\"Attribute\", color_attribute.id) variables = { \"type\": \"VARIANT\", \"productTypeId\": product_type_id, \"moves\":", "message } } } \"\"\" def test_sort_values_within_attribute_invalid_product_type( staff_api_client, permission_manage_products ):", "= data[\"productVariant\" if is_variant else \"product\"][\"attributes\"] actual_order = [ int(graphene.Node.from_global_id(attr[\"attribute\"][\"id\"])[1])", "assert data[\"productErrors\"][0][\"code\"] == ProductErrorCode.ALREADY_EXISTS.name assert data[\"productErrors\"][0][\"field\"] == \"name\" def test_create_attribute_value_capitalized_name(", "size_attribute): variables = {\"filters\": {\"search\": \"color\"}} attributes = get_graphql_content( api_client.post_graphql(ATTRIBUTES_FILTER_QUERY,", "== [ { \"field\": \"attributeId\", \"message\": f\"Couldn't resolve to an", "query = QUERY_ATTRIBUTES response = user_api_client.post_graphql(query) content = get_graphql_content(response) attributes_data", "pink_attribute_value node_id = graphene.Node.to_global_id(\"AttributeValue\", value.id) name = \"Crimson name\" variables", "\"ASC\"}} attributes = get_graphql_content( api_client.post_graphql(ATTRIBUTES_SORT_QUERY, variables) )[\"data\"][\"attributes\"][\"edges\"] assert len(attributes) ==", "\"sortOrder\": +1, }, { \"id\": graphene.Node.to_global_id(\"AttributeValue\", values[2].pk), \"sortOrder\": -1, },", "custom ordering inside a given product type.\"\"\" product_type = ProductType.objects.create(name=\"My", "= variant if is_variant else product # type: Union[Product, ProductVariant]", "variables = {\"filters\": {\"availableInGrid\": True}} attributes = get_graphql_content( api_client.post_graphql(ATTRIBUTES_FILTER_QUERY, variables)", "\"variant_attributes\", \"attributevariant\"), (\"PRODUCT\", \"product_attributes\", \"attributeproduct\"), ), ) def test_sort_attributes_within_product_type( staff_api_client,", "if expected_error is None: assert content[\"data\"][\"attributeCreate\"][\"attribute\"][\"slug\"] == expected_slug @pytest.mark.parametrize( \"name_1,", "not associated to the given attribute.\"\"\" attribute_id = graphene.Node.to_global_id(\"Attribute\", color_attribute.id)", "{name: $name, slug: $slug}) { errors { field message }", "\"\"\" mutation attributeReorderValues($attributeId: ID!, $moves: [ReorderInput]!) { attributeReorderValues(attributeId: $attributeId, moves:", "color_attribute.available_in_grid = False color_attribute.save(update_fields=[\"available_in_grid\"]) variables = {\"filters\": {\"availableInGrid\": True}} attributes", "attribute_list, permission_manage_products, attribute_type, relation_field, backref_field, ): attributes = attribute_list assert", "@pytest.mark.parametrize( \"raw_value, expected_type\", [ (\"#0000\", AttributeValueType.COLOR), (\"#FF69B4\", AttributeValueType.COLOR), (\"rgb(255, 0,", "from saleor.graphql.product.types.attributes import resolve_attribute_value_type from saleor.product import AttributeInputType from saleor.product.error_codes", "len(products) == 1 assert len(products[0][\"node\"][\"variants\"]) == 1 # Retrieve the", "= query % {\"filter_input\": \"filter: { %s: $nodeID }\" %", "ID!) { attributes(first: 20, %(filter_input)s) { edges { node {", "attribute_id = graphene.Node.to_global_id(\"Attribute\", attribute.id) value_name = attribute.values.first().name variables = {\"name\":", "expected_product_attribute_count assert len(product[\"variants\"][0][\"attributes\"]) == expected_variant_attribute_count def test_resolve_attribute_values(user_api_client, product, staff_user): \"\"\"Ensure", "len(product_attribute_values) assert len(variant_attributes) == len(variant_attribute_values) assert product_attributes[0][\"attribute\"][\"slug\"] == \"color\" assert", "field to filter attributes by raises a NotImplemented exception. \"\"\"", "variables, permissions=[permission_manage_products] ) with pytest.raises(value._meta.model.DoesNotExist): value.refresh_from_db() @pytest.mark.parametrize( \"raw_value, expected_type\", [", "product type (invalid ID).\"\"\" product_type_id = graphene.Node.to_global_id(\"ProductType\", -1) attribute_id =", "} attribute { name slug values { name slug }", "content = get_graphql_content(response) data = content[\"data\"][\"attributeValueUpdate\"] assert data[\"errors\"] assert data[\"errors\"][0][\"message\"]", "to_camel_case from saleor.core.taxes import zero_money from saleor.graphql.core.utils import snake_to_camel_case from", "users don't see hidden attributes, and staff users having the", "category, collection, collection_with_products, test_deprecated_filter, tested_field, ): if \"Collection\" in tested_field:", "slug cannot be blank.\"}], ), ), ) def test_create_attribute_with_given_slug( staff_api_client,", "product_type.product_attributes.add(attribute) elif product_type_attribute_type == AttributeTypeEnum.VARIANT: product_type.variant_attributes.add(attribute) else: raise ValueError(f\"Unknown: {product_type}\")", "= {\"name\": attribute_name, \"slug\": input_slug} content = get_graphql_content(staff_api_client.post_graphql(query, variables)) #", "variant = product[\"variants\"][0] # Ensure the product attributes values are", "(\"rgba(100%, 255, 0, 0)\", AttributeValueType.COLOR), (\"http://example.com\", AttributeValueType.URL), (\"https://example.com\", AttributeValueType.URL), (\"ftp://example.com\",", "= graphene.Node.to_global_id(\"AttributeValue\", value.id) variables = {\"id\": node_id} staff_api_client.post_graphql( query, variables,", "product): \"\"\"Ensure the attributes assigned to a product type are", "{ %s: $nodeID }\" % tested_field} variables = {\"nodeID\": filtered_by_node_id}", "} } \"\"\" def test_attributes_query(user_api_client, product): attributes = Attribute.objects query", "ATTRIBUTES_SORT_QUERY = \"\"\" query($sortBy: AttributeSortingInput) { attributes(first: 10, sortBy: $sortBy)", "== 0 def test_retrieve_product_attributes_input_type( staff_api_client, product, permission_manage_products ): query =", "{ \"field\": \"operations\", \"message\": ( \"Attributes having for input types", "name_2}], } response = staff_api_client.post_graphql( query, variables, permissions=[permission_manage_products] ) content", "test_sort_attributes_by_slug(api_client): Attribute.objects.bulk_create( [ Attribute(name=\"MyAttribute\", slug=\"b\"), Attribute(name=\"MyAttribute\", slug=\"a\"), ] ) variables", "this attribute.\" % str(size_attribute) assert errors[0][\"message\"] == err_msg product_errors =", "is_variant ): \"\"\"Ensures the attributes of products and variants are", "ID!) { attribute(id: $id) { id slug } } \"\"\"", "(\"visible_in_storefront\", True), (\"available_in_grid\", True), (\"value_required\", False), (\"storefront_search_position\", 0), ), )", "was correctly created assert data[\"attribute\"][\"name\"] == attribute_name assert data[\"attribute\"][\"slug\"] ==", "assert len(attributes) == 1 assert attributes[0][\"node\"][\"slug\"] == \"size\" def test_filter_attributes_by_global_id_list(api_client,", "), ) def test_update_attribute_and_add_attribute_values_errors( staff_api_client, name_1, name_2, error_msg, error_code, color_attribute,", "= [attr[\"node\"][\"slug\"] for attr in attributes_data] expected_flat_attributes_data = list(expected_qs.values_list(\"slug\", flat=True))", "assert errors[0][\"message\"] == err_msg product_errors = content[\"data\"][\"attributeUpdate\"][\"productErrors\"] assert product_errors[0][\"code\"] ==", "this should sort by name by default.\"\"\" Attribute.objects.bulk_create( [Attribute(name=\"A\", slug=\"b\"),", "slug } } variants { attributes { attribute { slug", "== product_attributes_ids assert found_variant_attrs_ids == variant_attributes_ids def test_assign_variant_attribute_to_product_type_with_disabled_variants( staff_api_client, permission_manage_products,", ")[\"data\"][\"attributeReorderValues\"] assert content[\"errors\"] == [ { \"field\": \"attributeId\", \"message\": f\"Couldn't", "\"moves\", \"message\": f\"Couldn't resolve to an attribute: {attribute_id}\", } ]", "color_attribute.save(update_fields=[\"visible_in_storefront\"]) attribute_count = Attribute.objects.all().count() # The user doesn't have the", "Retrieve the attributes data = get_graphql_content(staff_api_client.post_graphql(query, {\"id\": node_id}))[ \"data\" ]", "\"\"\" query($nodeID: ID!) { attributes(first: 20, %(filter_input)s) { edges {", "\"color\"}} attributes = get_graphql_content( api_client.post_graphql(ATTRIBUTES_FILTER_QUERY, variables) )[\"data\"][\"attributes\"][\"edges\"] assert len(attributes) ==", "attribute is part of the product type but not of", "} } } } } } \"\"\" found_products = get_graphql_content(", "the product type doesn't support variants\"\"\" product_type = product_type_without_variant attribute", "return the correct product type\" gql_attributes = content[\"productType\"][snake_to_camel_case(relation_field)] assert len(gql_attributes)", "staff_api_client, permission_manage_products, product_type_without_variant, color_attribute_without_values, ): \"\"\"The assignAttribute mutation should raise", "), ) def test_sort_attributes_within_product_type( staff_api_client, attribute_list, permission_manage_products, attribute_type, relation_field, backref_field,", "test_create_attribute_and_attribute_values_errors( staff_api_client, name_1, name_2, error_msg, error_code, permission_manage_products, product_type, ): query", "= graphene.Node.to_global_id(\"ProductType\", product_type.pk) if product_type_attribute_type == AttributeTypeEnum.PRODUCT: product_type.product_attributes.add(attribute) elif product_type_attribute_type", "Collection\", slug=\"other-collection\", is_published=True, description=\"Description\", ) other_collection.products.add(other_product) query = \"\"\" query($nodeID:", "inputType } } } } } } \"\"\" found_products =", "user_api_client, product, color_attribute, size_attribute, staff_user, is_staff, permission_manage_products, ): \"\"\"Ensure non-staff", "remaining_attribute_global_id ) def test_unassign_attributes_not_in_product_type( staff_api_client, permission_manage_products, color_attribute_without_values ): \"\"\"The unAssignAttribute", "color_attribute ): \"\"\"Try to reorder a value not associated to", "= attribute.values.first().name variables = {\"name\": value_name.upper(), \"attributeId\": attribute_id} response =", "from the PT may be missing\" assert product_attributes[0][\"attribute\"][\"slug\"] == \"product\"", "graphene.Node.to_global_id(\"ProductType\", product_type.pk) query = ASSIGN_ATTR_QUERY operations = [ {\"type\": \"VARIANT\",", "query, variables, permissions=[permission_manage_products] ) )[\"data\"][\"attributeUnassign\"] assert not content[\"errors\"] assert content[\"productType\"][\"id\"]", "== 1 assert attributes[0][\"node\"][\"slug\"] == \"size\" def test_filter_attributes_if_available_in_grid( api_client, color_attribute,", "CREATE_ATTRIBUTE_VALUE_QUERY attribute_id = graphene.Node.to_global_id(\"Attribute\", attribute.id) value_name = attribute.values.first().name variables =", "slug=\"b\"), Attribute(name=\"MyAttribute\", slug=\"a\"), ] ) variables = {\"sortBy\": {\"field\": \"SLUG\",", "} } } } } } \"\"\" def test_update_attribute_name( staff_api_client,", "assert data[\"productErrors\"][0][\"field\"] == \"name\" UPDATE_ATTRIBUTE_VALUE_QUERY = \"\"\" mutation updateChoice( $id:", "attributes ] # Compare the received data against our expectations", "} attribute { values { name } } } }", "attr_id)} ) for attr_id in variant_attributes_ids: operations.append( {\"type\": \"VARIANT\", \"id\":", "staff_api_client, permission_manage_products, color_attribute_without_values, product_type_attribute_type, gql_attribute_type, ): \"\"\"The assignAttribute mutation should", "[ Attribute(name=\"MyAttribute\", slug=\"b\"), Attribute(name=\"MyAttribute\", slug=\"a\"), ] ) variables = {\"sortBy\":", "an empty query set.\"\"\" category_id = graphene.Node.to_global_id(\"Category\", -1) mocked_qs =", "the attribute color_attribute.visible_in_storefront = False color_attribute.save(update_fields=[\"visible_in_storefront\"]) attribute_count = Attribute.objects.get_visible_to_user( user_api_client.user", "UNASSIGN_ATTR_QUERY variables = { \"productTypeId\": product_type_global_id, \"attributeIds\": [ graphene.Node.to_global_id(\"Attribute\", color_attribute_without_values.pk)", "expected_variant_attribute_count += 1 staff_user.user_permissions.add(permission_manage_products) # Hide one product and variant", "} } } } \"\"\" def test_create_attribute_and_attribute_values( staff_api_client, permission_manage_products ):", "= attribute.values.first().id value_id = graphene.Node.to_global_id(\"AttributeValue\", attribute_value_id) variables = { \"name\":", "2 received_slugs = sorted( [attributes[0][\"node\"][\"slug\"], attributes[1][\"node\"][\"slug\"]] ) assert received_slugs ==", "if is_variant: product.product_type.variant_attributes.set([color_attribute, other_attribute]) else: product.product_type.product_attributes.set([color_attribute, other_attribute]) # Retrieve the", "the query is actually passing the test. other_attribute = Attribute.objects.create(name=\"Other\",", "if the slug was correctly set if no error was", "them AttributeValue.objects.bulk_create( [ AttributeValue(slug=\"a\", name=\"A\", attribute=unassigned_product_attribute), AttributeValue(slug=\"b\", name=\"B\", attribute=unassigned_product_attribute), ]", "pytest.raises(NotImplementedError) as exc: filter_attributes_by_product_types(qs, \"in_space\", \"a-value\") assert exc.value.args == (\"Filtering", "graphene.Node.to_global_id(\"Attribute\", color_attribute_without_values.pk) ], } content = get_graphql_content(staff_api_client.post_graphql(query, variables))[ \"data\" ][\"attributeUnassign\"]", "ProductErrorCode.UNIQUE, ), ), ) def test_update_attribute_and_add_attribute_values_errors( staff_api_client, name_1, name_2, error_msg,", "productAttributes { id } variantAttributes { id } } }", "assert not attribute.values.filter(pk=attribute_value_id).exists() assert attribute.values.filter(name=attribute_value_name).exists() def test_update_empty_attribute_and_add_values( staff_api_client, color_attribute_without_values, permission_manage_products", "the given attribute.\"\"\" attribute_id = graphene.Node.to_global_id(\"Attribute\", color_attribute.id) value_id = graphene.Node.to_global_id(\"AttributeValue\",", "== product_attribute_values[0] assert product_attributes[0][\"value\"][\"slug\"] == product_attribute_values[0] assert variant_attributes[0][\"attribute\"][\"slug\"] == \"size\"", "): product_type = ProductType.objects.create(name=\"Type\") product_type_global_id = graphene.Node.to_global_id(\"ProductType\", product_type.pk) variant_attribute, *product_attributes", ") )[\"data\"][\"attributeUnassign\"] assert not content[\"errors\"] assert content[\"productType\"][\"id\"] == product_type_global_id assert", "= \"\"\" query($sortBy: AttributeSortingInput) { attributes(first: 10, sortBy: $sortBy) {", "len(products[0][\"node\"][\"variants\"]) == 1 # Retrieve the nodes data product =", "def test_sort_attributes_by_slug(api_client): Attribute.objects.bulk_create( [ Attribute(name=\"MyAttribute\", slug=\"b\"), Attribute(name=\"MyAttribute\", slug=\"a\"), ] )", "\"\"\" query($id: ID!) { product(id: $id) { attributes { attribute", "last attribute # when sorted by ID. Thus, we are", "= {\"name\": \"Example name\", \"values\": [{\"name\": name_1}, {\"name\": name_2}]} response", "value with a new slug should pass validate_value_is_unique( color_attribute, AttributeValue(slug=\"spanish-inquisition\")", "node_id, \"addValues\": [{\"name\": attribute_value_name}], \"removeValues\": [], } response = staff_api_client.post_graphql(", ") { productTypeReorderAttributes( productTypeId: $productTypeId moves: $moves type: $type )", "\"\") is qs assert filter_attributes_by_product_types(qs, \"...\", None) is qs def", "saleor.graphql.product.mutations.attributes import validate_value_is_unique from saleor.graphql.product.types.attributes import resolve_attribute_value_type from saleor.product import", "be missing\" assert len(variant_attributes) == 2, \"Non-assigned attr from the", "for value in data[\"attribute\"][\"values\"]] def test_create_attribute_value_not_unique_name( staff_api_client, color_attribute, permission_manage_products ):", "$slug: String) { attributeCreate(input: {name: $name, slug: $slug}) { errors", "get_graphql_content(response) data = content[\"data\"][\"attributeValueCreate\"] assert not data[\"productErrors\"] attr_data = data[\"attributeValue\"]", "[{\"name\": attribute_value_name}], \"removeValues\": [value_id], } response = staff_api_client.post_graphql( query, variables,", "error_code, color_attribute, permission_manage_products, ): query = UPDATE_ATTRIBUTE_QUERY attribute = color_attribute", "= product[\"variants\"][0] # Ensure the product attributes values are all", "} } } } \"\"\" @pytest.mark.parametrize(\"is_staff\", (False, True)) def test_resolve_attributes_with_hidden(", "1 # The user should now be able to see", "unassigned_variant_attribute = Attribute.objects.create(name=\"V\", slug=\"variant\") # Create a value for each", "slug } } } \"\"\" attribute_name = \"My Name\" variables", "= get_graphql_content( api_client.post_graphql(ATTRIBUTES_FILTER_QUERY, variables) )[\"data\"][\"attributes\"][\"edges\"] assert len(attributes) == 1 assert", "] @pytest.mark.parametrize( \"product_type_attribute_type, gql_attribute_type\", ( (AttributeTypeEnum.PRODUCT, AttributeTypeEnum.VARIANT), (AttributeTypeEnum.VARIANT, AttributeTypeEnum.PRODUCT), (AttributeTypeEnum.PRODUCT,", "data[\"attributeValue\"] assert attr_data[\"name\"] == name assert attr_data[\"slug\"] == slugify(name) assert", "assert not data[\"errors\"] assert data[\"attribute\"][\"name\"] == name == attribute.name assert", "\"id\": graphene.Node.to_global_id(\"Attribute\", attributes[0].pk), \"sortOrder\": +1, }, { \"id\": graphene.Node.to_global_id(\"Attribute\", attributes[2].pk),", "sort_order=0 ) m2m_model.objects.create( product_type=product_type, attribute=size_attribute, sort_order=1 ) variables = {\"sortBy\":", "to them AttributeValue.objects.bulk_create( [ AttributeValue(slug=\"a\", name=\"A\", attribute=unassigned_product_attribute), AttributeValue(slug=\"b\", name=\"B\", attribute=unassigned_product_attribute),", "variant[\"attributes\"][0][\"attribute\"][\"slug\"] == \"size\" assert variant[\"attributes\"][0][\"values\"] == [] ASSIGN_ATTR_QUERY = \"\"\"", "\"size\" assert variant[\"attributes\"][0][\"values\"] == [] ASSIGN_ATTR_QUERY = \"\"\" mutation assign($productTypeId:", "color_attribute_without_values.id ) query = \"\"\" query($id: ID!) { attribute(id: $id)", "attr_data[\"type\"] == \"STRING\" assert name in [value[\"name\"] for value in", "(color) have already been assigned to this product type.\", }", "is always the last attribute # when sorted by ID.", "\"\"\" query { attributes(first: 20) { edges { node {", "def test_unassign_attributes_from_product_type( staff_api_client, permission_manage_products, attribute_list ): product_type = ProductType.objects.create(name=\"Type\") product_type_global_id", "unique.\", ProductErrorCode.UNIQUE, ), ), ) def test_create_attribute_and_attribute_values_errors( staff_api_client, name_1, name_2,", "\"Red color\", \"Provided values are not unique.\", ProductErrorCode.UNIQUE, ), (", "), ), ) def test_update_attribute_and_add_attribute_values_errors( staff_api_client, name_1, name_2, error_msg, error_code,", "attr in attribute_list[2:]} for attr_id in product_attributes_ids: operations.append( {\"type\": \"PRODUCT\",", "= color_attribute name = \"<NAME>\" attribute_value_name = \"Red Color\" node_id", "== attribute_gql_id assert content[\"data\"][\"attribute\"][\"slug\"] == color_attribute_without_values.slug QUERY_ATTRIBUTES = \"\"\" query", "content[\"data\"][\"attributeCreate\"][\"productErrors\"] assert product_errors[0][\"code\"] == error_code.name UPDATE_ATTRIBUTE_QUERY = \"\"\" mutation updateAttribute(", "= Category.objects.create(name=\"Other Category\", slug=\"other-cat\") other_attribute = Attribute.objects.create(name=\"Other\", slug=\"other\") other_product_type =", "o.sort_order is not None else o.pk ), \"The values are", "saleor.product.models import ( Attribute, AttributeProduct, AttributeValue, AttributeVariant, Category, Collection, Product,", "} } } \"\"\" def test_update_attribute_name( staff_api_client, color_attribute, permission_manage_products ):", "Retrieve the product and variant's attributes products = get_graphql_content( api_client.post_graphql(", "AttributeTypeEnum, AttributeValueType from saleor.graphql.product.filters import filter_attributes_by_product_types from saleor.graphql.product.mutations.attributes import validate_value_is_unique", "def test_resolve_attributes_with_hidden( user_api_client, product, color_attribute, size_attribute, staff_user, is_staff, permission_manage_products, ):", "( ( \"Red color\", \"Red color\", \"Provided values are not", "filter attributes by raises a NotImplemented exception. \"\"\" qs =", "ID!, $attributeIds: [ID]! ) { attributeUnassign(productTypeId: $productTypeId, attributeIds: $attributeIds) {", "= filter_attributes_by_product_types(mocked_qs, \"in_category\", category_id) assert qs == mocked_qs.none.return_value @pytest.mark.parametrize(\"test_deprecated_filter\", [True,", "permissions=[permission_manage_products] ) content = get_graphql_content(response) errors = content[\"data\"][\"attributeCreate\"][\"errors\"] assert errors", "def test_unassign_attributes_not_in_product_type( staff_api_client, permission_manage_products, color_attribute_without_values ): \"\"\"The unAssignAttribute mutation should", "variant if is_variant else product # type: Union[Product, ProductVariant] node.attributesrelated.clear()", "{ attributes(first: 10, filter: $filters) { edges { node {", "} } } } } \"\"\" ) )[\"data\"][\"products\"][\"edges\"] # Ensure", "product, permission_manage_products ): query = \"\"\" { products(first: 10) {", "type are resolved even if the product doesn't provide any", "should now be able to see the attributes staff_api_client.user.user_permissions.add(permission_manage_products) response", "} } \"\"\" attribute_name = \"My Name\" variables = {\"name\":", "{ id variantAttributes { id } productAttributes { id }", "variant_attributes[0][\"value\"] is None def test_attributes_filter_by_product_type_with_empty_value(): \"\"\"Ensure passing an empty or", "an attribute: {attribute_id}\", } ] @pytest.mark.parametrize( \"attribute_type, relation_field, backref_field\", (", "= \"\"\" mutation updateAttribute( $id: ID!, $name: String!, $addValues: [AttributeValueCreateInput]!,", "color_attribute.save(update_fields=[\"available_in_grid\"]) variables = {\"filters\": {\"availableInGrid\": True}} attributes = get_graphql_content( api_client.post_graphql(ATTRIBUTES_FILTER_QUERY,", "will allow us to make sure it is always the", "product_type_global_id, \"attributeIds\": [ graphene.Node.to_global_id(\"Attribute\", color_attribute_without_values.pk) ], } content = get_graphql_content(staff_api_client.post_graphql(query,", "attribute that shouldn't get matched other_category = Category.objects.create(name=\"Other Category\", slug=\"other-cat\")", "attribute to the top and let the others to None", "( content[\"productType\"][\"productAttributes\"][0][\"id\"] == remaining_attribute_global_id ) def test_unassign_attributes_not_in_product_type( staff_api_client, permission_manage_products, color_attribute_without_values", "ordered\" variables = { \"attributeId\": attribute_id, \"moves\": [ { \"id\":", "variant = product.variants.first() product_type = product.product_type # Create dummy attributes", "is_variant: query = \"\"\" query($id: ID!) { productVariant(id: $id) {", "the hidden attributes assert Attribute.objects.get_visible_to_user(staff_api_client.user).count() == 1 # The user", "assert not content[\"errors\"] assert content[\"productType\"][\"id\"] == product_type_global_id assert len(content[\"productType\"][\"productAttributes\"]) ==", "product_type.pk) if product_type_attribute_type == AttributeTypeEnum.PRODUCT: product_type.product_attributes.add(attribute) elif product_type_attribute_type == AttributeTypeEnum.VARIANT:", "= content[\"data\"][\"attributeCreate\"][\"productErrors\"] assert product_errors[0][\"code\"] == error_code.name UPDATE_ATTRIBUTE_QUERY = \"\"\" mutation", "the storefront for attribute in (product_attribute, variant_attribute): attribute.visible_in_storefront = False", "\"sortOrder\": 1}], } content = get_graphql_content( staff_api_client.post_graphql( ATTRIBUTES_RESORT_QUERY, variables, permissions=[permission_manage_products]", "= { int(graphene.Node.from_global_id(attr[\"id\"])[1]) for attr in content[\"productType\"][\"variantAttributes\"] } assert found_product_attrs_ids", "{ \"name\": \"Example name\", \"id\": node_id, \"slug\": \"example-slug\", \"addValues\": [],", "product, staff_user): \"\"\"Ensure the attribute values are properly resolved.\"\"\" query", "errors = content[\"data\"][\"attributeUpdate\"][\"errors\"] assert errors assert errors[0][\"field\"] == \"removeValues\" err_msg", "= CREATE_ATTRIBUTES_QUERY attribute_name = \"<NAME>\" name = \"Value name\" variables", "[]), (None, \"my-name\", []), ( \"\", None, [{\"field\": \"slug\", \"message\":", "value.refresh_from_db() assert data[\"attributeValue\"][\"name\"] == name == value.name assert data[\"attributeValue\"][\"slug\"] ==", "\"\"\" query($id: ID!) { attribute(id: $id) { id slug }", "m2m_rel_other_attr = other_attribute.attributevariant.last() else: m2m_rel_other_attr = other_attribute.attributeproduct.last() # Push the", "an error when trying to add an attribute as a", "70%, 0.3)\", AttributeValueType.COLOR), (\"rgba(100%, 255, 0, 0)\", AttributeValueType.COLOR), (\"http://example.com\", AttributeValueType.URL),", "{ name } } } } } } } \"\"\"", "\"addValues\": [{\"name\": attribute_value_name}], \"removeValues\": [], } response = staff_api_client.post_graphql( query,", "are not returned # by the product or variant as", "variant_attributes[0][\"value\"] is None assert variant_attributes[0][\"attribute\"][\"slug\"] == \"variant\" assert variant_attributes[0][\"values\"] ==", "), ) def test_create_attribute_and_attribute_values_errors( staff_api_client, name_1, name_2, error_msg, error_code, permission_manage_products,", "gql_type, gql_attr_id = graphene.Node.from_global_id(attr[\"id\"]) assert gql_type == \"AttributeValue\" actual_order.append(int(gql_attr_id)) assert", "Collection, Product, ProductType, ProductVariant, ) from saleor.product.utils.attributes import associate_attribute_values_to_instance from", "{ name slug } } } } \"\"\" def test_search_attributes(api_client,", "attributes_data = content[\"data\"][\"attributes\"][\"edges\"] assert attributes_data assert len(attributes_data) == attributes.count() def", "query($id: ID!) { productVariant(id: $id) { attributes { attribute {", "name slug } productTypes(first: 10) { edges { node {", "dummy attributes to the product type and push them at", "content = get_graphql_content(staff_api_client.post_graphql(query, variables))[ \"data\" ][\"attributeAssign\"] assert content[\"errors\"] == [", "permissions=[permission_manage_products] ) content = get_graphql_content(response) data = content[\"data\"][\"attributeValueUpdate\"] value.refresh_from_db() assert", "query set.\"\"\" category_id = graphene.Node.to_global_id(\"Category\", -1) mocked_qs = mock.MagicMock() qs", "else: query = query % {\"filter_input\": \"filter: { %s: $nodeID", "str(size_attribute) assert errors[0][\"message\"] == err_msg product_errors = content[\"data\"][\"attributeUpdate\"][\"productErrors\"] assert product_errors[0][\"code\"]", "= get_graphql_content(response) data = content[\"data\"][\"attributeValueCreate\"] assert not data[\"productErrors\"] attr_data =", "$name: String!) { attributeValueUpdate( id: $id, input: {name: $name}) {", "attribute as a variant attribute when the attribute's input type", "} } } } \"\"\" else: query = \"\"\" query($id:", "field message } } } \"\"\" def test_sort_attributes_within_product_type_invalid_product_type( staff_api_client, permission_manage_products", "the slug was correctly set if no error was expected", "correctly set if no error was expected if expected_error is", "name_1}, {\"name\": name_2}], } response = staff_api_client.post_graphql( query, variables, permissions=[permission_manage_products]", "assert qs == mocked_qs.none.return_value @pytest.mark.parametrize(\"test_deprecated_filter\", [True, False]) @pytest.mark.parametrize(\"tested_field\", [\"inCategory\", \"inCollection\"])", "] ) variables = {\"sortBy\": {\"field\": \"SLUG\", \"direction\": \"ASC\"}} attributes", "shouldn't be taken into account validate_value_is_unique(color_attribute, value) def test_get_single_attribute_by_pk(user_api_client, color_attribute_without_values):", "with a new slug should pass validate_value_is_unique( color_attribute, AttributeValue(slug=\"spanish-inquisition\") )", "255, 0, 0)\", AttributeValueType.COLOR), (\"http://example.com\", AttributeValueType.URL), (\"https://example.com\", AttributeValueType.URL), (\"ftp://example.com\", AttributeValueType.URL),", "attribute_type, \"productTypeId\": product_type_id, \"moves\": [ { \"id\": graphene.Node.to_global_id(\"Attribute\", attributes[0].pk), \"sortOrder\":", "attributes and values from the product and its variant product.attributesrelated.clear()", "error_code.name def test_update_attribute_and_remove_others_attribute_value( staff_api_client, color_attribute, size_attribute, permission_manage_products ): query =", "permission_manage_products ): value = color_attribute.values.get(name=\"Red\") query = \"\"\" mutation updateChoice($id:", "moves: $moves type: $type ) { productType { id variantAttributes", "content = get_graphql_content( staff_api_client.post_graphql( ATTRIBUTES_RESORT_QUERY, variables, permissions=[permission_manage_products] ) )[\"data\"][\"productTypeReorderAttributes\"] assert", "product_type = ProductType.objects.create(name=\"Dummy Type\") product_type_id = graphene.Node.to_global_id(\"ProductType\", product_type.id) m2m_attributes =", "attribute (invalid ID).\"\"\" attribute_id = graphene.Node.to_global_id(\"Attribute\", -1) value_id = graphene.Node.to_global_id(\"AttributeValue\",", "from django.db.models import Q from django.template.defaultfilters import slugify from graphene.utils.str_converters", "[value_id], } response = staff_api_client.post_graphql( query, variables, permissions=[permission_manage_products] ) content", "data[\"productErrors\"] assert data[\"productErrors\"][0][\"code\"] == ProductErrorCode.ALREADY_EXISTS.name assert data[\"productErrors\"][0][\"field\"] == \"name\" def", "\"Should have succeeded\" assert content[\"productType\"][\"id\"] == product_type_global_id assert len(content[\"productType\"][\"productAttributes\"]) ==", "\"SLUG\", \"direction\": \"ASC\"}} attributes = get_graphql_content( api_client.post_graphql(ATTRIBUTES_SORT_QUERY, variables) )[\"data\"][\"attributes\"][\"edges\"] assert", ") content = get_graphql_content(response) data = content[\"data\"][\"attributeValueCreate\"] assert data[\"productErrors\"] assert", "products and variants are sorted.\"\"\" variant = product.variants.first() if is_variant:", "True), (\"available_in_grid\", True), (\"value_required\", False), (\"storefront_search_position\", 0), ), ) def", "\"\"\" { attributes(first: 10) { edges { node { %s", "][\"attributeAssign\"] assert content[\"errors\"] == [ { \"field\": \"operations\", \"message\": (", "\"raw_value, expected_type\", [ (\"#0000\", AttributeValueType.COLOR), (\"#FF69B4\", AttributeValueType.COLOR), (\"rgb(255, 0, 0)\",", "(\"my-slug\", \"my-slug\", []), (None, \"my-name\", []), ( \"\", None, [{\"field\":", "the error is as expected: null or something else assert", "other_category = Category.objects.create(name=\"Other Category\", slug=\"other-cat\") other_attribute = Attribute.objects.create(name=\"Other\", slug=\"other\") other_product_type", "sorted.\"\"\" variant = product.variants.first() if is_variant: query = \"\"\" query($id:", "permission can. \"\"\" query = QUERY_PRODUCT_AND_VARIANTS_ATTRIBUTES api_client = user_api_client variant", "the others to None m2m_rel_other_attr.sort_order = 0 m2m_rel_other_attr.save(update_fields=[\"sort_order\"]) # Assign", ")[\"data\"][\"attributes\"][\"edges\"] assert len(attributes) == 1 assert attributes[0][\"node\"][\"slug\"] == \"color\" def", "m2m_attributes.set(attributes) sort_method = getattr(m2m_attributes, f\"{relation_field}_sorted\") attributes = list(sort_method()) assert len(attributes)", "attribute.save(update_fields=[\"input_type\"]) product_type.variant_attributes.clear() staff_api_client.user.user_permissions.add(permission_manage_products) product_type_global_id = graphene.Node.to_global_id(\"ProductType\", product_type.pk) query = ASSIGN_ATTR_QUERY", "assert variant_attributes[0][\"attribute\"][\"slug\"] == \"size\" assert variant_attributes[0][\"values\"][0][\"slug\"] == variant_attribute_values[0] assert variant_attributes[0][\"value\"][\"slug\"]", "ATTRIBUTES_RESORT_QUERY, variables, permissions=[permission_manage_products] ) )[\"data\"][\"productTypeReorderAttributes\"] assert content[\"errors\"] == [ {", "assert data[\"errors\"][0][\"field\"] == \"name\" def test_delete_attribute_value( staff_api_client, color_attribute, pink_attribute_value, permission_manage_products", "} \"\"\" def test_sort_attributes_by_slug(api_client): Attribute.objects.bulk_create( [ Attribute(name=\"MyAttribute\", slug=\"b\"), Attribute(name=\"MyAttribute\", slug=\"a\"),", "assert data[\"attribute\"][\"name\"] == name == attribute.name assert not attribute.values.filter(pk=attribute_value_id).exists() assert", "@pytest.mark.parametrize( \"attribute_type, relation_field, backref_field\", ( (\"VARIANT\", \"variant_attributes\", \"attributevariant\"), (\"PRODUCT\", \"product_attributes\",", "id name slug } } } } \"\"\" if test_deprecated_filter:", "validate_value_is_unique(color_attribute, value) def test_get_single_attribute_by_pk(user_api_client, color_attribute_without_values): attribute_gql_id = graphene.Node.to_global_id( \"Attribute\", color_attribute_without_values.id", "permissions=[permission_manage_products] ) content = get_graphql_content(response) data = content[\"data\"][\"attributeValueCreate\"] assert not", "graphene.Node.to_global_id(\"Attribute\", attribute.pk)} ] variables = {\"productTypeId\": product_type_global_id, \"operations\": operations} content", "} value { slug } } } } } }", "type doesn't support variants\"\"\" attribute = size_attribute attribute.input_type = AttributeInputType.MULTISELECT", "support variants\"\"\" product_type = product_type_without_variant attribute = color_attribute_without_values staff_api_client.user.user_permissions.add(permission_manage_products) product_type_global_id", "to_camel_case(attribute) query = ( \"\"\" { attributes(first: 10) { edges", "\"a-value\") assert exc.value.args == (\"Filtering by in_space is unsupported\",) def", "for attr_id in variant_attributes_ids: operations.append( {\"type\": \"VARIANT\", \"id\": graphene.Node.to_global_id(\"Attribute\", attr_id)}", "[AttributeValueCreateInput]) { attributeCreate(input: {name: $name, values: $values}) { errors {", "\"Did not return the correct product type\" gql_attributes = content[\"productType\"][snake_to_camel_case(relation_field)]", "have already been assigned to this product type.\", } ]", "mutation deleteAttribute($id: ID!) { attributeDelete(id: $id) { errors { field", "attribute vs the product type if is_variant: m2m_rel_other_attr = other_attribute.attributevariant.last()", "product_errors = content[\"data\"][\"attributeCreate\"][\"productErrors\"] assert product_errors[0][\"code\"] == error_code.name UPDATE_ATTRIBUTE_QUERY = \"\"\"", "id } } } } \"\"\" def test_unassign_attributes_from_product_type( staff_api_client, permission_manage_products,", "== \"color\" assert product[\"attributes\"][0][\"values\"] == [] # Ensure the variant", "color\", \"Provided values are not unique.\", ProductErrorCode.UNIQUE, ), ), )", "test. other_attribute = Attribute.objects.create(name=\"Other\", slug=\"other\") # Add the attribute to", "assert len(attributes) == 2 received_slugs = sorted( [attributes[0][\"node\"][\"slug\"], attributes[1][\"node\"][\"slug\"]] )", "the product type.\"\"\" product_type = ProductType.objects.create(name=\"Type\") attribute = color_attribute_without_values staff_api_client.user.user_permissions.add(permission_manage_products)", "\"type\": attribute_type, \"productTypeId\": product_type_id, \"moves\": [ { \"id\": graphene.Node.to_global_id(\"Attribute\", attributes[0].pk),", "the expected one.\"\"\" attribute = to_camel_case(attribute) query = ( \"\"\"", "{ \"id\": graphene.Node.to_global_id(\"AttributeValue\", values[2].pk), \"sortOrder\": -1, }, ], } expected_order", "product[\"variants\"][0][\"attributes\"] assert len(product_attributes) == 2, \"Non-assigned attr from the PT", ") content = get_graphql_content(response) data = content[\"data\"][\"attributeValueCreate\"] assert not data[\"productErrors\"]", "product.attributesrelated.clear() variant.attributesrelated.clear() # Retrieve the product and variant's attributes products", "list(attribute.values.all()) assert len(values) == 3 staff_api_client.user.user_permissions.add(permission_manage_products) attribute_id = graphene.Node.to_global_id(\"Attribute\", attribute.id)", "permissions=[permission_manage_products], ) )[\"data\"][\"attributeReorderValues\"] assert content[\"errors\"] == [ { \"field\": \"attributeId\",", "be taken into account validate_value_is_unique(color_attribute, value) def test_get_single_attribute_by_pk(user_api_client, color_attribute_without_values): attribute_gql_id", "attribute.id) variables = { \"name\": \"Example name\", \"id\": node_id, \"removeValues\":", "color_attribute, permission_manage_products ): attribute = color_attribute query = CREATE_ATTRIBUTE_VALUE_QUERY attribute_id", "graphene.Node.to_global_id(\"AttributeValue\", value.id) variables = {\"name\": pink_attribute_value.name, \"id\": node_id} response =", "\"VARIANT\", \"id\": graphene.Node.to_global_id(\"Attribute\", attr_id)} ) content = get_graphql_content( staff_api_client.post_graphql( query,", "10, sortBy: $sortBy) { edges { node { slug }", "[value[\"name\"] for value in data[\"attribute\"][\"values\"]] def test_update_attribute_value_name_not_unique( staff_api_client, pink_attribute_value, permission_manage_products", "from unittest import mock import graphene import pytest from django.core.exceptions", "CREATE_ATTRIBUTE_VALUE_QUERY = \"\"\" mutation createAttributeValue( $attributeId: ID!, $name: String!) {", "(False, True)) def test_resolve_attributes_with_hidden( user_api_client, product, color_attribute, size_attribute, staff_user, is_staff,", "attributes = attribute_list assert len(attributes) == 3 staff_api_client.user.user_permissions.add(permission_manage_products) product_type =", "\"\"\" qs = Attribute.objects.all() with pytest.raises(NotImplementedError) as exc: filter_attributes_by_product_types(qs, \"in_space\",", "staff_api_client.post_graphql(ATTRIBUTES_RESORT_QUERY, variables) )[\"data\"][\"productTypeReorderAttributes\"] assert not content[\"errors\"] assert ( content[\"productType\"][\"id\"] ==", "# Push the last attribute to the top and let", "): query = UPDATE_ATTRIBUTE_QUERY attribute = color_attribute node_id = graphene.Node.to_global_id(\"Attribute\",", "graphene.Node.to_global_id(\"AttributeValue\", values[0].pk), \"sortOrder\": +1, }, { \"id\": graphene.Node.to_global_id(\"AttributeValue\", values[2].pk), \"sortOrder\":", "# Retrieve the product's variant variant = product.variants.get() # Remove", "attr_id = graphene.Node.to_global_id(\"AttributeValue\", size_attribute.pk) variables = { \"name\": \"Example name\",", "slug=\"a\")] ) attributes = get_graphql_content( api_client.post_graphql(ATTRIBUTES_SORT_QUERY, {}) )[\"data\"][\"attributes\"][\"edges\"] assert len(attributes)", "product and its variant product.attributesrelated.clear() variant.attributesrelated.clear() # Retrieve the product", "\"color\" def test_sort_attributes_by_default_sorting(api_client): \"\"\"Don't provide any sorting, this should sort", "from django.template.defaultfilters import slugify from graphene.utils.str_converters import to_camel_case from saleor.core.taxes", "id } } } \"\"\" node_id = graphene.Node.to_global_id(\"Attribute\", attribute.id) variables", "1 if is_staff: api_client.user = staff_user expected_product_attribute_count += 1 expected_variant_attribute_count", ").count() assert attribute_count == 1 response = user_api_client.post_graphql(query) content =", "to reorder an invalid product type (invalid ID).\"\"\" product_type_id =", "1 staff_user.user_permissions.add(permission_manage_products) # Hide one product and variant attribute from", "{ node { attributes { attribute { slug } values", "name}]} response = staff_api_client.post_graphql( query, variables, permissions=[permission_manage_products] ) content =", "data[\"errors\"] assert data[\"attribute\"][\"name\"] == name == attribute.name assert not attribute.values.filter(pk=attribute_value_id).exists()", "{product_type}\") query = ASSIGN_ATTR_QUERY operations = [ { \"type\": gql_attribute_type.value,", "{ attributeReorderValues(attributeId: $attributeId, moves: $moves) { attribute { id values", "in attribute_list[:2]} variant_attributes_ids = {attr.pk for attr in attribute_list[2:]} for", "{ slug } } variants { attributes { attribute {", "assert len(attributes_data) == attribute_count QUERY_PRODUCT_AND_VARIANTS_ATTRIBUTES = \"\"\" { products(first: 1)", "matched other_category = Category.objects.create(name=\"Other Category\", slug=\"other-cat\") other_attribute = Attribute.objects.create(name=\"Other\", slug=\"other\")", "database attributes by their sort order and ID (when None)", "60%, 70%, 0.3)\", AttributeValueType.COLOR), (\"rgba(100%, 255, 0, 0)\", AttributeValueType.COLOR), (\"http://example.com\",", "graphene.Node.to_global_id(\"Attribute\", attribute.id) variables = {\"name\": name, \"id\": node_id, \"addValues\": [],", "{ type inputType } } } } } } \"\"\"", "color_attribute, size_attribute, permission_manage_products ): query = UPDATE_ATTRIBUTE_QUERY attribute = color_attribute", "== \"size\" assert variant_attributes[0][\"values\"][0][\"slug\"] == variant_attribute_values[0] assert variant_attributes[0][\"value\"][\"slug\"] == variant_attribute_values[0]", "attribute_gql_id = graphene.Node.to_global_id( \"Attribute\", color_attribute_without_values.id ) query = \"\"\" query($id:", "to reorder an invalid attribute (invalid ID).\"\"\" attribute_id = graphene.Node.to_global_id(\"Attribute\",", "{ slug } } } } \"\"\" def test_sort_attributes_by_slug(api_client): Attribute.objects.bulk_create(", "len(variant_attribute_values) assert product_attributes[0][\"attribute\"][\"slug\"] == \"color\" assert product_attributes[0][\"values\"][0][\"slug\"] == product_attribute_values[0] assert", "\"Yellow Color\" node_id = graphene.Node.to_global_id(\"Attribute\", attribute.id) variables = { \"name\":", "attribute color_attribute.visible_in_storefront = False color_attribute.save(update_fields=[\"visible_in_storefront\"]) attribute_count = Attribute.objects.all().count() # The", "\"\"\" node_id = graphene.Node.to_global_id(\"AttributeValue\", value.id) variables = {\"id\": node_id} staff_api_client.post_graphql(", "} } \"\"\" ) )[\"data\"][\"products\"][\"edges\"] # Ensure we are only", "AttributeValue(slug=value.slug)) # a new value with a new slug should", "expected_order): gql_type, gql_attr_id = graphene.Node.from_global_id(attr[\"id\"]) assert gql_type == \"Attribute\" assert", "saleor.graphql.core.utils import snake_to_camel_case from saleor.graphql.product.enums import AttributeTypeEnum, AttributeValueType from saleor.graphql.product.filters", "= staff_user expected_product_attribute_count += 1 expected_variant_attribute_count += 1 staff_user.user_permissions.add(permission_manage_products) #", "assert gql_type == \"Attribute\" assert int(gql_attr_id) == expected_pk ATTRIBUTE_VALUES_RESORT_QUERY =", "= graphene.Node.to_global_id(\"Attribute\", -1) value_id = graphene.Node.to_global_id(\"AttributeValue\", -1) variables = {", "slug=\"other\") # Add the attribute to the product type if", "resolved.\"\"\" query = QUERY_PRODUCT_AND_VARIANTS_ATTRIBUTES api_client = user_api_client variant = product.variants.first()", "properly resolved when an attribute is part of the product", "len(attributes) == 3 staff_api_client.user.user_permissions.add(permission_manage_products) product_type = ProductType.objects.create(name=\"Dummy Type\") product_type_id =", "def test_assign_variant_attribute_to_product_type_with_disabled_variants( staff_api_client, permission_manage_products, product_type_without_variant, color_attribute_without_values, ): \"\"\"The assignAttribute mutation", "color_attribute, color_attribute.values.first() ) # Sort the database attributes by their", "assert flat_attributes_data == expected_flat_attributes_data CREATE_ATTRIBUTES_QUERY = \"\"\" mutation createAttribute($name: String!,", "} } \"\"\" content = get_graphql_content( user_api_client.post_graphql(query, {\"id\": attribute_gql_id}) )", "mutation should not raise any error when trying to remove", ") )[\"data\"][\"productTypeReorderAttributes\"] assert content[\"errors\"] == [ { \"field\": \"moves\", \"message\":", "attributes[0][\"node\"][\"slug\"] == \"a\" assert attributes[1][\"node\"][\"slug\"] == \"b\" @pytest.mark.parametrize( \"sort_field, m2m_model\",", "variables = {\"filters\": {\"search\": \"color\"}} attributes = get_graphql_content( api_client.post_graphql(ATTRIBUTES_FILTER_QUERY, variables)", "ASSIGN_ATTR_QUERY = \"\"\" mutation assign($productTypeId: ID!, $operations: [AttributeAssignInput]!) { attributeAssign(productTypeId:", "= graphene.Node.to_global_id(\"Attribute\", attribute.id) variables = { \"name\": \"Example name\", \"id\":", "collection_with_products, test_deprecated_filter, tested_field, ): if \"Collection\" in tested_field: filtered_by_node_id =", "content[\"data\"][\"attributeUpdate\"][\"errors\"] assert errors assert errors[0][\"field\"] == \"removeValues\" err_msg = \"Value", "= { \"name\": \"Example name\", \"id\": node_id, \"slug\": \"example-slug\", \"addValues\":", "+1, }, { \"id\": graphene.Node.to_global_id(\"AttributeValue\", values[2].pk), \"sortOrder\": -1, }, ],", "to the product type if is_variant: product.product_type.variant_attributes.set([color_attribute, other_attribute]) else: product.product_type.product_attributes.set([color_attribute,", "attribute.values.filter(pk=attribute_value_id).exists() assert attribute.values.filter(name=attribute_value_name).exists() def test_update_empty_attribute_and_add_values( staff_api_client, color_attribute_without_values, permission_manage_products ): query", "} \"\"\" def test_create_attribute_and_attribute_values( staff_api_client, permission_manage_products ): query = CREATE_ATTRIBUTES_QUERY", "0.3)\", AttributeValueType.COLOR), (\"rgba(100%, 255, 0, 0)\", AttributeValueType.COLOR), (\"http://example.com\", AttributeValueType.URL), (\"https://example.com\",", "given product type.\"\"\" product_type = ProductType.objects.create(name=\"Dummy Type\") product_type_id = graphene.Node.to_global_id(\"ProductType\",", "value_name = attribute.values.first().name variables = {\"name\": value_name, \"attributeId\": attribute_id} response", "staff_api_client, pink_attribute_value, permission_manage_products ): query = UPDATE_ATTRIBUTE_VALUE_QUERY value = pink_attribute_value", "attribute=color_attribute, sort_order=0 ) m2m_model.objects.create( product_type=product_type, attribute=size_attribute, sort_order=1 ) variables =", "{ attributes(first: 20, %(filter_input)s) { edges { node { id", "\"The default slug should be the slugified name\" assert (", "= \"\"\" mutation updateChoice( $id: ID!, $name: String!) { attributeValueUpdate(", "permission_manage_products, product_type, size_attribute ): \"\"\"The assignAttribute mutation should raise an", "def test_search_attributes(api_client, color_attribute, size_attribute): variables = {\"filters\": {\"search\": \"color\"}} attributes", "not have been assigned to a product type\" # Check", "{ products(first: 10) { edges { node { attributes {", "assert product_attributes[0][\"values\"][0][\"slug\"] == product_attribute_values[0] assert product_attributes[0][\"value\"][\"slug\"] == product_attribute_values[0] assert variant_attributes[0][\"attribute\"][\"slug\"]", "not unique.\", ProductErrorCode.UNIQUE, ), ( \"Red color\", \"red color\", \"Provided", "tested_field: filtered_by_node_id = graphene.Node.to_global_id(\"Category\", category.pk) else: raise AssertionError(tested_field) expected_qs =", "def test_update_attribute_name( staff_api_client, color_attribute, permission_manage_products ): query = UPDATE_ATTRIBUTE_QUERY attribute", "with pytest.raises(NotImplementedError) as exc: filter_attributes_by_product_types(qs, \"in_space\", \"a-value\") assert exc.value.args ==", "values { name slug } productTypes(first: 10) { edges {", "\"\"\" attribute_name = \"My Name\" variables = {\"name\": attribute_name, \"slug\":", "\"addValues\": [], \"removeValues\": []} response = staff_api_client.post_graphql( query, variables, permissions=[permission_manage_products]", "attr_id in product_attributes_ids: operations.append( {\"type\": \"PRODUCT\", \"id\": graphene.Node.to_global_id(\"Attribute\", attr_id)} )", "value: {value_id}\", } ] def test_sort_values_within_attribute( staff_api_client, color_attribute, permission_manage_products ):", "zip(gql_values, expected_order): gql_type, gql_attr_id = graphene.Node.from_global_id(attr[\"id\"]) assert gql_type == \"AttributeValue\"", "= get_graphql_content(response) errors = content[\"data\"][\"attributeCreate\"][\"errors\"] assert errors assert errors[0][\"field\"] ==", "attribute_value_name = \"Red Color\" node_id = graphene.Node.to_global_id(\"Attribute\", attribute.id) attribute_value_id =", "][\"attributeAssign\"] assert content[\"errors\"] == [ { \"field\": \"operations\", \"message\": \"Variants", "is None: assert content[\"data\"][\"attributeCreate\"][\"attribute\"][\"slug\"] == expected_slug @pytest.mark.parametrize( \"name_1, name_2, error_msg,", ")[\"data\"][\"attributeUnassign\"] assert not content[\"errors\"] assert content[\"productType\"][\"id\"] == product_type_global_id assert len(content[\"productType\"][\"productAttributes\"])", "variables = {\"nodeID\": filtered_by_node_id} content = get_graphql_content(user_api_client.post_graphql(query, variables)) attributes_data =", "product, color_attribute, size_attribute, staff_user, is_staff, permission_manage_products, ): \"\"\"Ensure non-staff users", "deleteAttribute($id: ID!) { attributeDelete(id: $id) { errors { field message", "True}} attributes = get_graphql_content( api_client.post_graphql(ATTRIBUTES_FILTER_QUERY, variables) )[\"data\"][\"attributes\"][\"edges\"] assert len(attributes) ==", "\"direction\": \"ASC\"}} attributes = get_graphql_content( api_client.post_graphql(ATTRIBUTES_SORT_QUERY, variables) )[\"data\"][\"attributes\"][\"edges\"] assert len(attributes)", "== 1 assert variant.attributes.count() == 1 product_attribute_values = list( product.attributes.first().values.values_list(\"slug\",", "= color_attribute query = \"\"\" mutation deleteAttribute($id: ID!) { attributeDelete(id:", "the top # through a sort_order=0 as the other attributes", "] variables = {\"productTypeId\": product_type_global_id, \"operations\": operations} content = get_graphql_content(staff_api_client.post_graphql(query,", "20) { edges { node { id name slug values", "permissions=[permission_manage_products] ) )[\"data\"][\"productTypeReorderAttributes\"] assert content[\"errors\"] == [ { \"field\": \"moves\",", "productErrors { field message code } attribute { name slug", "{ id } } errors { field message } }", "): query = CREATE_ATTRIBUTES_QUERY variables = {\"name\": \"Example name\", \"values\":", "= content[\"data\"][\"attributeCreate\"][\"errors\"] assert errors assert errors[0][\"field\"] == \"values\" assert errors[0][\"message\"]", "product_type_without_variant attribute = color_attribute_without_values staff_api_client.user.user_permissions.add(permission_manage_products) product_type_global_id = graphene.Node.to_global_id(\"ProductType\", product_type.pk) query", "mutation ProductTypeReorderAttributes( $productTypeId: ID! $moves: [ReorderInput]! $type: AttributeTypeEnum! ) {", "an attribute not associated to the given product type.\"\"\" product_type", "name slug } attribute { values { name } }", "{ \"type\": \"VARIANT\", \"attributeId\": attribute_id, \"moves\": [{\"id\": value_id, \"sortOrder\": 1}],", "values[2].pk, values[0].pk] content = get_graphql_content( staff_api_client.post_graphql(ATTRIBUTE_VALUES_RESORT_QUERY, variables) )[\"data\"][\"attributeReorderValues\"] assert not", "PT may be missing\" assert product_attributes[0][\"attribute\"][\"slug\"] == \"product\" assert product_attributes[0][\"values\"]", "unique.\", ProductErrorCode.UNIQUE, ), ), ) def test_update_attribute_and_add_attribute_values_errors( staff_api_client, name_1, name_2,", "Retrieve the product's variant variant = product.variants.get() # Remove all", "attributeReorderValues(attributeId: $attributeId, moves: $moves) { attribute { id values {", "values were correctly created assert len(data[\"attribute\"][\"values\"]) == 1 assert data[\"attribute\"][\"values\"][0][\"name\"]", "node_id, \"slug\": \"example-slug\", \"addValues\": [], \"removeValues\": [attr_id], } response =", "QUERY_ATTRIBUTES # hide the attribute color_attribute.visible_in_storefront = False color_attribute.save(update_fields=[\"visible_in_storefront\"]) attribute_count", "== expected_error # Check if the slug was correctly set", "productTypeId: $productTypeId moves: $moves type: $type ) { productType {", "= product_type_without_variant attribute = color_attribute_without_values staff_api_client.user.user_permissions.add(permission_manage_products) product_type_global_id = graphene.Node.to_global_id(\"ProductType\", product_type.pk)", "def test_sort_attributes_by_default_sorting(api_client): \"\"\"Don't provide any sorting, this should sort by", "permission_manage_products, ): query = UPDATE_ATTRIBUTE_QUERY attribute = color_attribute node_id =", "== product_type_id ), \"Did not return the correct product type\"", "= Attribute.objects query = QUERY_ATTRIBUTES response = user_api_client.post_graphql(query) content =", "flat=True) ) assert len(product_attribute_values) == 1 assert len(variant_attribute_values) == 1", "\"name\": \"Example name\", \"id\": node_id, \"removeValues\": [], \"addValues\": [{\"name\": name_1},", "for each dummy attribute to ensure they are not returned", "attribute.\"\"\" attribute_id = graphene.Node.to_global_id(\"Attribute\", color_attribute.id) value_id = graphene.Node.to_global_id(\"AttributeValue\", -1) variables", "import slugify from graphene.utils.str_converters import to_camel_case from saleor.core.taxes import zero_money", "are properly resolved when an attribute is part of the", "product_type = product.product_type # Create dummy attributes unassigned_product_attribute = Attribute.objects.create(name=\"P\",", "} } } \"\"\" else: query = \"\"\" query($id: ID!)", "Assign attributes to the product node = variant if is_variant", "color_attribute.pk] # Make the node ID if is_variant: node_id =", "sort order and ID (when None) expected_order = [other_attribute.pk, color_attribute.pk]", "attribute { name slug values { name slug } productTypes(first:", "== [] ), \"The attribute should not have been assigned", "AttributeTypeEnum.PRODUCT: product_type.product_attributes.add(attribute) elif product_type_attribute_type == AttributeTypeEnum.VARIANT: product_type.variant_attributes.add(attribute) else: raise ValueError(f\"Unknown:", "resolve to an attribute: {attribute_id}\", } ] def test_sort_values_within_attribute_invalid_id( staff_api_client,", "): query = UPDATE_ATTRIBUTE_QUERY attribute = color_attribute_without_values name = \"<NAME>\"", "= staff_api_client.post_graphql( query, variables, permissions=[permission_manage_products] ) content = get_graphql_content(response) data", "variables, permissions=[permission_manage_products] ) content = get_graphql_content(response) data = content[\"data\"][\"attributeValueUpdate\"] assert", "expected_type\", [ (\"#0000\", AttributeValueType.COLOR), (\"#FF69B4\", AttributeValueType.COLOR), (\"rgb(255, 0, 0)\", AttributeValueType.COLOR),", ")[\"data\"][\"attributeReorderValues\"] assert not content[\"errors\"] assert content[\"attribute\"][\"id\"] == attribute_id gql_values =", "type\", has_variants=True, is_shipping_required=True ) other_product_type.product_attributes.add(other_attribute) other_product = Product.objects.create( name=f\"Another Product\",", "attribute from the storefront for attribute in (product_attribute, variant_attribute): attribute.visible_in_storefront", "$attributeIds) { errors { field message } productType { id", "[attributes[1].pk, attributes[2].pk, attributes[0].pk] content = get_graphql_content( staff_api_client.post_graphql(ATTRIBUTES_RESORT_QUERY, variables) )[\"data\"][\"productTypeReorderAttributes\"] assert", "\"my-slug\", []), (None, \"my-name\", []), ( \"\", None, [{\"field\": \"slug\",", "assert product_errors[0][\"code\"] == error_code.name def test_update_attribute_and_remove_others_attribute_value( staff_api_client, color_attribute, size_attribute, permission_manage_products", "== product_type_global_id assert len(content[\"productType\"][\"productAttributes\"]) == 1 assert len(content[\"productType\"][\"variantAttributes\"]) == 1", "0), ), ) def test_retrieving_the_restricted_attributes_restricted( staff_api_client, color_attribute, permission_manage_products, attribute, expected_value,", "product type\" # Check if the attribute values were correctly", "the slugified name\" assert ( data[\"attribute\"][\"productTypes\"][\"edges\"] == [] ), \"The", "content[\"data\"][\"attributes\"][\"edges\"] assert len(attributes_data) == attribute_count QUERY_PRODUCT_AND_VARIANTS_ATTRIBUTES = \"\"\" { products(first:", "0)\", AttributeValueType.COLOR), (\"hsl(0, 100%, 50%)\", AttributeValueType.COLOR), (\"hsla(120, 60%, 70%, 0.3)\",", "= sorted( [attributes[0][\"node\"][\"slug\"], attributes[1][\"node\"][\"slug\"]] ) assert received_slugs == expected_slugs ATTRIBUTES_SORT_QUERY", "== slugify(name) assert name in [value[\"name\"] for value in data[\"attribute\"][\"values\"]]", "when the product type doesn't support variants\"\"\" product_type = product_type_without_variant", ") found_product_attrs_ids = { int(graphene.Node.from_global_id(attr[\"id\"])[1]) for attr in content[\"productType\"][\"productAttributes\"] }", "\"id\": graphene.Node.to_global_id(\"Attribute\", attribute.pk), } ] variables = {\"productTypeId\": product_type_global_id, \"operations\":", "error when trying to add an attribute already contained in", "import ValidationError from django.db.models import Q from django.template.defaultfilters import slugify", "data[\"attributeValue\"][\"name\"] == name == value.name assert data[\"attributeValue\"][\"slug\"] == slugify(name) assert", "== 2 received_slugs = sorted( [attributes[0][\"node\"][\"slug\"], attributes[1][\"node\"][\"slug\"]] ) assert received_slugs", "== \"color\" def test_sort_attributes_by_default_sorting(api_client): \"\"\"Don't provide any sorting, this should", "AttributeValueType.STRING), (\"Foo\", AttributeValueType.STRING), (\"linear-gradient(red, yellow)\", AttributeValueType.GRADIENT), (\"radial-gradient(#0000, yellow)\", AttributeValueType.GRADIENT), ],", "product_attribute_values = list( product.attributes.first().values.values_list(\"slug\", flat=True) ) variant_attribute_values = list( variant.attributes.first().values.values_list(\"slug\",", "queryset is simply returned without any modification. \"\"\" qs =", "productTypeReorderAttributes( productTypeId: $productTypeId moves: $moves type: $type ) { productType", "Compare the received data against our expectations assert actual_order ==", "assert len(attributes_data) == attribute_count def test_attributes_query_hidden_attribute_as_staff_user( staff_api_client, product, color_attribute, permission_manage_products", "= QUERY_PRODUCT_AND_VARIANTS_ATTRIBUTES api_client = user_api_client variant = product.variants.first() assert product.attributes.count()", "len(expected_order) for attr, expected_pk in zip(gql_attributes, expected_order): gql_type, gql_attr_id =", "variables = {\"productTypeId\": product_type_global_id, \"operations\": operations} product_attributes_ids = {attr.pk for", "} productAttributes { id } } errors { field message", "graphene.Node.to_global_id(\"ProductType\", product_type.id) attribute_id = graphene.Node.to_global_id(\"Attribute\", color_attribute.id) variables = { \"type\":", "\"Color (color) have already been assigned to this product type.\",", "(\"Foo\", AttributeValueType.STRING), (\"linear-gradient(red, yellow)\", AttributeValueType.GRADIENT), (\"radial-gradient(#0000, yellow)\", AttributeValueType.GRADIENT), ], )", "assert product[\"attributes\"][0][\"values\"] == [] # Ensure the variant attributes values", "== len(expected_order) actual_order = [] for attr, expected_pk in zip(gql_values,", "None) expected_order = [other_attribute.pk, color_attribute.pk] # Make the node ID", "= False color_attribute.save(update_fields=[\"filterable_in_dashboard\"]) variables = {\"filters\": {\"filterableInDashboard\": True}} attributes =", "\"type\": \"VARIANT\", \"productTypeId\": product_type_id, \"moves\": [{\"id\": attribute_id, \"sortOrder\": 1}], }", "\"productTypeId\": product_type_id, \"moves\": [ { \"id\": graphene.Node.to_global_id(\"Attribute\", attributes[0].pk), \"sortOrder\": +1,", "= CREATE_ATTRIBUTE_VALUE_QUERY attribute_id = graphene.Node.to_global_id(\"Attribute\", attribute.id) value_name = attribute.values.first().name variables", "\"\"\" mutation assign($productTypeId: ID!, $operations: [AttributeAssignInput]!) { attributeAssign(productTypeId: $productTypeId, operations:", "and attribute that shouldn't get matched other_category = Category.objects.create(name=\"Other Category\",", "product_attributes[1].pk ) query = UNASSIGN_ATTR_QUERY variables = { \"productTypeId\": product_type_global_id,", "{ id } } } } \"\"\" else: query =", "test_attributes_in_collection_query( user_api_client, product_type, category, collection, collection_with_products, test_deprecated_filter, tested_field, ): if", "from saleor.product import AttributeInputType from saleor.product.error_codes import ProductErrorCode from saleor.product.models", "\"input_slug, expected_slug, expected_error\", ( (\"my-slug\", \"my-slug\", []), (None, \"my-name\", []),", ")[\"data\"][\"attributes\"][\"edges\"] assert len(attributes) == 2 received_slugs = sorted( [attributes[0][\"node\"][\"slug\"], attributes[1][\"node\"][\"slug\"]]", "Union from unittest import mock import graphene import pytest from", "test_update_empty_attribute_and_add_values( staff_api_client, color_attribute_without_values, permission_manage_products ): query = UPDATE_ATTRIBUTE_QUERY attribute =", "attributes = get_graphql_content( api_client.post_graphql(ATTRIBUTES_SORT_QUERY, variables) )[\"data\"][\"attributes\"][\"edges\"] assert len(attributes) == 2", "or null value is ignored and the queryset is simply", "= ( \"\"\" { attributes(first: 10) { edges { node", "reorder an attribute not associated to the given product type.\"\"\"", "$name: String!, $addValues: [AttributeValueCreateInput]!, $removeValues: [ID]!) { attributeUpdate( id: $id,", "} attributeValue { name type slug } } } \"\"\"", "def test_attributes_filter_by_non_existing_category_id(): \"\"\"Ensure using a non-existing category ID returns an", "attribute = color_attribute node_id = graphene.Node.to_global_id(\"Attribute\", attribute.id) size_attribute = size_attribute.values.first()", "\"sortOrder\": +1, }, { \"id\": graphene.Node.to_global_id(\"Attribute\", attributes[2].pk), \"sortOrder\": -1, },", "== name assert attr_data[\"slug\"] == slugify(name) assert attr_data[\"type\"] == \"STRING\"", "= Attribute.objects.all() assert filter_attributes_by_product_types(qs, \"...\", \"\") is qs assert filter_attributes_by_product_types(qs,", "test_update_attribute_name( staff_api_client, color_attribute, permission_manage_products ): query = UPDATE_ATTRIBUTE_QUERY attribute =", "already contained in the product type.\"\"\" product_type = ProductType.objects.create(name=\"Type\") attribute", "content[\"errors\"], \"Should have succeeded\" assert content[\"productType\"][\"id\"] == product_type_global_id assert len(content[\"productType\"][\"productAttributes\"])", "The user doesn't have the permission yet to manage products,", "api_client = user_api_client variant = product.variants.first() assert product.attributes.count() == 1", "assert data[\"errors\"] assert data[\"errors\"][0][\"message\"] assert data[\"errors\"][0][\"field\"] == \"name\" def test_delete_attribute_value(", "attributeValue { name slug } } } \"\"\" node_id =", "1 assert len(content[\"productType\"][\"variantAttributes\"]) == 1 assert ( content[\"productType\"][\"productAttributes\"][0][\"id\"] == remaining_attribute_global_id", "attribute_type, relation_field, backref_field, ): attributes = attribute_list assert len(attributes) ==", "ProductVariant] node.attributesrelated.clear() associate_attribute_values_to_instance( node, color_attribute, color_attribute.values.first() ) # Sort the", "], ) def test_resolve_attribute_value_type(raw_value, expected_type): assert resolve_attribute_value_type(raw_value) == expected_type def", "other_product = Product.objects.create( name=f\"Another Product\", product_type=other_product_type, category=other_category, price=zero_money(), is_published=True, )", "m2m_rel_other_attr = other_attribute.attributeproduct.last() # Push the last attribute to the", "Product\", product_type=other_product_type, category=other_category, price=zero_money(), is_published=True, ) # Create another collection", "their default value is the expected one.\"\"\" attribute = to_camel_case(attribute)", "it is always the last attribute # when sorted by", "UPDATE_ATTRIBUTE_VALUE_QUERY value = pink_attribute_value.attribute.values.create( name=\"<NAME>\", slug=\"example-name\", value=\"#RED\" ) node_id =", "), ), ) def test_create_attribute_with_given_slug( staff_api_client, permission_manage_products, input_slug, expected_slug, expected_error,", "] def test_sort_attributes_within_product_type_invalid_id( staff_api_client, permission_manage_products, color_attribute ): \"\"\"Try to reorder", ") # Create another collection with products but shouldn't get", "expected_slugs ATTRIBUTES_SORT_QUERY = \"\"\" query($sortBy: AttributeSortingInput) { attributes(first: 10, sortBy:", "( content[\"productType\"][\"id\"] == product_type_id ), \"Did not return the correct", "if is_variant: query = \"\"\" query($id: ID!) { productVariant(id: $id)", ") variables = {\"sortBy\": {\"field\": \"SLUG\", \"direction\": \"ASC\"}} attributes =", "content = get_graphql_content( staff_api_client.post_graphql(ATTRIBUTE_VALUES_RESORT_QUERY, variables) )[\"data\"][\"attributeReorderValues\"] assert not content[\"errors\"] assert", "def test_create_attribute_value( staff_api_client, color_attribute, permission_manage_products ): attribute = color_attribute query", "\"slug\": \"example-slug\", \"addValues\": [], \"removeValues\": [attr_id], } response = staff_api_client.post_graphql(", "= color_attribute_without_values staff_api_client.user.user_permissions.add(permission_manage_products) product_type_global_id = graphene.Node.to_global_id(\"ProductType\", product_type.pk) query = ASSIGN_ATTR_QUERY", "content[\"errors\"] == [ { \"field\": \"operations\", \"message\": ( \"Attributes having", "is_published=True, ) # Create another collection with products but shouldn't", "[], } response = staff_api_client.post_graphql( query, variables, permissions=[permission_manage_products] ) get_graphql_content(response)", "= content[\"data\"][\"attributeValueUpdate\"] value.refresh_from_db() assert data[\"attributeValue\"][\"name\"] == name == value.name assert", "{ attribute { id } } } } \"\"\" #", "as they are not associated to them AttributeValue.objects.bulk_create( [ AttributeValue(slug=\"a\",", "} values { name } } } } } }", "name slug } } } } \"\"\" def test_search_attributes(api_client, color_attribute,", "\"Red color\", \"red color\", \"Provided values are not unique.\", ProductErrorCode.UNIQUE,", "key=lambda o: o.sort_order if o.sort_order is not None else o.pk", "color_attribute_without_values name = \"<NAME>\" attribute_value_name = \"Yellow Color\" node_id =", "variables) )[\"data\"][\"attributes\"][\"edges\"] assert len(attributes) == 1 assert attributes[0][\"node\"][\"slug\"] == \"color\"", "import associate_attribute_values_to_instance from tests.api.utils import get_graphql_content def test_validate_value_is_unique(color_attribute): value =", "assert variant.attributes.count() == 1 product_attribute_values = list( product.attributes.first().values.values_list(\"slug\", flat=True) )", "is_variant: node_id = graphene.Node.to_global_id(\"ProductVariant\", variant.pk) else: node_id = graphene.Node.to_global_id(\"Product\", product.pk)", "cannot be assigned \" \"as variant attributes\" ), } ]", "value { slug } } } } } } }", "collection with products but shouldn't get matched # as we", "= user_api_client.post_graphql(query) content = get_graphql_content(response) attributes_data = content[\"data\"][\"attributes\"][\"edges\"] assert attributes_data", "= \"My Name\" variables = {\"name\": attribute_name, \"slug\": input_slug} content", "(\"linear-gradient(red, yellow)\", AttributeValueType.GRADIENT), (\"radial-gradient(#0000, yellow)\", AttributeValueType.GRADIENT), ], ) def test_resolve_attribute_value_type(raw_value,", "attributes = get_graphql_content( api_client.post_graphql(ATTRIBUTES_SORT_QUERY, {}) )[\"data\"][\"attributes\"][\"edges\"] assert len(attributes) == 2", "attributeValueUpdate( id: $id, input: {name: $name}) { errors { field", "assert name in [value[\"name\"] for value in data[\"attribute\"][\"values\"]] def test_update_attribute_value_name_not_unique(", "if is_variant else product # type: Union[Product, ProductVariant] node.attributesrelated.clear() associate_attribute_values_to_instance(", "qs = Attribute.objects.all() with pytest.raises(NotImplementedError) as exc: filter_attributes_by_product_types(qs, \"in_space\", \"a-value\")", "product_type=product_type, sort_order=0 ) AttributeVariant.objects.create( attribute=unassigned_variant_attribute, product_type=product_type, sort_order=0 ) assert product.attributes.count()", "from graphene.utils.str_converters import to_camel_case from saleor.core.taxes import zero_money from saleor.graphql.core.utils", "[ { \"field\": \"operations\", \"message\": \"Color (color) have already been", "{ errors { field message } productErrors { field message", "content = get_graphql_content( staff_api_client.post_graphql( ATTRIBUTE_VALUES_RESORT_QUERY, variables, permissions=[permission_manage_products], ) )[\"data\"][\"attributeReorderValues\"] assert", "sort_order=0 ) AttributeVariant.objects.create( attribute=unassigned_variant_attribute, product_type=product_type, sort_order=0 ) assert product.attributes.count() ==", "attribute.save(update_fields=[\"visible_in_storefront\"]) product = get_graphql_content(api_client.post_graphql(query))[\"data\"][\"products\"][ \"edges\" ][0][\"node\"] assert len(product[\"attributes\"]) == expected_product_attribute_count", "import graphene import pytest from django.core.exceptions import ValidationError from django.db.models", "= \"\"\" mutation attributeReorderValues($attributeId: ID!, $moves: [ReorderInput]!) { attributeReorderValues(attributeId: $attributeId,", "staff_api_client.post_graphql( ATTRIBUTE_VALUES_RESORT_QUERY, variables, permissions=[permission_manage_products], ) )[\"data\"][\"attributeReorderValues\"] assert content[\"errors\"] == [", "color_attribute_without_values): attribute_gql_id = graphene.Node.to_global_id( \"Attribute\", color_attribute_without_values.id ) query = \"\"\"", "associated to them AttributeValue.objects.bulk_create( [ AttributeValue(slug=\"a\", name=\"A\", attribute=unassigned_product_attribute), AttributeValue(slug=\"b\", name=\"B\",", "input types ['multiselect'] cannot be assigned \" \"as variant attributes\"", "\"\"\" def test_attributes_query(user_api_client, product): attributes = Attribute.objects query = QUERY_ATTRIBUTES", "permissions=[permission_manage_products] ) content = get_graphql_content(response) attribute.refresh_from_db() data = content[\"data\"][\"attributeUpdate\"] assert", "staff_api_client, permission_manage_products ): \"\"\"Try to reorder an invalid product type", "type inputType } } } } } } \"\"\" found_products", "test_sort_values_within_attribute( staff_api_client, color_attribute, permission_manage_products ): attribute = color_attribute AttributeValue.objects.create(attribute=attribute, name=\"Green\",", "attributes of products and variants are sorted.\"\"\" variant = product.variants.first()", "= {\"name\": name, \"id\": node_id} response = staff_api_client.post_graphql( query, variables,", "attribute = size_attribute attribute.input_type = AttributeInputType.MULTISELECT attribute.save(update_fields=[\"input_type\"]) product_type.variant_attributes.clear() staff_api_client.user.user_permissions.add(permission_manage_products) product_type_global_id", "{ attributes(first: 20) { edges { node { id name", "variables, permissions=[permission_manage_products] ) content = get_graphql_content(response) data = content[\"data\"][\"attributeDelete\"] assert", "(\"example.com\", AttributeValueType.STRING), (\"Foo\", AttributeValueType.STRING), (\"linear-gradient(red, yellow)\", AttributeValueType.GRADIENT), (\"radial-gradient(#0000, yellow)\", AttributeValueType.GRADIENT),", "product type.\"\"\" product_type = ProductType.objects.create(name=\"Type\") attribute = color_attribute_without_values staff_api_client.user.user_permissions.add(permission_manage_products) product_type_global_id", "\"field\": \"operations\", \"message\": \"Color (color) have already been assigned to", ")[\"data\"][\"attributes\"][\"edges\"] assert len(attributes) == 2 assert attributes[0][\"node\"][\"slug\"] == \"a\" assert", "sort_field, \"direction\": \"DESC\"}} attributes = get_graphql_content( api_client.post_graphql(ATTRIBUTES_SORT_QUERY, variables) )[\"data\"][\"attributes\"][\"edges\"] assert", "get_graphql_content(response) attributes_data = content[\"data\"][\"attributes\"][\"edges\"] assert len(attributes_data) == attribute_count QUERY_PRODUCT_AND_VARIANTS_ATTRIBUTES =", "[attributes[0][\"node\"][\"slug\"], attributes[1][\"node\"][\"slug\"]] ) assert received_slugs == expected_slugs ATTRIBUTES_SORT_QUERY = \"\"\"", "value = color_attribute.values.first() # a new value but with existing", "len(found_products) == 1 for gql_attr in found_products[0][\"node\"][\"attributes\"]: assert len(gql_attr[\"values\"]) ==", "node_id = graphene.Node.to_global_id(\"Attribute\", attribute.id) variables = { \"name\": name, \"id\":", "False]) @pytest.mark.parametrize(\"tested_field\", [\"inCategory\", \"inCollection\"]) def test_attributes_in_collection_query( user_api_client, product_type, category, collection,", "staff_api_client.user.user_permissions.add(permission_manage_products) product_type = ProductType.objects.create(name=\"Type\") product_type_global_id = graphene.Node.to_global_id(\"ProductType\", product_type.pk) query =", "attribute when the product type doesn't support variants\"\"\" product_type =", "input: { name: $name, addValues: $addValues, removeValues: $removeValues}) { errors", "query = \"\"\" mutation updateChoice($id: ID!) { attributeValueDelete(id: $id) {", "% tested_field} variables = {\"nodeID\": filtered_by_node_id} content = get_graphql_content(user_api_client.post_graphql(query, variables))", "} } } } \"\"\" % attribute ) found_attributes =", "test_search_attributes(api_client, color_attribute, size_attribute): variables = {\"filters\": {\"search\": \"color\"}} attributes =", "%(filter_input)s) { edges { node { id name slug }", "assert filter_attributes_by_product_types(qs, \"...\", None) is qs def test_attributes_filter_by_product_type_with_unsupported_field(): \"\"\"Ensure using", "The user should now be able to see the attributes", "} } } \"\"\" # Create a dummy attribute with", "def test_update_attribute_remove_and_add_values( staff_api_client, color_attribute, permission_manage_products ): query = UPDATE_ATTRIBUTE_QUERY attribute", "ASSIGN_ATTR_QUERY operations = [ { \"type\": gql_attribute_type.value, \"id\": graphene.Node.to_global_id(\"Attribute\", attribute.pk),", "existing slug should raise an error with pytest.raises(ValidationError): validate_value_is_unique(color_attribute, AttributeValue(slug=value.slug))", "\"Example name\", \"values\": [{\"name\": name_1}, {\"name\": name_2}]} response = staff_api_client.post_graphql(", "@pytest.mark.parametrize( \"attribute, expected_value\", ( (\"filterable_in_storefront\", True), (\"filterable_in_dashboard\", True), (\"visible_in_storefront\", True),", "name == attribute.name assert data[\"attribute\"][\"productTypes\"][\"edges\"] == [] def test_update_attribute_remove_and_add_values( staff_api_client,", "\"STRING\" assert name in [value[\"name\"] for value in data[\"attribute\"][\"values\"]] def", "category_id = graphene.Node.to_global_id(\"Category\", -1) mocked_qs = mock.MagicMock() qs = filter_attributes_by_product_types(mocked_qs,", "= graphene.Node.to_global_id(\"ProductType\", product_type.id) attribute_id = graphene.Node.to_global_id(\"Attribute\", color_attribute.id) variables = {", "= product.attributes.count() - 1 expected_variant_attribute_count = variant.attributes.count() - 1 if", "1 assert found_attributes[0][\"node\"][attribute] == expected_value ATTRIBUTES_RESORT_QUERY = \"\"\" mutation ProductTypeReorderAttributes(", "ID!, $operations: [AttributeAssignInput]!) { attributeAssign(productTypeId: $productTypeId, operations: $operations) { errors", "variables = { \"attributeId\": attribute_id, \"moves\": [ { \"id\": graphene.Node.to_global_id(\"AttributeValue\",", "api_client.post_graphql( \"\"\" { products(first: 10) { edges { node {", "} } } \"\"\" node_id = graphene.Node.to_global_id(\"AttributeValue\", value.id) variables =", "data[\"productVariant\" if is_variant else \"product\"][\"attributes\"] actual_order = [ int(graphene.Node.from_global_id(attr[\"attribute\"][\"id\"])[1]) for", "Attribute.objects.all() assert filter_attributes_by_product_types(qs, \"...\", \"\") is qs assert filter_attributes_by_product_types(qs, \"...\",", "reorder an invalid product type (invalid ID).\"\"\" product_type_id = graphene.Node.to_global_id(\"ProductType\",", "== error_code.name def test_update_attribute_and_remove_others_attribute_value( staff_api_client, color_attribute, size_attribute, permission_manage_products ): query", "content[\"errors\"] == [ { \"field\": \"moves\", \"message\": f\"Couldn't resolve to", "# Check if the attribute values were correctly created assert", "if the attributes are restricted and if their default value", "product_type = ProductType.objects.create(name=\"Type\") attribute = color_attribute_without_values staff_api_client.user.user_permissions.add(permission_manage_products) product_type_global_id = graphene.Node.to_global_id(\"ProductType\",", "productType { id variantAttributes { id slug } productAttributes {", "} \"\"\" def test_search_attributes(api_client, color_attribute, size_attribute): variables = {\"filters\": {\"search\":", "\"\"\"Ensure the attribute values are properly resolved when an attribute", "== expected_variant_attribute_count def test_resolve_attribute_values(user_api_client, product, staff_user): \"\"\"Ensure the attribute values", "attribute.values.first().name variables = {\"name\": value_name.upper(), \"attributeId\": attribute_id} response = staff_api_client.post_graphql(", "and its variant product.attributesrelated.clear() variant.attributesrelated.clear() # Retrieve the product and", "query = UPDATE_ATTRIBUTE_QUERY attribute = color_attribute_without_values name = \"<NAME>\" attribute_value_name", "name = \"<NAME>\" attribute_value_name = \"Yellow Color\" node_id = graphene.Node.to_global_id(\"Attribute\",", "= user_api_client variant = product.variants.first() product_attribute = color_attribute variant_attribute =", "should raise an error with pytest.raises(ValidationError): validate_value_is_unique(color_attribute, AttributeValue(slug=value.slug)) # a", "staff_api_client.post_graphql( query, variables, permissions=[permission_manage_products] ) with pytest.raises(value._meta.model.DoesNotExist): value.refresh_from_db() @pytest.mark.parametrize( \"raw_value,", "product_attributes[0][\"attribute\"][\"slug\"] == \"color\" assert product_attributes[0][\"values\"][0][\"slug\"] == product_attribute_values[0] assert product_attributes[0][\"value\"][\"slug\"] ==", "product_attributes[0][\"value\"][\"slug\"] == product_attribute_values[0] assert variant_attributes[0][\"attribute\"][\"slug\"] == \"size\" assert variant_attributes[0][\"values\"][0][\"slug\"] ==", "{ attributes { values { type inputType } } }", "{ id variantAttributes { id slug } productAttributes { id", "a new slug should pass validate_value_is_unique( color_attribute, AttributeValue(slug=\"spanish-inquisition\") ) #", "= [] variables = {\"productTypeId\": product_type_global_id, \"operations\": operations} product_attributes_ids =", "assert content[\"errors\"] == [ { \"field\": \"attributeId\", \"message\": f\"Couldn't resolve", "has_variants=True) product_type_global_id = graphene.Node.to_global_id(\"ProductType\", product_type.pk) query = ASSIGN_ATTR_QUERY operations =", "resolve to an attribute value: {value_id}\", } ] def test_sort_values_within_attribute(", "unique.\", ProductErrorCode.UNIQUE, ), ( \"Red color\", \"red color\", \"Provided values", "AttributeInputType from saleor.product.error_codes import ProductErrorCode from saleor.product.models import ( Attribute,", "not unique.\", ProductErrorCode.UNIQUE, ), ), ) def test_update_attribute_and_add_attribute_values_errors( staff_api_client, name_1,", "name assert attr_data[\"slug\"] == slugify(name) assert attr_data[\"type\"] == \"STRING\" assert", "values are all None assert variant[\"attributes\"][0][\"attribute\"][\"slug\"] == \"size\" assert variant[\"attributes\"][0][\"values\"]", ") attributes = get_graphql_content( api_client.post_graphql(ATTRIBUTES_SORT_QUERY, {}) )[\"data\"][\"attributes\"][\"edges\"] assert len(attributes) ==", "= mock.MagicMock() qs = filter_attributes_by_product_types(mocked_qs, \"in_category\", category_id) assert qs ==", "not associated to them AttributeValue.objects.bulk_create( [ AttributeValue(slug=\"a\", name=\"A\", attribute=unassigned_product_attribute), AttributeValue(slug=\"b\",", "product[\"attributes\"][0][\"attribute\"][\"slug\"] == \"color\" assert product[\"attributes\"][0][\"values\"] == [] # Ensure the", "\"values\": [{\"name\": name_1}, {\"name\": name_2}]} response = staff_api_client.post_graphql( query, variables,", "} \"\"\" def test_unassign_attributes_from_product_type( staff_api_client, permission_manage_products, attribute_list ): product_type =", "def test_sort_attributes_within_product_type( staff_api_client, attribute_list, permission_manage_products, attribute_type, relation_field, backref_field, ): attributes", "AttributeValue.objects.create(attribute=attribute, name=\"Green\", slug=\"green\") values = list(attribute.values.all()) assert len(values) == 3", "any modification. \"\"\" qs = Attribute.objects.all() assert filter_attributes_by_product_types(qs, \"...\", \"\")", "attribute_id = graphene.Node.to_global_id(\"Attribute\", attribute.id) name = \"<NAME>\" variables = {\"name\":", "permissions=[permission_manage_products] ) content = get_graphql_content(response) data = content[\"data\"][\"attributeValueCreate\"] assert data[\"productErrors\"]", "content = get_graphql_content( user_api_client.post_graphql(query, {\"id\": attribute_gql_id}) ) assert content[\"data\"][\"attribute\"], \"Should", "product_type = product_type_without_variant attribute = color_attribute_without_values staff_api_client.user.user_permissions.add(permission_manage_products) product_type_global_id = graphene.Node.to_global_id(\"ProductType\",", "restricted and if their default value is the expected one.\"\"\"", "QUERY_PRODUCT_AND_VARIANTS_ATTRIBUTES api_client = user_api_client variant = product.variants.first() assert product.attributes.count() ==", "collection.pk) elif \"Category\" in tested_field: filtered_by_node_id = graphene.Node.to_global_id(\"Category\", category.pk) else:", "productType { id variantAttributes { id } productAttributes { id", "assert gql_attr[\"values\"][0][\"inputType\"] == \"DROPDOWN\" @pytest.mark.parametrize( \"attribute, expected_value\", ( (\"filterable_in_storefront\", True),", "node { attributes { attribute { slug } values {", "zip(gql_attributes, expected_order): gql_type, gql_attr_id = graphene.Node.from_global_id(attr[\"id\"]) assert gql_type == \"Attribute\"", "relation_field) m2m_attributes.set(attributes) sort_method = getattr(m2m_attributes, f\"{relation_field}_sorted\") attributes = list(sort_method()) assert", "user_api_client.post_graphql(query) content = get_graphql_content(response) attributes_data = content[\"data\"][\"attributes\"][\"edges\"] assert len(attributes_data) ==", "permissions=[permission_manage_products] ) content = get_graphql_content(response) data = content[\"data\"][\"attributeValueUpdate\"] assert data[\"errors\"]", "= \"<NAME>\" attribute_value_name = \"Red Color\" node_id = graphene.Node.to_global_id(\"Attribute\", attribute.id)", "assert attributes[0][\"node\"][\"slug\"] == \"size\" assert attributes[1][\"node\"][\"slug\"] == \"color\" def test_sort_attributes_by_default_sorting(api_client):", "query($id: ID!) { product(id: $id) { attributes { attribute {", "M2M object for the attribute vs the product type if", "def test_sort_attributes_within_product_type_invalid_product_type( staff_api_client, permission_manage_products ): \"\"\"Try to reorder an invalid", "attribute_list[:2] ] variables = {\"filters\": {\"ids\": global_ids}} expected_slugs = sorted([attribute_list[0].slug,", "assert len(attributes) == 1 assert attributes[0][\"node\"][\"slug\"] == \"color\" def test_filter_attributes_if_filterable_in_dashboard(", "= graphene.Node.to_global_id(\"ProductVariant\", variant.pk) else: node_id = graphene.Node.to_global_id(\"Product\", product.pk) # Retrieve", "color_attribute.values.first() # a new value but with existing slug should", "content[\"data\"][\"attributeCreate\"][\"errors\"] == expected_error # Check if the slug was correctly", "attributes[0][\"node\"][\"slug\"] == \"color\" def test_filter_attributes_if_filterable_in_dashboard( api_client, color_attribute, size_attribute ): color_attribute.filterable_in_dashboard", "pytest from django.core.exceptions import ValidationError from django.db.models import Q from", "attributes = data[\"productVariant\" if is_variant else \"product\"][\"attributes\"] actual_order = [", "are not properly ordered\" variables = { \"attributeId\": attribute_id, \"moves\":", "(invalid ID).\"\"\" product_type_id = graphene.Node.to_global_id(\"ProductType\", -1) attribute_id = graphene.Node.to_global_id(\"Attribute\", -1)", "== \"color\" assert product_attributes[0][\"values\"][0][\"slug\"] == product_attribute_values[0] assert product_attributes[0][\"value\"][\"slug\"] == product_attribute_values[0]", "expected_value, ): \"\"\"Checks if the attributes are restricted and if", "content = get_graphql_content(response) attribute.refresh_from_db() data = content[\"data\"][\"attributeUpdate\"] assert not data[\"errors\"]", "{\"name\": value_name, \"attributeId\": attribute_id} response = staff_api_client.post_graphql( query, variables, permissions=[permission_manage_products]", "content = get_graphql_content(response) data = content[\"data\"][\"attributeValueCreate\"] assert data[\"productErrors\"] assert data[\"productErrors\"][0][\"code\"]", "AttributeValueType.URL), (\"example.com\", AttributeValueType.STRING), (\"Foo\", AttributeValueType.STRING), (\"linear-gradient(red, yellow)\", AttributeValueType.GRADIENT), (\"radial-gradient(#0000, yellow)\",", "[AttributeValueCreateInput]!, $removeValues: [ID]!) { attributeUpdate( id: $id, input: { name:", "id } variantAttributes { id } } } } \"\"\"", "products(first: 10) { edges { node { attributes { attribute", "test_create_attribute_with_given_slug( staff_api_client, permission_manage_products, input_slug, expected_slug, expected_error, ): staff_api_client.user.user_permissions.add(permission_manage_products) query =", "AttributeValueType.COLOR), (\"hsl(0, 100%, 50%)\", AttributeValueType.COLOR), (\"hsla(120, 60%, 70%, 0.3)\", AttributeValueType.COLOR),", "color\", \"Red color\", \"Provided values are not unique.\", ProductErrorCode.UNIQUE, ),", "from saleor.core.taxes import zero_money from saleor.graphql.core.utils import snake_to_camel_case from saleor.graphql.product.enums", "# Sort the database attributes by their sort order and", "saleor.graphql.product.enums import AttributeTypeEnum, AttributeValueType from saleor.graphql.product.filters import filter_attributes_by_product_types from saleor.graphql.product.mutations.attributes", "slug } } } } \"\"\" if test_deprecated_filter: query =", "an invalid attribute (invalid ID).\"\"\" attribute_id = graphene.Node.to_global_id(\"Attribute\", -1) value_id", "variables = {\"productTypeId\": product_type_global_id, \"operations\": operations} content = get_graphql_content(staff_api_client.post_graphql(query, variables))[", "trying to add an attribute as a variant attribute when", "\"attributeIds\": [ graphene.Node.to_global_id(\"Attribute\", color_attribute_without_values.pk) ], } content = get_graphql_content(staff_api_client.post_graphql(query, variables))[", "== expected_slugs ATTRIBUTES_SORT_QUERY = \"\"\" query($sortBy: AttributeSortingInput) { attributes(first: 10,", "\"\"\" def test_assign_attributes_to_product_type( staff_api_client, permission_manage_products, attribute_list ): product_type = ProductType.objects.create(name=\"Default", "int(graphene.Node.from_global_id(attr[\"id\"])[1]) for attr in content[\"productType\"][\"variantAttributes\"] } assert found_product_attrs_ids == product_attributes_ids", "= graphene.Node.from_global_id(attr[\"id\"]) assert gql_type == \"AttributeValue\" actual_order.append(int(gql_attr_id)) assert actual_order ==", "(AttributeTypeEnum.VARIANT, AttributeTypeEnum.PRODUCT), (AttributeTypeEnum.PRODUCT, AttributeTypeEnum.PRODUCT), (AttributeTypeEnum.VARIANT, AttributeTypeEnum.VARIANT), ), ) def test_assign_attribute_to_product_type_having_already_that_attribute(", "addValues: $addValues, removeValues: $removeValues}) { errors { field message }", "color_attribute variant_attribute = size_attribute expected_product_attribute_count = product.attributes.count() - 1 expected_variant_attribute_count", "{ id } } } } \"\"\" def test_assign_attributes_to_product_type( staff_api_client,", "\"id\": graphene.Node.to_global_id(\"Attribute\", attributes[2].pk), \"sortOrder\": -1, }, ], } expected_order =", "# Create a value for each dummy attribute to ensure", "name, \"id\": node_id, \"addValues\": [{\"name\": attribute_value_name}], \"removeValues\": [value_id], } response", "message } attribute { id } } } \"\"\" node_id", "updateChoice( $id: ID!, $name: String!) { attributeValueUpdate( id: $id, input:", "in found_products[0][\"node\"][\"attributes\"]: assert len(gql_attr[\"values\"]) == 1 assert gql_attr[\"values\"][0][\"type\"] == \"STRING\"", "ID).\"\"\" attribute_id = graphene.Node.to_global_id(\"Attribute\", -1) value_id = graphene.Node.to_global_id(\"AttributeValue\", -1) variables", "= product[\"variants\"][0][\"attributes\"] assert len(product_attributes) == 2, \"Non-assigned attr from the", "name by default.\"\"\" Attribute.objects.bulk_create( [Attribute(name=\"A\", slug=\"b\"), Attribute(name=\"B\", slug=\"a\")] ) attributes", "in [value[\"name\"] for value in data[\"attribute\"][\"values\"]] def test_create_attribute_value_not_unique_name( staff_api_client, color_attribute,", "== AttributeTypeEnum.VARIANT: product_type.variant_attributes.add(attribute) else: raise ValueError(f\"Unknown: {product_type}\") query = ASSIGN_ATTR_QUERY", "{\"availableInGrid\": True}} attributes = get_graphql_content( api_client.post_graphql(ATTRIBUTES_FILTER_QUERY, variables) )[\"data\"][\"attributes\"][\"edges\"] assert len(attributes)", "able to see the hidden attributes assert Attribute.objects.get_visible_to_user(staff_api_client.user).count() == 1", "an attribute as a variant attribute when the attribute's input", "any error when trying to remove an attribute that is", "\"\"\" mutation updateChoice($id: ID!) { attributeValueDelete(id: $id) { attributeValue {", "relation_field, backref_field\", ( (\"VARIANT\", \"variant_attributes\", \"attributevariant\"), (\"PRODUCT\", \"product_attributes\", \"attributeproduct\"), ),", "may be missing\" assert product_attributes[0][\"attribute\"][\"slug\"] == \"product\" assert product_attributes[0][\"values\"] ==", "attribute { values { name } } } } \"\"\"", "slug } values { name } } } } }", "\"direction\": \"DESC\"}} attributes = get_graphql_content( api_client.post_graphql(ATTRIBUTES_SORT_QUERY, variables) )[\"data\"][\"attributes\"][\"edges\"] assert len(attributes)", "(when None) expected_order = [other_attribute.pk, color_attribute.pk] # Make the node", "the product node = variant if is_variant else product #", "node_id = graphene.Node.to_global_id(\"AttributeValue\", value.id) name = \"Crimson name\" variables =", "assert variant[\"attributes\"][0][\"values\"] == [] ASSIGN_ATTR_QUERY = \"\"\" mutation assign($productTypeId: ID!,", "ID! $moves: [ReorderInput]! $type: AttributeTypeEnum! ) { productTypeReorderAttributes( productTypeId: $productTypeId", "values[0].pk), \"sortOrder\": +1, }, { \"id\": graphene.Node.to_global_id(\"AttributeValue\", values[2].pk), \"sortOrder\": -1,", "the test. other_attribute = Attribute.objects.create(name=\"Other\", slug=\"other\") # Add the attribute", "len(product[\"attributes\"]) == 1 assert product[\"attributes\"][0][\"attribute\"][\"slug\"] == \"color\" assert product[\"attributes\"][0][\"values\"] ==", "assignAttribute mutation should raise an error when trying to use", "= size_attribute.values.first() attr_id = graphene.Node.to_global_id(\"AttributeValue\", size_attribute.pk) variables = { \"name\":", "import snake_to_camel_case from saleor.graphql.product.enums import AttributeTypeEnum, AttributeValueType from saleor.graphql.product.filters import", "len(content[\"productType\"][\"productAttributes\"]) == 1 assert len(content[\"productType\"][\"variantAttributes\"]) == 1 assert ( content[\"productType\"][\"productAttributes\"][0][\"id\"]", "content[\"productType\"][\"variantAttributes\"] } assert found_product_attrs_ids == product_attributes_ids assert found_variant_attrs_ids == variant_attributes_ids", "1}], } content = get_graphql_content( staff_api_client.post_graphql( ATTRIBUTES_RESORT_QUERY, variables, permissions=[permission_manage_products] )", "AttributeTypeEnum.PRODUCT), (AttributeTypeEnum.VARIANT, AttributeTypeEnum.VARIANT), ), ) def test_assign_attribute_to_product_type_having_already_that_attribute( staff_api_client, permission_manage_products, color_attribute_without_values,", "relation_field, backref_field, ): attributes = attribute_list assert len(attributes) == 3", "Attribute.objects.get_visible_to_user(staff_api_client.user).count() == 1 # The user should now be able", "if is_staff: api_client.user = staff_user expected_product_attribute_count += 1 expected_variant_attribute_count +=", "id variantAttributes { id slug } productAttributes { id }", "content = get_graphql_content(response) attributes_data = content[\"data\"][\"attributes\"][\"edges\"] assert len(attributes_data) == attribute_count", "for it or is not directly associated to it. \"\"\"", "product_type.variant_attributes.clear() staff_api_client.user.user_permissions.add(permission_manage_products) product_type_global_id = graphene.Node.to_global_id(\"ProductType\", product_type.pk) query = ASSIGN_ATTR_QUERY operations", "user_api_client variant = product.variants.first() assert product.attributes.count() == 1 assert variant.attributes.count()", "), ( \"Red color\", \"red color\", \"Provided values are not", "= [values[1].pk, values[2].pk, values[0].pk] content = get_graphql_content( staff_api_client.post_graphql(ATTRIBUTE_VALUES_RESORT_QUERY, variables) )[\"data\"][\"attributeReorderValues\"]", ") content = get_graphql_content(response) errors = content[\"data\"][\"attributeUpdate\"][\"errors\"] assert errors assert", "but shouldn't get matched # as we don't look for", ") found_attributes = get_graphql_content( staff_api_client.post_graphql(query, permissions=[permission_manage_products]) )[\"data\"][\"attributes\"][\"edges\"] assert len(found_attributes) ==", "def test_delete_attribute_value( staff_api_client, color_attribute, pink_attribute_value, permission_manage_products ): value = color_attribute.values.get(name=\"Red\")", "actual_order == expected_order ATTRIBUTES_FILTER_QUERY = \"\"\" query($filters: AttributeFilterInput!) { attributes(first:", "= get_graphql_content(response) attributes_data = content[\"data\"][\"attributes\"][\"edges\"] assert len(attributes_data) == attribute_count def", "name_2}]} response = staff_api_client.post_graphql( query, variables, permissions=[permission_manage_products] ) content =", "[AttributeAssignInput]!) { attributeAssign(productTypeId: $productTypeId, operations: $operations) { errors { field", "def test_filter_attributes_if_filterable_in_dashboard( api_client, color_attribute, size_attribute ): color_attribute.filterable_in_dashboard = False color_attribute.save(update_fields=[\"filterable_in_dashboard\"])", "\"operations\", \"message\": ( \"Attributes having for input types ['multiselect'] cannot", "= graphene.Node.to_global_id(\"Category\", -1) mocked_qs = mock.MagicMock() qs = filter_attributes_by_product_types(mocked_qs, \"in_category\",", "\"moves\": [{\"id\": attribute_id, \"sortOrder\": 1}], } content = get_graphql_content( staff_api_client.post_graphql(", "Color\" node_id = graphene.Node.to_global_id(\"Attribute\", attribute.id) attribute_value_id = attribute.values.first().id value_id =", "Check if the attribute values were correctly created assert len(data[\"attribute\"][\"values\"])", "in attribute_list[2:]} for attr_id in product_attributes_ids: operations.append( {\"type\": \"PRODUCT\", \"id\":", "color_attribute_without_values, product_type_attribute_type, gql_attribute_type, ): \"\"\"The assignAttribute mutation should raise an", "a variant attribute when the attribute's input type doesn't support", "api_client, color_attribute, size_attribute, sort_field: str, m2m_model: Union[AttributeVariant, AttributeProduct], ): \"\"\"Sorts", "}, ], } expected_order = [values[1].pk, values[2].pk, values[0].pk] content =", "attribute.pk), } ] variables = {\"productTypeId\": product_type_global_id, \"operations\": operations} content", "\"\"\" def test_sort_values_within_attribute_invalid_product_type( staff_api_client, permission_manage_products ): \"\"\"Try to reorder an", "query = QUERY_PRODUCT_AND_VARIANTS_ATTRIBUTES api_client = user_api_client variant = product.variants.first() product_type", "\"removeValues\": [], \"addValues\": [{\"name\": name_1}, {\"name\": name_2}], } response =", "even if the product doesn't provide any value for it", "products = get_graphql_content( api_client.post_graphql( \"\"\" { products(first: 10) { edges", "attribute { values { name } } attributeValue { name", "attribute { slug } values { name } } }", "that shouldn't get matched other_category = Category.objects.create(name=\"Other Category\", slug=\"other-cat\") other_attribute", "data[\"attributeValue\"][\"slug\"] == slugify(name) assert name in [value[\"name\"] for value in", "product_type_attribute_type == AttributeTypeEnum.PRODUCT: product_type.product_attributes.add(attribute) elif product_type_attribute_type == AttributeTypeEnum.VARIANT: product_type.variant_attributes.add(attribute) else:", "} \"\"\" def test_assign_attributes_to_product_type( staff_api_client, permission_manage_products, attribute_list ): product_type =", "test_get_single_attribute_by_pk(user_api_client, color_attribute_without_values): attribute_gql_id = graphene.Node.to_global_id( \"Attribute\", color_attribute_without_values.id ) query =", "def test_sort_values_within_attribute( staff_api_client, color_attribute, permission_manage_products ): attribute = color_attribute AttributeValue.objects.create(attribute=attribute,", "[Attribute(name=\"A\", slug=\"b\"), Attribute(name=\"B\", slug=\"a\")] ) attributes = get_graphql_content( api_client.post_graphql(ATTRIBUTES_SORT_QUERY, {})", "String!) { attributeValueCreate( attribute: $attributeId, input: {name: $name}) { productErrors", "query = ASSIGN_ATTR_QUERY operations = [ {\"type\": \"VARIANT\", \"id\": graphene.Node.to_global_id(\"Attribute\",", "(\"filterable_in_storefront\", True), (\"filterable_in_dashboard\", True), (\"visible_in_storefront\", True), (\"available_in_grid\", True), (\"value_required\", False),", "to a product type\" # Check if the attribute values", "): query = QUERY_ATTRIBUTES # hide the attribute color_attribute.visible_in_storefront =", ") content = get_graphql_content(response) errors = content[\"data\"][\"attributeCreate\"][\"errors\"] assert errors assert", "== expected_flat_attributes_data CREATE_ATTRIBUTES_QUERY = \"\"\" mutation createAttribute($name: String!, $values: [AttributeValueCreateInput])", "unittest import mock import graphene import pytest from django.core.exceptions import", "test_resolve_attribute_values(user_api_client, product, staff_user): \"\"\"Ensure the attribute values are properly resolved.\"\"\"", "{ edges { node { %s } } } }", "[ReorderInput]! $type: AttributeTypeEnum! ) { productTypeReorderAttributes( productTypeId: $productTypeId moves: $moves", "$id) { id slug } } \"\"\" content = get_graphql_content(", "\"id\": graphene.Node.to_global_id(\"Attribute\", attribute.pk)} ] variables = {\"productTypeId\": product_type_global_id, \"operations\": operations}", "other_attribute = Attribute.objects.create(name=\"Other\", slug=\"other\") # Add the attribute to the", "Ensure the variant attributes values are all None assert variant[\"attributes\"][0][\"attribute\"][\"slug\"]", "\"id\": graphene.Node.to_global_id(\"AttributeValue\", values[0].pk), \"sortOrder\": +1, }, { \"id\": graphene.Node.to_global_id(\"AttributeValue\", values[2].pk),", "= color_attribute.values.get(name=\"Red\") query = \"\"\" mutation updateChoice($id: ID!) { attributeValueDelete(id:", "} } } \"\"\" def test_sort_values_within_attribute_invalid_product_type( staff_api_client, permission_manage_products ): \"\"\"Try", "assert len(product_attributes) == len(product_attribute_values) assert len(variant_attributes) == len(variant_attribute_values) assert product_attributes[0][\"attribute\"][\"slug\"]", "test_unassign_attributes_not_in_product_type( staff_api_client, permission_manage_products, color_attribute_without_values ): \"\"\"The unAssignAttribute mutation should not", "staff_api_client.post_graphql( query, variables, permissions=[permission_manage_products] ) content = get_graphql_content(response) assert not", "{\"field\": \"SLUG\", \"direction\": \"ASC\"}} attributes = get_graphql_content( api_client.post_graphql(ATTRIBUTES_SORT_QUERY, variables) )[\"data\"][\"attributes\"][\"edges\"]", "product_type = ProductType.objects.create(name=\"Dummy Type\") product_type_id = graphene.Node.to_global_id(\"ProductType\", product_type.id) attribute_id =", "product.variants.get() # Remove all attributes and values from the product", "succeeded\" assert content[\"productType\"][\"id\"] == product_type_global_id assert len(content[\"productType\"][\"productAttributes\"]) == len( product_attributes_ids", "product type if is_variant: product.product_type.variant_attributes.set([color_attribute, other_attribute]) else: product.product_type.product_attributes.set([color_attribute, other_attribute]) #", "attributes { values { type inputType } } } }", "\"removeValues\": [attr_id], } response = staff_api_client.post_graphql( query, variables, permissions=[permission_manage_products] )", "= get_graphql_content( staff_api_client.post_graphql( query, variables, permissions=[permission_manage_products] ) )[\"data\"][\"attributeAssign\"] assert not", "== 3 staff_api_client.user.user_permissions.add(permission_manage_products) attribute_id = graphene.Node.to_global_id(\"Attribute\", attribute.id) m2m_values = attribute.values", "= user_api_client variant = product.variants.first() product_type = product.product_type # Create", "slug: $slug}) { errors { field message } attribute {", "nodes data product = products[0][\"node\"] variant = product[\"variants\"][0] # Ensure", "== len(variant_attribute_values) assert product_attributes[0][\"attribute\"][\"slug\"] == \"color\" assert product_attributes[0][\"values\"][0][\"slug\"] == product_attribute_values[0]", "1 for gql_attr in found_products[0][\"node\"][\"attributes\"]: assert len(gql_attr[\"values\"]) == 1 assert", "][0][\"node\"] product_attributes = product[\"attributes\"] variant_attributes = product[\"variants\"][0][\"attributes\"] assert len(product_attributes) ==", "String!, $addValues: [AttributeValueCreateInput]!, $removeValues: [ID]!) { attributeUpdate( id: $id, input:", "[{\"id\": attribute_id, \"sortOrder\": 1}], } content = get_graphql_content( staff_api_client.post_graphql( ATTRIBUTES_RESORT_QUERY,", "product_attribute_values[0] assert variant_attributes[0][\"attribute\"][\"slug\"] == \"size\" assert variant_attributes[0][\"values\"][0][\"slug\"] == variant_attribute_values[0] assert", "= { \"attributeId\": attribute_id, \"moves\": [{\"id\": value_id, \"sortOrder\": 1}], }", "with pytest.raises(attribute._meta.model.DoesNotExist): attribute.refresh_from_db() CREATE_ATTRIBUTE_VALUE_QUERY = \"\"\" mutation createAttributeValue( $attributeId: ID!,", "field message } attribute { slug } } } \"\"\"", "$attributeId, input: {name: $name}) { productErrors { field message code", "attribute in attribute_list[:2] ] variables = {\"filters\": {\"ids\": global_ids}} expected_slugs", "} ] @pytest.mark.parametrize( \"attribute_type, relation_field, backref_field\", ( (\"VARIANT\", \"variant_attributes\", \"attributevariant\"),", "= product.variants.first() product_type = product.product_type # Create dummy attributes unassigned_product_attribute", "attributes_data = content[\"data\"][\"attributes\"][\"edges\"] flat_attributes_data = [attr[\"node\"][\"slug\"] for attr in attributes_data]", "} } \"\"\" def test_update_attribute_value( staff_api_client, pink_attribute_value, permission_manage_products ): query", "as a variant attribute when the attribute's input type doesn't", "\"size\" def test_filter_attributes_if_available_in_grid( api_client, color_attribute, size_attribute ): color_attribute.available_in_grid = False", "ID!) { productVariant(id: $id) { attributes { attribute { id", "updateAttribute( $id: ID!, $name: String!, $addValues: [AttributeValueCreateInput]!, $removeValues: [ID]!) {", "should be resolved. \"\"\" query = QUERY_PRODUCT_AND_VARIANTS_ATTRIBUTES api_client = user_api_client", "\"attributeproduct\"), ), ) def test_sort_attributes_within_product_type( staff_api_client, attribute_list, permission_manage_products, attribute_type, relation_field,", "product type are resolved even if the product doesn't provide", "assert len(content[\"productType\"][\"variantAttributes\"]) == len( variant_attributes_ids ) found_product_attrs_ids = { int(graphene.Node.from_global_id(attr[\"id\"])[1])", "assert content[\"productType\"][\"id\"] == product_type_global_id assert len(content[\"productType\"][\"productAttributes\"]) == 1 assert len(content[\"productType\"][\"variantAttributes\"])", "assert data[\"attribute\"][\"values\"][0][\"name\"] == name assert data[\"attribute\"][\"values\"][0][\"slug\"] == slugify(name) @pytest.mark.parametrize( \"input_slug,", "test_attributes_filter_by_product_type_with_empty_value(): \"\"\"Ensure passing an empty or null value is ignored", "operations = [ {\"type\": \"VARIANT\", \"id\": graphene.Node.to_global_id(\"Attribute\", attribute.pk)} ] variables", "in attributes_data] expected_flat_attributes_data = list(expected_qs.values_list(\"slug\", flat=True)) assert flat_attributes_data == expected_flat_attributes_data", "have sort_order=null AttributeProduct.objects.create( attribute=unassigned_product_attribute, product_type=product_type, sort_order=0 ) AttributeVariant.objects.create( attribute=unassigned_variant_attribute, product_type=product_type,", "gql_attr[\"values\"][0][\"inputType\"] == \"DROPDOWN\" @pytest.mark.parametrize( \"attribute, expected_value\", ( (\"filterable_in_storefront\", True), (\"filterable_in_dashboard\",", "and staff users having the 'manage product' permission can. \"\"\"", "$moves) { attribute { id values { id } }", "the attribute values are properly resolved when an attribute is", "qs assert filter_attributes_by_product_types(qs, \"...\", None) is qs def test_attributes_filter_by_product_type_with_unsupported_field(): \"\"\"Ensure", "\"<NAME>\" name = \"Value name\" variables = {\"name\": attribute_name, \"values\":", "createAttribute( $name: String!, $slug: String) { attributeCreate(input: {name: $name, slug:", "} } } } \"\"\" def test_update_attribute_name( staff_api_client, color_attribute, permission_manage_products", "content = get_graphql_content(response) attribute.refresh_from_db() data = content[\"data\"][\"attributeUpdate\"] assert data[\"attribute\"][\"name\"] ==", "product_type_id ), \"Did not return the correct product type\" gql_attributes", "== attribute_id gql_values = content[\"attribute\"][\"values\"] assert len(gql_values) == len(expected_order) actual_order", "len(product_attributes) == len(product_attribute_values) assert len(variant_attributes) == len(variant_attribute_values) assert product_attributes[0][\"attribute\"][\"slug\"] ==", "assert variant_attributes[0][\"attribute\"][\"slug\"] == \"variant\" assert variant_attributes[0][\"values\"] == [] assert variant_attributes[0][\"value\"]", "} } \"\"\" @pytest.mark.parametrize(\"is_staff\", (False, True)) def test_resolve_attributes_with_hidden( user_api_client, product,", "simply returned without any modification. \"\"\" qs = Attribute.objects.all() assert", "assert len(products) == 1 assert len(products[0][\"node\"][\"variants\"]) == 1 # Retrieve", "assert attr_data[\"slug\"] == slugify(name) assert attr_data[\"type\"] == \"STRING\" assert name", "\"size\" assert variant_attributes[0][\"values\"][0][\"slug\"] == variant_attribute_values[0] assert variant_attributes[0][\"value\"][\"slug\"] == variant_attribute_values[0] def", "attribute.values.filter(name=attribute_value_name).exists() def test_update_empty_attribute_and_add_values( staff_api_client, color_attribute_without_values, permission_manage_products ): query = UPDATE_ATTRIBUTE_QUERY", "test_attributes_query_hidden_attribute(user_api_client, product, color_attribute): query = QUERY_ATTRIBUTES # hide the attribute", "\"\"\" mutation createAttribute( $name: String!, $slug: String) { attributeCreate(input: {name:", "one product and variant attribute from the storefront for attribute", "} productErrors { field message code } attribute { name", "product_errors[0][\"code\"] == error_code.name UPDATE_ATTRIBUTE_QUERY = \"\"\" mutation updateAttribute( $id: ID!,", "saleor.graphql.product.types.attributes import resolve_attribute_value_type from saleor.product import AttributeInputType from saleor.product.error_codes import", "created assert len(data[\"attribute\"][\"values\"]) == 1 assert data[\"attribute\"][\"values\"][0][\"name\"] == name assert", "= {\"nodeID\": filtered_by_node_id} content = get_graphql_content(user_api_client.post_graphql(query, variables)) attributes_data = content[\"data\"][\"attributes\"][\"edges\"]", "color_attribute query = \"\"\" mutation deleteAttribute($id: ID!) { attributeDelete(id: $id)", "updateChoice($id: ID!) { attributeValueDelete(id: $id) { attributeValue { name slug", "attr in content[\"productType\"][\"variantAttributes\"] } assert found_product_attrs_ids == product_attributes_ids assert found_variant_attrs_ids", "content[\"data\"][\"attribute\"][\"id\"] == attribute_gql_id assert content[\"data\"][\"attribute\"][\"slug\"] == color_attribute_without_values.slug QUERY_ATTRIBUTES = \"\"\"", "doesn't support variants\"\"\" product_type = product_type_without_variant attribute = color_attribute_without_values staff_api_client.user.user_permissions.add(permission_manage_products)", "staff_api_client.post_graphql(query, permissions=[permission_manage_products]) )[\"data\"][\"products\"][\"edges\"] assert len(found_products) == 1 for gql_attr in", "= list( product.attributes.first().values.values_list(\"slug\", flat=True) ) variant_attribute_values = list( variant.attributes.first().values.values_list(\"slug\", flat=True)", "permission_manage_products, attribute_type, relation_field, backref_field, ): attributes = attribute_list assert len(attributes)", ") def test_create_attribute_and_attribute_values_errors( staff_api_client, name_1, name_2, error_msg, error_code, permission_manage_products, product_type,", "not/no longer in the product type.\"\"\" staff_api_client.user.user_permissions.add(permission_manage_products) product_type = ProductType.objects.create(name=\"Type\")", "color_attribute.id) value_id = graphene.Node.to_global_id(\"AttributeValue\", -1) variables = { \"type\": \"VARIANT\",", "query = \"\"\" mutation createAttribute( $name: String!, $slug: String) {", "graphene.Node.to_global_id(\"Attribute\", attribute.id) value_name = attribute.values.first().name variables = {\"name\": value_name, \"attributeId\":", "attributes values are all None assert len(product[\"attributes\"]) == 1 assert", "gql_attribute_type.value, \"id\": graphene.Node.to_global_id(\"Attribute\", attribute.pk), } ] variables = {\"productTypeId\": product_type_global_id,", "api_client.post_graphql(ATTRIBUTES_FILTER_QUERY, variables) )[\"data\"][\"attributes\"][\"edges\"] assert len(attributes) == 1 assert attributes[0][\"node\"][\"slug\"] ==", "in data[\"attribute\"][\"values\"]] def test_create_attribute_value_not_unique_name( staff_api_client, color_attribute, permission_manage_products ): attribute =", "attr in attributes_data] expected_flat_attributes_data = list(expected_qs.values_list(\"slug\", flat=True)) assert flat_attributes_data ==", "product doesn't provide any value for it or is not", "= {\"id\": node_id} staff_api_client.post_graphql( query, variables, permissions=[permission_manage_products] ) with pytest.raises(value._meta.model.DoesNotExist):", "mutation attributeReorderValues($attributeId: ID!, $moves: [ReorderInput]!) { attributeReorderValues(attributeId: $attributeId, moves: $moves)", "product_type ): attribute = color_attribute query = \"\"\" mutation deleteAttribute($id:", "assert len(product_attribute_values) == 1 assert len(variant_attribute_values) == 1 product =", "= { \"productTypeId\": product_type_global_id, \"attributeIds\": [ graphene.Node.to_global_id(\"Attribute\", color_attribute_without_values.pk) ], }", "error_msg product_errors = content[\"data\"][\"attributeCreate\"][\"productErrors\"] assert product_errors[0][\"code\"] == error_code.name UPDATE_ATTRIBUTE_QUERY =", "assert len(values) == 3 staff_api_client.user.user_permissions.add(permission_manage_products) attribute_id = graphene.Node.to_global_id(\"Attribute\", attribute.id) m2m_values", "color_attribute, size_attribute ): color_attribute.filterable_in_dashboard = False color_attribute.save(update_fields=[\"filterable_in_dashboard\"]) variables = {\"filters\":", "{ \"name\": name, \"id\": node_id, \"addValues\": [{\"name\": attribute_value_name}], \"removeValues\": [],", "variantAttributes { id slug } productAttributes { id } }", "node { id } } } } } } \"\"\"", "value for it or is not directly associated to it.", "saleor.product.utils.attributes import associate_attribute_values_to_instance from tests.api.utils import get_graphql_content def test_validate_value_is_unique(color_attribute): value", "[attr[\"node\"][\"slug\"] for attr in attributes_data] expected_flat_attributes_data = list(expected_qs.values_list(\"slug\", flat=True)) assert", "assert ( content[\"productType\"][\"id\"] == product_type_id ), \"Did not return the", "\"name_1, name_2, error_msg, error_code\", ( ( \"Red color\", \"Red color\",", "product type.\"\"\" product_type = ProductType.objects.create(name=\"My Product Type\") m2m_model.objects.create( product_type=product_type, attribute=color_attribute,", "= graphene.Node.to_global_id( \"Attribute\", product_attributes[1].pk ) query = UNASSIGN_ATTR_QUERY variables =", "are properly resolved.\"\"\" query = QUERY_PRODUCT_AND_VARIANTS_ATTRIBUTES api_client = user_api_client variant", "the node ID if is_variant: node_id = graphene.Node.to_global_id(\"ProductVariant\", variant.pk) else:", "1 expected_variant_attribute_count = variant.attributes.count() - 1 if is_staff: api_client.user =", "{ attributeCreate(input: {name: $name, values: $values}) { errors { field", "flat_attributes_data == expected_flat_attributes_data CREATE_ATTRIBUTES_QUERY = \"\"\" mutation createAttribute($name: String!, $values:", "attribute_id = graphene.Node.to_global_id(\"Attribute\", color_attribute.id) variables = { \"type\": \"VARIANT\", \"productTypeId\":", "product and variant attribute from the storefront for attribute in", ") assert content[\"data\"][\"attribute\"], \"Should have found an attribute\" assert content[\"data\"][\"attribute\"][\"id\"]", "data = get_graphql_content(staff_api_client.post_graphql(query, {\"id\": node_id}))[ \"data\" ] attributes = data[\"productVariant\"", "} \"\"\" def test_create_attribute_value( staff_api_client, color_attribute, permission_manage_products ): attribute =", "assert len(product_attributes) == 2, \"Non-assigned attr from the PT may", "variant_attributes[0][\"values\"] == [] assert variant_attributes[0][\"value\"] is None def test_attributes_filter_by_product_type_with_empty_value(): \"\"\"Ensure", "a non-existing category ID returns an empty query set.\"\"\" category_id", "disabled in this product type.\", } ] def test_assign_variant_attribute_having_unsupported_input_type( staff_api_client,", "test_sort_values_within_attribute_invalid_product_type( staff_api_client, permission_manage_products ): \"\"\"Try to reorder an invalid attribute", "} expected_order = [values[1].pk, values[2].pk, values[0].pk] content = get_graphql_content( staff_api_client.post_graphql(ATTRIBUTE_VALUES_RESORT_QUERY,", "gql_attr[\"values\"][0][\"type\"] == \"STRING\" assert gql_attr[\"values\"][0][\"inputType\"] == \"DROPDOWN\" @pytest.mark.parametrize( \"attribute, expected_value\",", "attribute_list product_type.product_attributes.add(*product_attributes) product_type.variant_attributes.add(variant_attribute) remaining_attribute_global_id = graphene.Node.to_global_id( \"Attribute\", product_attributes[1].pk ) query", "content[\"data\"][\"attributes\"][\"edges\"] assert attributes_data assert len(attributes_data) == attributes.count() def test_attributes_query_hidden_attribute(user_api_client, product,", "} } \"\"\" def test_search_attributes(api_client, color_attribute, size_attribute): variables = {\"filters\":", "assert content[\"data\"][\"attribute\"][\"slug\"] == color_attribute_without_values.slug QUERY_ATTRIBUTES = \"\"\" query { attributes(first:", "query, variables, permissions=[permission_manage_products] ) content = get_graphql_content(response) data = content[\"data\"][\"attributeValueUpdate\"]", "user_api_client.user ).count() assert attribute_count == 1 response = user_api_client.post_graphql(query) content", "\"\", None, [{\"field\": \"slug\", \"message\": \"The attribute's slug cannot be", "= color_attribute node_id = graphene.Node.to_global_id(\"Attribute\", attribute.id) size_attribute = size_attribute.values.first() attr_id", "assert attributes_data assert len(attributes_data) == attributes.count() def test_attributes_query_hidden_attribute(user_api_client, product, color_attribute):", "in tested_field: filtered_by_node_id = graphene.Node.to_global_id(\"Collection\", collection.pk) elif \"Category\" in tested_field:", "(\"ftp://example.com\", AttributeValueType.URL), (\"example.com\", AttributeValueType.STRING), (\"Foo\", AttributeValueType.STRING), (\"linear-gradient(red, yellow)\", AttributeValueType.GRADIENT), (\"radial-gradient(#0000,", "= graphene.Node.to_global_id(\"AttributeValue\", size_attribute.pk) variables = { \"name\": \"Example name\", \"id\":", "): query = CREATE_ATTRIBUTES_QUERY attribute_name = \"<NAME>\" name = \"Value", "attribute.\" % str(size_attribute) assert errors[0][\"message\"] == err_msg product_errors = content[\"data\"][\"attributeUpdate\"][\"productErrors\"]", "): \"\"\"Try to reorder a value not associated to the", "color_attribute, size_attribute ): color_attribute.available_in_grid = False color_attribute.save(update_fields=[\"available_in_grid\"]) variables = {\"filters\":", "1 assert attributes[0][\"node\"][\"slug\"] == \"size\" def test_filter_attributes_by_global_id_list(api_client, attribute_list): global_ids =", "ProductType.objects.create(name=\"My Product Type\") m2m_model.objects.create( product_type=product_type, attribute=color_attribute, sort_order=0 ) m2m_model.objects.create( product_type=product_type,", "= product[\"variants\"][0][\"attributes\"] assert len(product_attributes) == len(product_attribute_values) assert len(variant_attributes) == len(variant_attribute_values)", "\"attributeId\": attribute_id, \"moves\": [{\"id\": value_id, \"sortOrder\": 1}], } content =", "value_name = attribute.values.first().name variables = {\"name\": value_name.upper(), \"attributeId\": attribute_id} response", "test_sort_attributes_within_product_type_invalid_product_type( staff_api_client, permission_manage_products ): \"\"\"Try to reorder an invalid product", "graphene.Node.to_global_id(\"ProductType\", -1) attribute_id = graphene.Node.to_global_id(\"Attribute\", -1) variables = { \"type\":", "== 1 assert found_attributes[0][\"node\"][attribute] == expected_value ATTRIBUTES_RESORT_QUERY = \"\"\" mutation", "(\"hsl(0, 100%, 50%)\", AttributeValueType.COLOR), (\"hsla(120, 60%, 70%, 0.3)\", AttributeValueType.COLOR), (\"rgba(100%,", "node = variant if is_variant else product # type: Union[Product,", "name, \"attributeId\": attribute_id} response = staff_api_client.post_graphql( query, variables, permissions=[permission_manage_products] )", "name in [value[\"name\"] for value in data[\"attribute\"][\"values\"]] def test_update_attribute_value_name_not_unique( staff_api_client,", "content[\"productType\"][\"id\"] == product_type_global_id assert len(content[\"productType\"][\"productAttributes\"]) == 0 assert len(content[\"productType\"][\"variantAttributes\"]) ==", "Type\", has_variants=True) product_type_global_id = graphene.Node.to_global_id(\"ProductType\", product_type.pk) query = ASSIGN_ATTR_QUERY operations", "type.\"\"\" product_type = ProductType.objects.create(name=\"Type\") attribute = color_attribute_without_values staff_api_client.user.user_permissions.add(permission_manage_products) product_type_global_id =", "if \"Collection\" in tested_field: filtered_by_node_id = graphene.Node.to_global_id(\"Collection\", collection.pk) elif \"Category\"", "query = UPDATE_ATTRIBUTE_QUERY attribute = color_attribute name = \"<NAME>\" node_id", "from saleor.graphql.core.utils import snake_to_camel_case from saleor.graphql.product.enums import AttributeTypeEnum, AttributeValueType from", "attributeValue { name slug } attribute { values { name", "are all None assert len(product[\"attributes\"]) == 1 assert product[\"attributes\"][0][\"attribute\"][\"slug\"] ==", "raise AssertionError(tested_field) expected_qs = Attribute.objects.filter( Q(attributeproduct__product_type_id=product_type.pk) | Q(attributevariant__product_type_id=product_type.pk) ) #", "response = staff_api_client.post_graphql( query, variables, permissions=[permission_manage_products] ) content = get_graphql_content(response)", "product type.\"\"\" staff_api_client.user.user_permissions.add(permission_manage_products) product_type = ProductType.objects.create(name=\"Type\") product_type_global_id = graphene.Node.to_global_id(\"ProductType\", product_type.pk)", "%s } } } } \"\"\" % attribute ) found_attributes", "assert len(variant_attributes) == 2, \"Non-assigned attr from the PT may", "variables, permissions=[permission_manage_products] ) content = get_graphql_content(response) attribute.refresh_from_db() data = content[\"data\"][\"attributeUpdate\"]", "): \"\"\"Try to reorder an invalid product type (invalid ID).\"\"\"", "staff_api_client.post_graphql( query, variables, permissions=[permission_manage_products] ) get_graphql_content(response) attribute.refresh_from_db() assert attribute.values.count() ==", "variables = {\"filters\": {\"ids\": global_ids}} expected_slugs = sorted([attribute_list[0].slug, attribute_list[1].slug]) attributes", "assert attr_data[\"type\"] == \"STRING\" assert name in [value[\"name\"] for value", "color_attribute, permission_manage_products, product_type ): attribute = color_attribute query = \"\"\"", "AttributeFilterInput!) { attributes(first: 10, filter: $filters) { edges { node", "query = UPDATE_ATTRIBUTE_VALUE_QUERY value = pink_attribute_value.attribute.values.create( name=\"<NAME>\", slug=\"example-name\", value=\"#RED\" )", "attribute_id, \"moves\": [{\"id\": value_id, \"sortOrder\": 1}], } content = get_graphql_content(", "graphene.Node.to_global_id(\"AttributeValue\", values[2].pk), \"sortOrder\": -1, }, ], } expected_order = [values[1].pk,", "staff_api_client.post_graphql( query, variables, permissions=[permission_manage_products] ) content = get_graphql_content(response) data =", "\"slug\", \"message\": \"The attribute's slug cannot be blank.\"}], ), ),", "mutation updateChoice( $id: ID!, $name: String!) { attributeValueUpdate( id: $id,", "= \"\"\" query($id: ID!) { productVariant(id: $id) { attributes {", "variables = {\"sortBy\": {\"field\": sort_field, \"direction\": \"DESC\"}} attributes = get_graphql_content(", "def test_assign_attributes_to_product_type( staff_api_client, permission_manage_products, attribute_list ): product_type = ProductType.objects.create(name=\"Default Type\",", "is_variant else \"product\"][\"attributes\"] actual_order = [ int(graphene.Node.from_global_id(attr[\"attribute\"][\"id\"])[1]) for attr in", ") assert product.attributes.count() == 1 assert variant.attributes.count() == 1 product", ") { productType { id variantAttributes { id slug }", "graphene.Node.to_global_id(\"Attribute\", attr_id)} ) content = get_graphql_content( staff_api_client.post_graphql( query, variables, permissions=[permission_manage_products]", "import filter_attributes_by_product_types from saleor.graphql.product.mutations.attributes import validate_value_is_unique from saleor.graphql.product.types.attributes import resolve_attribute_value_type", "= {\"name\": attribute_name, \"values\": [{\"name\": name}]} response = staff_api_client.post_graphql( query,", "= { \"productTypeId\": product_type_global_id, \"attributeIds\": [ graphene.Node.to_global_id(\"Attribute\", product_attributes[0].pk) ], }", "= get_graphql_content( staff_api_client.post_graphql(query, permissions=[permission_manage_products]) )[\"data\"][\"products\"][\"edges\"] assert len(found_products) == 1 for", "\"Non-assigned attr from the PT may be missing\" assert product_attributes[0][\"attribute\"][\"slug\"]", "len(found_attributes) == 1 assert found_attributes[0][\"node\"][attribute] == expected_value ATTRIBUTES_RESORT_QUERY = \"\"\"", "ensure they are not returned # by the product or", "product[\"attributes\"] variant_attributes = product[\"variants\"][0][\"attributes\"] assert len(product_attributes) == len(product_attribute_values) assert len(variant_attributes)", "are resolved even if the product doesn't provide any value", "in attributes ] # Compare the received data against our", "{ id name slug } } } } \"\"\" if", "in product_attributes_ids: operations.append( {\"type\": \"PRODUCT\", \"id\": graphene.Node.to_global_id(\"Attribute\", attr_id)} ) for", "= graphene.Node.to_global_id(\"AttributeValue\", -1) variables = { \"type\": \"VARIANT\", \"attributeId\": attribute_id,", "slug values { name slug } productTypes(first: 10) { edges", "assert attributes[0][\"node\"][\"slug\"] == \"size\" def test_filter_attributes_if_available_in_grid( api_client, color_attribute, size_attribute ):", "not None else o.pk ), \"The values are not properly", "attributes staff_api_client.user.user_permissions.add(permission_manage_products) response = staff_api_client.post_graphql(query) content = get_graphql_content(response) attributes_data =", "each dummy attribute to ensure they are not returned #", "content = get_graphql_content(staff_api_client.post_graphql(query, variables)) # Check if the error is", "an empty or null value is ignored and the queryset", "AttributeValue(slug=\"spanish-inquisition\") ) # value that already belongs to the attribute", "for attr in attribute_list[:2]} variant_attributes_ids = {attr.pk for attr in", "not attribute.values.filter(pk=attribute_value_id).exists() assert attribute.values.filter(name=attribute_value_name).exists() def test_update_empty_attribute_and_add_values( staff_api_client, color_attribute_without_values, permission_manage_products ):", "\"removeValues\" err_msg = \"Value %s does not belong to this", "} \"\"\" @pytest.mark.parametrize(\"is_staff\", (False, True)) def test_resolve_attributes_with_hidden( user_api_client, product, color_attribute,", "django.core.exceptions import ValidationError from django.db.models import Q from django.template.defaultfilters import", "} } } } } } } \"\"\" @pytest.mark.parametrize(\"is_staff\", (False,", "product type and push them at the top # through", "= graphene.Node.to_global_id(\"ProductType\", product_type.pk) query = ASSIGN_ATTR_QUERY operations = [] variables", ")[\"data\"][\"productTypeReorderAttributes\"] assert not content[\"errors\"] assert ( content[\"productType\"][\"id\"] == product_type_id ),", "\"\"\" query = QUERY_PRODUCT_AND_VARIANTS_ATTRIBUTES api_client = user_api_client variant = product.variants.first()", "attr from the PT may be missing\" assert len(variant_attributes) ==", "= {\"name\": name, \"id\": node_id, \"addValues\": [], \"removeValues\": []} response", "given attribute.\"\"\" attribute_id = graphene.Node.to_global_id(\"Attribute\", color_attribute.id) value_id = graphene.Node.to_global_id(\"AttributeValue\", -1)", "content[\"errors\"] assert content[\"productType\"][\"id\"] == product_type_global_id assert len(content[\"productType\"][\"productAttributes\"]) == 1 assert", "attributes(first: 20) { edges { node { id name slug", "variant.attributes.count() == 1 product = get_graphql_content(api_client.post_graphql(query))[\"data\"][\"products\"][ \"edges\" ][0][\"node\"] product_attributes =", "test_resolve_attribute_value_type(raw_value, expected_type): assert resolve_attribute_value_type(raw_value) == expected_type def test_resolve_assigned_attribute_without_values(api_client, product_type, product):", "data[\"errors\"][0][\"field\"] == \"name\" def test_delete_attribute_value( staff_api_client, color_attribute, pink_attribute_value, permission_manage_products ):", "= color_attribute query = CREATE_ATTRIBUTE_VALUE_QUERY attribute_id = graphene.Node.to_global_id(\"Attribute\", attribute.id) value_name", "get matched # as we don't look for this other", "permission_manage_products, attribute_list ): product_type = ProductType.objects.create(name=\"Default Type\", has_variants=True) product_type_global_id =", "color_attribute_without_values.pk) ], } content = get_graphql_content(staff_api_client.post_graphql(query, variables))[ \"data\" ][\"attributeUnassign\"] assert", "we are testing assert len(products) == 1 assert len(products[0][\"node\"][\"variants\"]) ==", "{ node { id name slug } } } }", "\"operations\": operations} content = get_graphql_content(staff_api_client.post_graphql(query, variables))[ \"data\" ][\"attributeAssign\"] assert content[\"errors\"]", "ATTRIBUTE_VALUES_RESORT_QUERY = \"\"\" mutation attributeReorderValues($attributeId: ID!, $moves: [ReorderInput]!) { attributeReorderValues(attributeId:", "assert data[\"attributeValue\"][\"slug\"] == slugify(name) assert name in [value[\"name\"] for value", "attribute_list assert len(attributes) == 3 staff_api_client.user.user_permissions.add(permission_manage_products) product_type = ProductType.objects.create(name=\"Dummy Type\")", "= graphene.Node.to_global_id(\"Attribute\", attribute.id) variables = {\"name\": name, \"id\": node_id, \"addValues\":", "have been assigned to a product type\" # Check if", "a NotImplemented exception. \"\"\" qs = Attribute.objects.all() with pytest.raises(NotImplementedError) as", "any sorting, this should sort by name by default.\"\"\" Attribute.objects.bulk_create(", "== expected_value ATTRIBUTES_RESORT_QUERY = \"\"\" mutation ProductTypeReorderAttributes( $productTypeId: ID! $moves:", "name slug } } } } \"\"\" if test_deprecated_filter: query", "value that already belongs to the attribute shouldn't be taken", "data[\"attribute\"][\"slug\"] == slugify( attribute_name ), \"The default slug should be", "True), (\"filterable_in_dashboard\", True), (\"visible_in_storefront\", True), (\"available_in_grid\", True), (\"value_required\", False), (\"storefront_search_position\",", "= {\"name\": name, \"attributeId\": attribute_id} response = staff_api_client.post_graphql( query, variables,", "graphene import pytest from django.core.exceptions import ValidationError from django.db.models import", "1 assert ( content[\"productType\"][\"productAttributes\"][0][\"id\"] == remaining_attribute_global_id ) def test_unassign_attributes_not_in_product_type( staff_api_client,", "} } } } \"\"\" def test_update_attribute_value( staff_api_client, pink_attribute_value, permission_manage_products", "assigned to a product type\" # Check if the attribute", "== 1 for gql_attr in found_products[0][\"node\"][\"attributes\"]: assert len(gql_attr[\"values\"]) == 1", "== 3 staff_api_client.user.user_permissions.add(permission_manage_products) product_type = ProductType.objects.create(name=\"Dummy Type\") product_type_id = graphene.Node.to_global_id(\"ProductType\",", "attr in attribute_list[:2]} variant_attributes_ids = {attr.pk for attr in attribute_list[2:]}", "== error_code.name UPDATE_ATTRIBUTE_QUERY = \"\"\" mutation updateAttribute( $id: ID!, $name:", "$attributeId, moves: $moves) { attribute { id values { id", "able to see the attributes staff_api_client.user.user_permissions.add(permission_manage_products) response = staff_api_client.post_graphql(query) content", "attribute_value_id = attribute.values.first().id value_id = graphene.Node.to_global_id(\"AttributeValue\", attribute_value_id) variables = {", "def test_attributes_in_collection_query( user_api_client, product_type, category, collection, collection_with_products, test_deprecated_filter, tested_field, ):", "variables) )[\"data\"][\"attributes\"][\"edges\"] assert len(attributes) == 2 received_slugs = sorted( [attributes[0][\"node\"][\"slug\"],", "attributes_data = content[\"data\"][\"attributes\"][\"edges\"] assert len(attributes_data) == attribute_count QUERY_PRODUCT_AND_VARIANTS_ATTRIBUTES = \"\"\"", "user_api_client, product, staff_user ): \"\"\"Ensure the attribute values are properly", "assert found_variant_attrs_ids == variant_attributes_ids def test_assign_variant_attribute_to_product_type_with_disabled_variants( staff_api_client, permission_manage_products, product_type_without_variant, color_attribute_without_values,", "found_attributes[0][\"node\"][attribute] == expected_value ATTRIBUTES_RESORT_QUERY = \"\"\" mutation ProductTypeReorderAttributes( $productTypeId: ID!", "variant attribute when the attribute's input type doesn't support variants\"\"\"", "staff_api_client, color_attribute, size_attribute, permission_manage_products ): query = UPDATE_ATTRIBUTE_QUERY attribute =", "staff users having the 'manage product' permission can. \"\"\" query", "{ \"id\": graphene.Node.to_global_id(\"AttributeValue\", values[0].pk), \"sortOrder\": +1, }, { \"id\": graphene.Node.to_global_id(\"AttributeValue\",", "errors { field message } attribute { slug } }", "{ attributes(first: 10) { edges { node { %s }", "to an attribute: {attribute_id}\", } ] @pytest.mark.parametrize( \"attribute_type, relation_field, backref_field\",", "# Compare the received data against our expectations assert actual_order", ") other_collection.products.add(other_product) query = \"\"\" query($nodeID: ID!) { attributes(first: 20,", "backref_field\", ( (\"VARIANT\", \"variant_attributes\", \"attributevariant\"), (\"PRODUCT\", \"product_attributes\", \"attributeproduct\"), ), )", "== \"Attribute\" assert int(gql_attr_id) == expected_pk ATTRIBUTE_VALUES_RESORT_QUERY = \"\"\" mutation", "len(gql_attributes) == len(expected_order) for attr, expected_pk in zip(gql_attributes, expected_order): gql_type,", "= [] for attr, expected_pk in zip(gql_values, expected_order): gql_type, gql_attr_id", "is qs def test_attributes_filter_by_product_type_with_unsupported_field(): \"\"\"Ensure using an unknown field to", "graphene.Node.to_global_id(\"Category\", -1) mocked_qs = mock.MagicMock() qs = filter_attributes_by_product_types(mocked_qs, \"in_category\", category_id)", "= 0 m2m_rel_other_attr.save(update_fields=[\"sort_order\"]) # Assign attributes to the product node", "get_graphql_content(response) data = content[\"data\"][\"attributeValueUpdate\"] assert data[\"errors\"] assert data[\"errors\"][0][\"message\"] assert data[\"errors\"][0][\"field\"]", "} values { slug } value { slug } }", "$values: [AttributeValueCreateInput]) { attributeCreate(input: {name: $name, values: $values}) { errors", "invalid attribute (invalid ID).\"\"\" attribute_id = graphene.Node.to_global_id(\"Attribute\", -1) value_id =", "Category\", slug=\"other-cat\") other_attribute = Attribute.objects.create(name=\"Other\", slug=\"other\") other_product_type = ProductType.objects.create( name=\"Other", "was correctly set if no error was expected if expected_error", "be able to see the attributes staff_api_client.user.user_permissions.add(permission_manage_products) response = staff_api_client.post_graphql(query)", "== expected_product_attribute_count assert len(product[\"variants\"][0][\"attributes\"]) == expected_variant_attribute_count def test_resolve_attribute_values(user_api_client, product, staff_user):", "= get_graphql_content(staff_api_client.post_graphql(query, variables))[ \"data\" ][\"attributeAssign\"] assert content[\"errors\"] == [ {", "= {\"filters\": {\"ids\": global_ids}} expected_slugs = sorted([attribute_list[0].slug, attribute_list[1].slug]) attributes =", "attribute_value_name = \"Yellow Color\" node_id = graphene.Node.to_global_id(\"Attribute\", attribute.id) variables =", "attribute_id = graphene.Node.to_global_id(\"Attribute\", attribute.id) m2m_values = attribute.values m2m_values.set(values) assert values", "Collection.objects.create( name=\"Other Collection\", slug=\"other-collection\", is_published=True, description=\"Description\", ) other_collection.products.add(other_product) query =", "}, { \"id\": graphene.Node.to_global_id(\"AttributeValue\", values[2].pk), \"sortOrder\": -1, }, ], }", "= \"Red Color\" node_id = graphene.Node.to_global_id(\"Attribute\", attribute.id) attribute_value_id = attribute.values.first().id", "False color_attribute.save(update_fields=[\"visible_in_storefront\"]) attribute_count = Attribute.objects.all().count() # The user doesn't have", "a product type\" # Check if the attribute values were", "content = get_graphql_content(response) errors = content[\"data\"][\"attributeUpdate\"][\"errors\"] assert errors assert errors[0][\"field\"]", "product_errors = content[\"data\"][\"attributeUpdate\"][\"productErrors\"] assert product_errors[0][\"code\"] == error_code.name def test_update_attribute_and_remove_others_attribute_value( staff_api_client,", "permissions=[permission_manage_products] ) )[\"data\"][\"attributeUnassign\"] assert not content[\"errors\"] assert content[\"productType\"][\"id\"] == product_type_global_id", "{ \"attributeId\": attribute_id, \"moves\": [ { \"id\": graphene.Node.to_global_id(\"AttributeValue\", values[0].pk), \"sortOrder\":", "1 assert len(variant_attribute_values) == 1 product = get_graphql_content(api_client.post_graphql(query))[\"data\"][\"products\"][ \"edges\" ][0][\"node\"]", "product_type_global_id = graphene.Node.to_global_id(\"ProductType\", product_type.pk) if product_type_attribute_type == AttributeTypeEnum.PRODUCT: product_type.product_attributes.add(attribute) elif", "filtered_by_node_id = graphene.Node.to_global_id(\"Category\", category.pk) else: raise AssertionError(tested_field) expected_qs = Attribute.objects.filter(", "1 assert attribute.values.filter(name=attribute_value_name).exists() @pytest.mark.parametrize( \"name_1, name_2, error_msg, error_code\", ( (", "the database attributes by their sort order and ID (when", "the attribute values are properly resolved.\"\"\" query = QUERY_PRODUCT_AND_VARIANTS_ATTRIBUTES api_client", "expected_order ATTRIBUTES_FILTER_QUERY = \"\"\" query($filters: AttributeFilterInput!) { attributes(first: 10, filter:", "$filters) { edges { node { name slug } }", "\"AttributeValue\" actual_order.append(int(gql_attr_id)) assert actual_order == expected_order ATTRIBUTES_FILTER_QUERY = \"\"\" query($filters:", "= content[\"data\"][\"attributeValueCreate\"] assert data[\"productErrors\"] assert data[\"productErrors\"][0][\"code\"] == ProductErrorCode.ALREADY_EXISTS.name assert data[\"productErrors\"][0][\"field\"]", "= { \"type\": \"VARIANT\", \"attributeId\": attribute_id, \"moves\": [{\"id\": value_id, \"sortOrder\":", "= {\"productTypeId\": product_type_global_id, \"operations\": operations} content = get_graphql_content(staff_api_client.post_graphql(query, variables))[ \"data\"", "2 assert attributes[0][\"node\"][\"slug\"] == \"a\" assert attributes[1][\"node\"][\"slug\"] == \"b\" @pytest.mark.parametrize(", "values { id name slug } } } } }", "sort_order=0 ) assert product.attributes.count() == 1 assert variant.attributes.count() == 1", "Attribute.objects.create(name=\"V\", slug=\"variant\") # Create a value for each dummy attribute", "[] ), \"The attribute should not have been assigned to", "= graphene.Node.to_global_id(\"Attribute\", attribute.id) attribute_value_id = attribute.values.first().id value_id = graphene.Node.to_global_id(\"AttributeValue\", attribute_value_id)", "from saleor.graphql.product.filters import filter_attributes_by_product_types from saleor.graphql.product.mutations.attributes import validate_value_is_unique from saleor.graphql.product.types.attributes", "expected_slug @pytest.mark.parametrize( \"name_1, name_2, error_msg, error_code\", ( ( \"Red color\",", "\"message\": \"Variants are disabled in this product type.\", } ]", ")[\"data\"][\"attributeReorderValues\"] assert content[\"errors\"] == [ { \"field\": \"moves\", \"message\": f\"Couldn't", "= graphene.Node.to_global_id(\"Attribute\", -1) variables = { \"type\": \"VARIANT\", \"productTypeId\": product_type_id,", "= {\"sortBy\": {\"field\": \"SLUG\", \"direction\": \"ASC\"}} attributes = get_graphql_content( api_client.post_graphql(ATTRIBUTES_SORT_QUERY,", "} \"\"\" node_id = graphene.Node.to_global_id(\"AttributeValue\", value.id) variables = {\"id\": node_id}", "default slug should be the slugified name\" assert ( data[\"attribute\"][\"productTypes\"][\"edges\"]", "len(content[\"productType\"][\"productAttributes\"]) == len( product_attributes_ids ) assert len(content[\"productType\"][\"variantAttributes\"]) == len( variant_attributes_ids", "attribute.pk)} ] variables = {\"productTypeId\": product_type_global_id, \"operations\": operations} content =", "= AttributeInputType.MULTISELECT attribute.save(update_fields=[\"input_type\"]) product_type.variant_attributes.clear() staff_api_client.user.user_permissions.add(permission_manage_products) product_type_global_id = graphene.Node.to_global_id(\"ProductType\", product_type.pk) query", "slugify(name) assert attr_data[\"type\"] == \"STRING\" assert name in [value[\"name\"] for", "= UNASSIGN_ATTR_QUERY variables = { \"productTypeId\": product_type_global_id, \"attributeIds\": [ graphene.Node.to_global_id(\"Attribute\",", "ordering inside a given product type.\"\"\" product_type = ProductType.objects.create(name=\"My Product", "and variants are sorted.\"\"\" variant = product.variants.first() if is_variant: query", "{\"filter_input\": \"filter: { %s: $nodeID }\" % tested_field} variables =", ") # Create another product type and attribute that shouldn't", "= {attr.pk for attr in attribute_list[:2]} variant_attributes_ids = {attr.pk for", "assert variant_attributes[0][\"value\"] is None def test_attributes_filter_by_product_type_with_empty_value(): \"\"\"Ensure passing an empty", "the attribute color_attribute.visible_in_storefront = False color_attribute.save(update_fields=[\"visible_in_storefront\"]) attribute_count = Attribute.objects.all().count() #", "def test_resolve_attribute_values_non_assigned_to_node( user_api_client, product, staff_user ): \"\"\"Ensure the attribute values", "\"\"\"Don't provide any sorting, this should sort by name by", "== \"variant\" assert variant_attributes[0][\"values\"] == [] assert variant_attributes[0][\"value\"] is None", "} assert found_product_attrs_ids == product_attributes_ids assert found_variant_attrs_ids == variant_attributes_ids def", "pink_attribute_value, permission_manage_products ): value = color_attribute.values.get(name=\"Red\") query = \"\"\" mutation", "{ node { %s } } } } \"\"\" %", "{ name slug } } } \"\"\" node_id = graphene.Node.to_global_id(\"AttributeValue\",", "by their sort order and ID (when None) expected_order =", "staff_api_client, name_1, name_2, error_msg, error_code, permission_manage_products, product_type, ): query =", "the attributes are restricted and if their default value is", "{ productTypeReorderAttributes( productTypeId: $productTypeId moves: $moves type: $type ) {", "dashboard custom ordering inside a given product type.\"\"\" product_type =", "color_attribute, size_attribute): variables = {\"filters\": {\"search\": \"color\"}} attributes = get_graphql_content(", "def test_retrieve_product_attributes_input_type( staff_api_client, product, permission_manage_products ): query = \"\"\" {", "get_graphql_content( api_client.post_graphql(ATTRIBUTES_SORT_QUERY, variables) )[\"data\"][\"attributes\"][\"edges\"] assert len(attributes) == 2 assert attributes[0][\"node\"][\"slug\"]", "see hidden attributes, and staff users having the 'manage product'", "{ slug } } } \"\"\" attribute_name = \"My Name\"", "longer in the product type.\"\"\" staff_api_client.user.user_permissions.add(permission_manage_products) product_type = ProductType.objects.create(name=\"Type\") product_type_global_id", "== len(expected_order) for attr, expected_pk in zip(gql_attributes, expected_order): gql_type, gql_attr_id", "== len(product_attribute_values) assert len(variant_attributes) == len(variant_attribute_values) assert product_attributes[0][\"attribute\"][\"slug\"] == \"color\"", "to this attribute.\" % str(size_attribute) assert errors[0][\"message\"] == err_msg product_errors", "= graphene.Node.to_global_id(\"ProductType\", product_type.pk) variant_attribute, *product_attributes = attribute_list product_type.product_attributes.add(*product_attributes) product_type.variant_attributes.add(variant_attribute) remaining_attribute_global_id", "values are not unique.\", ProductErrorCode.UNIQUE, ), ), ) def test_update_attribute_and_add_attribute_values_errors(", "def test_assign_variant_attribute_having_unsupported_input_type( staff_api_client, permission_manage_products, product_type, size_attribute ): \"\"\"The assignAttribute mutation", "expected_slug, expected_error, ): staff_api_client.user.user_permissions.add(permission_manage_products) query = \"\"\" mutation createAttribute( $name:", "= ProductType.objects.create(name=\"Type\") product_type_global_id = graphene.Node.to_global_id(\"ProductType\", product_type.pk) query = UNASSIGN_ATTR_QUERY variables", "unknown field to filter attributes by raises a NotImplemented exception.", "in the product type.\"\"\" product_type = ProductType.objects.create(name=\"Type\") attribute = color_attribute_without_values", "query = \"\"\" query($id: ID!) { product(id: $id) { attributes", "= graphene.Node.to_global_id(\"ProductType\", product_type.pk) query = UNASSIGN_ATTR_QUERY variables = { \"productTypeId\":", "attribute's slug cannot be blank.\"}], ), ), ) def test_create_attribute_with_given_slug(", "get_graphql_content(response) attribute.refresh_from_db() data = content[\"data\"][\"attributeUpdate\"] assert data[\"attribute\"][\"name\"] == name ==", "attributes { attribute { id } } } } \"\"\"", "= content[\"data\"][\"attributeUpdate\"][\"errors\"] assert errors assert errors[0][\"field\"] == \"removeValues\" err_msg =", "} \"\"\" attribute_name = \"My Name\" variables = {\"name\": attribute_name,", "\"\"\" ) )[\"data\"][\"products\"][\"edges\"] # Ensure we are only working on", "} } } } \"\"\" def test_assign_attributes_to_product_type( staff_api_client, permission_manage_products, attribute_list", "variables = { \"type\": \"VARIANT\", \"attributeId\": attribute_id, \"moves\": [{\"id\": value_id,", "= query % {\"filter_input\": f\"{tested_field}: $nodeID\"} else: query = query", "get_graphql_content(response) assert not content[\"data\"][\"attributeCreate\"][\"errors\"] data = content[\"data\"][\"attributeCreate\"] # Check if", "sort_order=null AttributeProduct.objects.create( attribute=unassigned_product_attribute, product_type=product_type, sort_order=0 ) AttributeVariant.objects.create( attribute=unassigned_variant_attribute, product_type=product_type, sort_order=0", "None: assert content[\"data\"][\"attributeCreate\"][\"attribute\"][\"slug\"] == expected_slug @pytest.mark.parametrize( \"name_1, name_2, error_msg, error_code\",", "is_published=True, description=\"Description\", ) other_collection.products.add(other_product) query = \"\"\" query($nodeID: ID!) {", "if test_deprecated_filter: query = query % {\"filter_input\": f\"{tested_field}: $nodeID\"} else:", "= {\"id\": node_id} response = staff_api_client.post_graphql( query, variables, permissions=[permission_manage_products] )", ") other_product_type.product_attributes.add(other_attribute) other_product = Product.objects.create( name=f\"Another Product\", product_type=other_product_type, category=other_category, price=zero_money(),", "permission_manage_products, color_attribute_without_values ): \"\"\"The unAssignAttribute mutation should not raise any", "attribute_name = \"<NAME>\" name = \"Value name\" variables = {\"name\":", "{ \"field\": \"attributeId\", \"message\": f\"Couldn't resolve to an attribute: {attribute_id}\",", "and ID (when None) expected_order = [other_attribute.pk, color_attribute.pk] # Make", "{ name: $name, addValues: $addValues, removeValues: $removeValues}) { errors {", "name = \"<NAME>\" variables = {\"name\": name, \"attributeId\": attribute_id} response", "} } } } \"\"\" def test_attributes_query(user_api_client, product): attributes =", "content = get_graphql_content(response) assert not content[\"data\"][\"attributeCreate\"][\"errors\"] data = content[\"data\"][\"attributeCreate\"] #", "product # type: Union[Product, ProductVariant] node.attributesrelated.clear() associate_attribute_values_to_instance( node, color_attribute, color_attribute.values.first()", "node_id = graphene.Node.to_global_id(\"Attribute\", attribute.id) variables = {\"id\": node_id} response =", "len(variant_attribute_values) == 1 product = get_graphql_content(api_client.post_graphql(query))[\"data\"][\"products\"][ \"edges\" ][0][\"node\"] product_attributes =", "[ID]!) { attributeUpdate( id: $id, input: { name: $name, addValues:", "get_graphql_content( staff_api_client.post_graphql( ATTRIBUTE_VALUES_RESORT_QUERY, variables, permissions=[permission_manage_products], ) )[\"data\"][\"attributeReorderValues\"] assert content[\"errors\"] ==", "# This will allow us to make sure it is", "Sort the database attributes by their sort order and ID", "slug should pass validate_value_is_unique( color_attribute, AttributeValue(slug=\"spanish-inquisition\") ) # value that", "len(expected_order) actual_order = [] for attr, expected_pk in zip(gql_values, expected_order):", "graphene.Node.to_global_id(\"Attribute\", attribute.id) variables = {\"id\": node_id} response = staff_api_client.post_graphql( query,", "variables = {\"id\": node_id} staff_api_client.post_graphql( query, variables, permissions=[permission_manage_products] ) with", "the variant attributes values are all None assert variant[\"attributes\"][0][\"attribute\"][\"slug\"] ==", "a value for each dummy attribute to ensure they are", "Add the attribute to the product type if is_variant: product.product_type.variant_attributes.set([color_attribute,", "sort_field: str, m2m_model: Union[AttributeVariant, AttributeProduct], ): \"\"\"Sorts attributes for dashboard", "{\"filter_input\": f\"{tested_field}: $nodeID\"} else: query = query % {\"filter_input\": \"filter:", "data[\"errors\"] assert data[\"errors\"][0][\"message\"] assert data[\"errors\"][0][\"field\"] == \"name\" def test_delete_attribute_value( staff_api_client,", "staff_api_client, color_attribute, permission_manage_products, product_type ): attribute = color_attribute query =", "\"\"\"Sorts attributes for dashboard custom ordering inside a given product", "query, variables, permissions=[permission_manage_products] ) content = get_graphql_content(response) attribute.refresh_from_db() data =", "\"VARIANT\", \"id\": graphene.Node.to_global_id(\"Attribute\", attribute.pk)} ] variables = {\"productTypeId\": product_type_global_id, \"operations\":", ")[\"data\"][\"productTypeReorderAttributes\"] assert content[\"errors\"] == [ { \"field\": \"moves\", \"message\": f\"Couldn't", "2 assert attributes[0][\"node\"][\"slug\"] == \"b\" assert attributes[1][\"node\"][\"slug\"] == \"a\" @pytest.mark.parametrize(\"is_variant\",", "= content[\"data\"][\"attributeCreate\"] # Check if the attribute was correctly created", "err_msg = \"Value %s does not belong to this attribute.\"", "size_attribute ): color_attribute.available_in_grid = False color_attribute.save(update_fields=[\"available_in_grid\"]) variables = {\"filters\": {\"availableInGrid\":", "== 1 assert len(products[0][\"node\"][\"variants\"]) == 1 # Retrieve the nodes", "or something else assert content[\"data\"][\"attributeCreate\"][\"errors\"] == expected_error # Check if", "None assert variant[\"attributes\"][0][\"attribute\"][\"slug\"] == \"size\" assert variant[\"attributes\"][0][\"values\"] == [] ASSIGN_ATTR_QUERY", "} \"\"\" def test_update_attribute_name( staff_api_client, color_attribute, permission_manage_products ): query =", "# Ensure the variant attributes values are all None assert", "== product_type_global_id assert len(content[\"productType\"][\"productAttributes\"]) == len( product_attributes_ids ) assert len(content[\"productType\"][\"variantAttributes\"])", "content = get_graphql_content(response) data = content[\"data\"][\"attributeValueUpdate\"] value.refresh_from_db() assert data[\"attributeValue\"][\"name\"] ==", "account validate_value_is_unique(color_attribute, value) def test_get_single_attribute_by_pk(user_api_client, color_attribute_without_values): attribute_gql_id = graphene.Node.to_global_id( \"Attribute\",", "for attr in content[\"productType\"][\"productAttributes\"] } found_variant_attrs_ids = { int(graphene.Node.from_global_id(attr[\"id\"])[1]) for", "test_sort_attributes_within_product_type_invalid_id( staff_api_client, permission_manage_products, color_attribute ): \"\"\"Try to reorder an attribute", "attribute_list[1].slug]) attributes = get_graphql_content( api_client.post_graphql(ATTRIBUTES_FILTER_QUERY, variables) )[\"data\"][\"attributes\"][\"edges\"] assert len(attributes) ==", "import pytest from django.core.exceptions import ValidationError from django.db.models import Q", "product_type_id = graphene.Node.to_global_id(\"ProductType\", product_type.id) m2m_attributes = getattr(product_type, relation_field) m2m_attributes.set(attributes) sort_method", "attr, expected_pk in zip(gql_attributes, expected_order): gql_type, gql_attr_id = graphene.Node.from_global_id(attr[\"id\"]) assert", "assert len(gql_values) == len(expected_order) actual_order = [] for attr, expected_pk", "] attributes = data[\"productVariant\" if is_variant else \"product\"][\"attributes\"] actual_order =", "attribute.id) variables = {\"id\": node_id} response = staff_api_client.post_graphql( query, variables,", "variables = {\"name\": pink_attribute_value.name, \"id\": node_id} response = staff_api_client.post_graphql( query,", "assert len(attributes) == 2 assert attributes[0][\"node\"][\"slug\"] == \"b\" assert attributes[1][\"node\"][\"slug\"]", "gql_values = content[\"attribute\"][\"values\"] assert len(gql_values) == len(expected_order) actual_order = []", "flat_attributes_data = [attr[\"node\"][\"slug\"] for attr in attributes_data] expected_flat_attributes_data = list(expected_qs.values_list(\"slug\",", "content[\"errors\"] == [ { \"field\": \"operations\", \"message\": \"Variants are disabled", "test_retrieving_the_restricted_attributes_restricted( staff_api_client, color_attribute, permission_manage_products, attribute, expected_value, ): \"\"\"Checks if the", "from saleor.product.error_codes import ProductErrorCode from saleor.product.models import ( Attribute, AttributeProduct,", "errors = content[\"data\"][\"attributeUpdate\"][\"errors\"] assert errors assert errors[0][\"field\"] == \"addValues\" assert", "\"\"\"The assignAttribute mutation should raise an error when trying to", "assert found_attributes[0][\"node\"][attribute] == expected_value ATTRIBUTES_RESORT_QUERY = \"\"\" mutation ProductTypeReorderAttributes( $productTypeId:", "invalid product type (invalid ID).\"\"\" product_type_id = graphene.Node.to_global_id(\"ProductType\", -1) attribute_id", "\"name\" def test_delete_attribute_value( staff_api_client, color_attribute, pink_attribute_value, permission_manage_products ): value =", "} } } \"\"\" @pytest.mark.parametrize(\"is_staff\", (False, True)) def test_resolve_attributes_with_hidden( user_api_client,", "= other_attribute.attributevariant.last() else: m2m_rel_other_attr = other_attribute.attributeproduct.last() # Push the last", ") )[\"data\"][\"attributeReorderValues\"] assert content[\"errors\"] == [ { \"field\": \"moves\", \"message\":", "slug } values { slug } value { slug }", "attribute.values.first().id value_id = graphene.Node.to_global_id(\"AttributeValue\", attribute_value_id) variables = { \"name\": name,", "{ errors { field message } attribute { slug }", "\"red color\", \"Provided values are not unique.\", ProductErrorCode.UNIQUE, ), ),", "== variant_attribute_values[0] assert variant_attributes[0][\"value\"][\"slug\"] == variant_attribute_values[0] def test_resolve_attribute_values_non_assigned_to_node( user_api_client, product,", "{attr.pk for attr in attribute_list[2:]} for attr_id in product_attributes_ids: operations.append(", "product, color_attribute): query = QUERY_ATTRIBUTES # hide the attribute color_attribute.visible_in_storefront", "# Create another collection with products but shouldn't get matched", "{ slug } value { slug } } variants {", "{ attributeValue { name slug } } } \"\"\" node_id", "assert product_attributes[0][\"attribute\"][\"slug\"] == \"product\" assert product_attributes[0][\"values\"] == [] assert variant_attributes[0][\"value\"]", "= Product.objects.create( name=f\"Another Product\", product_type=other_product_type, category=other_category, price=zero_money(), is_published=True, ) #", "id } } } } \"\"\" def test_assign_attributes_to_product_type( staff_api_client, permission_manage_products,", "\"id\": graphene.Node.to_global_id(\"Attribute\", attr_id)} ) content = get_graphql_content( staff_api_client.post_graphql( query, variables,", "to reorder a value not associated to the given attribute.\"\"\"", "permission_manage_products ): query = CREATE_ATTRIBUTES_QUERY attribute_name = \"<NAME>\" name =", "and the queryset is simply returned without any modification. \"\"\"", "attribute = color_attribute_without_values name = \"<NAME>\" attribute_value_name = \"Yellow Color\"", "len(attributes) == 1 assert attributes[0][\"node\"][\"slug\"] == \"color\" def test_filter_attributes_if_filterable_in_dashboard( api_client,", "the attribute to the product type if is_variant: product.product_type.variant_attributes.set([color_attribute, other_attribute])", "= list( variant.attributes.first().values.values_list(\"slug\", flat=True) ) assert len(product_attribute_values) == 1 assert", "= graphene.Node.to_global_id(\"Attribute\", attribute.id) value_name = attribute.values.first().name variables = {\"name\": value_name.upper(),", "= CREATE_ATTRIBUTE_VALUE_QUERY attribute_id = graphene.Node.to_global_id(\"Attribute\", attribute.id) name = \"<NAME>\" variables", "when trying to add an attribute already contained in the", "{ values { type inputType } } } } }", "$nodeID\"} else: query = query % {\"filter_input\": \"filter: { %s:", "} \"\"\" node_id = graphene.Node.to_global_id(\"Attribute\", attribute.id) variables = {\"id\": node_id}", "= \"\"\" mutation unAssignAttribute( $productTypeId: ID!, $attributeIds: [ID]! ) {", "product_attributes_ids assert found_variant_attrs_ids == variant_attributes_ids def test_assign_variant_attribute_to_product_type_with_disabled_variants( staff_api_client, permission_manage_products, product_type_without_variant,", "expected_variant_attribute_count def test_resolve_attribute_values(user_api_client, product, staff_user): \"\"\"Ensure the attribute values are", "attributes_data assert len(attributes_data) == attributes.count() def test_attributes_query_hidden_attribute(user_api_client, product, color_attribute): query", "AttributeValueType.COLOR), (\"rgba(100%, 255, 0, 0)\", AttributeValueType.COLOR), (\"http://example.com\", AttributeValueType.URL), (\"https://example.com\", AttributeValueType.URL),", "assert errors[0][\"message\"] == error_msg product_errors = content[\"data\"][\"attributeCreate\"][\"productErrors\"] assert product_errors[0][\"code\"] ==", "errors[0][\"message\"] == err_msg product_errors = content[\"data\"][\"attributeUpdate\"][\"productErrors\"] assert product_errors[0][\"code\"] == ProductErrorCode.INVALID.name", "\"\"\" def test_create_attribute_value( staff_api_client, color_attribute, permission_manage_products ): attribute = color_attribute", "color_attribute, pink_attribute_value, permission_manage_products ): value = color_attribute.values.get(name=\"Red\") query = \"\"\"", "permission_manage_products ): query = UPDATE_ATTRIBUTE_VALUE_QUERY value = pink_attribute_value node_id =", "type doesn't support variants\"\"\" product_type = product_type_without_variant attribute = color_attribute_without_values", "def test_retrieving_the_restricted_attributes_restricted( staff_api_client, color_attribute, permission_manage_products, attribute, expected_value, ): \"\"\"Checks if", "\"b\" assert attributes[1][\"node\"][\"slug\"] == \"a\" @pytest.mark.parametrize(\"is_variant\", (True, False)) def test_attributes_of_products_are_sorted(", "name = \"Value name\" variables = {\"name\": attribute_name, \"values\": [{\"name\":", "import ( Attribute, AttributeProduct, AttributeValue, AttributeVariant, Category, Collection, Product, ProductType,", "ProductType, ProductVariant, ) from saleor.product.utils.attributes import associate_attribute_values_to_instance from tests.api.utils import", "attr_data[\"name\"] == name assert attr_data[\"slug\"] == slugify(name) assert attr_data[\"type\"] ==", "product = get_graphql_content(api_client.post_graphql(query))[\"data\"][\"products\"][ \"edges\" ][0][\"node\"] product_attributes = product[\"attributes\"] variant_attributes =", "\"My Name\" variables = {\"name\": attribute_name, \"slug\": input_slug} content =", "assert content[\"errors\"] == [ { \"field\": \"operations\", \"message\": \"Color (color)", "1 assert variant.attributes.count() == 1 product_attribute_values = list( product.attributes.first().values.values_list(\"slug\", flat=True)", "-1) variables = { \"attributeId\": attribute_id, \"moves\": [{\"id\": value_id, \"sortOrder\":", "variant.attributes.count() == 1 product_attribute_values = list( product.attributes.first().values.values_list(\"slug\", flat=True) ) variant_attribute_values", "\"message\": f\"Couldn't resolve to an attribute value: {value_id}\", } ]", "category=other_category, price=zero_money(), is_published=True, ) # Create another collection with products", "createAttributeValue( $attributeId: ID!, $name: String!) { attributeValueCreate( attribute: $attributeId, input:", "ProductErrorCode from saleor.product.models import ( Attribute, AttributeProduct, AttributeValue, AttributeVariant, Category,", "errors[0][\"field\"] == \"values\" assert errors[0][\"message\"] == error_msg product_errors = content[\"data\"][\"attributeCreate\"][\"productErrors\"]", "== expected_type def test_resolve_assigned_attribute_without_values(api_client, product_type, product): \"\"\"Ensure the attributes assigned", "it or is not directly associated to it. \"\"\" #", "product_type_global_id = graphene.Node.to_global_id(\"ProductType\", product_type.pk) query = ASSIGN_ATTR_QUERY operations = []", "get_graphql_content( api_client.post_graphql( \"\"\" { products(first: 10) { edges { node", "variables, permissions=[permission_manage_products] ) )[\"data\"][\"attributeUnassign\"] assert not content[\"errors\"] assert content[\"productType\"][\"id\"] ==", "): \"\"\"Ensure non-staff users don't see hidden attributes, and staff", "error was expected if expected_error is None: assert content[\"data\"][\"attributeCreate\"][\"attribute\"][\"slug\"] ==", "len(attributes) == 2 assert attributes[0][\"node\"][\"slug\"] == \"b\" assert attributes[1][\"node\"][\"slug\"] ==", "staff_api_client, permission_manage_products, attribute_list ): product_type = ProductType.objects.create(name=\"Type\") product_type_global_id = graphene.Node.to_global_id(\"ProductType\",", "\"my-name\", []), ( \"\", None, [{\"field\": \"slug\", \"message\": \"The attribute's", "data[\"productErrors\"][0][\"code\"] == ProductErrorCode.ALREADY_EXISTS.name assert data[\"productErrors\"][0][\"field\"] == \"name\" UPDATE_ATTRIBUTE_VALUE_QUERY = \"\"\"", "attribute_list[2:]} for attr_id in product_attributes_ids: operations.append( {\"type\": \"PRODUCT\", \"id\": graphene.Node.to_global_id(\"Attribute\",", "{ \"field\": \"moves\", \"message\": f\"Couldn't resolve to an attribute value:", "def test_update_empty_attribute_and_add_values( staff_api_client, color_attribute_without_values, permission_manage_products ): query = UPDATE_ATTRIBUTE_QUERY attribute", "permissions=[permission_manage_products]) )[\"data\"][\"products\"][\"edges\"] assert len(found_products) == 1 for gql_attr in found_products[0][\"node\"][\"attributes\"]:", "variant_attribute, *product_attributes = attribute_list product_type.product_attributes.add(*product_attributes) product_type.variant_attributes.add(variant_attribute) remaining_attribute_global_id = graphene.Node.to_global_id( \"Attribute\",", "m2m_model: Union[AttributeVariant, AttributeProduct], ): \"\"\"Sorts attributes for dashboard custom ordering", "None else o.pk ), \"The values are not properly ordered\"", "createAttribute($name: String!, $values: [AttributeValueCreateInput]) { attributeCreate(input: {name: $name, values: $values})", "= staff_api_client.post_graphql( query, variables, permissions=[permission_manage_products] ) get_graphql_content(response) attribute.refresh_from_db() assert attribute.values.count()", "Thus, we are sure the query is actually passing the", "query, variables, permissions=[permission_manage_products] ) content = get_graphql_content(response) data = content[\"data\"][\"attributeDelete\"]", "\"inCollection\"]) def test_attributes_in_collection_query( user_api_client, product_type, category, collection, collection_with_products, test_deprecated_filter, tested_field,", "[], \"addValues\": [{\"name\": name_1}, {\"name\": name_2}], } response = staff_api_client.post_graphql(", "# by the product or variant as they are not", ") variables = {\"sortBy\": {\"field\": sort_field, \"direction\": \"DESC\"}} attributes =", "variants are sorted.\"\"\" variant = product.variants.first() if is_variant: query =", "query = CREATE_ATTRIBUTES_QUERY attribute_name = \"<NAME>\" name = \"Value name\"", "pytest.raises(ValidationError): validate_value_is_unique(color_attribute, AttributeValue(slug=value.slug)) # a new value with a new", "color_attribute, permission_manage_products, ): query = UPDATE_ATTRIBUTE_QUERY attribute = color_attribute node_id", "= color_attribute node_id = graphene.Node.to_global_id(\"Attribute\", attribute.id) variables = { \"name\":", "Ensure the product attributes values are all None assert len(product[\"attributes\"])", "UNASSIGN_ATTR_QUERY variables = { \"productTypeId\": product_type_global_id, \"attributeIds\": [ graphene.Node.to_global_id(\"Attribute\", product_attributes[0].pk)", "): \"\"\"Try to reorder an attribute not associated to the", "{ field message } productType { id productAttributes { id", "working on one product and variant, the ones we are", "color_attribute query = CREATE_ATTRIBUTE_VALUE_QUERY attribute_id = graphene.Node.to_global_id(\"Attribute\", attribute.id) name =", "permission_manage_products, color_attribute ): \"\"\"Try to reorder a value not associated", "slug } } } } } \"\"\" def test_attributes_query(user_api_client, product):", "test_delete_attribute( staff_api_client, color_attribute, permission_manage_products, product_type ): attribute = color_attribute query", "+= 1 staff_user.user_permissions.add(permission_manage_products) # Hide one product and variant attribute", "\"\"\"Ensure using an unknown field to filter attributes by raises", "attribute ) found_attributes = get_graphql_content( staff_api_client.post_graphql(query, permissions=[permission_manage_products]) )[\"data\"][\"attributes\"][\"edges\"] assert len(found_attributes)", "ignored and the queryset is simply returned without any modification.", "and variant, the ones we are testing assert len(products) ==", "ProductType.objects.create(name=\"Type\") attribute = color_attribute_without_values staff_api_client.user.user_permissions.add(permission_manage_products) product_type_global_id = graphene.Node.to_global_id(\"ProductType\", product_type.pk) if", "sorted( values, key=lambda o: o.sort_order if o.sort_order is not None", "by raises a NotImplemented exception. \"\"\" qs = Attribute.objects.all() with", "{ values { name } } attributeValue { name type", "size_attribute ): color_attribute.filterable_in_dashboard = False color_attribute.save(update_fields=[\"filterable_in_dashboard\"]) variables = {\"filters\": {\"filterableInDashboard\":", "[value[\"name\"] for value in data[\"attribute\"][\"values\"]] def test_create_attribute_value_not_unique_name( staff_api_client, color_attribute, permission_manage_products", "\"example-slug\", \"addValues\": [], \"removeValues\": [attr_id], } response = staff_api_client.post_graphql( query,", "name } } } } } } } \"\"\" )", "assert content[\"data\"][\"attribute\"], \"Should have found an attribute\" assert content[\"data\"][\"attribute\"][\"id\"] ==", "\"name\": name, \"id\": node_id, \"addValues\": [{\"name\": attribute_value_name}], \"removeValues\": [], }", "error_msg product_errors = content[\"data\"][\"attributeUpdate\"][\"productErrors\"] assert product_errors[0][\"code\"] == error_code.name def test_update_attribute_and_remove_others_attribute_value(", "using an unknown field to filter attributes by raises a", "[], \"removeValues\": [attr_id], } response = staff_api_client.post_graphql( query, variables, permissions=[permission_manage_products]", "not return the correct product type\" gql_attributes = content[\"productType\"][snake_to_camel_case(relation_field)] assert", "[{\"name\": name}]} response = staff_api_client.post_graphql( query, variables, permissions=[permission_manage_products] ) content", "query, variables, permissions=[permission_manage_products] ) content = get_graphql_content(response) errors = content[\"data\"][\"attributeUpdate\"][\"errors\"]", "} variantAttributes { id } } } } \"\"\" def", "AttributeValueType.COLOR), (\"hsla(120, 60%, 70%, 0.3)\", AttributeValueType.COLOR), (\"rgba(100%, 255, 0, 0)\",", "= color_attribute_without_values name = \"<NAME>\" attribute_value_name = \"Yellow Color\" node_id", "provide any sorting, this should sort by name by default.\"\"\"", "not data[\"productErrors\"] attr_data = data[\"attributeValue\"] assert attr_data[\"name\"] == name assert", "variant_attributes[0][\"attribute\"][\"slug\"] == \"variant\" assert variant_attributes[0][\"values\"] == [] assert variant_attributes[0][\"value\"] is", "attribute { slug } } } \"\"\" attribute_name = \"My", "= graphene.Node.to_global_id(\"AttributeValue\", attribute_value_id) variables = { \"name\": name, \"id\": node_id,", "name type slug } } } \"\"\" def test_create_attribute_value( staff_api_client,", "{ id productAttributes { id } variantAttributes { id }", ") def test_resolve_attribute_value_type(raw_value, expected_type): assert resolve_attribute_value_type(raw_value) == expected_type def test_resolve_assigned_attribute_without_values(api_client,", "values are not properly ordered\" variables = { \"attributeId\": attribute_id,", "( \"Attributes having for input types ['multiselect'] cannot be assigned", "value_name, \"attributeId\": attribute_id} response = staff_api_client.post_graphql( query, variables, permissions=[permission_manage_products] )", "an attribute already contained in the product type.\"\"\" product_type =", "color_attribute query = CREATE_ATTRIBUTE_VALUE_QUERY attribute_id = graphene.Node.to_global_id(\"Attribute\", attribute.id) value_name =", "sure it is always the last attribute # when sorted", "CREATE_ATTRIBUTES_QUERY = \"\"\" mutation createAttribute($name: String!, $values: [AttributeValueCreateInput]) { attributeCreate(input:", "a value not associated to the given attribute.\"\"\" attribute_id =", "from typing import Union from unittest import mock import graphene", "} } \"\"\" def test_sort_attributes_by_slug(api_client): Attribute.objects.bulk_create( [ Attribute(name=\"MyAttribute\", slug=\"b\"), Attribute(name=\"MyAttribute\",", "( \"Red color\", \"Red color\", \"Provided values are not unique.\",", "content = get_graphql_content(response) data = content[\"data\"][\"attributeValueCreate\"] assert not data[\"productErrors\"] attr_data", "hidden attributes assert Attribute.objects.get_visible_to_user(staff_api_client.user).count() == 1 # The user should", "{ id } productAttributes { id } } } }", "size_attribute, staff_user, is_staff, permission_manage_products, ): \"\"\"Ensure non-staff users don't see", "assert errors[0][\"field\"] == \"addValues\" assert errors[0][\"message\"] == error_msg product_errors =", "} } \"\"\" % attribute ) found_attributes = get_graphql_content( staff_api_client.post_graphql(query,", "permission_manage_products, color_attribute ): \"\"\"Try to reorder an attribute not associated", "% {\"filter_input\": f\"{tested_field}: $nodeID\"} else: query = query % {\"filter_input\":", "mutation should raise an error when trying to use an", "= QUERY_ATTRIBUTES # hide the attribute color_attribute.visible_in_storefront = False color_attribute.save(update_fields=[\"visible_in_storefront\"])", "} } } \"\"\" def test_attributes_query(user_api_client, product): attributes = Attribute.objects", "found_products[0][\"node\"][\"attributes\"]: assert len(gql_attr[\"values\"]) == 1 assert gql_attr[\"values\"][0][\"type\"] == \"STRING\" assert", "\"moves\": [ { \"id\": graphene.Node.to_global_id(\"Attribute\", attributes[0].pk), \"sortOrder\": +1, }, {", "associate_attribute_values_to_instance from tests.api.utils import get_graphql_content def test_validate_value_is_unique(color_attribute): value = color_attribute.values.first()", "= UPDATE_ATTRIBUTE_QUERY attribute = color_attribute_without_values name = \"<NAME>\" attribute_value_name =", "sorted( [attributes[0][\"node\"][\"slug\"], attributes[1][\"node\"][\"slug\"]] ) assert received_slugs == expected_slugs ATTRIBUTES_SORT_QUERY =", "attributeValueDelete(id: $id) { attributeValue { name slug } } }", ") # Assign the dummy attributes to the product type", "qs def test_attributes_filter_by_product_type_with_unsupported_field(): \"\"\"Ensure using an unknown field to filter", "else assert content[\"data\"][\"attributeCreate\"][\"errors\"] == expected_error # Check if the slug", "for value in data[\"attribute\"][\"values\"]] def test_update_attribute_value_name_not_unique( staff_api_client, pink_attribute_value, permission_manage_products ):", "id } } } } } } \"\"\" def test_create_attribute_and_attribute_values(", "( \"\", None, [{\"field\": \"slug\", \"message\": \"The attribute's slug cannot", "errors = content[\"data\"][\"attributeCreate\"][\"errors\"] assert errors assert errors[0][\"field\"] == \"values\" assert", "values, key=lambda o: o.sort_order if o.sort_order is not None else", "0 m2m_rel_other_attr.save(update_fields=[\"sort_order\"]) # Assign attributes to the product node =", "get_graphql_content(response) errors = content[\"data\"][\"attributeCreate\"][\"errors\"] assert errors assert errors[0][\"field\"] == \"values\"", "value is the expected one.\"\"\" attribute = to_camel_case(attribute) query =", "): query = UPDATE_ATTRIBUTE_QUERY attribute = color_attribute name = \"<NAME>\"", "an attribute value: {value_id}\", } ] def test_sort_values_within_attribute( staff_api_client, color_attribute,", "{\"sortBy\": {\"field\": \"SLUG\", \"direction\": \"ASC\"}} attributes = get_graphql_content( api_client.post_graphql(ATTRIBUTES_SORT_QUERY, variables)", "variant = product.variants.get() # Remove all attributes and values from", "errors { field message } } } \"\"\" def test_sort_values_within_attribute_invalid_product_type(", "== expected_slug @pytest.mark.parametrize( \"name_1, name_2, error_msg, error_code\", ( ( \"Red", "if is_variant: node_id = graphene.Node.to_global_id(\"ProductVariant\", variant.pk) else: node_id = graphene.Node.to_global_id(\"Product\",", "color_attribute, permission_manage_products, attribute, expected_value, ): \"\"\"Checks if the attributes are", "assert content[\"data\"][\"attributeCreate\"][\"errors\"] == expected_error # Check if the slug was", "staff_api_client, color_attribute, permission_manage_products ): attribute = color_attribute AttributeValue.objects.create(attribute=attribute, name=\"Green\", slug=\"green\")", "} } } \"\"\" def test_assign_attributes_to_product_type( staff_api_client, permission_manage_products, attribute_list ):", "are only working on one product and variant, the ones", "staff_api_client, permission_manage_products, color_attribute ): \"\"\"Try to reorder an attribute not", "): \"\"\"The unAssignAttribute mutation should not raise any error when", "{ id } } } } \"\"\" def test_unassign_attributes_from_product_type( staff_api_client,", "found_product_attrs_ids = { int(graphene.Node.from_global_id(attr[\"id\"])[1]) for attr in content[\"productType\"][\"productAttributes\"] } found_variant_attrs_ids", "= \"\"\" { products(first: 1) { edges { node {", "name } } attributeValue { name type slug } }", "= graphene.Node.to_global_id(\"Collection\", collection.pk) elif \"Category\" in tested_field: filtered_by_node_id = graphene.Node.to_global_id(\"Category\",", "mocked_qs.none.return_value @pytest.mark.parametrize(\"test_deprecated_filter\", [True, False]) @pytest.mark.parametrize(\"tested_field\", [\"inCategory\", \"inCollection\"]) def test_attributes_in_collection_query( user_api_client,", "get_graphql_content(response) attribute.refresh_from_db() assert attribute.values.count() == 1 assert attribute.values.filter(name=attribute_value_name).exists() @pytest.mark.parametrize( \"name_1,", "{ field message } attributeValue { name slug } attribute", "pink_attribute_value, permission_manage_products ): query = UPDATE_ATTRIBUTE_VALUE_QUERY value = pink_attribute_value node_id", "{attribute_id}\", } ] @pytest.mark.parametrize( \"attribute_type, relation_field, backref_field\", ( (\"VARIANT\", \"variant_attributes\",", "get_graphql_content( api_client.post_graphql(ATTRIBUTES_FILTER_QUERY, variables) )[\"data\"][\"attributes\"][\"edges\"] assert len(attributes) == 2 received_slugs =", "is not/no longer in the product type.\"\"\" staff_api_client.user.user_permissions.add(permission_manage_products) product_type =", "AttributeTypeEnum.VARIANT), ), ) def test_assign_attribute_to_product_type_having_already_that_attribute( staff_api_client, permission_manage_products, color_attribute_without_values, product_type_attribute_type, gql_attribute_type,", "that already belongs to the attribute shouldn't be taken into", "attributes[1][\"node\"][\"slug\"] == \"a\" @pytest.mark.parametrize(\"is_variant\", (True, False)) def test_attributes_of_products_are_sorted( staff_api_client, product,", "} } } \"\"\" attribute_name = \"My Name\" variables =", "\"product_attributes\", \"attributeproduct\"), ), ) def test_sort_attributes_within_product_type( staff_api_client, attribute_list, permission_manage_products, attribute_type,", "to the product type and push them at the top", "This will allow us to make sure it is always", "attribute=unassigned_variant_attribute, product_type=product_type, sort_order=0 ) assert product.attributes.count() == 1 assert variant.attributes.count()", "== value.name assert data[\"attributeValue\"][\"slug\"] == slugify(name) assert name in [value[\"name\"]", "{ productVariant(id: $id) { attributes { attribute { id }", "passing the test. other_attribute = Attribute.objects.create(name=\"Other\", slug=\"other\") # Add the", "data[\"attribute\"][\"productTypes\"][\"edges\"] == [] ), \"The attribute should not have been", "value in data[\"attribute\"][\"values\"]] def test_update_attribute_value_name_not_unique( staff_api_client, pink_attribute_value, permission_manage_products ): query", "an attribute that is not/no longer in the product type.\"\"\"", "{\"id\": node_id} staff_api_client.post_graphql( query, variables, permissions=[permission_manage_products] ) with pytest.raises(value._meta.model.DoesNotExist): value.refresh_from_db()", "attribute_name, \"values\": [{\"name\": name}]} response = staff_api_client.post_graphql( query, variables, permissions=[permission_manage_products]", "== attribute.name assert not attribute.values.filter(pk=attribute_value_id).exists() assert attribute.values.filter(name=attribute_value_name).exists() def test_update_empty_attribute_and_add_values( staff_api_client,", "of the node (product/variant), thus no values should be resolved.", "assert data[\"productErrors\"][0][\"field\"] == \"name\" def test_create_attribute_value_capitalized_name( staff_api_client, color_attribute, permission_manage_products ):", "\"\"\"The unAssignAttribute mutation should not raise any error when trying", "import zero_money from saleor.graphql.core.utils import snake_to_camel_case from saleor.graphql.product.enums import AttributeTypeEnum,", "slugify( attribute_name ), \"The default slug should be the slugified", "other_attribute.attributevariant.last() else: m2m_rel_other_attr = other_attribute.attributeproduct.last() # Push the last attribute", "color_attribute_without_values, ): \"\"\"The assignAttribute mutation should raise an error when", "{ node { slug } } } } \"\"\" def", "is actually passing the test. other_attribute = Attribute.objects.create(name=\"Other\", slug=\"other\") #", "non-staff users don't see hidden attributes, and staff users having", "(True, False)) def test_attributes_of_products_are_sorted( staff_api_client, product, color_attribute, is_variant ): \"\"\"Ensures", "][\"attributeUnassign\"] assert not content[\"errors\"] assert content[\"productType\"][\"id\"] == product_type_global_id assert len(content[\"productType\"][\"productAttributes\"])", "attributes for dashboard custom ordering inside a given product type.\"\"\"", "attribute with a higher ID # This will allow us", "\"\"\"Ensure the attribute values are properly resolved.\"\"\" query = QUERY_PRODUCT_AND_VARIANTS_ATTRIBUTES", "{\"search\": \"color\"}} attributes = get_graphql_content( api_client.post_graphql(ATTRIBUTES_FILTER_QUERY, variables) )[\"data\"][\"attributes\"][\"edges\"] assert len(attributes)", "Create a value for each dummy attribute to ensure they", "== ProductErrorCode.INVALID.name def test_delete_attribute( staff_api_client, color_attribute, permission_manage_products, product_type ): attribute", "} \"\"\" found_products = get_graphql_content( staff_api_client.post_graphql(query, permissions=[permission_manage_products]) )[\"data\"][\"products\"][\"edges\"] assert len(found_products)", "AttributeValue(slug=\"a\", name=\"A\", attribute=unassigned_product_attribute), AttributeValue(slug=\"b\", name=\"B\", attribute=unassigned_product_attribute), ] ) # Assign", "product, staff_user ): \"\"\"Ensure the attribute values are properly resolved", "variables = { \"type\": \"VARIANT\", \"productTypeId\": product_type_id, \"moves\": [{\"id\": attribute_id,", "user_api_client variant = product.variants.first() product_type = product.product_type # Create dummy", "Attribute(name=\"MyAttribute\", slug=\"a\"), ] ) variables = {\"sortBy\": {\"field\": \"SLUG\", \"direction\":", "or is not directly associated to it. \"\"\" # Retrieve", ")[\"data\"][\"attributes\"][\"edges\"] assert len(found_attributes) == 1 assert found_attributes[0][\"node\"][attribute] == expected_value ATTRIBUTES_RESORT_QUERY", "using a non-existing category ID returns an empty query set.\"\"\"", "len(content[\"productType\"][\"productAttributes\"]) == 0 assert len(content[\"productType\"][\"variantAttributes\"]) == 0 def test_retrieve_product_attributes_input_type( staff_api_client,", "the product's variant variant = product.variants.get() # Remove all attributes", "is_variant else product # type: Union[Product, ProductVariant] node.attributesrelated.clear() associate_attribute_values_to_instance( node,", "len(gql_values) == len(expected_order) actual_order = [] for attr, expected_pk in", "\"Variants are disabled in this product type.\", } ] def", "assert variant[\"attributes\"][0][\"attribute\"][\"slug\"] == \"size\" assert variant[\"attributes\"][0][\"values\"] == [] ASSIGN_ATTR_QUERY =", "): staff_api_client.user.user_permissions.add(permission_manage_products) query = \"\"\" mutation createAttribute( $name: String!, $slug:", "= get_graphql_content( staff_api_client.post_graphql(ATTRIBUTES_RESORT_QUERY, variables) )[\"data\"][\"productTypeReorderAttributes\"] assert not content[\"errors\"] assert (", "errors { field message } attribute { id } }", "values are not unique.\", ProductErrorCode.UNIQUE, ), ), ) def test_create_attribute_and_attribute_values_errors(", "variant_attributes = product[\"variants\"][0][\"attributes\"] assert len(product_attributes) == len(product_attribute_values) assert len(variant_attributes) ==", "} } } } } } \"\"\" @pytest.mark.parametrize(\"is_staff\", (False, True))", "CREATE_ATTRIBUTES_QUERY variables = {\"name\": \"Example name\", \"values\": [{\"name\": name_1}, {\"name\":", "$id: ID!, $name: String!) { attributeValueUpdate( id: $id, input: {name:", "{\"name\": name, \"id\": node_id} response = staff_api_client.post_graphql( query, variables, permissions=[permission_manage_products]", "\"field\": \"moves\", \"message\": f\"Couldn't resolve to an attribute value: {value_id}\",", "} } } } } } \"\"\" def test_create_attribute_and_attribute_values( staff_api_client,", "and if their default value is the expected one.\"\"\" attribute", "to make sure it is always the last attribute #", "content = get_graphql_content(response) attributes_data = content[\"data\"][\"attributes\"][\"edges\"] assert attributes_data assert len(attributes_data)", "AttributeValueType.COLOR), (\"#FF69B4\", AttributeValueType.COLOR), (\"rgb(255, 0, 0)\", AttributeValueType.COLOR), (\"hsl(0, 100%, 50%)\",", "for attr in content[\"productType\"][\"variantAttributes\"] } assert found_product_attrs_ids == product_attributes_ids assert", "color_attribute node_id = graphene.Node.to_global_id(\"Attribute\", attribute.id) size_attribute = size_attribute.values.first() attr_id =", "graphene.Node.to_global_id(\"ProductType\", product_type.pk) if product_type_attribute_type == AttributeTypeEnum.PRODUCT: product_type.product_attributes.add(attribute) elif product_type_attribute_type ==", "else: query = \"\"\" query($id: ID!) { product(id: $id) {", "inside a given product type.\"\"\" product_type = ProductType.objects.create(name=\"My Product Type\")", "is_variant: product.product_type.variant_attributes.set([color_attribute, other_attribute]) else: product.product_type.product_attributes.set([color_attribute, other_attribute]) # Retrieve the M2M", "attribute.visible_in_storefront = False attribute.save(update_fields=[\"visible_in_storefront\"]) product = get_graphql_content(api_client.post_graphql(query))[\"data\"][\"products\"][ \"edges\" ][0][\"node\"] assert", "= content[\"data\"][\"attributeUpdate\"] assert data[\"attribute\"][\"name\"] == name == attribute.name assert data[\"attribute\"][\"productTypes\"][\"edges\"]", "= \"\"\" mutation createAttribute( $name: String!, $slug: String) { attributeCreate(input:", "assert attributes[1][\"node\"][\"slug\"] == \"b\" @pytest.mark.parametrize( \"sort_field, m2m_model\", ( (\"DASHBOARD_VARIANT_POSITION\", AttributeVariant),", "\"removeValues\": []} response = staff_api_client.post_graphql( query, variables, permissions=[permission_manage_products] ) content", "staff_api_client, pink_attribute_value, permission_manage_products ): query = UPDATE_ATTRIBUTE_VALUE_QUERY value = pink_attribute_value.attribute.values.create(", "null value is ignored and the queryset is simply returned", "\"\"\"Ensure using a non-existing category ID returns an empty query", "content[\"data\"][\"attributeCreate\"][\"errors\"] assert errors assert errors[0][\"field\"] == \"values\" assert errors[0][\"message\"] ==", "in zip(gql_attributes, expected_order): gql_type, gql_attr_id = graphene.Node.from_global_id(attr[\"id\"]) assert gql_type ==", "assert content[\"attribute\"][\"id\"] == attribute_id gql_values = content[\"attribute\"][\"values\"] assert len(gql_values) ==", "user_api_client variant = product.variants.first() product_attribute = color_attribute variant_attribute = size_attribute", "staff_api_client, permission_manage_products, input_slug, expected_slug, expected_error, ): staff_api_client.user.user_permissions.add(permission_manage_products) query = \"\"\"", "edges { node { attributes { values { type inputType", "\"Provided values are not unique.\", ProductErrorCode.UNIQUE, ), ), ) def", "staff_api_client.user.user_permissions.add(permission_manage_products) product_type_global_id = graphene.Node.to_global_id(\"ProductType\", product_type.pk) if product_type_attribute_type == AttributeTypeEnum.PRODUCT: product_type.product_attributes.add(attribute)", "name_1, name_2, error_msg, error_code, color_attribute, permission_manage_products, ): query = UPDATE_ATTRIBUTE_QUERY", "product_type=product_type, attribute=size_attribute, sort_order=1 ) variables = {\"sortBy\": {\"field\": sort_field, \"direction\":", "\"name\" UPDATE_ATTRIBUTE_VALUE_QUERY = \"\"\" mutation updateChoice( $id: ID!, $name: String!)", "attribute.id) size_attribute = size_attribute.values.first() attr_id = graphene.Node.to_global_id(\"AttributeValue\", size_attribute.pk) variables =", "\"\"\" # Create a dummy attribute with a higher ID", "), ) def test_assign_attribute_to_product_type_having_already_that_attribute( staff_api_client, permission_manage_products, color_attribute_without_values, product_type_attribute_type, gql_attribute_type, ):", "an attribute is part of the product type but not", "by the product or variant as they are not associated", "{ name type slug } } } \"\"\" def test_create_attribute_value(", "null or something else assert content[\"data\"][\"attributeCreate\"][\"errors\"] == expected_error # Check", "\"\"\"Try to reorder a value not associated to the given", "(\"Filtering by in_space is unsupported\",) def test_attributes_filter_by_non_existing_category_id(): \"\"\"Ensure using a", "an error when trying to add an attribute already contained", "[ID]! ) { attributeUnassign(productTypeId: $productTypeId, attributeIds: $attributeIds) { errors {", "assert data[\"attribute\"][\"slug\"] == slugify( attribute_name ), \"The default slug should", "{name: $name}) { productErrors { field message code } attribute", "Attribute.objects.filter( Q(attributeproduct__product_type_id=product_type.pk) | Q(attributevariant__product_type_id=product_type.pk) ) # Create another product type", "= get_graphql_content( api_client.post_graphql(ATTRIBUTES_SORT_QUERY, variables) )[\"data\"][\"attributes\"][\"edges\"] assert len(attributes) == 2 assert", "resolve to an attribute: {attribute_id}\", } ] @pytest.mark.parametrize( \"attribute_type, relation_field,", "shouldn't get matched other_category = Category.objects.create(name=\"Other Category\", slug=\"other-cat\") other_attribute =", "ProductErrorCode.UNIQUE, ), ( \"Red color\", \"red color\", \"Provided values are", "us to make sure it is always the last attribute", "variant variant = product.variants.get() # Remove all attributes and values", "f\"Couldn't resolve to a product type: {product_type_id}\", } ] def", "color_attribute_without_values.slug QUERY_ATTRIBUTES = \"\"\" query { attributes(first: 20) { edges", "values == sorted( values, key=lambda o: o.sort_order if o.sort_order is", "ATTRIBUTES_FILTER_QUERY = \"\"\" query($filters: AttributeFilterInput!) { attributes(first: 10, filter: $filters)", "\"\"\" found_products = get_graphql_content( staff_api_client.post_graphql(query, permissions=[permission_manage_products]) )[\"data\"][\"products\"][\"edges\"] assert len(found_products) ==", "\"Attribute\", product_attributes[1].pk ) query = UNASSIGN_ATTR_QUERY variables = { \"productTypeId\":", "product_type.pk) query = ASSIGN_ATTR_QUERY operations = [ {\"type\": \"VARIANT\", \"id\":", ") content = get_graphql_content(response) assert not content[\"data\"][\"attributeCreate\"][\"errors\"] data = content[\"data\"][\"attributeCreate\"]", "products(first: 1) { edges { node { attributes { attribute", "content = get_graphql_content(response) data = content[\"data\"][\"attributeDelete\"] assert data[\"attribute\"][\"id\"] == variables[\"id\"]", "] @pytest.mark.parametrize( \"attribute_type, relation_field, backref_field\", ( (\"VARIANT\", \"variant_attributes\", \"attributevariant\"), (\"PRODUCT\",", "test_sort_values_within_attribute_invalid_id( staff_api_client, permission_manage_products, color_attribute ): \"\"\"Try to reorder a value", "= ProductType.objects.create(name=\"My Product Type\") m2m_model.objects.create( product_type=product_type, attribute=color_attribute, sort_order=0 ) m2m_model.objects.create(", "product_type, ): query = CREATE_ATTRIBUTES_QUERY variables = {\"name\": \"Example name\",", "} ] def test_sort_values_within_attribute( staff_api_client, color_attribute, permission_manage_products ): attribute =", "data = content[\"data\"][\"attributeCreate\"] # Check if the attribute was correctly", "def test_update_attribute_value( staff_api_client, pink_attribute_value, permission_manage_products ): query = UPDATE_ATTRIBUTE_VALUE_QUERY value", "errors { field message } } } \"\"\" def test_sort_attributes_within_product_type_invalid_product_type(", "), ) def test_retrieving_the_restricted_attributes_restricted( staff_api_client, color_attribute, permission_manage_products, attribute, expected_value, ):", "\"sortOrder\": -1, }, ], } expected_order = [values[1].pk, values[2].pk, values[0].pk]", "staff_api_client, permission_manage_products, attribute_list ): product_type = ProductType.objects.create(name=\"Default Type\", has_variants=True) product_type_global_id", "variant_attribute_values[0] assert variant_attributes[0][\"value\"][\"slug\"] == variant_attribute_values[0] def test_resolve_attribute_values_non_assigned_to_node( user_api_client, product, staff_user", "variables, permissions=[permission_manage_products], ) )[\"data\"][\"attributeReorderValues\"] assert content[\"errors\"] == [ { \"field\":", "== [ { \"field\": \"moves\", \"message\": f\"Couldn't resolve to an", "== \"size\" assert variant[\"attributes\"][0][\"values\"] == [] ASSIGN_ATTR_QUERY = \"\"\" mutation", "= graphene.Node.to_global_id(\"AttributeValue\", value.id) variables = {\"name\": pink_attribute_value.name, \"id\": node_id} response", "(\"radial-gradient(#0000, yellow)\", AttributeValueType.GRADIENT), ], ) def test_resolve_attribute_value_type(raw_value, expected_type): assert resolve_attribute_value_type(raw_value)", "message } productType { id productAttributes { id } variantAttributes", "# through a sort_order=0 as the other attributes have sort_order=null", "content[\"productType\"][\"productAttributes\"] } found_variant_attrs_ids = { int(graphene.Node.from_global_id(attr[\"id\"])[1]) for attr in content[\"productType\"][\"variantAttributes\"]", "default.\"\"\" Attribute.objects.bulk_create( [Attribute(name=\"A\", slug=\"b\"), Attribute(name=\"B\", slug=\"a\")] ) attributes = get_graphql_content(", "{ attributes { attribute { slug } values { slug", "QUERY_PRODUCT_AND_VARIANTS_ATTRIBUTES api_client = user_api_client variant = product.variants.first() product_attribute = color_attribute", "product.attributes.count() == 1 assert variant.attributes.count() == 1 product_attribute_values = list(", "test_create_attribute_value_not_unique_name( staff_api_client, color_attribute, permission_manage_products ): attribute = color_attribute query =", "field message code } attribute { values { name }", "type: Union[Product, ProductVariant] node.attributesrelated.clear() associate_attribute_values_to_instance( node, color_attribute, color_attribute.values.first() ) #", "don't look for this other collection other_collection = Collection.objects.create( name=\"Other", "} } \"\"\" if test_deprecated_filter: query = query % {\"filter_input\":", "graphene.Node.to_global_id(\"Collection\", collection.pk) elif \"Category\" in tested_field: filtered_by_node_id = graphene.Node.to_global_id(\"Category\", category.pk)", "product_type, product): \"\"\"Ensure the attributes assigned to a product type", "be the slugified name\" assert ( data[\"attribute\"][\"productTypes\"][\"edges\"] == [] ),", "attribute values are properly resolved.\"\"\" query = QUERY_PRODUCT_AND_VARIANTS_ATTRIBUTES api_client =", "Remove all attributes and values from the product and its", "assert len(found_products) == 1 for gql_attr in found_products[0][\"node\"][\"attributes\"]: assert len(gql_attr[\"values\"])", "variables) )[\"data\"][\"attributes\"][\"edges\"] assert len(attributes) == 1 assert attributes[0][\"node\"][\"slug\"] == \"size\"", "== remaining_attribute_global_id ) def test_unassign_attributes_not_in_product_type( staff_api_client, permission_manage_products, color_attribute_without_values ): \"\"\"The", "\"removeValues\": [], } response = staff_api_client.post_graphql( query, variables, permissions=[permission_manage_products] )", "AttributeValueType.GRADIENT), (\"radial-gradient(#0000, yellow)\", AttributeValueType.GRADIENT), ], ) def test_resolve_attribute_value_type(raw_value, expected_type): assert", "data[\"attribute\"][\"name\"] == attribute_name assert data[\"attribute\"][\"slug\"] == slugify( attribute_name ), \"The", "expected if expected_error is None: assert content[\"data\"][\"attributeCreate\"][\"attribute\"][\"slug\"] == expected_slug @pytest.mark.parametrize(", "other_attribute = Attribute.objects.create(name=\"Other\", slug=\"other\") other_product_type = ProductType.objects.create( name=\"Other type\", has_variants=True,", "to see the hidden attributes assert Attribute.objects.get_visible_to_user(staff_api_client.user).count() == 1 #", "{ id slug } } \"\"\" content = get_graphql_content( user_api_client.post_graphql(query,", "== \"STRING\" assert gql_attr[\"values\"][0][\"inputType\"] == \"DROPDOWN\" @pytest.mark.parametrize( \"attribute, expected_value\", (", "= get_graphql_content( user_api_client.post_graphql(query, {\"id\": attribute_gql_id}) ) assert content[\"data\"][\"attribute\"], \"Should have", "api_client = user_api_client variant = product.variants.first() product_attribute = color_attribute variant_attribute", "variant attribute when the product type doesn't support variants\"\"\" product_type", "content = get_graphql_content(response) errors = content[\"data\"][\"attributeCreate\"][\"errors\"] assert errors assert errors[0][\"field\"]", "# Create dummy attributes unassigned_product_attribute = Attribute.objects.create(name=\"P\", slug=\"product\") unassigned_variant_attribute =", "get_graphql_content(response) attribute.refresh_from_db() data = content[\"data\"][\"attributeUpdate\"] assert not data[\"errors\"] assert data[\"attribute\"][\"name\"]", "{ slug } values { name } } variants {", "\"field\": \"attributeId\", \"message\": f\"Couldn't resolve to an attribute: {attribute_id}\", }", "{ edges { node { id } } } }", "have the permission yet to manage products, # the user", "Attribute, AttributeProduct, AttributeValue, AttributeVariant, Category, Collection, Product, ProductType, ProductVariant, )", "\"\"\" node_id = graphene.Node.to_global_id(\"Attribute\", attribute.id) variables = {\"id\": node_id} response", "variant.attributesrelated.clear() # Retrieve the product and variant's attributes products =", "graphene.Node.to_global_id(\"ProductType\", product_type.pk) query = ASSIGN_ATTR_QUERY operations = [] variables =", "node { slug } } } } \"\"\" def test_sort_attributes_by_slug(api_client):", "AttributeProduct], ): \"\"\"Sorts attributes for dashboard custom ordering inside a", "len(attributes) == 2 assert attributes[0][\"node\"][\"slug\"] == \"size\" assert attributes[1][\"node\"][\"slug\"] ==", "{ name slug } attribute { values { name }", "top and let the others to None m2m_rel_other_attr.sort_order = 0", "}\" % tested_field} variables = {\"nodeID\": filtered_by_node_id} content = get_graphql_content(user_api_client.post_graphql(query,", "attribute.values.count() == 1 assert attribute.values.filter(name=attribute_value_name).exists() @pytest.mark.parametrize( \"name_1, name_2, error_msg, error_code\",", "== [ { \"field\": \"operations\", \"message\": ( \"Attributes having for", "= {\"name\": value_name, \"attributeId\": attribute_id} response = staff_api_client.post_graphql( query, variables,", ")[\"data\"][\"attributeAssign\"] assert not content[\"errors\"], \"Should have succeeded\" assert content[\"productType\"][\"id\"] ==", "yellow)\", AttributeValueType.GRADIENT), ], ) def test_resolve_attribute_value_type(raw_value, expected_type): assert resolve_attribute_value_type(raw_value) ==", "staff_api_client, permission_manage_products, color_attribute ): \"\"\"Try to reorder a value not", "product(id: $id) { attributes { attribute { id } }", "data = content[\"data\"][\"attributeValueUpdate\"] value.refresh_from_db() assert data[\"attributeValue\"][\"name\"] == name == value.name", "product): attributes = Attribute.objects query = QUERY_ATTRIBUTES response = user_api_client.post_graphql(query)", "== 1 product = get_graphql_content(api_client.post_graphql(query))[\"data\"][\"products\"][ \"edges\" ][0][\"node\"] product_attributes = product[\"attributes\"]", "product_attributes[0].pk) ], } content = get_graphql_content( staff_api_client.post_graphql( query, variables, permissions=[permission_manage_products]", "f\"Couldn't resolve to an attribute value: {value_id}\", } ] def", "== 1 assert attributes[0][\"node\"][\"slug\"] == \"color\" def test_filter_attributes_if_filterable_in_dashboard( api_client, color_attribute,", "\"\"\" def test_update_attribute_name( staff_api_client, color_attribute, permission_manage_products ): query = UPDATE_ATTRIBUTE_QUERY", "[]} response = staff_api_client.post_graphql( query, variables, permissions=[permission_manage_products] ) content =", "attribute_name = \"My Name\" variables = {\"name\": attribute_name, \"slug\": input_slug}", "remove an attribute that is not/no longer in the product", "expected_value\", ( (\"filterable_in_storefront\", True), (\"filterable_in_dashboard\", True), (\"visible_in_storefront\", True), (\"available_in_grid\", True),", "\"<NAME>\" node_id = graphene.Node.to_global_id(\"Attribute\", attribute.id) variables = {\"name\": name, \"id\":", "type if is_variant: m2m_rel_other_attr = other_attribute.attributevariant.last() else: m2m_rel_other_attr = other_attribute.attributeproduct.last()", "qs = filter_attributes_by_product_types(mocked_qs, \"in_category\", category_id) assert qs == mocked_qs.none.return_value @pytest.mark.parametrize(\"test_deprecated_filter\",", "assert variant.attributes.count() == 1 product = get_graphql_content(api_client.post_graphql(query))[\"data\"][\"products\"][ \"edges\" ][0][\"node\"] product_attributes", "permission_manage_products, attribute_list ): product_type = ProductType.objects.create(name=\"Type\") product_type_global_id = graphene.Node.to_global_id(\"ProductType\", product_type.pk)", "flat=True) ) variant_attribute_values = list( variant.attributes.first().values.values_list(\"slug\", flat=True) ) assert len(product_attribute_values)", "manage products, # the user shouldn't be able to see", "): \"\"\"Ensure the attribute values are properly resolved when an", "def test_resolve_attribute_value_type(raw_value, expected_type): assert resolve_attribute_value_type(raw_value) == expected_type def test_resolve_assigned_attribute_without_values(api_client, product_type,", "node { %s } } } } \"\"\" % attribute", "\"id\": node_id, \"removeValues\": [], \"addValues\": [{\"name\": name_1}, {\"name\": name_2}], }", "= Collection.objects.create( name=\"Other Collection\", slug=\"other-collection\", is_published=True, description=\"Description\", ) other_collection.products.add(other_product) query", "= content[\"data\"][\"attributes\"][\"edges\"] assert attributes_data assert len(attributes_data) == attributes.count() def test_attributes_query_hidden_attribute(user_api_client,", "product_attribute_values[0] assert product_attributes[0][\"value\"][\"slug\"] == product_attribute_values[0] assert variant_attributes[0][\"attribute\"][\"slug\"] == \"size\" assert", "} } \"\"\" def test_create_attribute_and_attribute_values( staff_api_client, permission_manage_products ): query =", "attributeValue { name type slug } } } \"\"\" def", "} values { name } } variants { attributes {", "ones we are testing assert len(products) == 1 assert len(products[0][\"node\"][\"variants\"])", "variant_attributes_ids = {attr.pk for attr in attribute_list[2:]} for attr_id in", "\"operations\", \"message\": \"Color (color) have already been assigned to this", "value.name assert data[\"attributeValue\"][\"slug\"] == slugify(name) assert name in [value[\"name\"] for", "\"\"\" def test_search_attributes(api_client, color_attribute, size_attribute): variables = {\"filters\": {\"search\": \"color\"}}", "attribute.pk) for attribute in attribute_list[:2] ] variables = {\"filters\": {\"ids\":", "get_graphql_content(response) errors = content[\"data\"][\"attributeUpdate\"][\"errors\"] assert errors assert errors[0][\"field\"] == \"removeValues\"", "== 2 assert attributes[0][\"node\"][\"slug\"] == \"b\" assert attributes[1][\"node\"][\"slug\"] == \"a\"", "associated to the given attribute.\"\"\" attribute_id = graphene.Node.to_global_id(\"Attribute\", color_attribute.id) value_id", "== 1 assert ( content[\"productType\"][\"productAttributes\"][0][\"id\"] == remaining_attribute_global_id ) def test_unassign_attributes_not_in_product_type(", "== attribute_count QUERY_PRODUCT_AND_VARIANTS_ATTRIBUTES = \"\"\" { products(first: 1) { edges", "== [ { \"field\": \"operations\", \"message\": \"Variants are disabled in", "\"message\": f\"Couldn't resolve to an attribute: {attribute_id}\", } ] @pytest.mark.parametrize(", "value_id = graphene.Node.to_global_id(\"AttributeValue\", -1) variables = { \"attributeId\": attribute_id, \"moves\":", "graphene.Node.to_global_id( \"Attribute\", product_attributes[1].pk ) query = UNASSIGN_ATTR_QUERY variables = {", "== 1 # Retrieve the nodes data product = products[0][\"node\"]", ") with pytest.raises(value._meta.model.DoesNotExist): value.refresh_from_db() @pytest.mark.parametrize( \"raw_value, expected_type\", [ (\"#0000\", AttributeValueType.COLOR),", "ID returns an empty query set.\"\"\" category_id = graphene.Node.to_global_id(\"Category\", -1)", "attribute_id, \"moves\": [ { \"id\": graphene.Node.to_global_id(\"AttributeValue\", values[0].pk), \"sortOrder\": +1, },", "== \"size\" def test_filter_attributes_by_global_id_list(api_client, attribute_list): global_ids = [ graphene.Node.to_global_id(\"Attribute\", attribute.pk)", "list(sort_method()) assert len(attributes) == 3 variables = { \"type\": attribute_type,", "if the error is as expected: null or something else", "sort_order=0 as the other attributes have sort_order=null AttributeProduct.objects.create( attribute=unassigned_product_attribute, product_type=product_type,", "== ProductErrorCode.ALREADY_EXISTS.name assert data[\"productErrors\"][0][\"field\"] == \"name\" def test_create_attribute_value_capitalized_name( staff_api_client, color_attribute,", "$moves: [ReorderInput]!) { attributeReorderValues(attributeId: $attributeId, moves: $moves) { attribute {", "found an attribute\" assert content[\"data\"][\"attribute\"][\"id\"] == attribute_gql_id assert content[\"data\"][\"attribute\"][\"slug\"] ==", "values are not unique.\", ProductErrorCode.UNIQUE, ), ( \"Red color\", \"red", "slug should raise an error with pytest.raises(ValidationError): validate_value_is_unique(color_attribute, AttributeValue(slug=value.slug)) #", "for attr, expected_pk in zip(gql_values, expected_order): gql_type, gql_attr_id = graphene.Node.from_global_id(attr[\"id\"])", "but not of the node (product/variant), thus no values should", "yet to manage products, # the user shouldn't be able", "permission_manage_products ): \"\"\"Try to reorder an invalid product type (invalid", "others to None m2m_rel_other_attr.sort_order = 0 m2m_rel_other_attr.save(update_fields=[\"sort_order\"]) # Assign attributes", "Check if the error is as expected: null or something", "else: raise AssertionError(tested_field) expected_qs = Attribute.objects.filter( Q(attributeproduct__product_type_id=product_type.pk) | Q(attributevariant__product_type_id=product_type.pk) )", "name\", \"id\": node_id, \"removeValues\": [], \"addValues\": [{\"name\": name_1}, {\"name\": name_2}],", "} \"\"\" def test_attributes_query(user_api_client, product): attributes = Attribute.objects query =", "color_attribute, permission_manage_products ): attribute = color_attribute AttributeValue.objects.create(attribute=attribute, name=\"Green\", slug=\"green\") values", "\"a\" @pytest.mark.parametrize(\"is_variant\", (True, False)) def test_attributes_of_products_are_sorted( staff_api_client, product, color_attribute, is_variant", "values are properly resolved.\"\"\" query = QUERY_PRODUCT_AND_VARIANTS_ATTRIBUTES api_client = user_api_client", "= graphene.Node.from_global_id(attr[\"id\"]) assert gql_type == \"Attribute\" assert int(gql_attr_id) == expected_pk", "QUERY_ATTRIBUTES = \"\"\" query { attributes(first: 20) { edges {", "\"Example name\", \"id\": node_id, \"removeValues\": [], \"addValues\": [{\"name\": name_1}, {\"name\":", "to the product node = variant if is_variant else product", "color_attribute AttributeValue.objects.create(attribute=attribute, name=\"Green\", slug=\"green\") values = list(attribute.values.all()) assert len(values) ==", "type: {product_type_id}\", } ] def test_sort_attributes_within_product_type_invalid_id( staff_api_client, permission_manage_products, color_attribute ):", "\"Collection\" in tested_field: filtered_by_node_id = graphene.Node.to_global_id(\"Collection\", collection.pk) elif \"Category\" in", "elif product_type_attribute_type == AttributeTypeEnum.VARIANT: product_type.variant_attributes.add(attribute) else: raise ValueError(f\"Unknown: {product_type}\") query", "in attribute_list[:2] ] variables = {\"filters\": {\"ids\": global_ids}} expected_slugs =", "{ int(graphene.Node.from_global_id(attr[\"id\"])[1]) for attr in content[\"productType\"][\"productAttributes\"] } found_variant_attrs_ids = {", "global_ids = [ graphene.Node.to_global_id(\"Attribute\", attribute.pk) for attribute in attribute_list[:2] ]", "content[\"data\"][\"attributeValueCreate\"] assert data[\"productErrors\"] assert data[\"productErrors\"][0][\"code\"] == ProductErrorCode.ALREADY_EXISTS.name assert data[\"productErrors\"][0][\"field\"] ==", "variant = product.variants.first() assert product.attributes.count() == 1 assert variant.attributes.count() ==", "found_products = get_graphql_content( staff_api_client.post_graphql(query, permissions=[permission_manage_products]) )[\"data\"][\"products\"][\"edges\"] assert len(found_products) == 1", "an unknown field to filter attributes by raises a NotImplemented", "the last attribute to the top and let the others", "staff_api_client.user.user_permissions.add(permission_manage_products) query = \"\"\" mutation createAttribute( $name: String!, $slug: String)", "{\"name\": name, \"attributeId\": attribute_id} response = staff_api_client.post_graphql( query, variables, permissions=[permission_manage_products]", "errors { field message } productType { id productAttributes {", "with pytest.raises(value._meta.model.DoesNotExist): value.refresh_from_db() @pytest.mark.parametrize( \"raw_value, expected_type\", [ (\"#0000\", AttributeValueType.COLOR), (\"#FF69B4\",", "= UPDATE_ATTRIBUTE_VALUE_QUERY value = pink_attribute_value node_id = graphene.Node.to_global_id(\"AttributeValue\", value.id) name", "= { int(graphene.Node.from_global_id(attr[\"id\"])[1]) for attr in content[\"productType\"][\"productAttributes\"] } found_variant_attrs_ids =", "len(product_attributes) == 2, \"Non-assigned attr from the PT may be", "get_graphql_content( staff_api_client.post_graphql(query, permissions=[permission_manage_products]) )[\"data\"][\"products\"][\"edges\"] assert len(found_products) == 1 for gql_attr", "import AttributeInputType from saleor.product.error_codes import ProductErrorCode from saleor.product.models import (", "attribute=unassigned_product_attribute, product_type=product_type, sort_order=0 ) AttributeVariant.objects.create( attribute=unassigned_variant_attribute, product_type=product_type, sort_order=0 ) assert", "node { attributes { values { type inputType } }", "product.product_type.product_attributes.set([color_attribute, other_attribute]) # Retrieve the M2M object for the attribute", "permission_manage_products, color_attribute_without_values, product_type_attribute_type, gql_attribute_type, ): \"\"\"The assignAttribute mutation should raise", "(\"http://example.com\", AttributeValueType.URL), (\"https://example.com\", AttributeValueType.URL), (\"ftp://example.com\", AttributeValueType.URL), (\"example.com\", AttributeValueType.STRING), (\"Foo\", AttributeValueType.STRING),", "{\"name\": name_2}], } response = staff_api_client.post_graphql( query, variables, permissions=[permission_manage_products] )", "def test_update_attribute_and_remove_others_attribute_value( staff_api_client, color_attribute, size_attribute, permission_manage_products ): query = UPDATE_ATTRIBUTE_QUERY", "{\"filters\": {\"filterableInDashboard\": True}} attributes = get_graphql_content( api_client.post_graphql(ATTRIBUTES_FILTER_QUERY, variables) )[\"data\"][\"attributes\"][\"edges\"] assert", "= content[\"data\"][\"attributes\"][\"edges\"] assert len(attributes_data) == attribute_count QUERY_PRODUCT_AND_VARIANTS_ATTRIBUTES = \"\"\" {", "attr, expected_pk in zip(gql_values, expected_order): gql_type, gql_attr_id = graphene.Node.from_global_id(attr[\"id\"]) assert", "for attr in attribute_list[2:]} for attr_id in product_attributes_ids: operations.append( {\"type\":", "$id) { errors { field message } attribute { id", "= graphene.Node.to_global_id(\"ProductType\", -1) attribute_id = graphene.Node.to_global_id(\"Attribute\", -1) variables = {", "else: node_id = graphene.Node.to_global_id(\"Product\", product.pk) # Retrieve the attributes data", "f\"Couldn't resolve to an attribute: {attribute_id}\", } ] @pytest.mark.parametrize( \"attribute_type,", "# Check if the error is as expected: null or", "assert len(content[\"productType\"][\"productAttributes\"]) == 0 assert len(content[\"productType\"][\"variantAttributes\"]) == 0 def test_retrieve_product_attributes_input_type(", "name=f\"Another Product\", product_type=other_product_type, category=other_category, price=zero_money(), is_published=True, ) # Create another", "graphene.Node.to_global_id(\"Attribute\", attr_id)} ) for attr_id in variant_attributes_ids: operations.append( {\"type\": \"VARIANT\",", "= [other_attribute.pk, color_attribute.pk] # Make the node ID if is_variant:", "is_staff: api_client.user = staff_user expected_product_attribute_count += 1 expected_variant_attribute_count += 1", "f\"{relation_field}_sorted\") attributes = list(sort_method()) assert len(attributes) == 3 variables =", "= staff_api_client.post_graphql( query, variables, permissions=[permission_manage_products] ) content = get_graphql_content(response) assert", "other_product_type = ProductType.objects.create( name=\"Other type\", has_variants=True, is_shipping_required=True ) other_product_type.product_attributes.add(other_attribute) other_product", "query = QUERY_ATTRIBUTES # hide the attribute color_attribute.visible_in_storefront = False", "productTypes(first: 10) { edges { node { id } }", "been assigned to this product type.\", } ] UNASSIGN_ATTR_QUERY =", "variables) )[\"data\"][\"attributeReorderValues\"] assert not content[\"errors\"] assert content[\"attribute\"][\"id\"] == attribute_id gql_values", "(\"value_required\", False), (\"storefront_search_position\", 0), ), ) def test_retrieving_the_restricted_attributes_restricted( staff_api_client, color_attribute,", "part of the product type but not of the node", "assert data[\"attribute\"][\"name\"] == name == attribute.name assert data[\"attribute\"][\"productTypes\"][\"edges\"] == []", "edges { node { attributes { attribute { slug }", "$operations: [AttributeAssignInput]!) { attributeAssign(productTypeId: $productTypeId, operations: $operations) { errors {", "be able to see the hidden attributes assert Attribute.objects.get_visible_to_user(staff_api_client.user).count() ==", "data[\"attribute\"][\"values\"]] def test_create_attribute_value_not_unique_name( staff_api_client, color_attribute, permission_manage_products ): attribute = color_attribute", "variants { attributes { attribute { slug } values {", "= \"\"\" { products(first: 10) { edges { node {", "sort_method = getattr(m2m_attributes, f\"{relation_field}_sorted\") attributes = list(sort_method()) assert len(attributes) ==", "type\" # Check if the attribute values were correctly created", "an invalid product type (invalid ID).\"\"\" product_type_id = graphene.Node.to_global_id(\"ProductType\", -1)", "\"\"\"Try to reorder an invalid attribute (invalid ID).\"\"\" attribute_id =", "{ attribute { id } } } } \"\"\" else:", "$name, addValues: $addValues, removeValues: $removeValues}) { errors { field message", "type if is_variant: product.product_type.variant_attributes.set([color_attribute, other_attribute]) else: product.product_type.product_attributes.set([color_attribute, other_attribute]) # Retrieve", "one.\"\"\" attribute = to_camel_case(attribute) query = ( \"\"\" { attributes(first:", "len(product_attribute_values) == 1 assert len(variant_attribute_values) == 1 product = get_graphql_content(api_client.post_graphql(query))[\"data\"][\"products\"][", "default value is the expected one.\"\"\" attribute = to_camel_case(attribute) query", "test_filter_attributes_if_available_in_grid( api_client, color_attribute, size_attribute ): color_attribute.available_in_grid = False color_attribute.save(update_fields=[\"available_in_grid\"]) variables", "} } } } \"\"\" # Create a dummy attribute", "), ) def test_create_attribute_with_given_slug( staff_api_client, permission_manage_products, input_slug, expected_slug, expected_error, ):", "attribute = color_attribute query = CREATE_ATTRIBUTE_VALUE_QUERY attribute_id = graphene.Node.to_global_id(\"Attribute\", attribute.id)", "] UNASSIGN_ATTR_QUERY = \"\"\" mutation unAssignAttribute( $productTypeId: ID!, $attributeIds: [ID]!", "{\"name\": attribute_name, \"slug\": input_slug} content = get_graphql_content(staff_api_client.post_graphql(query, variables)) # Check", "def test_sort_values_within_attribute_invalid_product_type( staff_api_client, permission_manage_products ): \"\"\"Try to reorder an invalid", "{ product(id: $id) { attributes { attribute { id }", "= \"\"\" mutation createAttribute($name: String!, $values: [AttributeValueCreateInput]) { attributeCreate(input: {name:", "raise an error when trying to add an attribute as", "1 product = get_graphql_content(api_client.post_graphql(query))[\"data\"][\"products\"][ \"edges\" ][0][\"node\"] product_attributes = product[\"attributes\"] variant_attributes", "len(product[\"variants\"][0][\"attributes\"]) == expected_variant_attribute_count def test_resolve_attribute_values(user_api_client, product, staff_user): \"\"\"Ensure the attribute", "== ProductErrorCode.ALREADY_EXISTS.name assert data[\"productErrors\"][0][\"field\"] == \"name\" UPDATE_ATTRIBUTE_VALUE_QUERY = \"\"\" mutation", "\"productTypeId\": product_type_global_id, \"attributeIds\": [ graphene.Node.to_global_id(\"Attribute\", product_attributes[0].pk) ], } content =", "} } } \"\"\" ) )[\"data\"][\"products\"][\"edges\"] # Ensure we are", "$operations) { errors { field message } productType { id", "permission_manage_products, product_type, ): query = CREATE_ATTRIBUTES_QUERY variables = {\"name\": \"Example", "attribute values are properly resolved when an attribute is part", "is_staff, permission_manage_products, ): \"\"\"Ensure non-staff users don't see hidden attributes,", "{ name slug } productTypes(first: 10) { edges { node", "to the attribute shouldn't be taken into account validate_value_is_unique(color_attribute, value)", "collection other_collection = Collection.objects.create( name=\"Other Collection\", slug=\"other-collection\", is_published=True, description=\"Description\", )", "== attribute_count def test_attributes_query_hidden_attribute_as_staff_user( staff_api_client, product, color_attribute, permission_manage_products ): query", "(AttributeTypeEnum.VARIANT, AttributeTypeEnum.VARIANT), ), ) def test_assign_attribute_to_product_type_having_already_that_attribute( staff_api_client, permission_manage_products, color_attribute_without_values, product_type_attribute_type,", "attribute.id) name = \"<NAME>\" variables = {\"name\": name, \"attributeId\": attribute_id}", "assert product_errors[0][\"code\"] == error_code.name UPDATE_ATTRIBUTE_QUERY = \"\"\" mutation updateAttribute( $id:", "the attribute was correctly created assert data[\"attribute\"][\"name\"] == attribute_name assert", "(\"available_in_grid\", True), (\"value_required\", False), (\"storefront_search_position\", 0), ), ) def test_retrieving_the_restricted_attributes_restricted(", "attribute to the product type if is_variant: product.product_type.variant_attributes.set([color_attribute, other_attribute]) else:", "node ID if is_variant: node_id = graphene.Node.to_global_id(\"ProductVariant\", variant.pk) else: node_id", "correctly created assert len(data[\"attribute\"][\"values\"]) == 1 assert data[\"attribute\"][\"values\"][0][\"name\"] == name", "ID!, $moves: [ReorderInput]!) { attributeReorderValues(attributeId: $attributeId, moves: $moves) { attribute", "%s: $nodeID }\" % tested_field} variables = {\"nodeID\": filtered_by_node_id} content", "validate_value_is_unique from saleor.graphql.product.types.attributes import resolve_attribute_value_type from saleor.product import AttributeInputType from", "expected_flat_attributes_data = list(expected_qs.values_list(\"slug\", flat=True)) assert flat_attributes_data == expected_flat_attributes_data CREATE_ATTRIBUTES_QUERY =", "attributes are restricted and if their default value is the", "ProductType.objects.create(name=\"Dummy Type\") product_type_id = graphene.Node.to_global_id(\"ProductType\", product_type.id) m2m_attributes = getattr(product_type, relation_field)", "name in [value[\"name\"] for value in data[\"attribute\"][\"values\"]] def test_create_attribute_value_not_unique_name( staff_api_client,", "value not associated to the given attribute.\"\"\" attribute_id = graphene.Node.to_global_id(\"Attribute\",", "10, filter: $filters) { edges { node { name slug", "): \"\"\"Sorts attributes for dashboard custom ordering inside a given", "\"The values are not properly ordered\" variables = { \"attributeId\":", "% str(size_attribute) assert errors[0][\"message\"] == err_msg product_errors = content[\"data\"][\"attributeUpdate\"][\"productErrors\"] assert", "color_attribute, is_variant ): \"\"\"Ensures the attributes of products and variants", "\"\"\" { products(first: 10) { edges { node { attributes", "{ field message } productErrors { field message code }", "other_attribute.attributeproduct.last() # Push the last attribute to the top and", "assert data[\"attribute\"][\"productTypes\"][\"edges\"] == [] def test_update_attribute_remove_and_add_values( staff_api_client, color_attribute, permission_manage_products ):", "slug } productTypes(first: 10) { edges { node { id", "node_id = graphene.Node.to_global_id(\"Product\", product.pk) # Retrieve the attributes data =", "node (product/variant), thus no values should be resolved. \"\"\" query", "= attribute.values m2m_values.set(values) assert values == sorted( values, key=lambda o:", "{\"ids\": global_ids}} expected_slugs = sorted([attribute_list[0].slug, attribute_list[1].slug]) attributes = get_graphql_content( api_client.post_graphql(ATTRIBUTES_FILTER_QUERY,", "product_attributes = product[\"attributes\"] variant_attributes = product[\"variants\"][0][\"attributes\"] assert len(product_attributes) == 2,", "permissions=[permission_manage_products] ) get_graphql_content(response) attribute.refresh_from_db() assert attribute.values.count() == 1 assert attribute.values.filter(name=attribute_value_name).exists()", "pink_attribute_value, permission_manage_products ): query = UPDATE_ATTRIBUTE_VALUE_QUERY value = pink_attribute_value.attribute.values.create( name=\"<NAME>\",", "slug=\"a\"), ] ) variables = {\"sortBy\": {\"field\": \"SLUG\", \"direction\": \"ASC\"}}", "attributes products = get_graphql_content( api_client.post_graphql( \"\"\" { products(first: 10) {", "== [ { \"field\": \"productTypeId\", \"message\": f\"Couldn't resolve to a", "product_type.id) attribute_id = graphene.Node.to_global_id(\"Attribute\", color_attribute.id) variables = { \"type\": \"VARIANT\",", "test_resolve_attribute_values_non_assigned_to_node( user_api_client, product, staff_user ): \"\"\"Ensure the attribute values are", "slugified name\" assert ( data[\"attribute\"][\"productTypes\"][\"edges\"] == [] ), \"The attribute", ") assert len(content[\"productType\"][\"variantAttributes\"]) == len( variant_attributes_ids ) found_product_attrs_ids = {", "== \"STRING\" assert name in [value[\"name\"] for value in data[\"attribute\"][\"values\"]]", "product or variant as they are not associated to them", ") query = UNASSIGN_ATTR_QUERY variables = { \"productTypeId\": product_type_global_id, \"attributeIds\":", "set if no error was expected if expected_error is None:", "test_update_attribute_and_remove_others_attribute_value( staff_api_client, color_attribute, size_attribute, permission_manage_products ): query = UPDATE_ATTRIBUTE_QUERY attribute", "m2m_values.set(values) assert values == sorted( values, key=lambda o: o.sort_order if", "and push them at the top # through a sort_order=0", "value_id = graphene.Node.to_global_id(\"AttributeValue\", attribute_value_id) variables = { \"name\": name, \"id\":", "staff_user, is_staff, permission_manage_products, ): \"\"\"Ensure non-staff users don't see hidden", "test_sort_attributes_within_product_type( staff_api_client, attribute_list, permission_manage_products, attribute_type, relation_field, backref_field, ): attributes =", "variant_attributes_ids ) found_product_attrs_ids = { int(graphene.Node.from_global_id(attr[\"id\"])[1]) for attr in content[\"productType\"][\"productAttributes\"]", "product, color_attribute, permission_manage_products ): query = QUERY_ATTRIBUTES # hide the", "has_variants=True, is_shipping_required=True ) other_product_type.product_attributes.add(other_attribute) other_product = Product.objects.create( name=f\"Another Product\", product_type=other_product_type,", "all attributes and values from the product and its variant", "tested_field} variables = {\"nodeID\": filtered_by_node_id} content = get_graphql_content(user_api_client.post_graphql(query, variables)) attributes_data", "type: $type ) { productType { id variantAttributes { id", "== mocked_qs.none.return_value @pytest.mark.parametrize(\"test_deprecated_filter\", [True, False]) @pytest.mark.parametrize(\"tested_field\", [\"inCategory\", \"inCollection\"]) def test_attributes_in_collection_query(", "-1) attribute_id = graphene.Node.to_global_id(\"Attribute\", -1) variables = { \"type\": \"VARIANT\",", "(\"#0000\", AttributeValueType.COLOR), (\"#FF69B4\", AttributeValueType.COLOR), (\"rgb(255, 0, 0)\", AttributeValueType.COLOR), (\"hsl(0, 100%,", "content = get_graphql_content( staff_api_client.post_graphql(ATTRIBUTES_RESORT_QUERY, variables) )[\"data\"][\"productTypeReorderAttributes\"] assert not content[\"errors\"] assert", "= to_camel_case(attribute) query = ( \"\"\" { attributes(first: 10) {", "variant attributes values are all None assert variant[\"attributes\"][0][\"attribute\"][\"slug\"] == \"size\"", "} \"\"\" content = get_graphql_content( user_api_client.post_graphql(query, {\"id\": attribute_gql_id}) ) assert", "UPDATE_ATTRIBUTE_QUERY attribute = color_attribute node_id = graphene.Node.to_global_id(\"Attribute\", attribute.id) size_attribute =", "Name\" variables = {\"name\": attribute_name, \"slug\": input_slug} content = get_graphql_content(staff_api_client.post_graphql(query,", "mutation createAttribute($name: String!, $values: [AttributeValueCreateInput]) { attributeCreate(input: {name: $name, values:", "{\"id\": attribute_gql_id}) ) assert content[\"data\"][\"attribute\"], \"Should have found an attribute\"", "query = UPDATE_ATTRIBUTE_VALUE_QUERY value = pink_attribute_value node_id = graphene.Node.to_global_id(\"AttributeValue\", value.id)", "content = get_graphql_content( staff_api_client.post_graphql( query, variables, permissions=[permission_manage_products] ) )[\"data\"][\"attributeUnassign\"] assert", "def test_sort_attributes_within_product_type_invalid_id( staff_api_client, permission_manage_products, color_attribute ): \"\"\"Try to reorder an", "False)) def test_attributes_of_products_are_sorted( staff_api_client, product, color_attribute, is_variant ): \"\"\"Ensures the", "1 assert data[\"attribute\"][\"values\"][0][\"name\"] == name assert data[\"attribute\"][\"values\"][0][\"slug\"] == slugify(name) @pytest.mark.parametrize(", "\"edges\" ][0][\"node\"] product_attributes = product[\"attributes\"] variant_attributes = product[\"variants\"][0][\"attributes\"] assert len(product_attributes)", "attribute_value_name}], \"removeValues\": [], } response = staff_api_client.post_graphql( query, variables, permissions=[permission_manage_products]", "allow us to make sure it is always the last", "node_id = graphene.Node.to_global_id(\"ProductVariant\", variant.pk) else: node_id = graphene.Node.to_global_id(\"Product\", product.pk) #", "m2m_attributes = getattr(product_type, relation_field) m2m_attributes.set(attributes) sort_method = getattr(m2m_attributes, f\"{relation_field}_sorted\") attributes", "{\"productTypeId\": product_type_global_id, \"operations\": operations} content = get_graphql_content(staff_api_client.post_graphql(query, variables))[ \"data\" ][\"attributeAssign\"]", "name = \"Crimson name\" variables = {\"name\": name, \"id\": node_id}", "\"message\": ( \"Attributes having for input types ['multiselect'] cannot be", "= list(expected_qs.values_list(\"slug\", flat=True)) assert flat_attributes_data == expected_flat_attributes_data CREATE_ATTRIBUTES_QUERY = \"\"\"", "['multiselect'] cannot be assigned \" \"as variant attributes\" ), }", "assert received_slugs == expected_slugs ATTRIBUTES_SORT_QUERY = \"\"\" query($sortBy: AttributeSortingInput) {", "str, m2m_model: Union[AttributeVariant, AttributeProduct], ): \"\"\"Sorts attributes for dashboard custom", "properly resolved.\"\"\" query = QUERY_PRODUCT_AND_VARIANTS_ATTRIBUTES api_client = user_api_client variant =", "== \"AttributeValue\" actual_order.append(int(gql_attr_id)) assert actual_order == expected_order ATTRIBUTES_FILTER_QUERY = \"\"\"", "\"productTypeId\", \"message\": f\"Couldn't resolve to a product type: {product_type_id}\", }", "def test_create_attribute_value_capitalized_name( staff_api_client, color_attribute, permission_manage_products ): attribute = color_attribute query", "look for this other collection other_collection = Collection.objects.create( name=\"Other Collection\",", "# Hide one product and variant attribute from the storefront", "\"\"\" mutation ProductTypeReorderAttributes( $productTypeId: ID! $moves: [ReorderInput]! $type: AttributeTypeEnum! )", "test_resolve_attributes_with_hidden( user_api_client, product, color_attribute, size_attribute, staff_user, is_staff, permission_manage_products, ): \"\"\"Ensure", "attributes\" ), } ] @pytest.mark.parametrize( \"product_type_attribute_type, gql_attribute_type\", ( (AttributeTypeEnum.PRODUCT, AttributeTypeEnum.VARIANT),", "[] ASSIGN_ATTR_QUERY = \"\"\" mutation assign($productTypeId: ID!, $operations: [AttributeAssignInput]!) {", "= Attribute.objects.create(name=\"V\", slug=\"variant\") # Create a value for each dummy", "been assigned to a product type\" # Check if the", ")[\"data\"][\"attributes\"][\"edges\"] assert len(attributes) == 2 assert attributes[0][\"node\"][\"slug\"] == \"size\" assert", "= product.variants.get() # Remove all attributes and values from the", "get_graphql_content( staff_api_client.post_graphql(ATTRIBUTE_VALUES_RESORT_QUERY, variables) )[\"data\"][\"attributeReorderValues\"] assert not content[\"errors\"] assert content[\"attribute\"][\"id\"] ==", "= {\"name\": pink_attribute_value.name, \"id\": node_id} response = staff_api_client.post_graphql( query, variables,", "content[\"productType\"][snake_to_camel_case(relation_field)] assert len(gql_attributes) == len(expected_order) for attr, expected_pk in zip(gql_attributes,", "# Assign attributes to the product node = variant if", "\"id\": graphene.Node.to_global_id(\"AttributeValue\", values[2].pk), \"sortOrder\": -1, }, ], } expected_order =", "{\"id\": node_id}))[ \"data\" ] attributes = data[\"productVariant\" if is_variant else", "if the attribute values were correctly created assert len(data[\"attribute\"][\"values\"]) ==", "def test_create_attribute_value_not_unique_name( staff_api_client, color_attribute, permission_manage_products ): attribute = color_attribute query", "= content[\"data\"][\"attributeDelete\"] assert data[\"attribute\"][\"id\"] == variables[\"id\"] with pytest.raises(attribute._meta.model.DoesNotExist): attribute.refresh_from_db() CREATE_ATTRIBUTE_VALUE_QUERY", "= get_graphql_content(user_api_client.post_graphql(query, variables)) attributes_data = content[\"data\"][\"attributes\"][\"edges\"] flat_attributes_data = [attr[\"node\"][\"slug\"] for", "value but with existing slug should raise an error with", "= \"<NAME>\" name = \"Value name\" variables = {\"name\": attribute_name,", "} variants { attributes { attribute { slug } values", "variant_attribute_values[0] def test_resolve_attribute_values_non_assigned_to_node( user_api_client, product, staff_user ): \"\"\"Ensure the attribute", "== expected_pk ATTRIBUTE_VALUES_RESORT_QUERY = \"\"\" mutation attributeReorderValues($attributeId: ID!, $moves: [ReorderInput]!)", "1 # Retrieve the nodes data product = products[0][\"node\"] variant", "{\"type\": \"VARIANT\", \"id\": graphene.Node.to_global_id(\"Attribute\", attr_id)} ) content = get_graphql_content( staff_api_client.post_graphql(", "AttributeValue(slug=\"b\", name=\"B\", attribute=unassigned_product_attribute), ] ) # Assign the dummy attributes", "attribute { id } } } } \"\"\" # Create", "product type but not of the node (product/variant), thus no", "may be missing\" assert len(variant_attributes) == 2, \"Non-assigned attr from", "errors { field message } attributeValue { name slug }", "test_assign_attribute_to_product_type_having_already_that_attribute( staff_api_client, permission_manage_products, color_attribute_without_values, product_type_attribute_type, gql_attribute_type, ): \"\"\"The assignAttribute mutation", "== AttributeTypeEnum.PRODUCT: product_type.product_attributes.add(attribute) elif product_type_attribute_type == AttributeTypeEnum.VARIANT: product_type.variant_attributes.add(attribute) else: raise", "slug=\"other-cat\") other_attribute = Attribute.objects.create(name=\"Other\", slug=\"other\") other_product_type = ProductType.objects.create( name=\"Other type\",", "attributes[0].pk), \"sortOrder\": +1, }, { \"id\": graphene.Node.to_global_id(\"Attribute\", attributes[2].pk), \"sortOrder\": -1,", ") from saleor.product.utils.attributes import associate_attribute_values_to_instance from tests.api.utils import get_graphql_content def", "= ProductType.objects.create( name=\"Other type\", has_variants=True, is_shipping_required=True ) other_product_type.product_attributes.add(other_attribute) other_product =", "= CREATE_ATTRIBUTES_QUERY variables = {\"name\": \"Example name\", \"values\": [{\"name\": name_1},", "): attribute = color_attribute query = \"\"\" mutation deleteAttribute($id: ID!)", "is qs assert filter_attributes_by_product_types(qs, \"...\", None) is qs def test_attributes_filter_by_product_type_with_unsupported_field():", "\"color\" assert product_attributes[0][\"values\"][0][\"slug\"] == product_attribute_values[0] assert product_attributes[0][\"value\"][\"slug\"] == product_attribute_values[0] assert", "{attribute_id}\", } ] def test_sort_values_within_attribute_invalid_id( staff_api_client, permission_manage_products, color_attribute ): \"\"\"Try", "variables = {\"name\": name, \"id\": node_id} response = staff_api_client.post_graphql( query,", "color_attribute, AttributeValue(slug=\"spanish-inquisition\") ) # value that already belongs to the", "slug } } } \"\"\" def test_create_attribute_value( staff_api_client, color_attribute, permission_manage_products", "None, [{\"field\": \"slug\", \"message\": \"The attribute's slug cannot be blank.\"}],", "$type: AttributeTypeEnum! ) { productTypeReorderAttributes( productTypeId: $productTypeId moves: $moves type:", "= ProductType.objects.create(name=\"Type\") attribute = color_attribute_without_values staff_api_client.user.user_permissions.add(permission_manage_products) product_type_global_id = graphene.Node.to_global_id(\"ProductType\", product_type.pk)", "# Retrieve the M2M object for the attribute vs the", "operations} product_attributes_ids = {attr.pk for attr in attribute_list[:2]} variant_attributes_ids =", "AttributeTypeEnum! ) { productTypeReorderAttributes( productTypeId: $productTypeId moves: $moves type: $type", "content[\"data\"][\"attributeUpdate\"][\"productErrors\"] assert product_errors[0][\"code\"] == error_code.name def test_update_attribute_and_remove_others_attribute_value( staff_api_client, color_attribute, size_attribute,", "= product.variants.first() assert product.attributes.count() == 1 assert variant.attributes.count() == 1", "query, variables, permissions=[permission_manage_products] ) content = get_graphql_content(response) data = content[\"data\"][\"attributeValueCreate\"]", "graphene.Node.to_global_id(\"Attribute\", attribute.id) name = \"<NAME>\" variables = {\"name\": name, \"attributeId\":", "= graphene.Node.to_global_id(\"ProductType\", product_type.pk) query = ASSIGN_ATTR_QUERY operations = [ {\"type\":", "\"VARIANT\", \"productTypeId\": product_type_id, \"moves\": [{\"id\": attribute_id, \"sortOrder\": 1}], } content", "len(attributes_data) == attributes.count() def test_attributes_query_hidden_attribute(user_api_client, product, color_attribute): query = QUERY_ATTRIBUTES", "product_attribute = color_attribute variant_attribute = size_attribute expected_product_attribute_count = product.attributes.count() -", "= get_graphql_content( staff_api_client.post_graphql( query, variables, permissions=[permission_manage_products] ) )[\"data\"][\"attributeUnassign\"] assert not", "len(variant_attributes) == 2, \"Non-assigned attr from the PT may be", "Product, ProductType, ProductVariant, ) from saleor.product.utils.attributes import associate_attribute_values_to_instance from tests.api.utils", "20, %(filter_input)s) { edges { node { id name slug", "def test_delete_attribute( staff_api_client, color_attribute, permission_manage_products, product_type ): attribute = color_attribute", "test_retrieve_product_attributes_input_type( staff_api_client, product, permission_manage_products ): query = \"\"\" { products(first:", "name slug } } } \"\"\" node_id = graphene.Node.to_global_id(\"AttributeValue\", value.id)", "the correct product type\" gql_attributes = content[\"productType\"][snake_to_camel_case(relation_field)] assert len(gql_attributes) ==", "values from the product and its variant product.attributesrelated.clear() variant.attributesrelated.clear() #", "are all None assert variant[\"attributes\"][0][\"attribute\"][\"slug\"] == \"size\" assert variant[\"attributes\"][0][\"values\"] ==", "variables) )[\"data\"][\"productTypeReorderAttributes\"] assert not content[\"errors\"] assert ( content[\"productType\"][\"id\"] == product_type_id", "Attribute.objects.get_visible_to_user( user_api_client.user ).count() assert attribute_count == 1 response = user_api_client.post_graphql(query)", "color\", \"red color\", \"Provided values are not unique.\", ProductErrorCode.UNIQUE, ),", "test_deprecated_filter: query = query % {\"filter_input\": f\"{tested_field}: $nodeID\"} else: query", "= color_attribute AttributeValue.objects.create(attribute=attribute, name=\"Green\", slug=\"green\") values = list(attribute.values.all()) assert len(values)", "operations.append( {\"type\": \"VARIANT\", \"id\": graphene.Node.to_global_id(\"Attribute\", attr_id)} ) content = get_graphql_content(", "assert gql_type == \"AttributeValue\" actual_order.append(int(gql_attr_id)) assert actual_order == expected_order ATTRIBUTES_FILTER_QUERY", "attributes[0][\"node\"][\"slug\"] == \"size\" def test_filter_attributes_by_global_id_list(api_client, attribute_list): global_ids = [ graphene.Node.to_global_id(\"Attribute\",", "= \"<NAME>\" variables = {\"name\": name, \"attributeId\": attribute_id} response =", "query, variables, permissions=[permission_manage_products] ) )[\"data\"][\"attributeAssign\"] assert not content[\"errors\"], \"Should have", "\"a\" assert attributes[1][\"node\"][\"slug\"] == \"b\" @pytest.mark.parametrize( \"sort_field, m2m_model\", ( (\"DASHBOARD_VARIANT_POSITION\",", "{ field message } } } \"\"\" def test_sort_values_within_attribute_invalid_product_type( staff_api_client,", "\"\"\" mutation createAttributeValue( $attributeId: ID!, $name: String!) { attributeValueCreate( attribute:", "{ slug } values { name } } } }", "len(variant_attributes) == len(variant_attribute_values) assert product_attributes[0][\"attribute\"][\"slug\"] == \"color\" assert product_attributes[0][\"values\"][0][\"slug\"] ==", "= user_api_client.post_graphql(query) content = get_graphql_content(response) attributes_data = content[\"data\"][\"attributes\"][\"edges\"] assert len(attributes_data)", "(product_attribute, variant_attribute): attribute.visible_in_storefront = False attribute.save(update_fields=[\"visible_in_storefront\"]) product = get_graphql_content(api_client.post_graphql(query))[\"data\"][\"products\"][ \"edges\"", "\"Value name\" variables = {\"name\": attribute_name, \"values\": [{\"name\": name}]} response", "def test_assign_attribute_to_product_type_having_already_that_attribute( staff_api_client, permission_manage_products, color_attribute_without_values, product_type_attribute_type, gql_attribute_type, ): \"\"\"The assignAttribute", "attributes[0][\"node\"][\"slug\"] == \"size\" assert attributes[1][\"node\"][\"slug\"] == \"color\" def test_sort_attributes_by_default_sorting(api_client): \"\"\"Don't", "graphene.Node.to_global_id(\"AttributeValue\", value.id) name = \"Crimson name\" variables = {\"name\": name,", "== \"b\" @pytest.mark.parametrize( \"sort_field, m2m_model\", ( (\"DASHBOARD_VARIANT_POSITION\", AttributeVariant), (\"DASHBOARD_PRODUCT_POSITION\", AttributeProduct),", "be resolved. \"\"\" query = QUERY_PRODUCT_AND_VARIANTS_ATTRIBUTES api_client = user_api_client variant", "to filter attributes by raises a NotImplemented exception. \"\"\" qs", "ProductErrorCode.UNIQUE, ), ), ) def test_create_attribute_and_attribute_values_errors( staff_api_client, name_1, name_2, error_msg,", "\"Attribute\", color_attribute_without_values.id ) query = \"\"\" query($id: ID!) { attribute(id:", "$id, input: { name: $name, addValues: $addValues, removeValues: $removeValues}) {", "True), (\"visible_in_storefront\", True), (\"available_in_grid\", True), (\"value_required\", False), (\"storefront_search_position\", 0), ),", "= get_graphql_content( api_client.post_graphql(ATTRIBUTES_FILTER_QUERY, variables) )[\"data\"][\"attributes\"][\"edges\"] assert len(attributes) == 2 received_slugs", "name\" assert ( data[\"attribute\"][\"productTypes\"][\"edges\"] == [] ), \"The attribute should", "\"type\": gql_attribute_type.value, \"id\": graphene.Node.to_global_id(\"Attribute\", attribute.pk), } ] variables = {\"productTypeId\":", "in this product type.\", } ] def test_assign_variant_attribute_having_unsupported_input_type( staff_api_client, permission_manage_products,", "attributeUpdate( id: $id, input: { name: $name, addValues: $addValues, removeValues:", "content[\"attribute\"][\"id\"] == attribute_id gql_values = content[\"attribute\"][\"values\"] assert len(gql_values) == len(expected_order)", "reorder an invalid attribute (invalid ID).\"\"\" attribute_id = graphene.Node.to_global_id(\"Attribute\", -1)", ") content = get_graphql_content(response) data = content[\"data\"][\"attributeValueUpdate\"] assert data[\"errors\"] assert", "to use an attribute as a variant attribute when the", "variant = product.variants.first() if is_variant: query = \"\"\" query($id: ID!)", "resolved. \"\"\" query = QUERY_PRODUCT_AND_VARIANTS_ATTRIBUTES api_client = user_api_client variant =", "tested_field, ): if \"Collection\" in tested_field: filtered_by_node_id = graphene.Node.to_global_id(\"Collection\", collection.pk)", "0 def test_retrieve_product_attributes_input_type( staff_api_client, product, permission_manage_products ): query = \"\"\"", "staff_user.user_permissions.add(permission_manage_products) # Hide one product and variant attribute from the", "tested_field: filtered_by_node_id = graphene.Node.to_global_id(\"Collection\", collection.pk) elif \"Category\" in tested_field: filtered_by_node_id", "category_id) assert qs == mocked_qs.none.return_value @pytest.mark.parametrize(\"test_deprecated_filter\", [True, False]) @pytest.mark.parametrize(\"tested_field\", [\"inCategory\",", "= UPDATE_ATTRIBUTE_QUERY attribute = color_attribute name = \"<NAME>\" node_id =", "id } } } } } } \"\"\" def test_update_attribute_name(", "node_id = graphene.Node.to_global_id(\"AttributeValue\", value.id) variables = {\"id\": node_id} staff_api_client.post_graphql( query,", "content = get_graphql_content( staff_api_client.post_graphql( query, variables, permissions=[permission_manage_products] ) )[\"data\"][\"attributeAssign\"] assert", "when trying to add an attribute as a variant attribute", "AttributeTypeEnum.PRODUCT), (AttributeTypeEnum.PRODUCT, AttributeTypeEnum.PRODUCT), (AttributeTypeEnum.VARIANT, AttributeTypeEnum.VARIANT), ), ) def test_assign_attribute_to_product_type_having_already_that_attribute( staff_api_client,", "{attr.pk for attr in attribute_list[:2]} variant_attributes_ids = {attr.pk for attr", "assert attribute_count == 1 response = user_api_client.post_graphql(query) content = get_graphql_content(response)", "@pytest.mark.parametrize(\"is_staff\", (False, True)) def test_resolve_attributes_with_hidden( user_api_client, product, color_attribute, size_attribute, staff_user,", "pass validate_value_is_unique( color_attribute, AttributeValue(slug=\"spanish-inquisition\") ) # value that already belongs", "assert len(content[\"productType\"][\"variantAttributes\"]) == 1 assert ( content[\"productType\"][\"productAttributes\"][0][\"id\"] == remaining_attribute_global_id )", "AttributeValueType.COLOR), (\"http://example.com\", AttributeValueType.URL), (\"https://example.com\", AttributeValueType.URL), (\"ftp://example.com\", AttributeValueType.URL), (\"example.com\", AttributeValueType.STRING), (\"Foo\",", "directly associated to it. \"\"\" # Retrieve the product's variant", "[ { \"type\": gql_attribute_type.value, \"id\": graphene.Node.to_global_id(\"Attribute\", attribute.pk), } ] variables", "} attribute { values { name } } attributeValue {", "{ %s } } } } \"\"\" % attribute )", "product type\" gql_attributes = content[\"productType\"][snake_to_camel_case(relation_field)] assert len(gql_attributes) == len(expected_order) for", "sure the query is actually passing the test. other_attribute =", "variant[\"attributes\"][0][\"values\"] == [] ASSIGN_ATTR_QUERY = \"\"\" mutation assign($productTypeId: ID!, $operations:", "{ name } } } } \"\"\" def test_update_attribute_value( staff_api_client,", "] # Compare the received data against our expectations assert", "modification. \"\"\" qs = Attribute.objects.all() assert filter_attributes_by_product_types(qs, \"...\", \"\") is", "= variant.attributes.count() - 1 if is_staff: api_client.user = staff_user expected_product_attribute_count", "id slug } } \"\"\" content = get_graphql_content( user_api_client.post_graphql(query, {\"id\":", "[] assert variant_attributes[0][\"value\"] is None assert variant_attributes[0][\"attribute\"][\"slug\"] == \"variant\" assert", "[ graphene.Node.to_global_id(\"Attribute\", attribute.pk) for attribute in attribute_list[:2] ] variables =", "[values[1].pk, values[2].pk, values[0].pk] content = get_graphql_content( staff_api_client.post_graphql(ATTRIBUTE_VALUES_RESORT_QUERY, variables) )[\"data\"][\"attributeReorderValues\"] assert", "Retrieve the nodes data product = products[0][\"node\"] variant = product[\"variants\"][0]", "= Attribute.objects.create(name=\"Other\", slug=\"other\") # Add the attribute to the product", "new value with a new slug should pass validate_value_is_unique( color_attribute,", "permission_manage_products ): \"\"\"Try to reorder an invalid attribute (invalid ID).\"\"\"", "saleor.graphql.product.filters import filter_attributes_by_product_types from saleor.graphql.product.mutations.attributes import validate_value_is_unique from saleor.graphql.product.types.attributes import", "not directly associated to it. \"\"\" # Retrieve the product's", "== \"a\" @pytest.mark.parametrize(\"is_variant\", (True, False)) def test_attributes_of_products_are_sorted( staff_api_client, product, color_attribute,", "id } } } } \"\"\" else: query = \"\"\"", "this product type.\", } ] def test_assign_variant_attribute_having_unsupported_input_type( staff_api_client, permission_manage_products, product_type,", "staff_api_client, permission_manage_products, color_attribute_without_values ): \"\"\"The unAssignAttribute mutation should not raise", "%s does not belong to this attribute.\" % str(size_attribute) assert", "# The user should now be able to see the", "Category, Collection, Product, ProductType, ProductVariant, ) from saleor.product.utils.attributes import associate_attribute_values_to_instance", "product_type_global_id = graphene.Node.to_global_id(\"ProductType\", product_type.pk) variant_attribute, *product_attributes = attribute_list product_type.product_attributes.add(*product_attributes) product_type.variant_attributes.add(variant_attribute)", "the given product type.\"\"\" product_type = ProductType.objects.create(name=\"Dummy Type\") product_type_id =", "expected_order = [attributes[1].pk, attributes[2].pk, attributes[0].pk] content = get_graphql_content( staff_api_client.post_graphql(ATTRIBUTES_RESORT_QUERY, variables)", "1 assert product[\"attributes\"][0][\"attribute\"][\"slug\"] == \"color\" assert product[\"attributes\"][0][\"values\"] == [] #", "if is_variant: m2m_rel_other_attr = other_attribute.attributevariant.last() else: m2m_rel_other_attr = other_attribute.attributeproduct.last() #", "def test_sort_values_within_attribute_invalid_id( staff_api_client, permission_manage_products, color_attribute ): \"\"\"Try to reorder a", "associate_attribute_values_to_instance( node, color_attribute, color_attribute.values.first() ) # Sort the database attributes", "(None, \"my-name\", []), ( \"\", None, [{\"field\": \"slug\", \"message\": \"The", "} } } } } \"\"\" def test_create_attribute_and_attribute_values( staff_api_client, permission_manage_products", "name\", \"values\": [{\"name\": name_1}, {\"name\": name_2}]} response = staff_api_client.post_graphql( query,", "variant product.attributesrelated.clear() variant.attributesrelated.clear() # Retrieve the product and variant's attributes", "for attribute in attribute_list[:2] ] variables = {\"filters\": {\"ids\": global_ids}}", "== \"product\" assert product_attributes[0][\"values\"] == [] assert variant_attributes[0][\"value\"] is None", "\"filter: { %s: $nodeID }\" % tested_field} variables = {\"nodeID\":", "= Attribute.objects.get_visible_to_user( user_api_client.user ).count() assert attribute_count == 1 response =", "we don't look for this other collection other_collection = Collection.objects.create(", "name = \"<NAME>\" attribute_value_name = \"Red Color\" node_id = graphene.Node.to_global_id(\"Attribute\",", "graphene.Node.to_global_id(\"ProductVariant\", variant.pk) else: node_id = graphene.Node.to_global_id(\"Product\", product.pk) # Retrieve the", "== \"name\" def test_create_attribute_value_capitalized_name( staff_api_client, color_attribute, permission_manage_products ): attribute =", "name, \"id\": node_id, \"addValues\": [], \"removeValues\": []} response = staff_api_client.post_graphql(", "= { \"name\": \"Example name\", \"id\": node_id, \"removeValues\": [], \"addValues\":", "name=\"B\", attribute=unassigned_product_attribute), ] ) # Assign the dummy attributes to", "expected_error, ): staff_api_client.user.user_permissions.add(permission_manage_products) query = \"\"\" mutation createAttribute( $name: String!,", "filtered_by_node_id} content = get_graphql_content(user_api_client.post_graphql(query, variables)) attributes_data = content[\"data\"][\"attributes\"][\"edges\"] flat_attributes_data =", ") content = get_graphql_content(response) data = content[\"data\"][\"attributeValueUpdate\"] value.refresh_from_db() assert data[\"attributeValue\"][\"name\"]", "test_attributes_of_products_are_sorted( staff_api_client, product, color_attribute, is_variant ): \"\"\"Ensures the attributes of", "query = query % {\"filter_input\": \"filter: { %s: $nodeID }\"", "1 product_attribute_values = list( product.attributes.first().values.values_list(\"slug\", flat=True) ) variant_attribute_values = list(", "$attributeIds: [ID]! ) { attributeUnassign(productTypeId: $productTypeId, attributeIds: $attributeIds) { errors", "sorted by ID. Thus, we are sure the query is", "mock import graphene import pytest from django.core.exceptions import ValidationError from", "attribute_list ): product_type = ProductType.objects.create(name=\"Type\") product_type_global_id = graphene.Node.to_global_id(\"ProductType\", product_type.pk) variant_attribute,", "== error_msg product_errors = content[\"data\"][\"attributeCreate\"][\"productErrors\"] assert product_errors[0][\"code\"] == error_code.name UPDATE_ATTRIBUTE_QUERY", "graphene.Node.to_global_id(\"Attribute\", attribute.id) size_attribute = size_attribute.values.first() attr_id = graphene.Node.to_global_id(\"AttributeValue\", size_attribute.pk) variables", "} } \"\"\" def test_update_attribute_name( staff_api_client, color_attribute, permission_manage_products ): query", "query = \"\"\" query($id: ID!) { productVariant(id: $id) { attributes", "the attributes data = get_graphql_content(staff_api_client.post_graphql(query, {\"id\": node_id}))[ \"data\" ] attributes", "api_client.post_graphql(ATTRIBUTES_SORT_QUERY, {}) )[\"data\"][\"attributes\"][\"edges\"] assert len(attributes) == 2 assert attributes[0][\"node\"][\"slug\"] ==", "yellow)\", AttributeValueType.GRADIENT), (\"radial-gradient(#0000, yellow)\", AttributeValueType.GRADIENT), ], ) def test_resolve_attribute_value_type(raw_value, expected_type):", "query = \"\"\" query($id: ID!) { attribute(id: $id) { id", "slug=\"b\"), Attribute(name=\"B\", slug=\"a\")] ) attributes = get_graphql_content( api_client.post_graphql(ATTRIBUTES_SORT_QUERY, {}) )[\"data\"][\"attributes\"][\"edges\"]", "UPDATE_ATTRIBUTE_VALUE_QUERY value = pink_attribute_value node_id = graphene.Node.to_global_id(\"AttributeValue\", value.id) name =", "): \"\"\"Ensures the attributes of products and variants are sorted.\"\"\"", "gql_type == \"Attribute\" assert int(gql_attr_id) == expected_pk ATTRIBUTE_VALUES_RESORT_QUERY = \"\"\"", "or variant as they are not associated to them AttributeValue.objects.bulk_create(", "message code } attribute { values { name } }", "= get_graphql_content(api_client.post_graphql(query))[\"data\"][\"products\"][ \"edges\" ][0][\"node\"] product_attributes = product[\"attributes\"] variant_attributes = product[\"variants\"][0][\"attributes\"]", "len(attributes) == 1 assert attributes[0][\"node\"][\"slug\"] == \"size\" def test_filter_attributes_by_global_id_list(api_client, attribute_list):", "product_type_id = graphene.Node.to_global_id(\"ProductType\", product_type.id) attribute_id = graphene.Node.to_global_id(\"Attribute\", color_attribute.id) variables =", "$addValues: [AttributeValueCreateInput]!, $removeValues: [ID]!) { attributeUpdate( id: $id, input: {", "= \"Crimson name\" variables = {\"name\": name, \"id\": node_id} response", "AttributeValue, AttributeVariant, Category, Collection, Product, ProductType, ProductVariant, ) from saleor.product.utils.attributes", "getattr(m2m_attributes, f\"{relation_field}_sorted\") attributes = list(sort_method()) assert len(attributes) == 3 variables", "= get_graphql_content(staff_api_client.post_graphql(query, variables)) # Check if the error is as", "assert not data[\"productErrors\"] attr_data = data[\"attributeValue\"] assert attr_data[\"name\"] == name", "attribute_id} response = staff_api_client.post_graphql( query, variables, permissions=[permission_manage_products] ) content =", "type.\", } ] def test_assign_variant_attribute_having_unsupported_input_type( staff_api_client, permission_manage_products, product_type, size_attribute ):", "values { name } } } } \"\"\" def test_update_attribute_value(", "\"name\": \"Example name\", \"id\": node_id, \"slug\": \"example-slug\", \"addValues\": [], \"removeValues\":", "attribute(id: $id) { id slug } } \"\"\" content =", "the dummy attributes to the product type and push them", "in data[\"attribute\"][\"values\"]] def test_update_attribute_value_name_not_unique( staff_api_client, pink_attribute_value, permission_manage_products ): query =", "== \"size\" def test_filter_attributes_if_available_in_grid( api_client, color_attribute, size_attribute ): color_attribute.available_in_grid =", "UPDATE_ATTRIBUTE_QUERY attribute = color_attribute name = \"<NAME>\" attribute_value_name = \"Red", "operations = [ { \"type\": gql_attribute_type.value, \"id\": graphene.Node.to_global_id(\"Attribute\", attribute.pk), }", "content[\"data\"][\"attributeValueCreate\"] assert not data[\"productErrors\"] attr_data = data[\"attributeValue\"] assert attr_data[\"name\"] ==", "content[\"errors\"] assert content[\"attribute\"][\"id\"] == attribute_id gql_values = content[\"attribute\"][\"values\"] assert len(gql_values)", "test_sort_attributes_by_position_in_product_type( api_client, color_attribute, size_attribute, sort_field: str, m2m_model: Union[AttributeVariant, AttributeProduct], ):", "attribute.refresh_from_db() data = content[\"data\"][\"attributeUpdate\"] assert data[\"attribute\"][\"name\"] == name == attribute.name", "only working on one product and variant, the ones we", "their sort order and ID (when None) expected_order = [other_attribute.pk,", "user doesn't have the permission yet to manage products, #", "values { slug } value { slug } } variants", "# Retrieve the product and variant's attributes products = get_graphql_content(", "slug=\"other-collection\", is_published=True, description=\"Description\", ) other_collection.products.add(other_product) query = \"\"\" query($nodeID: ID!)", "== [ { \"field\": \"operations\", \"message\": \"Color (color) have already", "= {\"filters\": {\"search\": \"color\"}} attributes = get_graphql_content( api_client.post_graphql(ATTRIBUTES_FILTER_QUERY, variables) )[\"data\"][\"attributes\"][\"edges\"]", "the 'manage product' permission can. \"\"\" query = QUERY_PRODUCT_AND_VARIANTS_ATTRIBUTES api_client", "in [value[\"name\"] for value in data[\"attribute\"][\"values\"]] def test_update_attribute_value_name_not_unique( staff_api_client, pink_attribute_value,", "values { name } } } } } } }", "Check if the slug was correctly set if no error", "variants\"\"\" product_type = product_type_without_variant attribute = color_attribute_without_values staff_api_client.user.user_permissions.add(permission_manage_products) product_type_global_id =", "\"edges\" ][0][\"node\"] assert len(product[\"attributes\"]) == expected_product_attribute_count assert len(product[\"variants\"][0][\"attributes\"]) == expected_variant_attribute_count", "products(first: 10) { edges { node { attributes { values", "== \"size\" assert attributes[1][\"node\"][\"slug\"] == \"color\" def test_sort_attributes_by_default_sorting(api_client): \"\"\"Don't provide", "\"\"\"Checks if the attributes are restricted and if their default", "( Attribute, AttributeProduct, AttributeValue, AttributeVariant, Category, Collection, Product, ProductType, ProductVariant,", "= get_graphql_content(response) attributes_data = content[\"data\"][\"attributes\"][\"edges\"] assert len(attributes_data) == attribute_count QUERY_PRODUCT_AND_VARIANTS_ATTRIBUTES", "having the 'manage product' permission can. \"\"\" query = QUERY_PRODUCT_AND_VARIANTS_ATTRIBUTES", "error_code, permission_manage_products, product_type, ): query = CREATE_ATTRIBUTES_QUERY variables = {\"name\":", "{ node { name slug } } } } \"\"\"", "[ { \"field\": \"operations\", \"message\": ( \"Attributes having for input", "= [ {\"type\": \"VARIANT\", \"id\": graphene.Node.to_global_id(\"Attribute\", attribute.pk)} ] variables =", "contained in the product type.\"\"\" product_type = ProductType.objects.create(name=\"Type\") attribute =", "[ { \"field\": \"moves\", \"message\": f\"Couldn't resolve to an attribute:", "test_attributes_query_hidden_attribute_as_staff_user( staff_api_client, product, color_attribute, permission_manage_products ): query = QUERY_ATTRIBUTES #", "): value = color_attribute.values.get(name=\"Red\") query = \"\"\" mutation updateChoice($id: ID!)", "product_errors = content[\"data\"][\"attributeUpdate\"][\"productErrors\"] assert product_errors[0][\"code\"] == ProductErrorCode.INVALID.name def test_delete_attribute( staff_api_client,", ") # Sort the database attributes by their sort order", "= \"\"\" mutation createAttributeValue( $attributeId: ID!, $name: String!) { attributeValueCreate(", "ProductErrorCode.INVALID.name def test_delete_attribute( staff_api_client, color_attribute, permission_manage_products, product_type ): attribute =", "} } } \"\"\" def test_update_attribute_value( staff_api_client, pink_attribute_value, permission_manage_products ):", "let the others to None m2m_rel_other_attr.sort_order = 0 m2m_rel_other_attr.save(update_fields=[\"sort_order\"]) #", "== \"a\" assert attributes[1][\"node\"][\"slug\"] == \"b\" @pytest.mark.parametrize( \"sort_field, m2m_model\", (", "values: $values}) { errors { field message } productErrors {", "name } } } } \"\"\" def test_update_attribute_value( staff_api_client, pink_attribute_value,", "assert gql_attr[\"values\"][0][\"type\"] == \"STRING\" assert gql_attr[\"values\"][0][\"inputType\"] == \"DROPDOWN\" @pytest.mark.parametrize( \"attribute,", "input_slug} content = get_graphql_content(staff_api_client.post_graphql(query, variables)) # Check if the error", "[\"inCategory\", \"inCollection\"]) def test_attributes_in_collection_query( user_api_client, product_type, category, collection, collection_with_products, test_deprecated_filter,", "attribute.id) variables = { \"name\": name, \"id\": node_id, \"addValues\": [{\"name\":", "attribute.id) attribute_value_id = attribute.values.first().id value_id = graphene.Node.to_global_id(\"AttributeValue\", attribute_value_id) variables =", "name, \"id\": node_id} response = staff_api_client.post_graphql( query, variables, permissions=[permission_manage_products] )", "== name == value.name assert data[\"attributeValue\"][\"slug\"] == slugify(name) assert name", "attribute = color_attribute name = \"<NAME>\" node_id = graphene.Node.to_global_id(\"Attribute\", attribute.id)", "): query = \"\"\" { products(first: 10) { edges {", "name = \"<NAME>\" node_id = graphene.Node.to_global_id(\"Attribute\", attribute.id) variables = {\"name\":", "\"\"\"Try to reorder an attribute not associated to the given", "2 assert attributes[0][\"node\"][\"slug\"] == \"size\" assert attributes[1][\"node\"][\"slug\"] == \"color\" def", "\"moves\": [{\"id\": value_id, \"sortOrder\": 1}], } content = get_graphql_content( staff_api_client.post_graphql(", "content[\"data\"][\"attributeCreate\"][\"attribute\"][\"slug\"] == expected_slug @pytest.mark.parametrize( \"name_1, name_2, error_msg, error_code\", ( (", "\"data\" ][\"attributeUnassign\"] assert not content[\"errors\"] assert content[\"productType\"][\"id\"] == product_type_global_id assert", "slug=\"other\") other_product_type = ProductType.objects.create( name=\"Other type\", has_variants=True, is_shipping_required=True ) other_product_type.product_attributes.add(other_attribute)", "by name by default.\"\"\" Attribute.objects.bulk_create( [Attribute(name=\"A\", slug=\"b\"), Attribute(name=\"B\", slug=\"a\")] )", "get_graphql_content(response) data = content[\"data\"][\"attributeValueCreate\"] assert data[\"productErrors\"] assert data[\"productErrors\"][0][\"code\"] == ProductErrorCode.ALREADY_EXISTS.name", "the user shouldn't be able to see the hidden attributes", "variant as they are not associated to them AttributeValue.objects.bulk_create( [", "int(graphene.Node.from_global_id(attr[\"id\"])[1]) for attr in content[\"productType\"][\"productAttributes\"] } found_variant_attrs_ids = { int(graphene.Node.from_global_id(attr[\"id\"])[1])", "graphene.Node.to_global_id(\"AttributeValue\", -1) variables = { \"attributeId\": attribute_id, \"moves\": [{\"id\": value_id,", "( (\"VARIANT\", \"variant_attributes\", \"attributevariant\"), (\"PRODUCT\", \"product_attributes\", \"attributeproduct\"), ), ) def", "attributes[2].pk), \"sortOrder\": -1, }, ], } expected_order = [attributes[1].pk, attributes[2].pk,", "message code } attribute { name slug values { name", "[attr_id], } response = staff_api_client.post_graphql( query, variables, permissions=[permission_manage_products] ) content", "product_type.id) m2m_attributes = getattr(product_type, relation_field) m2m_attributes.set(attributes) sort_method = getattr(m2m_attributes, f\"{relation_field}_sorted\")", "= list(attribute.values.all()) assert len(values) == 3 staff_api_client.user.user_permissions.add(permission_manage_products) attribute_id = graphene.Node.to_global_id(\"Attribute\",", "= UPDATE_ATTRIBUTE_QUERY attribute = color_attribute node_id = graphene.Node.to_global_id(\"Attribute\", attribute.id) variables", "is the expected one.\"\"\" attribute = to_camel_case(attribute) query = (", "== name == attribute.name assert data[\"attribute\"][\"productTypes\"][\"edges\"] == [] def test_update_attribute_remove_and_add_values(", "content[\"data\"][\"attributes\"][\"edges\"] flat_attributes_data = [attr[\"node\"][\"slug\"] for attr in attributes_data] expected_flat_attributes_data =", "= QUERY_ATTRIBUTES response = user_api_client.post_graphql(query) content = get_graphql_content(response) attributes_data =", "{name: $name, values: $values}) { errors { field message }", "qs = Attribute.objects.all() assert filter_attributes_by_product_types(qs, \"...\", \"\") is qs assert", "{ attributeValueCreate( attribute: $attributeId, input: {name: $name}) { productErrors {", "graphene.Node.to_global_id(\"Attribute\", -1) variables = { \"type\": \"VARIANT\", \"productTypeId\": product_type_id, \"moves\":", "\"sort_field, m2m_model\", ( (\"DASHBOARD_VARIANT_POSITION\", AttributeVariant), (\"DASHBOARD_PRODUCT_POSITION\", AttributeProduct), ), ) def", "name_2, error_msg, error_code\", ( ( \"Red color\", \"Red color\", \"Provided", "attribute.name assert not attribute.values.filter(pk=attribute_value_id).exists() assert attribute.values.filter(name=attribute_value_name).exists() def test_update_empty_attribute_and_add_values( staff_api_client, color_attribute_without_values,", "} \"\"\" def test_update_attribute_value( staff_api_client, pink_attribute_value, permission_manage_products ): query =", "edges { node { slug } } } } \"\"\"", "10) { edges { node { id } } }", "product_type = ProductType.objects.create(name=\"Type\") product_type_global_id = graphene.Node.to_global_id(\"ProductType\", product_type.pk) variant_attribute, *product_attributes =", "product_type = ProductType.objects.create(name=\"My Product Type\") m2m_model.objects.create( product_type=product_type, attribute=color_attribute, sort_order=0 )", "node_id = graphene.Node.to_global_id(\"Attribute\", attribute.id) variables = {\"name\": name, \"id\": node_id,", "len(content[\"productType\"][\"variantAttributes\"]) == 0 def test_retrieve_product_attributes_input_type( staff_api_client, product, permission_manage_products ): query", "$name: String!, $slug: String) { attributeCreate(input: {name: $name, slug: $slug})", "attributes[0][\"node\"][\"slug\"] == \"b\" assert attributes[1][\"node\"][\"slug\"] == \"a\" @pytest.mark.parametrize(\"is_variant\", (True, False))", "product[\"attributes\"][0][\"values\"] == [] # Ensure the variant attributes values are", "attribute.values.filter(name=attribute_value_name).exists() @pytest.mark.parametrize( \"name_1, name_2, error_msg, error_code\", ( ( \"Red color\",", "value.id) name = \"Crimson name\" variables = {\"name\": name, \"id\":", "assert len(attributes) == 2 assert attributes[0][\"node\"][\"slug\"] == \"size\" assert attributes[1][\"node\"][\"slug\"]", "permissions=[permission_manage_products] ) content = get_graphql_content(response) data = content[\"data\"][\"attributeDelete\"] assert data[\"attribute\"][\"id\"]", "attribute_id, \"sortOrder\": 1}], } content = get_graphql_content( staff_api_client.post_graphql( ATTRIBUTES_RESORT_QUERY, variables,", "cannot be blank.\"}], ), ), ) def test_create_attribute_with_given_slug( staff_api_client, permission_manage_products,", "an attribute\" assert content[\"data\"][\"attribute\"][\"id\"] == attribute_gql_id assert content[\"data\"][\"attribute\"][\"slug\"] == color_attribute_without_values.slug", "product, color_attribute, is_variant ): \"\"\"Ensures the attributes of products and", "\"message\": \"Color (color) have already been assigned to this product", "returned without any modification. \"\"\" qs = Attribute.objects.all() assert filter_attributes_by_product_types(qs,", "any value for it or is not directly associated to", "Product Type\") m2m_model.objects.create( product_type=product_type, attribute=color_attribute, sort_order=0 ) m2m_model.objects.create( product_type=product_type, attribute=size_attribute,", "m2m_values = attribute.values m2m_values.set(values) assert values == sorted( values, key=lambda", "assert content[\"data\"][\"attribute\"][\"id\"] == attribute_gql_id assert content[\"data\"][\"attribute\"][\"slug\"] == color_attribute_without_values.slug QUERY_ATTRIBUTES =", "get_graphql_content( staff_api_client.post_graphql( query, variables, permissions=[permission_manage_products] ) )[\"data\"][\"attributeAssign\"] assert not content[\"errors\"],", "$id, input: {name: $name}) { errors { field message }", "10) { edges { node { attributes { attribute {", "def test_attributes_filter_by_product_type_with_unsupported_field(): \"\"\"Ensure using an unknown field to filter attributes", "name=\"Other Collection\", slug=\"other-collection\", is_published=True, description=\"Description\", ) other_collection.products.add(other_product) query = \"\"\"", "graphene.Node.to_global_id( \"Attribute\", color_attribute_without_values.id ) query = \"\"\" query($id: ID!) {", "variants\"\"\" attribute = size_attribute attribute.input_type = AttributeInputType.MULTISELECT attribute.save(update_fields=[\"input_type\"]) product_type.variant_attributes.clear() staff_api_client.user.user_permissions.add(permission_manage_products)", "product's variant variant = product.variants.get() # Remove all attributes and", "content[\"data\"][\"attribute\"][\"slug\"] == color_attribute_without_values.slug QUERY_ATTRIBUTES = \"\"\" query { attributes(first: 20)", "== attribute.name assert data[\"attribute\"][\"productTypes\"][\"edges\"] == [] def test_update_attribute_remove_and_add_values( staff_api_client, color_attribute,", "# as we don't look for this other collection other_collection", "assert exc.value.args == (\"Filtering by in_space is unsupported\",) def test_attributes_filter_by_non_existing_category_id():", "{ id name slug } } } } } \"\"\"", "expected_slug, expected_error\", ( (\"my-slug\", \"my-slug\", []), (None, \"my-name\", []), (", "Color\" node_id = graphene.Node.to_global_id(\"Attribute\", attribute.id) variables = { \"name\": name,", "test_attributes_filter_by_non_existing_category_id(): \"\"\"Ensure using a non-existing category ID returns an empty", "already belongs to the attribute shouldn't be taken into account", "node { id name slug values { id name slug", "\"removeValues\": [value_id], } response = staff_api_client.post_graphql( query, variables, permissions=[permission_manage_products] )", "and variant attribute from the storefront for attribute in (product_attribute,", "\"\"\" def test_create_attribute_and_attribute_values( staff_api_client, permission_manage_products ): query = CREATE_ATTRIBUTES_QUERY attribute_name", "query = ( \"\"\" { attributes(first: 10) { edges {", "$moves type: $type ) { productType { id variantAttributes {", "# hide the attribute color_attribute.visible_in_storefront = False color_attribute.save(update_fields=[\"visible_in_storefront\"]) attribute_count =", "== 1 assert data[\"attribute\"][\"values\"][0][\"name\"] == name assert data[\"attribute\"][\"values\"][0][\"slug\"] == slugify(name)", "from saleor.product.utils.attributes import associate_attribute_values_to_instance from tests.api.utils import get_graphql_content def test_validate_value_is_unique(color_attribute):", "by in_space is unsupported\",) def test_attributes_filter_by_non_existing_category_id(): \"\"\"Ensure using a non-existing", "data[\"productErrors\"][0][\"field\"] == \"name\" UPDATE_ATTRIBUTE_VALUE_QUERY = \"\"\" mutation updateChoice( $id: ID!,", "= \"\"\" mutation assign($productTypeId: ID!, $operations: [AttributeAssignInput]!) { attributeAssign(productTypeId: $productTypeId,", "= graphene.Node.to_global_id(\"Attribute\", attribute.id) m2m_values = attribute.values m2m_values.set(values) assert values ==", "content = get_graphql_content(user_api_client.post_graphql(query, variables)) attributes_data = content[\"data\"][\"attributes\"][\"edges\"] flat_attributes_data = [attr[\"node\"][\"slug\"]", "not content[\"errors\"] assert content[\"attribute\"][\"id\"] == attribute_id gql_values = content[\"attribute\"][\"values\"] assert", "@pytest.mark.parametrize(\"is_variant\", (True, False)) def test_attributes_of_products_are_sorted( staff_api_client, product, color_attribute, is_variant ):", "} value { slug } } variants { attributes {", "= content[\"data\"][\"attributeUpdate\"][\"productErrors\"] assert product_errors[0][\"code\"] == error_code.name def test_update_attribute_and_remove_others_attribute_value( staff_api_client, color_attribute,", "on one product and variant, the ones we are testing", "color_attribute.save(update_fields=[\"filterable_in_dashboard\"]) variables = {\"filters\": {\"filterableInDashboard\": True}} attributes = get_graphql_content( api_client.post_graphql(ATTRIBUTES_FILTER_QUERY,", "variables[\"id\"] with pytest.raises(attribute._meta.model.DoesNotExist): attribute.refresh_from_db() CREATE_ATTRIBUTE_VALUE_QUERY = \"\"\" mutation createAttributeValue( $attributeId:", "validate_value_is_unique(color_attribute, AttributeValue(slug=value.slug)) # a new value with a new slug", "color_attribute name = \"<NAME>\" node_id = graphene.Node.to_global_id(\"Attribute\", attribute.id) variables =", "exc.value.args == (\"Filtering by in_space is unsupported\",) def test_attributes_filter_by_non_existing_category_id(): \"\"\"Ensure", "Category.objects.create(name=\"Other Category\", slug=\"other-cat\") other_attribute = Attribute.objects.create(name=\"Other\", slug=\"other\") other_product_type = ProductType.objects.create(", "= ProductType.objects.create(name=\"Dummy Type\") product_type_id = graphene.Node.to_global_id(\"ProductType\", product_type.id) attribute_id = graphene.Node.to_global_id(\"Attribute\",", "assert resolve_attribute_value_type(raw_value) == expected_type def test_resolve_assigned_attribute_without_values(api_client, product_type, product): \"\"\"Ensure the", "ValidationError from django.db.models import Q from django.template.defaultfilters import slugify from", "color_attribute): query = QUERY_ATTRIBUTES # hide the attribute color_attribute.visible_in_storefront =", "attribute not associated to the given product type.\"\"\" product_type =", "color_attribute, size_attribute, sort_field: str, m2m_model: Union[AttributeVariant, AttributeProduct], ): \"\"\"Sorts attributes", "), ), ) def test_create_attribute_and_attribute_values_errors( staff_api_client, name_1, name_2, error_msg, error_code,", "import AttributeTypeEnum, AttributeValueType from saleor.graphql.product.filters import filter_attributes_by_product_types from saleor.graphql.product.mutations.attributes import", "operations = [] variables = {\"productTypeId\": product_type_global_id, \"operations\": operations} product_attributes_ids", "= ASSIGN_ATTR_QUERY operations = [ { \"type\": gql_attribute_type.value, \"id\": graphene.Node.to_global_id(\"Attribute\",", "are disabled in this product type.\", } ] def test_assign_variant_attribute_having_unsupported_input_type(", "productAttributes { id } } errors { field message }", "product_type.product_attributes.add(*product_attributes) product_type.variant_attributes.add(variant_attribute) remaining_attribute_global_id = graphene.Node.to_global_id( \"Attribute\", product_attributes[1].pk ) query =", "variables, permissions=[permission_manage_products] ) content = get_graphql_content(response) data = content[\"data\"][\"attributeValueUpdate\"] value.refresh_from_db()", "get_graphql_content(response) attributes_data = content[\"data\"][\"attributes\"][\"edges\"] assert len(attributes_data) == attribute_count def test_attributes_query_hidden_attribute_as_staff_user(", "[{\"name\": name_1}, {\"name\": name_2}], } response = staff_api_client.post_graphql( query, variables,", "a product type: {product_type_id}\", } ] def test_sort_attributes_within_product_type_invalid_id( staff_api_client, permission_manage_products,", "\"\"\"Ensure non-staff users don't see hidden attributes, and staff users", "product_attributes_ids: operations.append( {\"type\": \"PRODUCT\", \"id\": graphene.Node.to_global_id(\"Attribute\", attr_id)} ) for attr_id", "(\"https://example.com\", AttributeValueType.URL), (\"ftp://example.com\", AttributeValueType.URL), (\"example.com\", AttributeValueType.STRING), (\"Foo\", AttributeValueType.STRING), (\"linear-gradient(red, yellow)\",", "$name: String!) { attributeValueCreate( attribute: $attributeId, input: {name: $name}) {", "{ \"name\": name, \"id\": node_id, \"addValues\": [{\"name\": attribute_value_name}], \"removeValues\": [value_id],", "from saleor.graphql.product.mutations.attributes import validate_value_is_unique from saleor.graphql.product.types.attributes import resolve_attribute_value_type from saleor.product", "data = content[\"data\"][\"attributeValueUpdate\"] assert data[\"errors\"] assert data[\"errors\"][0][\"message\"] assert data[\"errors\"][0][\"field\"] ==", "productVariant(id: $id) { attributes { attribute { id } }", "assert content[\"data\"][\"attributeCreate\"][\"attribute\"][\"slug\"] == expected_slug @pytest.mark.parametrize( \"name_1, name_2, error_msg, error_code\", (", "= {\"filters\": {\"filterableInDashboard\": True}} attributes = get_graphql_content( api_client.post_graphql(ATTRIBUTES_FILTER_QUERY, variables) )[\"data\"][\"attributes\"][\"edges\"]", "\"product_type_attribute_type, gql_attribute_type\", ( (AttributeTypeEnum.PRODUCT, AttributeTypeEnum.VARIANT), (AttributeTypeEnum.VARIANT, AttributeTypeEnum.PRODUCT), (AttributeTypeEnum.PRODUCT, AttributeTypeEnum.PRODUCT), (AttributeTypeEnum.VARIANT,", "\"attribute, expected_value\", ( (\"filterable_in_storefront\", True), (\"filterable_in_dashboard\", True), (\"visible_in_storefront\", True), (\"available_in_grid\",", "errors[0][\"message\"] == error_msg product_errors = content[\"data\"][\"attributeCreate\"][\"productErrors\"] assert product_errors[0][\"code\"] == error_code.name", "value { slug } } variants { attributes { attribute", "test_resolve_assigned_attribute_without_values(api_client, product_type, product): \"\"\"Ensure the attributes assigned to a product", "] def test_sort_values_within_attribute( staff_api_client, color_attribute, permission_manage_products ): attribute = color_attribute", "for dashboard custom ordering inside a given product type.\"\"\" product_type", "node_id, \"addValues\": [{\"name\": attribute_value_name}], \"removeValues\": [value_id], } response = staff_api_client.post_graphql(", "= get_graphql_content( staff_api_client.post_graphql(query, permissions=[permission_manage_products]) )[\"data\"][\"attributes\"][\"edges\"] assert len(found_attributes) == 1 assert", "= \"\"\" query { attributes(first: 20) { edges { node", "but with existing slug should raise an error with pytest.raises(ValidationError):", "expected_order): gql_type, gql_attr_id = graphene.Node.from_global_id(attr[\"id\"]) assert gql_type == \"AttributeValue\" actual_order.append(int(gql_attr_id))", "AttributeVariant, Category, Collection, Product, ProductType, ProductVariant, ) from saleor.product.utils.attributes import", "created assert data[\"attribute\"][\"name\"] == attribute_name assert data[\"attribute\"][\"slug\"] == slugify( attribute_name", "{ attributeUpdate( id: $id, input: { name: $name, addValues: $addValues,", "{ attributeAssign(productTypeId: $productTypeId, operations: $operations) { errors { field message", "Type\") m2m_model.objects.create( product_type=product_type, attribute=color_attribute, sort_order=0 ) m2m_model.objects.create( product_type=product_type, attribute=size_attribute, sort_order=1", "\"operations\", \"message\": \"Variants are disabled in this product type.\", }", "= get_graphql_content(api_client.post_graphql(query))[\"data\"][\"products\"][ \"edges\" ][0][\"node\"] assert len(product[\"attributes\"]) == expected_product_attribute_count assert len(product[\"variants\"][0][\"attributes\"])", "= {\"name\": value_name.upper(), \"attributeId\": attribute_id} response = staff_api_client.post_graphql( query, variables,", "color_attribute_without_values staff_api_client.user.user_permissions.add(permission_manage_products) product_type_global_id = graphene.Node.to_global_id(\"ProductType\", product_type.pk) if product_type_attribute_type == AttributeTypeEnum.PRODUCT:", "slug=\"green\") values = list(attribute.values.all()) assert len(values) == 3 staff_api_client.user.user_permissions.add(permission_manage_products) attribute_id", "not returned # by the product or variant as they", "user_api_client, product_type, category, collection, collection_with_products, test_deprecated_filter, tested_field, ): if \"Collection\"", "] def test_sort_values_within_attribute_invalid_id( staff_api_client, permission_manage_products, color_attribute ): \"\"\"Try to reorder", "test_sort_attributes_by_default_sorting(api_client): \"\"\"Don't provide any sorting, this should sort by name", "(product/variant), thus no values should be resolved. \"\"\" query =", "AttributeTypeEnum.VARIANT: product_type.variant_attributes.add(attribute) else: raise ValueError(f\"Unknown: {product_type}\") query = ASSIGN_ATTR_QUERY operations", "staff_api_client.post_graphql( query, variables, permissions=[permission_manage_products] ) )[\"data\"][\"attributeAssign\"] assert not content[\"errors\"], \"Should", ")[\"data\"][\"attributes\"][\"edges\"] assert len(attributes) == 2 assert attributes[0][\"node\"][\"slug\"] == \"b\" assert", "query = CREATE_ATTRIBUTE_VALUE_QUERY attribute_id = graphene.Node.to_global_id(\"Attribute\", attribute.id) value_name = attribute.values.first().name", "\"\"\" # Retrieve the product's variant variant = product.variants.get() #", "filter_attributes_by_product_types(qs, \"...\", None) is qs def test_attributes_filter_by_product_type_with_unsupported_field(): \"\"\"Ensure using an", "query, variables, permissions=[permission_manage_products] ) with pytest.raises(value._meta.model.DoesNotExist): value.refresh_from_db() @pytest.mark.parametrize( \"raw_value, expected_type\",", "attribute\" assert content[\"data\"][\"attribute\"][\"id\"] == attribute_gql_id assert content[\"data\"][\"attribute\"][\"slug\"] == color_attribute_without_values.slug QUERY_ATTRIBUTES", "query = UNASSIGN_ATTR_QUERY variables = { \"productTypeId\": product_type_global_id, \"attributeIds\": [", "not content[\"errors\"] assert content[\"productType\"][\"id\"] == product_type_global_id assert len(content[\"productType\"][\"productAttributes\"]) == 0", "attribute.id) value_name = attribute.values.first().name variables = {\"name\": value_name, \"attributeId\": attribute_id}", "\"id\": graphene.Node.to_global_id(\"Attribute\", attr_id)} ) for attr_id in variant_attributes_ids: operations.append( {\"type\":", "operations} content = get_graphql_content(staff_api_client.post_graphql(query, variables))[ \"data\" ][\"attributeAssign\"] assert content[\"errors\"] ==", "len(content[\"productType\"][\"variantAttributes\"]) == 1 assert ( content[\"productType\"][\"productAttributes\"][0][\"id\"] == remaining_attribute_global_id ) def", "attribute_id = graphene.Node.to_global_id(\"Attribute\", -1) value_id = graphene.Node.to_global_id(\"AttributeValue\", -1) variables =", "o.sort_order if o.sort_order is not None else o.pk ), \"The", "\"\"\" def test_sort_attributes_by_slug(api_client): Attribute.objects.bulk_create( [ Attribute(name=\"MyAttribute\", slug=\"b\"), Attribute(name=\"MyAttribute\", slug=\"a\"), ]", "name, \"id\": node_id, \"addValues\": [{\"name\": attribute_value_name}], \"removeValues\": [], } response", "), \"The default slug should be the slugified name\" assert", "{\"type\": \"PRODUCT\", \"id\": graphene.Node.to_global_id(\"Attribute\", attr_id)} ) for attr_id in variant_attributes_ids:", "= user_api_client variant = product.variants.first() assert product.attributes.count() == 1 assert", "mocked_qs = mock.MagicMock() qs = filter_attributes_by_product_types(mocked_qs, \"in_category\", category_id) assert qs", "content[\"data\"][\"attributeCreate\"][\"errors\"] data = content[\"data\"][\"attributeCreate\"] # Check if the attribute was", "not content[\"errors\"], \"Should have succeeded\" assert content[\"productType\"][\"id\"] == product_type_global_id assert", "expected_error # Check if the slug was correctly set if", "0 assert len(content[\"productType\"][\"variantAttributes\"]) == 0 def test_retrieve_product_attributes_input_type( staff_api_client, product, permission_manage_products", "staff_api_client, color_attribute, pink_attribute_value, permission_manage_products ): value = color_attribute.values.get(name=\"Red\") query =", "} } \"\"\" def test_assign_attributes_to_product_type( staff_api_client, permission_manage_products, attribute_list ): product_type", ") def test_retrieving_the_restricted_attributes_restricted( staff_api_client, color_attribute, permission_manage_products, attribute, expected_value, ): \"\"\"Checks", "they are not returned # by the product or variant", "variables))[ \"data\" ][\"attributeUnassign\"] assert not content[\"errors\"] assert content[\"productType\"][\"id\"] == product_type_global_id", "attribute_count = Attribute.objects.all().count() # The user doesn't have the permission", "attribute_gql_id}) ) assert content[\"data\"][\"attribute\"], \"Should have found an attribute\" assert", "found_variant_attrs_ids = { int(graphene.Node.from_global_id(attr[\"id\"])[1]) for attr in content[\"productType\"][\"variantAttributes\"] } assert", "AttributeValue.objects.bulk_create( [ AttributeValue(slug=\"a\", name=\"A\", attribute=unassigned_product_attribute), AttributeValue(slug=\"b\", name=\"B\", attribute=unassigned_product_attribute), ] )", "assert product_errors[0][\"code\"] == ProductErrorCode.INVALID.name def test_delete_attribute( staff_api_client, color_attribute, permission_manage_products, product_type", "should not raise any error when trying to remove an", "], } expected_order = [values[1].pk, values[2].pk, values[0].pk] content = get_graphql_content(", "\"\"\" query($id: ID!) { productVariant(id: $id) { attributes { attribute", "the PT may be missing\" assert product_attributes[0][\"attribute\"][\"slug\"] == \"product\" assert", "message } productErrors { field message code } attribute {", "missing\" assert product_attributes[0][\"attribute\"][\"slug\"] == \"product\" assert product_attributes[0][\"values\"] == [] assert", "content[\"data\"][\"attributeCreate\"] # Check if the attribute was correctly created assert", "= { \"name\": name, \"id\": node_id, \"addValues\": [{\"name\": attribute_value_name}], \"removeValues\":", "in (product_attribute, variant_attribute): attribute.visible_in_storefront = False attribute.save(update_fields=[\"visible_in_storefront\"]) product = get_graphql_content(api_client.post_graphql(query))[\"data\"][\"products\"][", "content[\"data\"][\"attributeDelete\"] assert data[\"attribute\"][\"id\"] == variables[\"id\"] with pytest.raises(attribute._meta.model.DoesNotExist): attribute.refresh_from_db() CREATE_ATTRIBUTE_VALUE_QUERY =", "def test_resolve_assigned_attribute_without_values(api_client, product_type, product): \"\"\"Ensure the attributes assigned to a", "code } attribute { name slug values { name slug", "== 1 assert attribute.values.filter(name=attribute_value_name).exists() @pytest.mark.parametrize( \"name_1, name_2, error_msg, error_code\", (", "{ errors { field message } productType { id productAttributes", "id name slug values { id name slug } }", "\"productTypeId\": product_type_id, \"moves\": [{\"id\": attribute_id, \"sortOrder\": 1}], } content =", "slug values { id name slug } } } }", "query = \"\"\" query($nodeID: ID!) { attributes(first: 20, %(filter_input)s) {", "\"addValues\" assert errors[0][\"message\"] == error_msg product_errors = content[\"data\"][\"attributeUpdate\"][\"productErrors\"] assert product_errors[0][\"code\"]", "attribute_value_id) variables = { \"name\": name, \"id\": node_id, \"addValues\": [{\"name\":", "support variants\"\"\" attribute = size_attribute attribute.input_type = AttributeInputType.MULTISELECT attribute.save(update_fields=[\"input_type\"]) product_type.variant_attributes.clear()", "slugify from graphene.utils.str_converters import to_camel_case from saleor.core.taxes import zero_money from", "attribute.name assert data[\"attribute\"][\"productTypes\"][\"edges\"] == [] def test_update_attribute_remove_and_add_values( staff_api_client, color_attribute, permission_manage_products", "# Create another product type and attribute that shouldn't get", "len(values) == 3 staff_api_client.user.user_permissions.add(permission_manage_products) attribute_id = graphene.Node.to_global_id(\"Attribute\", attribute.id) m2m_values =", "@pytest.mark.parametrize( \"input_slug, expected_slug, expected_error\", ( (\"my-slug\", \"my-slug\", []), (None, \"my-name\",", "to the given product type.\"\"\" product_type = ProductType.objects.create(name=\"Dummy Type\") product_type_id", "sort_order=1 ) variables = {\"sortBy\": {\"field\": sort_field, \"direction\": \"DESC\"}} attributes", "== name assert data[\"attribute\"][\"values\"][0][\"slug\"] == slugify(name) @pytest.mark.parametrize( \"input_slug, expected_slug, expected_error\",", "raise any error when trying to remove an attribute that", "Create dummy attributes unassigned_product_attribute = Attribute.objects.create(name=\"P\", slug=\"product\") unassigned_variant_attribute = Attribute.objects.create(name=\"V\",", "pytest.raises(attribute._meta.model.DoesNotExist): attribute.refresh_from_db() CREATE_ATTRIBUTE_VALUE_QUERY = \"\"\" mutation createAttributeValue( $attributeId: ID!, $name:", "in variant_attributes_ids: operations.append( {\"type\": \"VARIANT\", \"id\": graphene.Node.to_global_id(\"Attribute\", attr_id)} ) content", "graphene.Node.from_global_id(attr[\"id\"]) assert gql_type == \"Attribute\" assert int(gql_attr_id) == expected_pk ATTRIBUTE_VALUES_RESORT_QUERY", "NotImplemented exception. \"\"\" qs = Attribute.objects.all() with pytest.raises(NotImplementedError) as exc:", "attribute.refresh_from_db() data = content[\"data\"][\"attributeUpdate\"] assert not data[\"errors\"] assert data[\"attribute\"][\"name\"] ==", "$id: ID!, $name: String!, $addValues: [AttributeValueCreateInput]!, $removeValues: [ID]!) { attributeUpdate(", "+= 1 expected_variant_attribute_count += 1 staff_user.user_permissions.add(permission_manage_products) # Hide one product", "query = \"\"\" mutation deleteAttribute($id: ID!) { attributeDelete(id: $id) {", "test_update_attribute_value_name_not_unique( staff_api_client, pink_attribute_value, permission_manage_products ): query = UPDATE_ATTRIBUTE_VALUE_QUERY value =", "= color_attribute.values.first() # a new value but with existing slug", "resolved even if the product doesn't provide any value for", "message } productType { id variantAttributes { id } productAttributes", "staff_api_client, permission_manage_products ): \"\"\"Try to reorder an invalid attribute (invalid", "): \"\"\"Try to reorder an invalid attribute (invalid ID).\"\"\" attribute_id", "assert len(product[\"attributes\"]) == 1 assert product[\"attributes\"][0][\"attribute\"][\"slug\"] == \"color\" assert product[\"attributes\"][0][\"values\"]", "staff_user expected_product_attribute_count += 1 expected_variant_attribute_count += 1 staff_user.user_permissions.add(permission_manage_products) # Hide", "{ \"productTypeId\": product_type_global_id, \"attributeIds\": [ graphene.Node.to_global_id(\"Attribute\", color_attribute_without_values.pk) ], } content", "attributes by their sort order and ID (when None) expected_order", "the attributes staff_api_client.user.user_permissions.add(permission_manage_products) response = staff_api_client.post_graphql(query) content = get_graphql_content(response) attributes_data", "errors assert errors[0][\"field\"] == \"values\" assert errors[0][\"message\"] == error_msg product_errors", "} } \"\"\" node_id = graphene.Node.to_global_id(\"AttributeValue\", value.id) variables = {\"id\":", "slug=\"example-name\", value=\"#RED\" ) node_id = graphene.Node.to_global_id(\"AttributeValue\", value.id) variables = {\"name\":", "AttributeValueType.GRADIENT), ], ) def test_resolve_attribute_value_type(raw_value, expected_type): assert resolve_attribute_value_type(raw_value) == expected_type", "ProductErrorCode.ALREADY_EXISTS.name assert data[\"productErrors\"][0][\"field\"] == \"name\" def test_create_attribute_value_capitalized_name( staff_api_client, color_attribute, permission_manage_products", "= get_graphql_content(staff_api_client.post_graphql(query, {\"id\": node_id}))[ \"data\" ] attributes = data[\"productVariant\" if", "color\", \"Provided values are not unique.\", ProductErrorCode.UNIQUE, ), ( \"Red", "AttributeSortingInput) { attributes(first: 10, sortBy: $sortBy) { edges { node", "query($nodeID: ID!) { attributes(first: 20, %(filter_input)s) { edges { node", "have succeeded\" assert content[\"productType\"][\"id\"] == product_type_global_id assert len(content[\"productType\"][\"productAttributes\"]) == len(", "data = content[\"data\"][\"attributeValueCreate\"] assert data[\"productErrors\"] assert data[\"productErrors\"][0][\"code\"] == ProductErrorCode.ALREADY_EXISTS.name assert", "\"color\" assert product[\"attributes\"][0][\"values\"] == [] # Ensure the variant attributes", "== \"DROPDOWN\" @pytest.mark.parametrize( \"attribute, expected_value\", ( (\"filterable_in_storefront\", True), (\"filterable_in_dashboard\", True),", "content[\"data\"][\"attributeUpdate\"] assert data[\"attribute\"][\"name\"] == name == attribute.name assert data[\"attribute\"][\"productTypes\"][\"edges\"] ==", ")[\"data\"][\"productTypeReorderAttributes\"] assert content[\"errors\"] == [ { \"field\": \"productTypeId\", \"message\": f\"Couldn't", "\"\"\"Ensures the attributes of products and variants are sorted.\"\"\" variant", "raise ValueError(f\"Unknown: {product_type}\") query = ASSIGN_ATTR_QUERY operations = [ {", "assert attribute.values.filter(name=attribute_value_name).exists() def test_update_empty_attribute_and_add_values( staff_api_client, color_attribute_without_values, permission_manage_products ): query =", "permission_manage_products ): attribute = color_attribute AttributeValue.objects.create(attribute=attribute, name=\"Green\", slug=\"green\") values =", "by ID. Thus, we are sure the query is actually", "== color_attribute_without_values.slug QUERY_ATTRIBUTES = \"\"\" query { attributes(first: 20) {", "assert len(attributes_data) == attributes.count() def test_attributes_query_hidden_attribute(user_api_client, product, color_attribute): query =", "QUERY_PRODUCT_AND_VARIANTS_ATTRIBUTES api_client = user_api_client variant = product.variants.first() product_type = product.product_type", "with products but shouldn't get matched # as we don't", "actually passing the test. other_attribute = Attribute.objects.create(name=\"Other\", slug=\"other\") # Add", "3 staff_api_client.user.user_permissions.add(permission_manage_products) product_type = ProductType.objects.create(name=\"Dummy Type\") product_type_id = graphene.Node.to_global_id(\"ProductType\", product_type.id)", "other_attribute]) # Retrieve the M2M object for the attribute vs", "import to_camel_case from saleor.core.taxes import zero_money from saleor.graphql.core.utils import snake_to_camel_case", "[{\"name\": name_1}, {\"name\": name_2}]} response = staff_api_client.post_graphql( query, variables, permissions=[permission_manage_products]", "= content[\"data\"][\"attributes\"][\"edges\"] assert len(attributes_data) == attribute_count def test_attributes_query_hidden_attribute_as_staff_user( staff_api_client, product,", "\"id\": node_id, \"addValues\": [{\"name\": attribute_value_name}], \"removeValues\": [], } response =", "= \"\"\" mutation ProductTypeReorderAttributes( $productTypeId: ID! $moves: [ReorderInput]! $type: AttributeTypeEnum!", "provide any value for it or is not directly associated", "id slug } productAttributes { id } } errors {", "(\"rgb(255, 0, 0)\", AttributeValueType.COLOR), (\"hsl(0, 100%, 50%)\", AttributeValueType.COLOR), (\"hsla(120, 60%,", "variables = {\"name\": name, \"id\": node_id, \"addValues\": [], \"removeValues\": []}", "a new value with a new slug should pass validate_value_is_unique(", "staff_api_client.post_graphql(query, permissions=[permission_manage_products]) )[\"data\"][\"attributes\"][\"edges\"] assert len(found_attributes) == 1 assert found_attributes[0][\"node\"][attribute] ==", "productType { id productAttributes { id } variantAttributes { id", "permissions=[permission_manage_products] ) content = get_graphql_content(response) errors = content[\"data\"][\"attributeUpdate\"][\"errors\"] assert errors", "values { name } } attributeValue { name type slug", "attributes(first: 10) { edges { node { %s } }", "are restricted and if their default value is the expected", "query = ASSIGN_ATTR_QUERY operations = [] variables = {\"productTypeId\": product_type_global_id,", "== \"removeValues\" err_msg = \"Value %s does not belong to", "staff_api_client.post_graphql( query, variables, permissions=[permission_manage_products] ) content = get_graphql_content(response) attribute.refresh_from_db() data", "storefront for attribute in (product_attribute, variant_attribute): attribute.visible_in_storefront = False attribute.save(update_fields=[\"visible_in_storefront\"])", "query { attributes(first: 20) { edges { node { id", "[] # Ensure the variant attributes values are all None", "\"Red Color\" node_id = graphene.Node.to_global_id(\"Attribute\", attribute.id) attribute_value_id = attribute.values.first().id value_id", "{\"id\": node_id} response = staff_api_client.post_graphql( query, variables, permissions=[permission_manage_products] ) content", "product_type.variant_attributes.add(variant_attribute) remaining_attribute_global_id = graphene.Node.to_global_id( \"Attribute\", product_attributes[1].pk ) query = UNASSIGN_ATTR_QUERY", "variables = { \"type\": attribute_type, \"productTypeId\": product_type_id, \"moves\": [ {", "= get_graphql_content( api_client.post_graphql( \"\"\" { products(first: 10) { edges {", "], } expected_order = [attributes[1].pk, attributes[2].pk, attributes[0].pk] content = get_graphql_content(", "False color_attribute.save(update_fields=[\"filterable_in_dashboard\"]) variables = {\"filters\": {\"filterableInDashboard\": True}} attributes = get_graphql_content(", "see the attributes staff_api_client.user.user_permissions.add(permission_manage_products) response = staff_api_client.post_graphql(query) content = get_graphql_content(response)", "} } } \"\"\" node_id = graphene.Node.to_global_id(\"Attribute\", attribute.id) variables =", "input: {name: $name}) { errors { field message } attributeValue", "saleor.product.error_codes import ProductErrorCode from saleor.product.models import ( Attribute, AttributeProduct, AttributeValue,", "attributes have sort_order=null AttributeProduct.objects.create( attribute=unassigned_product_attribute, product_type=product_type, sort_order=0 ) AttributeVariant.objects.create( attribute=unassigned_variant_attribute,", "-1) variables = { \"type\": \"VARIANT\", \"productTypeId\": product_type_id, \"moves\": [{\"id\":", "data[\"attribute\"][\"values\"]] def test_update_attribute_value_name_not_unique( staff_api_client, pink_attribute_value, permission_manage_products ): query = UPDATE_ATTRIBUTE_VALUE_QUERY", "= Attribute.objects.all() with pytest.raises(NotImplementedError) as exc: filter_attributes_by_product_types(qs, \"in_space\", \"a-value\") assert", "== 0 assert len(content[\"productType\"][\"variantAttributes\"]) == 0 def test_retrieve_product_attributes_input_type( staff_api_client, product,", "as exc: filter_attributes_by_product_types(qs, \"in_space\", \"a-value\") assert exc.value.args == (\"Filtering by", "not of the node (product/variant), thus no values should be", "name assert data[\"attribute\"][\"values\"][0][\"slug\"] == slugify(name) @pytest.mark.parametrize( \"input_slug, expected_slug, expected_error\", (", "variables, permissions=[permission_manage_products] ) content = get_graphql_content(response) errors = content[\"data\"][\"attributeUpdate\"][\"errors\"] assert", "50%)\", AttributeValueType.COLOR), (\"hsla(120, 60%, 70%, 0.3)\", AttributeValueType.COLOR), (\"rgba(100%, 255, 0,", "= get_graphql_content( api_client.post_graphql(ATTRIBUTES_SORT_QUERY, {}) )[\"data\"][\"attributes\"][\"edges\"] assert len(attributes) == 2 assert", "{ attributeValueDelete(id: $id) { attributeValue { name slug } }", "variant_attribute_values = list( variant.attributes.first().values.values_list(\"slug\", flat=True) ) assert len(product_attribute_values) == 1", "attributeAssign(productTypeId: $productTypeId, operations: $operations) { errors { field message }", "trying to add an attribute already contained in the product", "should pass validate_value_is_unique( color_attribute, AttributeValue(slug=\"spanish-inquisition\") ) # value that already", "-1) variables = { \"type\": \"VARIANT\", \"attributeId\": attribute_id, \"moves\": [{\"id\":", "tests.api.utils import get_graphql_content def test_validate_value_is_unique(color_attribute): value = color_attribute.values.first() # a", "an attribute as a variant attribute when the product type", "} ] def test_sort_attributes_within_product_type_invalid_id( staff_api_client, permission_manage_products, color_attribute ): \"\"\"Try to", "def test_attributes_query_hidden_attribute_as_staff_user( staff_api_client, product, color_attribute, permission_manage_products ): query = QUERY_ATTRIBUTES", "assert len(gql_attributes) == len(expected_order) for attr, expected_pk in zip(gql_attributes, expected_order):", "attributes[1][\"node\"][\"slug\"] == \"b\" @pytest.mark.parametrize( \"sort_field, m2m_model\", ( (\"DASHBOARD_VARIANT_POSITION\", AttributeVariant), (\"DASHBOARD_PRODUCT_POSITION\",", "True)) def test_resolve_attributes_with_hidden( user_api_client, product, color_attribute, size_attribute, staff_user, is_staff, permission_manage_products,", "[ { \"field\": \"moves\", \"message\": f\"Couldn't resolve to an attribute", "attribute already contained in the product type.\"\"\" product_type = ProductType.objects.create(name=\"Type\")", "attr in content[\"productType\"][\"productAttributes\"] } found_variant_attrs_ids = { int(graphene.Node.from_global_id(attr[\"id\"])[1]) for attr", "attributes { attribute { slug } values { slug }", "0, 0)\", AttributeValueType.COLOR), (\"http://example.com\", AttributeValueType.URL), (\"https://example.com\", AttributeValueType.URL), (\"ftp://example.com\", AttributeValueType.URL), (\"example.com\",", "the product and variant's attributes products = get_graphql_content( api_client.post_graphql( \"\"\"", "[ReorderInput]!) { attributeReorderValues(attributeId: $attributeId, moves: $moves) { attribute { id", "product.product_type.variant_attributes.set([color_attribute, other_attribute]) else: product.product_type.product_attributes.set([color_attribute, other_attribute]) # Retrieve the M2M object", "assert len(gql_attr[\"values\"]) == 1 assert gql_attr[\"values\"][0][\"type\"] == \"STRING\" assert gql_attr[\"values\"][0][\"inputType\"]", "the product and its variant product.attributesrelated.clear() variant.attributesrelated.clear() # Retrieve the", "data = content[\"data\"][\"attributeValueCreate\"] assert not data[\"productErrors\"] attr_data = data[\"attributeValue\"] assert", "== 1 # The user should now be able to", "product[\"attributes\"] variant_attributes = product[\"variants\"][0][\"attributes\"] assert len(product_attributes) == 2, \"Non-assigned attr", "qs == mocked_qs.none.return_value @pytest.mark.parametrize(\"test_deprecated_filter\", [True, False]) @pytest.mark.parametrize(\"tested_field\", [\"inCategory\", \"inCollection\"]) def", "size_attribute ): \"\"\"The assignAttribute mutation should raise an error when", "$id) { attributes { attribute { id } } }", "\"product\" assert product_attributes[0][\"values\"] == [] assert variant_attributes[0][\"value\"] is None assert", "staff_api_client.post_graphql( query, variables, permissions=[permission_manage_products] ) )[\"data\"][\"attributeUnassign\"] assert not content[\"errors\"] assert", ") content = get_graphql_content(response) attribute.refresh_from_db() data = content[\"data\"][\"attributeUpdate\"] assert data[\"attribute\"][\"name\"]", "order and ID (when None) expected_order = [other_attribute.pk, color_attribute.pk] #", "permission_manage_products ): query = UPDATE_ATTRIBUTE_QUERY attribute = color_attribute node_id =", "when trying to remove an attribute that is not/no longer", "(AttributeTypeEnum.PRODUCT, AttributeTypeEnum.PRODUCT), (AttributeTypeEnum.VARIANT, AttributeTypeEnum.VARIANT), ), ) def test_assign_attribute_to_product_type_having_already_that_attribute( staff_api_client, permission_manage_products,", "graphene.Node.to_global_id(\"ProductType\", product_type.id) m2m_attributes = getattr(product_type, relation_field) m2m_attributes.set(attributes) sort_method = getattr(m2m_attributes,", "product_type=other_product_type, category=other_category, price=zero_money(), is_published=True, ) # Create another collection with", "attribute color_attribute.visible_in_storefront = False color_attribute.save(update_fields=[\"visible_in_storefront\"]) attribute_count = Attribute.objects.get_visible_to_user( user_api_client.user ).count()", "get_graphql_content(staff_api_client.post_graphql(query, variables))[ \"data\" ][\"attributeUnassign\"] assert not content[\"errors\"] assert content[\"productType\"][\"id\"] ==", "{ edges { node { id name slug } }", "\"values\" assert errors[0][\"message\"] == error_msg product_errors = content[\"data\"][\"attributeCreate\"][\"productErrors\"] assert product_errors[0][\"code\"]", "content[\"productType\"][\"productAttributes\"][0][\"id\"] == remaining_attribute_global_id ) def test_unassign_attributes_not_in_product_type( staff_api_client, permission_manage_products, color_attribute_without_values ):", "String!, $values: [AttributeValueCreateInput]) { attributeCreate(input: {name: $name, values: $values}) {", "if is_variant else \"product\"][\"attributes\"] actual_order = [ int(graphene.Node.from_global_id(attr[\"attribute\"][\"id\"])[1]) for attr", "ID!, $name: String!) { attributeValueCreate( attribute: $attributeId, input: {name: $name})", "attr in attributes ] # Compare the received data against", "assert data[\"attributeValue\"][\"name\"] == name == value.name assert data[\"attributeValue\"][\"slug\"] == slugify(name)", "content[\"data\"][\"attributeValueUpdate\"] assert data[\"errors\"] assert data[\"errors\"][0][\"message\"] assert data[\"errors\"][0][\"field\"] == \"name\" def", "[True, False]) @pytest.mark.parametrize(\"tested_field\", [\"inCategory\", \"inCollection\"]) def test_attributes_in_collection_query( user_api_client, product_type, category,", "AttributeValueType.URL), (\"https://example.com\", AttributeValueType.URL), (\"ftp://example.com\", AttributeValueType.URL), (\"example.com\", AttributeValueType.STRING), (\"Foo\", AttributeValueType.STRING), (\"linear-gradient(red,", "): color_attribute.available_in_grid = False color_attribute.save(update_fields=[\"available_in_grid\"]) variables = {\"filters\": {\"availableInGrid\": True}}", "int(graphene.Node.from_global_id(attr[\"attribute\"][\"id\"])[1]) for attr in attributes ] # Compare the received", "product_type = ProductType.objects.create(name=\"Type\") product_type_global_id = graphene.Node.to_global_id(\"ProductType\", product_type.pk) query = UNASSIGN_ATTR_QUERY", "attribute_count == 1 response = user_api_client.post_graphql(query) content = get_graphql_content(response) attributes_data", "by default.\"\"\" Attribute.objects.bulk_create( [Attribute(name=\"A\", slug=\"b\"), Attribute(name=\"B\", slug=\"a\")] ) attributes =", "color_attribute.visible_in_storefront = False color_attribute.save(update_fields=[\"visible_in_storefront\"]) attribute_count = Attribute.objects.get_visible_to_user( user_api_client.user ).count() assert", "Q(attributeproduct__product_type_id=product_type.pk) | Q(attributevariant__product_type_id=product_type.pk) ) # Create another product type and", "are not associated to them AttributeValue.objects.bulk_create( [ AttributeValue(slug=\"a\", name=\"A\", attribute=unassigned_product_attribute),", "test_create_attribute_value_capitalized_name( staff_api_client, color_attribute, permission_manage_products ): attribute = color_attribute query =", "{ id } } } \"\"\" node_id = graphene.Node.to_global_id(\"Attribute\", attribute.id)", "@pytest.mark.parametrize(\"tested_field\", [\"inCategory\", \"inCollection\"]) def test_attributes_in_collection_query( user_api_client, product_type, category, collection, collection_with_products,", "== \"values\" assert errors[0][\"message\"] == error_msg product_errors = content[\"data\"][\"attributeCreate\"][\"productErrors\"] assert", "product_type=product_type, attribute=color_attribute, sort_order=0 ) m2m_model.objects.create( product_type=product_type, attribute=size_attribute, sort_order=1 ) variables", "vs the product type if is_variant: m2m_rel_other_attr = other_attribute.attributevariant.last() else:", "product[\"variants\"][0] # Ensure the product attributes values are all None", "to remove an attribute that is not/no longer in the", "[ (\"#0000\", AttributeValueType.COLOR), (\"#FF69B4\", AttributeValueType.COLOR), (\"rgb(255, 0, 0)\", AttributeValueType.COLOR), (\"hsl(0,", "Attribute.objects query = QUERY_ATTRIBUTES response = user_api_client.post_graphql(query) content = get_graphql_content(response)", "product_type_global_id, \"operations\": operations} product_attributes_ids = {attr.pk for attr in attribute_list[:2]}", "list( variant.attributes.first().values.values_list(\"slug\", flat=True) ) assert len(product_attribute_values) == 1 assert len(variant_attribute_values)", ")[\"data\"][\"products\"][\"edges\"] assert len(found_products) == 1 for gql_attr in found_products[0][\"node\"][\"attributes\"]: assert", "} } } \"\"\" def test_sort_attributes_by_slug(api_client): Attribute.objects.bulk_create( [ Attribute(name=\"MyAttribute\", slug=\"b\"),", "does not belong to this attribute.\" % str(size_attribute) assert errors[0][\"message\"]", "def test_update_attribute_value_name_not_unique( staff_api_client, pink_attribute_value, permission_manage_products ): query = UPDATE_ATTRIBUTE_VALUE_QUERY value", "to an attribute: {attribute_id}\", } ] def test_sort_values_within_attribute_invalid_id( staff_api_client, permission_manage_products,", "\"message\": \"The attribute's slug cannot be blank.\"}], ), ), )", "\"\"\" def test_unassign_attributes_from_product_type( staff_api_client, permission_manage_products, attribute_list ): product_type = ProductType.objects.create(name=\"Type\")", "the attribute's input type doesn't support variants\"\"\" attribute = size_attribute", "assert ( data[\"attribute\"][\"productTypes\"][\"edges\"] == [] ), \"The attribute should not", "{ \"field\": \"productTypeId\", \"message\": f\"Couldn't resolve to a product type:", "products, # the user shouldn't be able to see the", "o.pk ), \"The values are not properly ordered\" variables =", "= get_graphql_content(response) attribute.refresh_from_db() data = content[\"data\"][\"attributeUpdate\"] assert not data[\"errors\"] assert", "typing import Union from unittest import mock import graphene import", "\"field\": \"productTypeId\", \"message\": f\"Couldn't resolve to a product type: {product_type_id}\",", "), ) def test_sort_attributes_by_position_in_product_type( api_client, color_attribute, size_attribute, sort_field: str, m2m_model:", "the attribute vs the product type if is_variant: m2m_rel_other_attr =", "Attribute.objects.bulk_create( [Attribute(name=\"A\", slug=\"b\"), Attribute(name=\"B\", slug=\"a\")] ) attributes = get_graphql_content( api_client.post_graphql(ATTRIBUTES_SORT_QUERY,", "not data[\"errors\"] assert data[\"attribute\"][\"name\"] == name == attribute.name assert not", "expected_pk in zip(gql_attributes, expected_order): gql_type, gql_attr_id = graphene.Node.from_global_id(attr[\"id\"]) assert gql_type", ") def test_sort_attributes_within_product_type( staff_api_client, attribute_list, permission_manage_products, attribute_type, relation_field, backref_field, ):", "variant_attribute = size_attribute expected_product_attribute_count = product.attributes.count() - 1 expected_variant_attribute_count =", "assert not content[\"errors\"] assert content[\"attribute\"][\"id\"] == attribute_id gql_values = content[\"attribute\"][\"values\"]", "getattr(product_type, relation_field) m2m_attributes.set(attributes) sort_method = getattr(m2m_attributes, f\"{relation_field}_sorted\") attributes = list(sort_method())", "when sorted by ID. Thus, we are sure the query", "query = QUERY_PRODUCT_AND_VARIANTS_ATTRIBUTES api_client = user_api_client variant = product.variants.first() product_attribute", "query % {\"filter_input\": f\"{tested_field}: $nodeID\"} else: query = query %", "attribute.refresh_from_db() assert attribute.values.count() == 1 assert attribute.values.filter(name=attribute_value_name).exists() @pytest.mark.parametrize( \"name_1, name_2,", "= get_graphql_content(response) assert not content[\"data\"][\"attributeCreate\"][\"errors\"] data = content[\"data\"][\"attributeCreate\"] # Check", "\"id\": node_id} response = staff_api_client.post_graphql( query, variables, permissions=[permission_manage_products] ) content", "def test_create_attribute_and_attribute_values( staff_api_client, permission_manage_products ): query = CREATE_ATTRIBUTES_QUERY attribute_name =", "# Add the attribute to the product type if is_variant:", "product_type_id = graphene.Node.to_global_id(\"ProductType\", -1) attribute_id = graphene.Node.to_global_id(\"Attribute\", -1) variables =", "permission_manage_products ): query = \"\"\" { products(first: 10) { edges", "permission yet to manage products, # the user shouldn't be", "$values}) { errors { field message } productErrors { field", "variables = {\"sortBy\": {\"field\": \"SLUG\", \"direction\": \"ASC\"}} attributes = get_graphql_content(", "color_attribute, permission_manage_products ): query = QUERY_ATTRIBUTES # hide the attribute", "empty or null value is ignored and the queryset is", "(\"PRODUCT\", \"product_attributes\", \"attributeproduct\"), ), ) def test_sort_attributes_within_product_type( staff_api_client, attribute_list, permission_manage_products,", "[{\"id\": value_id, \"sortOrder\": 1}], } content = get_graphql_content( staff_api_client.post_graphql( ATTRIBUTE_VALUES_RESORT_QUERY,", "= \"\"\" mutation deleteAttribute($id: ID!) { attributeDelete(id: $id) { errors", "} } } \"\"\" def test_sort_attributes_within_product_type_invalid_product_type( staff_api_client, permission_manage_products ): \"\"\"Try", "graphene.Node.to_global_id(\"AttributeValue\", -1) variables = { \"type\": \"VARIANT\", \"attributeId\": attribute_id, \"moves\":", "{ products(first: 1) { edges { node { attributes {", "content[\"data\"][\"attributeUpdate\"] assert not data[\"errors\"] assert data[\"attribute\"][\"name\"] == name == attribute.name", "permissions=[permission_manage_products] ) )[\"data\"][\"attributeAssign\"] assert not content[\"errors\"], \"Should have succeeded\" assert", "assert product.attributes.count() == 1 assert variant.attributes.count() == 1 product_attribute_values =", "name=\"Other type\", has_variants=True, is_shipping_required=True ) other_product_type.product_attributes.add(other_attribute) other_product = Product.objects.create( name=f\"Another", "other collection other_collection = Collection.objects.create( name=\"Other Collection\", slug=\"other-collection\", is_published=True, description=\"Description\",", "product_type_global_id assert len(content[\"productType\"][\"productAttributes\"]) == len( product_attributes_ids ) assert len(content[\"productType\"][\"variantAttributes\"]) ==", "be assigned \" \"as variant attributes\" ), } ] @pytest.mark.parametrize(", "\"addValues\": [{\"name\": attribute_value_name}], \"removeValues\": [value_id], } response = staff_api_client.post_graphql( query,", "slug should be the slugified name\" assert ( data[\"attribute\"][\"productTypes\"][\"edges\"] ==", "attribute.id) variables = {\"name\": name, \"id\": node_id, \"addValues\": [], \"removeValues\":", "other_product_type.product_attributes.add(other_attribute) other_product = Product.objects.create( name=f\"Another Product\", product_type=other_product_type, category=other_category, price=zero_money(), is_published=True,", "-1, }, ], } expected_order = [attributes[1].pk, attributes[2].pk, attributes[0].pk] content", "\"PRODUCT\", \"id\": graphene.Node.to_global_id(\"Attribute\", attr_id)} ) for attr_id in variant_attributes_ids: operations.append(", "all None assert variant[\"attributes\"][0][\"attribute\"][\"slug\"] == \"size\" assert variant[\"attributes\"][0][\"values\"] == []", "# The user doesn't have the permission yet to manage", "blank.\"}], ), ), ) def test_create_attribute_with_given_slug( staff_api_client, permission_manage_products, input_slug, expected_slug,", "errors[0][\"field\"] == \"addValues\" assert errors[0][\"message\"] == error_msg product_errors = content[\"data\"][\"attributeUpdate\"][\"productErrors\"]", "get_graphql_content( staff_api_client.post_graphql( query, variables, permissions=[permission_manage_products] ) )[\"data\"][\"attributeUnassign\"] assert not content[\"errors\"]", "attribute_id = graphene.Node.to_global_id(\"Attribute\", -1) variables = { \"type\": \"VARIANT\", \"productTypeId\":", "values should be resolved. \"\"\" query = QUERY_PRODUCT_AND_VARIANTS_ATTRIBUTES api_client =", "flat=True)) assert flat_attributes_data == expected_flat_attributes_data CREATE_ATTRIBUTES_QUERY = \"\"\" mutation createAttribute($name:", "value in data[\"attribute\"][\"values\"]] def test_create_attribute_value_not_unique_name( staff_api_client, color_attribute, permission_manage_products ): attribute", "node_id = graphene.Node.to_global_id(\"Attribute\", attribute.id) size_attribute = size_attribute.values.first() attr_id = graphene.Node.to_global_id(\"AttributeValue\",", "AttributeValueType.COLOR), (\"rgb(255, 0, 0)\", AttributeValueType.COLOR), (\"hsl(0, 100%, 50%)\", AttributeValueType.COLOR), (\"hsla(120,", "attribute = color_attribute AttributeValue.objects.create(attribute=attribute, name=\"Green\", slug=\"green\") values = list(attribute.values.all()) assert", "def test_attributes_query_hidden_attribute(user_api_client, product, color_attribute): query = QUERY_ATTRIBUTES # hide the", "missing\" assert len(variant_attributes) == 2, \"Non-assigned attr from the PT", "product.attributes.count() - 1 expected_variant_attribute_count = variant.attributes.count() - 1 if is_staff:", "staff_api_client.post_graphql(ATTRIBUTE_VALUES_RESORT_QUERY, variables) )[\"data\"][\"attributeReorderValues\"] assert not content[\"errors\"] assert content[\"attribute\"][\"id\"] == attribute_id", "query, variables, permissions=[permission_manage_products] ) get_graphql_content(response) attribute.refresh_from_db() assert attribute.values.count() == 1", "found_attributes = get_graphql_content( staff_api_client.post_graphql(query, permissions=[permission_manage_products]) )[\"data\"][\"attributes\"][\"edges\"] assert len(found_attributes) == 1", "get_graphql_content( api_client.post_graphql(ATTRIBUTES_SORT_QUERY, {}) )[\"data\"][\"attributes\"][\"edges\"] assert len(attributes) == 2 assert attributes[0][\"node\"][\"slug\"]", "staff_api_client, color_attribute, permission_manage_products, attribute, expected_value, ): \"\"\"Checks if the attributes", "matched # as we don't look for this other collection", "graphene.Node.to_global_id(\"Attribute\", product_attributes[0].pk) ], } content = get_graphql_content( staff_api_client.post_graphql( query, variables,", ") )[\"data\"][\"attributeReorderValues\"] assert content[\"errors\"] == [ { \"field\": \"attributeId\", \"message\":", "Hide one product and variant attribute from the storefront for", "attributes, and staff users having the 'manage product' permission can.", "values = list(attribute.values.all()) assert len(values) == 3 staff_api_client.user.user_permissions.add(permission_manage_products) attribute_id =", ") { attributeUnassign(productTypeId: $productTypeId, attributeIds: $attributeIds) { errors { field", "the product type if is_variant: m2m_rel_other_attr = other_attribute.attributevariant.last() else: m2m_rel_other_attr", "): color_attribute.filterable_in_dashboard = False color_attribute.save(update_fields=[\"filterable_in_dashboard\"]) variables = {\"filters\": {\"filterableInDashboard\": True}}", "= product[\"attributes\"] variant_attributes = product[\"variants\"][0][\"attributes\"] assert len(product_attributes) == 2, \"Non-assigned", "10) { edges { node { attributes { values {", "product.attributes.count() == 1 assert variant.attributes.count() == 1 product = get_graphql_content(api_client.post_graphql(query))[\"data\"][\"products\"][", "query = UPDATE_ATTRIBUTE_QUERY attribute = color_attribute name = \"<NAME>\" attribute_value_name", "the product doesn't provide any value for it or is", "another product type and attribute that shouldn't get matched other_category", "AttributeTypeEnum.VARIANT), (AttributeTypeEnum.VARIANT, AttributeTypeEnum.PRODUCT), (AttributeTypeEnum.PRODUCT, AttributeTypeEnum.PRODUCT), (AttributeTypeEnum.VARIANT, AttributeTypeEnum.VARIANT), ), ) def", "$moves: [ReorderInput]! $type: AttributeTypeEnum! ) { productTypeReorderAttributes( productTypeId: $productTypeId moves:", "] variables = {\"filters\": {\"ids\": global_ids}} expected_slugs = sorted([attribute_list[0].slug, attribute_list[1].slug])", "value is ignored and the queryset is simply returned without", "} productType { id variantAttributes { id } productAttributes {", "attributes(first: 20, %(filter_input)s) { edges { node { id name", "mutation createAttributeValue( $attributeId: ID!, $name: String!) { attributeValueCreate( attribute: $attributeId,", "variant_attributes = product[\"variants\"][0][\"attributes\"] assert len(product_attributes) == 2, \"Non-assigned attr from", "edges { node { %s } } } } \"\"\"", "assert len(products[0][\"node\"][\"variants\"]) == 1 # Retrieve the nodes data product", "): \"\"\"Checks if the attributes are restricted and if their", "value = pink_attribute_value.attribute.values.create( name=\"<NAME>\", slug=\"example-name\", value=\"#RED\" ) node_id = graphene.Node.to_global_id(\"AttributeValue\",", "get_graphql_content(response) data = content[\"data\"][\"attributeValueUpdate\"] value.refresh_from_db() assert data[\"attributeValue\"][\"name\"] == name ==", "assert len(product[\"attributes\"]) == expected_product_attribute_count assert len(product[\"variants\"][0][\"attributes\"]) == expected_variant_attribute_count def test_resolve_attribute_values(user_api_client,", "node_id = graphene.Node.to_global_id(\"Attribute\", attribute.id) attribute_value_id = attribute.values.first().id value_id = graphene.Node.to_global_id(\"AttributeValue\",", "data[\"attribute\"][\"name\"] == name == attribute.name assert not attribute.values.filter(pk=attribute_value_id).exists() assert attribute.values.filter(name=attribute_value_name).exists()", "(\"hsla(120, 60%, 70%, 0.3)\", AttributeValueType.COLOR), (\"rgba(100%, 255, 0, 0)\", AttributeValueType.COLOR),", "= ASSIGN_ATTR_QUERY operations = [] variables = {\"productTypeId\": product_type_global_id, \"operations\":", "1}], } content = get_graphql_content( staff_api_client.post_graphql( ATTRIBUTE_VALUES_RESORT_QUERY, variables, permissions=[permission_manage_products], )", "product_type_without_variant, color_attribute_without_values, ): \"\"\"The assignAttribute mutation should raise an error", "Q(attributevariant__product_type_id=product_type.pk) ) # Create another product type and attribute that", ") get_graphql_content(response) attribute.refresh_from_db() assert attribute.values.count() == 1 assert attribute.values.filter(name=attribute_value_name).exists() @pytest.mark.parametrize(", "AttributeValueType.STRING), (\"linear-gradient(red, yellow)\", AttributeValueType.GRADIENT), (\"radial-gradient(#0000, yellow)\", AttributeValueType.GRADIENT), ], ) def", "} } \"\"\" found_products = get_graphql_content( staff_api_client.post_graphql(query, permissions=[permission_manage_products]) )[\"data\"][\"products\"][\"edges\"] assert", "assignAttribute mutation should raise an error when trying to add", "graphene.Node.to_global_id(\"AttributeValue\", attribute_value_id) variables = { \"name\": name, \"id\": node_id, \"addValues\":", "content[\"errors\"] == [ { \"field\": \"productTypeId\", \"message\": f\"Couldn't resolve to", "graphene.Node.to_global_id(\"Attribute\", attribute.id) m2m_values = attribute.values m2m_values.set(values) assert values == sorted(", "} } } } \"\"\" def test_sort_attributes_by_slug(api_client): Attribute.objects.bulk_create( [ Attribute(name=\"MyAttribute\",", "type.\"\"\" product_type = ProductType.objects.create(name=\"Dummy Type\") product_type_id = graphene.Node.to_global_id(\"ProductType\", product_type.id) attribute_id", "test_attributes_filter_by_product_type_with_unsupported_field(): \"\"\"Ensure using an unknown field to filter attributes by", "len( variant_attributes_ids ) found_product_attrs_ids = { int(graphene.Node.from_global_id(attr[\"id\"])[1]) for attr in", "\"in_category\", category_id) assert qs == mocked_qs.none.return_value @pytest.mark.parametrize(\"test_deprecated_filter\", [True, False]) @pytest.mark.parametrize(\"tested_field\",", "not content[\"errors\"] assert content[\"productType\"][\"id\"] == product_type_global_id assert len(content[\"productType\"][\"productAttributes\"]) == 1", "attribute_list[:2]} variant_attributes_ids = {attr.pk for attr in attribute_list[2:]} for attr_id", "get_graphql_content( staff_api_client.post_graphql(query, permissions=[permission_manage_products]) )[\"data\"][\"attributes\"][\"edges\"] assert len(found_attributes) == 1 assert found_attributes[0][\"node\"][attribute]", "attributes = Attribute.objects query = QUERY_ATTRIBUTES response = user_api_client.post_graphql(query) content", "hidden attributes, and staff users having the 'manage product' permission", "the node (product/variant), thus no values should be resolved. \"\"\"", "= get_graphql_content(response) data = content[\"data\"][\"attributeValueUpdate\"] assert data[\"errors\"] assert data[\"errors\"][0][\"message\"] assert", "[{\"field\": \"slug\", \"message\": \"The attribute's slug cannot be blank.\"}], ),", "to this product type.\", } ] UNASSIGN_ATTR_QUERY = \"\"\" mutation", "\"\"\" def test_sort_attributes_within_product_type_invalid_product_type( staff_api_client, permission_manage_products ): \"\"\"Try to reorder an", "type\" gql_attributes = content[\"productType\"][snake_to_camel_case(relation_field)] assert len(gql_attributes) == len(expected_order) for attr,", "name_2, error_msg, error_code, permission_manage_products, product_type, ): query = CREATE_ATTRIBUTES_QUERY variables", "product.attributes.first().values.values_list(\"slug\", flat=True) ) variant_attribute_values = list( variant.attributes.first().values.values_list(\"slug\", flat=True) ) assert", "[ { \"id\": graphene.Node.to_global_id(\"Attribute\", attributes[0].pk), \"sortOrder\": +1, }, { \"id\":", "slug } } } } \"\"\" def test_search_attributes(api_client, color_attribute, size_attribute):", "error is as expected: null or something else assert content[\"data\"][\"attributeCreate\"][\"errors\"]", "product_errors[0][\"code\"] == error_code.name def test_update_attribute_and_remove_others_attribute_value( staff_api_client, color_attribute, size_attribute, permission_manage_products ):", "staff_api_client, product, permission_manage_products ): query = \"\"\" { products(first: 10)", "product type doesn't support variants\"\"\" product_type = product_type_without_variant attribute =", "we are only working on one product and variant, the", "get_graphql_content(staff_api_client.post_graphql(query, {\"id\": node_id}))[ \"data\" ] attributes = data[\"productVariant\" if is_variant", "is None assert variant_attributes[0][\"attribute\"][\"slug\"] == \"variant\" assert variant_attributes[0][\"values\"] == []", "graphene.Node.to_global_id(\"Category\", category.pk) else: raise AssertionError(tested_field) expected_qs = Attribute.objects.filter( Q(attributeproduct__product_type_id=product_type.pk) |", "the attribute shouldn't be taken into account validate_value_is_unique(color_attribute, value) def", "attributes_data = content[\"data\"][\"attributes\"][\"edges\"] assert len(attributes_data) == attribute_count def test_attributes_query_hidden_attribute_as_staff_user( staff_api_client,", "= graphene.Node.to_global_id(\"Attribute\", attribute.id) variables = { \"name\": name, \"id\": node_id,", "= \"<NAME>\" attribute_value_name = \"Yellow Color\" node_id = graphene.Node.to_global_id(\"Attribute\", attribute.id)", "= [ graphene.Node.to_global_id(\"Attribute\", attribute.pk) for attribute in attribute_list[:2] ] variables", "data = content[\"data\"][\"attributeUpdate\"] assert data[\"attribute\"][\"name\"] == name == attribute.name assert", "product type and attribute that shouldn't get matched other_category =", "== [] ASSIGN_ATTR_QUERY = \"\"\" mutation assign($productTypeId: ID!, $operations: [AttributeAssignInput]!)", "product_type_global_id assert len(content[\"productType\"][\"productAttributes\"]) == 0 assert len(content[\"productType\"][\"variantAttributes\"]) == 0 def", "graphene.Node.to_global_id(\"AttributeValue\", value.id) variables = {\"id\": node_id} staff_api_client.post_graphql( query, variables, permissions=[permission_manage_products]", "{ attributeDelete(id: $id) { errors { field message } attribute", "make sure it is always the last attribute # when", "# when sorted by ID. Thus, we are sure the", "elif \"Category\" in tested_field: filtered_by_node_id = graphene.Node.to_global_id(\"Category\", category.pk) else: raise", "= other_attribute.attributeproduct.last() # Push the last attribute to the top", "is as expected: null or something else assert content[\"data\"][\"attributeCreate\"][\"errors\"] ==", "= attribute.values.first().name variables = {\"name\": value_name, \"attributeId\": attribute_id} response =", "not belong to this attribute.\" % str(size_attribute) assert errors[0][\"message\"] ==", "are not unique.\", ProductErrorCode.UNIQUE, ), ( \"Red color\", \"red color\",", "{ id } variantAttributes { id } } } }", "a variant attribute when the product type doesn't support variants\"\"\"", "data product = products[0][\"node\"] variant = product[\"variants\"][0] # Ensure the", "the product type and push them at the top #", "# value that already belongs to the attribute shouldn't be", "attribute_list ): product_type = ProductType.objects.create(name=\"Default Type\", has_variants=True) product_type_global_id = graphene.Node.to_global_id(\"ProductType\",", ") def test_update_attribute_and_add_attribute_values_errors( staff_api_client, name_1, name_2, error_msg, error_code, color_attribute, permission_manage_products,", "staff_user): \"\"\"Ensure the attribute values are properly resolved.\"\"\" query =", "edges { node { id name slug } } }", "permission_manage_products ): query = QUERY_ATTRIBUTES # hide the attribute color_attribute.visible_in_storefront", "a given product type.\"\"\" product_type = ProductType.objects.create(name=\"My Product Type\") m2m_model.objects.create(", "attr_id)} ) content = get_graphql_content( staff_api_client.post_graphql( query, variables, permissions=[permission_manage_products] )", "= ProductType.objects.create(name=\"Dummy Type\") product_type_id = graphene.Node.to_global_id(\"ProductType\", product_type.id) m2m_attributes = getattr(product_type,", ") )[\"data\"][\"attributeAssign\"] assert not content[\"errors\"], \"Should have succeeded\" assert content[\"productType\"][\"id\"]", "slug } } } } } } } \"\"\" @pytest.mark.parametrize(\"is_staff\",", "\"\"\" @pytest.mark.parametrize(\"is_staff\", (False, True)) def test_resolve_attributes_with_hidden( user_api_client, product, color_attribute, size_attribute,", "f\"{tested_field}: $nodeID\"} else: query = query % {\"filter_input\": \"filter: {", "{ values { name } } } } \"\"\" def", "received_slugs == expected_slugs ATTRIBUTES_SORT_QUERY = \"\"\" query($sortBy: AttributeSortingInput) { attributes(first:", "attribute_name, \"slug\": input_slug} content = get_graphql_content(staff_api_client.post_graphql(query, variables)) # Check if", "attribute.id) value_name = attribute.values.first().name variables = {\"name\": value_name.upper(), \"attributeId\": attribute_id}", "error_msg, error_code, color_attribute, permission_manage_products, ): query = UPDATE_ATTRIBUTE_QUERY attribute =", "[ { \"field\": \"operations\", \"message\": \"Variants are disabled in this", "assert variant_attributes[0][\"value\"][\"slug\"] == variant_attribute_values[0] def test_resolve_attribute_values_non_assigned_to_node( user_api_client, product, staff_user ):", "attribute=unassigned_product_attribute), AttributeValue(slug=\"b\", name=\"B\", attribute=unassigned_product_attribute), ] ) # Assign the dummy", "set.\"\"\" category_id = graphene.Node.to_global_id(\"Category\", -1) mocked_qs = mock.MagicMock() qs =", "} } } \"\"\" % attribute ) found_attributes = get_graphql_content(", "{ attribute { id values { id } } errors", "users having the 'manage product' permission can. \"\"\" query =", "# Ensure the product attributes values are all None assert", "slugify(name) assert name in [value[\"name\"] for value in data[\"attribute\"][\"values\"]] def", "} } } } \"\"\" found_products = get_graphql_content( staff_api_client.post_graphql(query, permissions=[permission_manage_products])", "assert values == sorted( values, key=lambda o: o.sort_order if o.sort_order", "assert found_product_attrs_ids == product_attributes_ids assert found_variant_attrs_ids == variant_attributes_ids def test_assign_variant_attribute_to_product_type_with_disabled_variants(", "{value_id}\", } ] def test_sort_values_within_attribute( staff_api_client, color_attribute, permission_manage_products ): attribute", "== 1 assert variant.attributes.count() == 1 product = get_graphql_content(api_client.post_graphql(query))[\"data\"][\"products\"][ \"edges\"", "[] def test_update_attribute_remove_and_add_values( staff_api_client, color_attribute, permission_manage_products ): query = UPDATE_ATTRIBUTE_QUERY", "node_id, \"removeValues\": [], \"addValues\": [{\"name\": name_1}, {\"name\": name_2}], } response", "size_attribute.pk) variables = { \"name\": \"Example name\", \"id\": node_id, \"slug\":", "{\"name\": pink_attribute_value.name, \"id\": node_id} response = staff_api_client.post_graphql( query, variables, permissions=[permission_manage_products]", "of products and variants are sorted.\"\"\" variant = product.variants.first() if", "permission_manage_products ): query = UPDATE_ATTRIBUTE_VALUE_QUERY value = pink_attribute_value.attribute.values.create( name=\"<NAME>\", slug=\"example-name\",", "get_graphql_content(api_client.post_graphql(query))[\"data\"][\"products\"][ \"edges\" ][0][\"node\"] assert len(product[\"attributes\"]) == expected_product_attribute_count assert len(product[\"variants\"][0][\"attributes\"]) ==", "{ int(graphene.Node.from_global_id(attr[\"id\"])[1]) for attr in content[\"productType\"][\"variantAttributes\"] } assert found_product_attrs_ids ==", "assert len(attributes) == 2 assert attributes[0][\"node\"][\"slug\"] == \"a\" assert attributes[1][\"node\"][\"slug\"]", "[other_attribute.pk, color_attribute.pk] # Make the node ID if is_variant: node_id", "attributes data = get_graphql_content(staff_api_client.post_graphql(query, {\"id\": node_id}))[ \"data\" ] attributes =", "\"Should have found an attribute\" assert content[\"data\"][\"attribute\"][\"id\"] == attribute_gql_id assert", "attributes to the product type and push them at the", "slug } values { name } } variants { attributes", "gql_attributes = content[\"productType\"][snake_to_camel_case(relation_field)] assert len(gql_attributes) == len(expected_order) for attr, expected_pk", "String!, $slug: String) { attributeCreate(input: {name: $name, slug: $slug}) {", "= sorted([attribute_list[0].slug, attribute_list[1].slug]) attributes = get_graphql_content( api_client.post_graphql(ATTRIBUTES_FILTER_QUERY, variables) )[\"data\"][\"attributes\"][\"edges\"] assert", "len(attributes_data) == attribute_count QUERY_PRODUCT_AND_VARIANTS_ATTRIBUTES = \"\"\" { products(first: 1) {", "assert errors assert errors[0][\"field\"] == \"removeValues\" err_msg = \"Value %s", "% attribute ) found_attributes = get_graphql_content( staff_api_client.post_graphql(query, permissions=[permission_manage_products]) )[\"data\"][\"attributes\"][\"edges\"] assert", "top # through a sort_order=0 as the other attributes have", "== sorted( values, key=lambda o: o.sort_order if o.sort_order is not", "having for input types ['multiselect'] cannot be assigned \" \"as", "permission_manage_products ): query = UPDATE_ATTRIBUTE_QUERY attribute = color_attribute_without_values name =", "errors { field message } productErrors { field message code", "= content[\"attribute\"][\"values\"] assert len(gql_values) == len(expected_order) actual_order = [] for", "assert Attribute.objects.get_visible_to_user(staff_api_client.user).count() == 1 # The user should now be", "attribute that is not/no longer in the product type.\"\"\" staff_api_client.user.user_permissions.add(permission_manage_products)", "one product and variant, the ones we are testing assert", "(\"DASHBOARD_PRODUCT_POSITION\", AttributeProduct), ), ) def test_sort_attributes_by_position_in_product_type( api_client, color_attribute, size_attribute, sort_field:", "when trying to use an attribute as a variant attribute", "False color_attribute.save(update_fields=[\"visible_in_storefront\"]) attribute_count = Attribute.objects.get_visible_to_user( user_api_client.user ).count() assert attribute_count ==", "{ slug } value { slug } } } }", "\"attributeId\": attribute_id} response = staff_api_client.post_graphql( query, variables, permissions=[permission_manage_products] ) content", "( (\"my-slug\", \"my-slug\", []), (None, \"my-name\", []), ( \"\", None,", "assert content[\"errors\"] == [ { \"field\": \"moves\", \"message\": f\"Couldn't resolve", "\"addValues\": [{\"name\": name_1}, {\"name\": name_2}], } response = staff_api_client.post_graphql( query,", "= [ int(graphene.Node.from_global_id(attr[\"attribute\"][\"id\"])[1]) for attr in attributes ] # Compare", "saleor.product import AttributeInputType from saleor.product.error_codes import ProductErrorCode from saleor.product.models import", "slug } } } } \"\"\" def test_sort_attributes_by_slug(api_client): Attribute.objects.bulk_create( [", "are testing assert len(products) == 1 assert len(products[0][\"node\"][\"variants\"]) == 1", "assert content[\"productType\"][\"id\"] == product_type_global_id assert len(content[\"productType\"][\"productAttributes\"]) == len( product_attributes_ids )", "$removeValues}) { errors { field message } productErrors { field", "price=zero_money(), is_published=True, ) # Create another collection with products but", "\"data\" ][\"attributeAssign\"] assert content[\"errors\"] == [ { \"field\": \"operations\", \"message\":", "node { id name slug } } } } \"\"\"", "-1) value_id = graphene.Node.to_global_id(\"AttributeValue\", -1) variables = { \"attributeId\": attribute_id,", "\"field\": \"moves\", \"message\": f\"Couldn't resolve to an attribute: {attribute_id}\", }", "color_attribute, size_attribute, staff_user, is_staff, permission_manage_products, ): \"\"\"Ensure non-staff users don't", "name\" variables = {\"name\": attribute_name, \"values\": [{\"name\": name}]} response =", "= get_graphql_content(response) data = content[\"data\"][\"attributeValueUpdate\"] value.refresh_from_db() assert data[\"attributeValue\"][\"name\"] == name", "Type\") product_type_id = graphene.Node.to_global_id(\"ProductType\", product_type.id) m2m_attributes = getattr(product_type, relation_field) m2m_attributes.set(attributes)", "product_type = ProductType.objects.create(name=\"Default Type\", has_variants=True) product_type_global_id = graphene.Node.to_global_id(\"ProductType\", product_type.pk) query", "assert data[\"errors\"][0][\"message\"] assert data[\"errors\"][0][\"field\"] == \"name\" def test_delete_attribute_value( staff_api_client, color_attribute,", "staff_api_client.user.user_permissions.add(permission_manage_products) product_type_global_id = graphene.Node.to_global_id(\"ProductType\", product_type.pk) query = ASSIGN_ATTR_QUERY operations =", "# Check if the attribute was correctly created assert data[\"attribute\"][\"name\"]", "{ attributeValueUpdate( id: $id, input: {name: $name}) { errors {", "} } } } } } } \"\"\" ) )[\"data\"][\"products\"][\"edges\"]", "error with pytest.raises(ValidationError): validate_value_is_unique(color_attribute, AttributeValue(slug=value.slug)) # a new value with", "variant attributes\" ), } ] @pytest.mark.parametrize( \"product_type_attribute_type, gql_attribute_type\", ( (AttributeTypeEnum.PRODUCT,", "color_attribute ): \"\"\"Try to reorder an attribute not associated to", "attribute.input_type = AttributeInputType.MULTISELECT attribute.save(update_fields=[\"input_type\"]) product_type.variant_attributes.clear() staff_api_client.user.user_permissions.add(permission_manage_products) product_type_global_id = graphene.Node.to_global_id(\"ProductType\", product_type.pk)", "False color_attribute.save(update_fields=[\"available_in_grid\"]) variables = {\"filters\": {\"availableInGrid\": True}} attributes = get_graphql_content(", "filter_attributes_by_product_types(qs, \"...\", \"\") is qs assert filter_attributes_by_product_types(qs, \"...\", None) is", "don't see hidden attributes, and staff users having the 'manage", "the product type but not of the node (product/variant), thus", "{\"filterableInDashboard\": True}} attributes = get_graphql_content( api_client.post_graphql(ATTRIBUTES_FILTER_QUERY, variables) )[\"data\"][\"attributes\"][\"edges\"] assert len(attributes)", "err_msg product_errors = content[\"data\"][\"attributeUpdate\"][\"productErrors\"] assert product_errors[0][\"code\"] == ProductErrorCode.INVALID.name def test_delete_attribute(", "variables, permissions=[permission_manage_products] ) content = get_graphql_content(response) errors = content[\"data\"][\"attributeCreate\"][\"errors\"] assert", "attr_id in variant_attributes_ids: operations.append( {\"type\": \"VARIANT\", \"id\": graphene.Node.to_global_id(\"Attribute\", attr_id)} )", "{\"name\": attribute_name, \"values\": [{\"name\": name}]} response = staff_api_client.post_graphql( query, variables,", "gql_type, gql_attr_id = graphene.Node.from_global_id(attr[\"id\"]) assert gql_type == \"Attribute\" assert int(gql_attr_id)", "color_attribute.values.first() ) # Sort the database attributes by their sort", "query % {\"filter_input\": \"filter: { %s: $nodeID }\" % tested_field}", "attribute = color_attribute query = \"\"\" mutation deleteAttribute($id: ID!) {", "at the top # through a sort_order=0 as the other", "{ edges { node { slug } } } }", "\"\"\" else: query = \"\"\" query($id: ID!) { product(id: $id)", "passing an empty or null value is ignored and the", "| Q(attributevariant__product_type_id=product_type.pk) ) # Create another product type and attribute", "= content[\"data\"][\"attributeUpdate\"][\"productErrors\"] assert product_errors[0][\"code\"] == ProductErrorCode.INVALID.name def test_delete_attribute( staff_api_client, color_attribute,", "color_attribute.id) variables = { \"type\": \"VARIANT\", \"productTypeId\": product_type_id, \"moves\": [{\"id\":", "{\"sortBy\": {\"field\": sort_field, \"direction\": \"DESC\"}} attributes = get_graphql_content( api_client.post_graphql(ATTRIBUTES_SORT_QUERY, variables)", "( (\"DASHBOARD_VARIANT_POSITION\", AttributeVariant), (\"DASHBOARD_PRODUCT_POSITION\", AttributeProduct), ), ) def test_sort_attributes_by_position_in_product_type( api_client,", "== 1 product_attribute_values = list( product.attributes.first().values.values_list(\"slug\", flat=True) ) variant_attribute_values =", "import validate_value_is_unique from saleor.graphql.product.types.attributes import resolve_attribute_value_type from saleor.product import AttributeInputType", "type.\", } ] UNASSIGN_ATTR_QUERY = \"\"\" mutation unAssignAttribute( $productTypeId: ID!,", "\"attributeId\": attribute_id, \"moves\": [ { \"id\": graphene.Node.to_global_id(\"AttributeValue\", values[0].pk), \"sortOrder\": +1,", "expected_type): assert resolve_attribute_value_type(raw_value) == expected_type def test_resolve_assigned_attribute_without_values(api_client, product_type, product): \"\"\"Ensure", "UPDATE_ATTRIBUTE_QUERY attribute = color_attribute_without_values name = \"<NAME>\" attribute_value_name = \"Yellow", "assert content[\"errors\"] == [ { \"field\": \"productTypeId\", \"message\": f\"Couldn't resolve", "mutation createAttribute( $name: String!, $slug: String) { attributeCreate(input: {name: $name,", "to a product type: {product_type_id}\", } ] def test_sort_attributes_within_product_type_invalid_id( staff_api_client,", "api_client.post_graphql(ATTRIBUTES_FILTER_QUERY, variables) )[\"data\"][\"attributes\"][\"edges\"] assert len(attributes) == 2 received_slugs = sorted(", "values { type inputType } } } } } }", "test_assign_variant_attribute_to_product_type_with_disabled_variants( staff_api_client, permission_manage_products, product_type_without_variant, color_attribute_without_values, ): \"\"\"The assignAttribute mutation should", "= UPDATE_ATTRIBUTE_QUERY attribute = color_attribute name = \"<NAME>\" attribute_value_name =", "when an attribute is part of the product type but", "= False attribute.save(update_fields=[\"visible_in_storefront\"]) product = get_graphql_content(api_client.post_graphql(query))[\"data\"][\"products\"][ \"edges\" ][0][\"node\"] assert len(product[\"attributes\"])", "query($id: ID!) { attribute(id: $id) { id slug } }", "len(product[\"attributes\"]) == expected_product_attribute_count assert len(product[\"variants\"][0][\"attributes\"]) == expected_variant_attribute_count def test_resolve_attribute_values(user_api_client, product,", "content[\"productType\"][\"id\"] == product_type_global_id assert len(content[\"productType\"][\"productAttributes\"]) == 1 assert len(content[\"productType\"][\"variantAttributes\"]) ==", "[ { \"field\": \"productTypeId\", \"message\": f\"Couldn't resolve to a product", "expected_product_attribute_count += 1 expected_variant_attribute_count += 1 staff_user.user_permissions.add(permission_manage_products) # Hide one", "ProductType.objects.create(name=\"Default Type\", has_variants=True) product_type_global_id = graphene.Node.to_global_id(\"ProductType\", product_type.pk) query = ASSIGN_ATTR_QUERY", "attributes[2].pk, attributes[0].pk] content = get_graphql_content( staff_api_client.post_graphql(ATTRIBUTES_RESORT_QUERY, variables) )[\"data\"][\"productTypeReorderAttributes\"] assert not", "operations: $operations) { errors { field message } productType {", "assert attributes[1][\"node\"][\"slug\"] == \"color\" def test_sort_attributes_by_default_sorting(api_client): \"\"\"Don't provide any sorting,", "filter: $filters) { edges { node { name slug }", "permission_manage_products, input_slug, expected_slug, expected_error, ): staff_api_client.user.user_permissions.add(permission_manage_products) query = \"\"\" mutation", "for input types ['multiselect'] cannot be assigned \" \"as variant", "\"id\": node_id, \"addValues\": [{\"name\": attribute_value_name}], \"removeValues\": [value_id], } response =", "types ['multiselect'] cannot be assigned \" \"as variant attributes\" ),", "\"variant\" assert variant_attributes[0][\"values\"] == [] assert variant_attributes[0][\"value\"] is None def", "with existing slug should raise an error with pytest.raises(ValidationError): validate_value_is_unique(color_attribute,", "assert content[\"productType\"][\"id\"] == product_type_global_id assert len(content[\"productType\"][\"productAttributes\"]) == 0 assert len(content[\"productType\"][\"variantAttributes\"])", "String) { attributeCreate(input: {name: $name, slug: $slug}) { errors {", "), } ] @pytest.mark.parametrize( \"product_type_attribute_type, gql_attribute_type\", ( (AttributeTypeEnum.PRODUCT, AttributeTypeEnum.VARIANT), (AttributeTypeEnum.VARIANT,", "attribute: $attributeId, input: {name: $name}) { productErrors { field message", ") content = get_graphql_content(response) attribute.refresh_from_db() data = content[\"data\"][\"attributeUpdate\"] assert not", "edges { node { id name slug values { id", "def test_attributes_filter_by_product_type_with_empty_value(): \"\"\"Ensure passing an empty or null value is", "products but shouldn't get matched # as we don't look", "expected one.\"\"\" attribute = to_camel_case(attribute) query = ( \"\"\" {", "name_2, error_msg, error_code, color_attribute, permission_manage_products, ): query = UPDATE_ATTRIBUTE_QUERY attribute", "len( product_attributes_ids ) assert len(content[\"productType\"][\"variantAttributes\"]) == len( variant_attributes_ids ) found_product_attrs_ids", "\"attribute_type, relation_field, backref_field\", ( (\"VARIANT\", \"variant_attributes\", \"attributevariant\"), (\"PRODUCT\", \"product_attributes\", \"attributeproduct\"),", "filter_attributes_by_product_types(mocked_qs, \"in_category\", category_id) assert qs == mocked_qs.none.return_value @pytest.mark.parametrize(\"test_deprecated_filter\", [True, False])", "are not unique.\", ProductErrorCode.UNIQUE, ), ), ) def test_update_attribute_and_add_attribute_values_errors( staff_api_client,", "} } \"\"\" # Create a dummy attribute with a", "= staff_api_client.post_graphql( query, variables, permissions=[permission_manage_products] ) content = get_graphql_content(response) errors", "attribute: {attribute_id}\", } ] def test_sort_values_within_attribute_invalid_id( staff_api_client, permission_manage_products, color_attribute ):", "node_id} response = staff_api_client.post_graphql( query, variables, permissions=[permission_manage_products] ) content =", "} attribute { slug } } } \"\"\" attribute_name =", "staff_api_client.post_graphql(query) content = get_graphql_content(response) attributes_data = content[\"data\"][\"attributes\"][\"edges\"] assert len(attributes_data) ==", "removeValues: $removeValues}) { errors { field message } productErrors {", "given product type.\"\"\" product_type = ProductType.objects.create(name=\"My Product Type\") m2m_model.objects.create( product_type=product_type,", "= \"\"\" query($id: ID!) { product(id: $id) { attributes {", "attributeDelete(id: $id) { errors { field message } attribute {", "attributeIds: $attributeIds) { errors { field message } productType {", "validate_value_is_unique( color_attribute, AttributeValue(slug=\"spanish-inquisition\") ) # value that already belongs to", "product.product_type # Create dummy attributes unassigned_product_attribute = Attribute.objects.create(name=\"P\", slug=\"product\") unassigned_variant_attribute", "\"VARIANT\", \"attributeId\": attribute_id, \"moves\": [{\"id\": value_id, \"sortOrder\": 1}], } content", ") def test_create_attribute_with_given_slug( staff_api_client, permission_manage_products, input_slug, expected_slug, expected_error, ): staff_api_client.user.user_permissions.add(permission_manage_products)", "} \"\"\" def test_sort_attributes_within_product_type_invalid_product_type( staff_api_client, permission_manage_products ): \"\"\"Try to reorder", "$productTypeId, attributeIds: $attributeIds) { errors { field message } productType", "{}) )[\"data\"][\"attributes\"][\"edges\"] assert len(attributes) == 2 assert attributes[0][\"node\"][\"slug\"] == \"b\"", "data[\"attribute\"][\"name\"] == name == attribute.name assert data[\"attribute\"][\"productTypes\"][\"edges\"] == [] def", "as we don't look for this other collection other_collection =", "None assert len(product[\"attributes\"]) == 1 assert product[\"attributes\"][0][\"attribute\"][\"slug\"] == \"color\" assert", "len(attributes) == 2 assert attributes[0][\"node\"][\"slug\"] == \"a\" assert attributes[1][\"node\"][\"slug\"] ==", "raise an error when trying to add an attribute already", "$type ) { productType { id variantAttributes { id slug", "name slug values { id name slug } } }", "in content[\"productType\"][\"productAttributes\"] } found_variant_attrs_ids = { int(graphene.Node.from_global_id(attr[\"id\"])[1]) for attr in", "filtered_by_node_id = graphene.Node.to_global_id(\"Collection\", collection.pk) elif \"Category\" in tested_field: filtered_by_node_id =", "id productAttributes { id } variantAttributes { id } }", "{ \"field\": \"operations\", \"message\": \"Variants are disabled in this product", "= graphene.Node.to_global_id(\"AttributeValue\", value.id) name = \"Crimson name\" variables = {\"name\":", "test_attributes_query(user_api_client, product): attributes = Attribute.objects query = QUERY_ATTRIBUTES response =", "attribute: {attribute_id}\", } ] @pytest.mark.parametrize( \"attribute_type, relation_field, backref_field\", ( (\"VARIANT\",", "+1, }, { \"id\": graphene.Node.to_global_id(\"Attribute\", attributes[2].pk), \"sortOrder\": -1, }, ],", "test_filter_attributes_by_global_id_list(api_client, attribute_list): global_ids = [ graphene.Node.to_global_id(\"Attribute\", attribute.pk) for attribute in", "variant = product.variants.first() product_attribute = color_attribute variant_attribute = size_attribute expected_product_attribute_count", "} } \"\"\" def test_sort_attributes_within_product_type_invalid_product_type( staff_api_client, permission_manage_products ): \"\"\"Try to", "# Assign the dummy attributes to the product type and", "{ \"type\": attribute_type, \"productTypeId\": product_type_id, \"moves\": [ { \"id\": graphene.Node.to_global_id(\"Attribute\",", "ProductVariant, ) from saleor.product.utils.attributes import associate_attribute_values_to_instance from tests.api.utils import get_graphql_content", "assert attributes[0][\"node\"][\"slug\"] == \"color\" def test_filter_attributes_if_filterable_in_dashboard( api_client, color_attribute, size_attribute ):", "errors[0][\"field\"] == \"removeValues\" err_msg = \"Value %s does not belong", "zero_money from saleor.graphql.core.utils import snake_to_camel_case from saleor.graphql.product.enums import AttributeTypeEnum, AttributeValueType", "graphene.Node.to_global_id(\"Attribute\", attribute.id) value_name = attribute.values.first().name variables = {\"name\": value_name.upper(), \"attributeId\":", "test_create_attribute_and_attribute_values( staff_api_client, permission_manage_products ): query = CREATE_ATTRIBUTES_QUERY attribute_name = \"<NAME>\"", "assert data[\"attribute\"][\"name\"] == attribute_name assert data[\"attribute\"][\"slug\"] == slugify( attribute_name ),", "assert attributes[0][\"node\"][\"slug\"] == \"b\" assert attributes[1][\"node\"][\"slug\"] == \"a\" @pytest.mark.parametrize(\"is_variant\", (True,", "ID!) { product(id: $id) { attributes { attribute { id", "and let the others to None m2m_rel_other_attr.sort_order = 0 m2m_rel_other_attr.save(update_fields=[\"sort_order\"])", "AttributeProduct, AttributeValue, AttributeVariant, Category, Collection, Product, ProductType, ProductVariant, ) from", "errors { field message } productType { id variantAttributes {", "staff_api_client, color_attribute, permission_manage_products ): query = UPDATE_ATTRIBUTE_QUERY attribute = color_attribute", "value_id = graphene.Node.to_global_id(\"AttributeValue\", -1) variables = { \"type\": \"VARIANT\", \"attributeId\":", "= get_graphql_content(response) attributes_data = content[\"data\"][\"attributes\"][\"edges\"] assert attributes_data assert len(attributes_data) ==", "= {\"productTypeId\": product_type_global_id, \"operations\": operations} product_attributes_ids = {attr.pk for attr", "== attributes.count() def test_attributes_query_hidden_attribute(user_api_client, product, color_attribute): query = QUERY_ATTRIBUTES #", "the last attribute # when sorted by ID. Thus, we", "graphene.utils.str_converters import to_camel_case from saleor.core.taxes import zero_money from saleor.graphql.core.utils import", "response = user_api_client.post_graphql(query) content = get_graphql_content(response) attributes_data = content[\"data\"][\"attributes\"][\"edges\"] assert", "{ field message code } attribute { values { name", "Type\") product_type_id = graphene.Node.to_global_id(\"ProductType\", product_type.id) attribute_id = graphene.Node.to_global_id(\"Attribute\", color_attribute.id) variables", "\"\"\" % attribute ) found_attributes = get_graphql_content( staff_api_client.post_graphql(query, permissions=[permission_manage_products]) )[\"data\"][\"attributes\"][\"edges\"]", "doesn't support variants\"\"\" attribute = size_attribute attribute.input_type = AttributeInputType.MULTISELECT attribute.save(update_fields=[\"input_type\"])", "(\"filterable_in_dashboard\", True), (\"visible_in_storefront\", True), (\"available_in_grid\", True), (\"value_required\", False), (\"storefront_search_position\", 0),", "assigned to a product type are resolved even if the", "== attribute_name assert data[\"attribute\"][\"slug\"] == slugify( attribute_name ), \"The default", "\"operations\": operations} product_attributes_ids = {attr.pk for attr in attribute_list[:2]} variant_attributes_ids", "1 assert len(products[0][\"node\"][\"variants\"]) == 1 # Retrieve the nodes data", "def test_resolve_attribute_values(user_api_client, product, staff_user): \"\"\"Ensure the attribute values are properly", "from the PT may be missing\" assert len(variant_attributes) == 2,", "= product.product_type # Create dummy attributes unassigned_product_attribute = Attribute.objects.create(name=\"P\", slug=\"product\")", "} \"\"\" # Create a dummy attribute with a higher", "Union[AttributeVariant, AttributeProduct], ): \"\"\"Sorts attributes for dashboard custom ordering inside", "query is actually passing the test. other_attribute = Attribute.objects.create(name=\"Other\", slug=\"other\")", "higher ID # This will allow us to make sure", "== product_type_global_id assert len(content[\"productType\"][\"productAttributes\"]) == 0 assert len(content[\"productType\"][\"variantAttributes\"]) == 0", "product_type, size_attribute ): \"\"\"The assignAttribute mutation should raise an error", "- 1 if is_staff: api_client.user = staff_user expected_product_attribute_count += 1", "attribute.values.first().name variables = {\"name\": value_name, \"attributeId\": attribute_id} response = staff_api_client.post_graphql(", "slugify(name) @pytest.mark.parametrize( \"input_slug, expected_slug, expected_error\", ( (\"my-slug\", \"my-slug\", []), (None,", "attribute_gql_id assert content[\"data\"][\"attribute\"][\"slug\"] == color_attribute_without_values.slug QUERY_ATTRIBUTES = \"\"\" query {", "id values { id } } errors { field message", "= {\"filters\": {\"availableInGrid\": True}} attributes = get_graphql_content( api_client.post_graphql(ATTRIBUTES_FILTER_QUERY, variables) )[\"data\"][\"attributes\"][\"edges\"]", "attributes to the product node = variant if is_variant else", "else: raise ValueError(f\"Unknown: {product_type}\") query = ASSIGN_ATTR_QUERY operations = [", "attributes values are all None assert variant[\"attributes\"][0][\"attribute\"][\"slug\"] == \"size\" assert", "}, ], } expected_order = [attributes[1].pk, attributes[2].pk, attributes[0].pk] content =", "== error_msg product_errors = content[\"data\"][\"attributeUpdate\"][\"productErrors\"] assert product_errors[0][\"code\"] == error_code.name def", "content[\"data\"][\"attribute\"], \"Should have found an attribute\" assert content[\"data\"][\"attribute\"][\"id\"] == attribute_gql_id", "content[\"errors\"] == [ { \"field\": \"attributeId\", \"message\": f\"Couldn't resolve to", "name slug values { name slug } productTypes(first: 10) {", "attribute.refresh_from_db() CREATE_ATTRIBUTE_VALUE_QUERY = \"\"\" mutation createAttributeValue( $attributeId: ID!, $name: String!)", "resolve_attribute_value_type(raw_value) == expected_type def test_resolve_assigned_attribute_without_values(api_client, product_type, product): \"\"\"Ensure the attributes", "unassigned_product_attribute = Attribute.objects.create(name=\"P\", slug=\"product\") unassigned_variant_attribute = Attribute.objects.create(name=\"V\", slug=\"variant\") # Create", "category ID returns an empty query set.\"\"\" category_id = graphene.Node.to_global_id(\"Category\",", "} productType { id productAttributes { id } variantAttributes {", "variables, permissions=[permission_manage_products] ) content = get_graphql_content(response) data = content[\"data\"][\"attributeValueCreate\"] assert", "{ attributeUnassign(productTypeId: $productTypeId, attributeIds: $attributeIds) { errors { field message", "product type if is_variant: m2m_rel_other_attr = other_attribute.attributevariant.last() else: m2m_rel_other_attr =", "} expected_order = [attributes[1].pk, attributes[2].pk, attributes[0].pk] content = get_graphql_content( staff_api_client.post_graphql(ATTRIBUTES_RESORT_QUERY,", "value = color_attribute.values.get(name=\"Red\") query = \"\"\" mutation updateChoice($id: ID!) {", "assert data[\"productErrors\"][0][\"code\"] == ProductErrorCode.ALREADY_EXISTS.name assert data[\"productErrors\"][0][\"field\"] == \"name\" UPDATE_ATTRIBUTE_VALUE_QUERY =", "], } content = get_graphql_content(staff_api_client.post_graphql(query, variables))[ \"data\" ][\"attributeUnassign\"] assert not", "variables = {\"name\": attribute_name, \"values\": [{\"name\": name}]} response = staff_api_client.post_graphql(", "expected_type def test_resolve_assigned_attribute_without_values(api_client, product_type, product): \"\"\"Ensure the attributes assigned to", "Attribute.objects.create(name=\"Other\", slug=\"other\") other_product_type = ProductType.objects.create( name=\"Other type\", has_variants=True, is_shipping_required=True )", "attribute in (product_attribute, variant_attribute): attribute.visible_in_storefront = False attribute.save(update_fields=[\"visible_in_storefront\"]) product =", "): query = UPDATE_ATTRIBUTE_VALUE_QUERY value = pink_attribute_value node_id = graphene.Node.to_global_id(\"AttributeValue\",", "variables, permissions=[permission_manage_products] ) )[\"data\"][\"attributeAssign\"] assert not content[\"errors\"], \"Should have succeeded\"", "\"attributeIds\": [ graphene.Node.to_global_id(\"Attribute\", product_attributes[0].pk) ], } content = get_graphql_content( staff_api_client.post_graphql(", "def test_get_single_attribute_by_pk(user_api_client, color_attribute_without_values): attribute_gql_id = graphene.Node.to_global_id( \"Attribute\", color_attribute_without_values.id ) query", "{ attributes { attribute { id } } } }", "into account validate_value_is_unique(color_attribute, value) def test_get_single_attribute_by_pk(user_api_client, color_attribute_without_values): attribute_gql_id = graphene.Node.to_global_id(", "= graphene.Node.to_global_id(\"AttributeValue\", -1) variables = { \"attributeId\": attribute_id, \"moves\": [{\"id\":", "attribute_count = Attribute.objects.get_visible_to_user( user_api_client.user ).count() assert attribute_count == 1 response", "= content[\"data\"][\"attributeUpdate\"][\"errors\"] assert errors assert errors[0][\"field\"] == \"addValues\" assert errors[0][\"message\"]", "= products[0][\"node\"] variant = product[\"variants\"][0] # Ensure the product attributes", "error_code\", ( ( \"Red color\", \"Red color\", \"Provided values are", "product_attributes[0][\"attribute\"][\"slug\"] == \"product\" assert product_attributes[0][\"values\"] == [] assert variant_attributes[0][\"value\"] is", "attributes by raises a NotImplemented exception. \"\"\" qs = Attribute.objects.all()", "} productTypes(first: 10) { edges { node { id }", "}, { \"id\": graphene.Node.to_global_id(\"Attribute\", attributes[2].pk), \"sortOrder\": -1, }, ], }", "} ] def test_assign_variant_attribute_having_unsupported_input_type( staff_api_client, permission_manage_products, product_type, size_attribute ): \"\"\"The", "), \"The values are not properly ordered\" variables = {", "expected_error\", ( (\"my-slug\", \"my-slug\", []), (None, \"my-name\", []), ( \"\",", "now be able to see the attributes staff_api_client.user.user_permissions.add(permission_manage_products) response =", "variables = { \"attributeId\": attribute_id, \"moves\": [{\"id\": value_id, \"sortOrder\": 1}],", "= product[\"attributes\"] variant_attributes = product[\"variants\"][0][\"attributes\"] assert len(product_attributes) == len(product_attribute_values) assert", "api_client.post_graphql(ATTRIBUTES_SORT_QUERY, variables) )[\"data\"][\"attributes\"][\"edges\"] assert len(attributes) == 2 assert attributes[0][\"node\"][\"slug\"] ==", "input_slug, expected_slug, expected_error, ): staff_api_client.user.user_permissions.add(permission_manage_products) query = \"\"\" mutation createAttribute(", "{\"name\": \"Example name\", \"values\": [{\"name\": name_1}, {\"name\": name_2}]} response =", "product.variants.first() if is_variant: query = \"\"\" query($id: ID!) { productVariant(id:", "gql_type == \"AttributeValue\" actual_order.append(int(gql_attr_id)) assert actual_order == expected_order ATTRIBUTES_FILTER_QUERY =", "ID!) { attributeValueDelete(id: $id) { attributeValue { name slug }", "attribute_name assert data[\"attribute\"][\"slug\"] == slugify( attribute_name ), \"The default slug" ]
[ "File to upload :param bucket: Bucket to upload to :param", "object s3.download_file(input_bucket_name, file_key, local_input_temp_file) # HSV range # (36, 25,", "local temp file names local_input_temp_file = '/tmp/' + file_key local_output_temp_file", "to upload to :param object_name: S3 object name. If not", "botocore.exceptions.ClientError as e: logging.error(e) return False return True def scale_image(image):", "# Extract the non-green parts of the image result =", "> 1: _image = cv2.resize(image, (int(width/scale), int(height/scale))) height, width, channels", "= eval(os.environ[\"HSV_UPPER\"]) print('Lower HSV range: ', lower_range) print('Upper HSV range:", "get the object s3.download_file(input_bucket_name, file_key, local_input_temp_file) # HSV range #", "same as file_name :return: True if file was uploaded, else", "local_output_temp_file = '/tmp/out_' + file_key.replace('.jpg', '.png') logger.info('Local input file: {}'.format(local_input_temp_file))", "255, 255) - default upper_range = eval(os.environ[\"HSV_UPPER\"]) print('Lower HSV range:", "s3 = boto3.client('s3') logger = logging.getLogger() logger.setLevel(logging.INFO) def upload_file(file_name, bucket,", "os.environ['OUTPUT_BUCKET_NAME'] output_file_key = file_key.<KEY>') print(\"Input bucket: \", input_bucket_name) print(\"Output bucket:", "hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV) # convert to RGBA image_alpha =", "+ file_key local_output_temp_file = '/tmp/out_' + file_key.replace('.jpg', '.png') logger.info('Local input", "= 800 height, width, channels = _image.shape logger.info('Original size: {}h", "input file: {}'.format(local_input_temp_file)) logger.info('Local output file: {}'.format(local_output_temp_file)) # get the", "environment variable specified.\") return # set up local temp file", "try: response = s3_client.upload_file(file_name, bucket, object_name) except botocore.exceptions.ClientError as e:", "os import json import cv2 import logging import boto3 import", "lambda_handler(event, context): print (\"Starting handler\") # get object metadata from", "file_key = event['Records'][0]['s3']['object']['key'] output_bucket_name = os.environ['OUTPUT_BUCKET_NAME'] output_file_key = file_key.<KEY>') print(\"Input", "scale = height/target_height if scale > 1: _image = cv2.resize(image,", "# (36, 50, 50) - average # (36, 100, 100)", "to upload :param bucket: Bucket to upload to :param object_name:", "image to only green colors mask = cv2.inRange(hsv, lower_range, upper_range)", "name. If not specified then same as file_name :return: True", "# get object metadata from event input_bucket_name = event['Records'][0]['s3']['bucket']['name'] file_key", "scale_image(image) # Flip from RGB of JPEG to BGR of", "mask=mask) #Save the result cv2.imwrite(local_output_temp_file,result) #Save to S3 if upload_file(local_output_temp_file,", "S3 bucket :param file_name: File to upload :param bucket: Bucket", "logger.info('Local input file: {}'.format(local_input_temp_file)) logger.info('Local output file: {}'.format(local_output_temp_file)) # get", "(\"Starting handler\") # get object metadata from event input_bucket_name =", "- relaxed lower_range = eval(os.environ[\"HSV_LOWER\"]) # (70, 255, 255) -", "import cv2 import logging import boto3 import botocore s3 =", "event input_bucket_name = event['Records'][0]['s3']['bucket']['name'] file_key = event['Records'][0]['s3']['object']['key'] output_bucket_name = os.environ['OUTPUT_BUCKET_NAME']", "25) - most extreme # (36, 50, 50) - average", "variable specified.\") return # set up local temp file names", "of OpenCV image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) # Convert BGR to", "an S3 bucket :param file_name: File to upload :param bucket:", "logger.info('Original size: {}h x {}w'.format(height, width)) scale = height/target_height if", "#Save the result cv2.imwrite(local_output_temp_file,result) #Save to S3 if upload_file(local_output_temp_file, output_bucket_name,", "S3 if upload_file(local_output_temp_file, output_bucket_name, output_file_key): print('Processed file uploaded.') return True", "# Convert BGR to HSV color space hsv = cv2.cvtColor(image,", "default upper_range = eval(os.environ[\"HSV_UPPER\"]) print('Lower HSV range: ', lower_range) print('Upper", "channels = image.shape logger.info('New size: {}h x {}w'.format(int(height/scale), int(width/scale))) return", "bucket, object_name=None): \"\"\"Upload a file to an S3 bucket :param", "= cv2.inRange(hsv, lower_range, upper_range) # Invert the mask (i.e. select", "object name. If not specified then same as file_name :return:", "uploaded, else False \"\"\" # If S3 object_name was not", "in the file image = cv2.imread(local_input_temp_file) # Resize the image", "object_name is None: object_name = file_name # Upload the file", "= file_key.<KEY>') print(\"Input bucket: \", input_bucket_name) print(\"Output bucket: \", output_bucket_name)", "'.png') logger.info('Local input file: {}'.format(local_input_temp_file)) logger.info('Local output file: {}'.format(local_output_temp_file)) #", "+ file_key.replace('.jpg', '.png') logger.info('Local input file: {}'.format(local_input_temp_file)) logger.info('Local output file:", "(36, 25, 25) - most extreme # (36, 50, 50)", "to :param object_name: S3 object name. If not specified then", "return _image def lambda_handler(event, context): print (\"Starting handler\") # get", "file_name if object_name is None: object_name = file_name # Upload", "average # (36, 100, 100) - relaxed lower_range = eval(os.environ[\"HSV_LOWER\"])", ":param object_name: S3 object name. If not specified then same", "bucket: \", input_bucket_name) print(\"Output bucket: \", output_bucket_name) if output_bucket_name is", "range # (36, 25, 25) - most extreme # (36,", "(int(width/scale), int(height/scale))) height, width, channels = image.shape logger.info('New size: {}h", "import json import cv2 import logging import boto3 import botocore", "# Threshold the HSV image to only green colors mask", "else False \"\"\" # If S3 object_name was not specified,", "True if file was uploaded, else False \"\"\" # If", "everything not green) mask = ~mask # Extract the non-green", "target_height = 800 height, width, channels = _image.shape logger.info('Original size:", "{}'.format(local_input_temp_file)) logger.info('Local output file: {}'.format(local_output_temp_file)) # get the object s3.download_file(input_bucket_name,", "\"\"\"Upload a file to an S3 bucket :param file_name: File", "the mask (i.e. select everything not green) mask = ~mask", "- most extreme # (36, 50, 50) - average #", "= boto3.client('s3') logger = logging.getLogger() logger.setLevel(logging.INFO) def upload_file(file_name, bucket, object_name=None):", "the object s3.download_file(input_bucket_name, file_key, local_input_temp_file) # HSV range # (36,", "get object metadata from event input_bucket_name = event['Records'][0]['s3']['bucket']['name'] file_key =", "= cv2.cvtColor(image, cv2.COLOR_BGR2HSV) # convert to RGBA image_alpha = cv2.cvtColor(image,", "cv2.cvtColor(image, cv2.COLOR_BGR2RGBA) # Threshold the HSV image to only green", "cv2.bitwise_and(image_alpha, image_alpha, mask=mask) #Save the result cv2.imwrite(local_output_temp_file,result) #Save to S3", "# Upload the file s3_client = s3 try: response =", "from RGB of JPEG to BGR of OpenCV image =", "parts of the image result = cv2.bitwise_and(image_alpha, image_alpha, mask=mask) #Save", "the image if larger than target size image = scale_image(image)", "= eval(os.environ[\"HSV_LOWER\"]) # (70, 255, 255) - default upper_range =", "int(height/scale))) height, width, channels = image.shape logger.info('New size: {}h x", "= file_name # Upload the file s3_client = s3 try:", "metadata from event input_bucket_name = event['Records'][0]['s3']['bucket']['name'] file_key = event['Records'][0]['s3']['object']['key'] output_bucket_name", "# Resize the image if larger than target size image", "Resize the image if larger than target size image =", "height, width, channels = image.shape logger.info('New size: {}h x {}w'.format(int(height/scale),", "output_bucket_name is None: print(\"Error: No OUTPUT_BUCKET_NAME environment variable specified.\") return", "if scale > 1: _image = cv2.resize(image, (int(width/scale), int(height/scale))) height,", "# Invert the mask (i.e. select everything not green) mask", "# set up local temp file names local_input_temp_file = '/tmp/'", "not green) mask = ~mask # Extract the non-green parts", "json import cv2 import logging import boto3 import botocore s3", "output_file_key = file_key.<KEY>') print(\"Input bucket: \", input_bucket_name) print(\"Output bucket: \",", ":param bucket: Bucket to upload to :param object_name: S3 object", "lower_range, upper_range) # Invert the mask (i.e. select everything not", "than target size image = scale_image(image) # Flip from RGB", "_image = cv2.resize(image, (int(width/scale), int(height/scale))) height, width, channels = image.shape", "if output_bucket_name is None: print(\"Error: No OUTPUT_BUCKET_NAME environment variable specified.\")", "# HSV range # (36, 25, 25) - most extreme", "width, channels = _image.shape logger.info('Original size: {}h x {}w'.format(height, width))", "from event input_bucket_name = event['Records'][0]['s3']['bucket']['name'] file_key = event['Records'][0]['s3']['object']['key'] output_bucket_name =", "s3_client.upload_file(file_name, bucket, object_name) except botocore.exceptions.ClientError as e: logging.error(e) return False", "of the image result = cv2.bitwise_and(image_alpha, image_alpha, mask=mask) #Save the", "\", output_bucket_name) if output_bucket_name is None: print(\"Error: No OUTPUT_BUCKET_NAME environment", "= s3_client.upload_file(file_name, bucket, object_name) except botocore.exceptions.ClientError as e: logging.error(e) return", "# (70, 255, 255) - default upper_range = eval(os.environ[\"HSV_UPPER\"]) print('Lower", "height, width, channels = _image.shape logger.info('Original size: {}h x {}w'.format(height,", "logger.info('Local output file: {}'.format(local_output_temp_file)) # get the object s3.download_file(input_bucket_name, file_key,", "image if larger than target size image = scale_image(image) #", "larger than target size image = scale_image(image) # Flip from", "JPEG to BGR of OpenCV image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) #", "= cv2.cvtColor(image, cv2.COLOR_BGR2RGB) # Convert BGR to HSV color space", "import os import json import cv2 import logging import boto3", "BGR to HSV color space hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV) #", "Invert the mask (i.e. select everything not green) mask =", "_image def lambda_handler(event, context): print (\"Starting handler\") # get object", "the image result = cv2.bitwise_and(image_alpha, image_alpha, mask=mask) #Save the result", "s3.download_file(input_bucket_name, file_key, local_input_temp_file) # HSV range # (36, 25, 25)", "= event['Records'][0]['s3']['object']['key'] output_bucket_name = os.environ['OUTPUT_BUCKET_NAME'] output_file_key = file_key.<KEY>') print(\"Input bucket:", "eval(os.environ[\"HSV_LOWER\"]) # (70, 255, 255) - default upper_range = eval(os.environ[\"HSV_UPPER\"])", "Bucket to upload to :param object_name: S3 object name. If", "use file_name if object_name is None: object_name = file_name #", "def scale_image(image): _image = image target_height = 800 height, width,", "upload :param bucket: Bucket to upload to :param object_name: S3", "as e: logging.error(e) return False return True def scale_image(image): _image", "logger = logging.getLogger() logger.setLevel(logging.INFO) def upload_file(file_name, bucket, object_name=None): \"\"\"Upload a", "context): print (\"Starting handler\") # get object metadata from event", "object_name=None): \"\"\"Upload a file to an S3 bucket :param file_name:", "def lambda_handler(event, context): print (\"Starting handler\") # get object metadata", "logging.error(e) return False return True def scale_image(image): _image = image", "print('Lower HSV range: ', lower_range) print('Upper HSV range: ', upper_range)", "file_name: File to upload :param bucket: Bucket to upload to", "was uploaded, else False \"\"\" # If S3 object_name was", "most extreme # (36, 50, 50) - average # (36,", "local_input_temp_file = '/tmp/' + file_key local_output_temp_file = '/tmp/out_' + file_key.replace('.jpg',", "to an S3 bucket :param file_name: File to upload :param", "cv2.cvtColor(image, cv2.COLOR_BGR2HSV) # convert to RGBA image_alpha = cv2.cvtColor(image, cv2.COLOR_BGR2RGBA)", "channels = _image.shape logger.info('Original size: {}h x {}w'.format(height, width)) scale", "non-green parts of the image result = cv2.bitwise_and(image_alpha, image_alpha, mask=mask)", "file_name # Upload the file s3_client = s3 try: response", "the HSV image to only green colors mask = cv2.inRange(hsv,", "import botocore s3 = boto3.client('s3') logger = logging.getLogger() logger.setLevel(logging.INFO) def", "set up local temp file names local_input_temp_file = '/tmp/' +", "= cv2.bitwise_and(image_alpha, image_alpha, mask=mask) #Save the result cv2.imwrite(local_output_temp_file,result) #Save to", "of JPEG to BGR of OpenCV image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)", "local_input_temp_file) # HSV range # (36, 25, 25) - most", "upper_range = eval(os.environ[\"HSV_UPPER\"]) print('Lower HSV range: ', lower_range) print('Upper HSV", "specified, use file_name if object_name is None: object_name = file_name", "file_key local_output_temp_file = '/tmp/out_' + file_key.replace('.jpg', '.png') logger.info('Local input file:", "not specified then same as file_name :return: True if file", "# (36, 25, 25) - most extreme # (36, 50,", "size: {}h x {}w'.format(height, width)) scale = height/target_height if scale", "S3 object name. If not specified then same as file_name", "cv2.inRange(hsv, lower_range, upper_range) # Invert the mask (i.e. select everything", "800 height, width, channels = _image.shape logger.info('Original size: {}h x", "1: _image = cv2.resize(image, (int(width/scale), int(height/scale))) height, width, channels =", "Threshold the HSV image to only green colors mask =", "50) - average # (36, 100, 100) - relaxed lower_range", "OUTPUT_BUCKET_NAME environment variable specified.\") return # set up local temp", "file_name :return: True if file was uploaded, else False \"\"\"", "colors mask = cv2.inRange(hsv, lower_range, upper_range) # Invert the mask", "then same as file_name :return: True if file was uploaded,", "a file to an S3 bucket :param file_name: File to", "bucket: Bucket to upload to :param object_name: S3 object name.", "except botocore.exceptions.ClientError as e: logging.error(e) return False return True def", "file: {}'.format(local_input_temp_file)) logger.info('Local output file: {}'.format(local_output_temp_file)) # get the object", "= logging.getLogger() logger.setLevel(logging.INFO) def upload_file(file_name, bucket, object_name=None): \"\"\"Upload a file", "is None: print(\"Error: No OUTPUT_BUCKET_NAME environment variable specified.\") return #", "output file: {}'.format(local_output_temp_file)) # get the object s3.download_file(input_bucket_name, file_key, local_input_temp_file)", "file was uploaded, else False \"\"\" # If S3 object_name", "HSV range: ', lower_range) print('Upper HSV range: ', upper_range) #", "Read in the file image = cv2.imread(local_input_temp_file) # Resize the", "cv2.imread(local_input_temp_file) # Resize the image if larger than target size", "= image target_height = 800 height, width, channels = _image.shape", "logger.info('New size: {}h x {}w'.format(int(height/scale), int(width/scale))) return _image def lambda_handler(event,", "return False return True def scale_image(image): _image = image target_height", "color space hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV) # convert to RGBA", "- average # (36, 100, 100) - relaxed lower_range =", "{}w'.format(height, width)) scale = height/target_height if scale > 1: _image", "input_bucket_name = event['Records'][0]['s3']['bucket']['name'] file_key = event['Records'][0]['s3']['object']['key'] output_bucket_name = os.environ['OUTPUT_BUCKET_NAME'] output_file_key", "only green colors mask = cv2.inRange(hsv, lower_range, upper_range) # Invert", "scale > 1: _image = cv2.resize(image, (int(width/scale), int(height/scale))) height, width,", "False return True def scale_image(image): _image = image target_height =", "if larger than target size image = scale_image(image) # Flip", "size image = scale_image(image) # Flip from RGB of JPEG", "None: object_name = file_name # Upload the file s3_client =", "'/tmp/' + file_key local_output_temp_file = '/tmp/out_' + file_key.replace('.jpg', '.png') logger.info('Local", "(36, 100, 100) - relaxed lower_range = eval(os.environ[\"HSV_LOWER\"]) # (70,", "result = cv2.bitwise_and(image_alpha, image_alpha, mask=mask) #Save the result cv2.imwrite(local_output_temp_file,result) #Save", "= cv2.imread(local_input_temp_file) # Resize the image if larger than target", "names local_input_temp_file = '/tmp/' + file_key local_output_temp_file = '/tmp/out_' +", "convert to RGBA image_alpha = cv2.cvtColor(image, cv2.COLOR_BGR2RGBA) # Threshold the", "mask (i.e. select everything not green) mask = ~mask #", "HSV range # (36, 25, 25) - most extreme #", "cv2.imwrite(local_output_temp_file,result) #Save to S3 if upload_file(local_output_temp_file, output_bucket_name, output_file_key): print('Processed file", ":param file_name: File to upload :param bucket: Bucket to upload", "select everything not green) mask = ~mask # Extract the", "= '/tmp/out_' + file_key.replace('.jpg', '.png') logger.info('Local input file: {}'.format(local_input_temp_file)) logger.info('Local", "logging.getLogger() logger.setLevel(logging.INFO) def upload_file(file_name, bucket, object_name=None): \"\"\"Upload a file to", "logger.setLevel(logging.INFO) def upload_file(file_name, bucket, object_name=None): \"\"\"Upload a file to an", "{}w'.format(int(height/scale), int(width/scale))) return _image def lambda_handler(event, context): print (\"Starting handler\")", "', lower_range) print('Upper HSV range: ', upper_range) # Read in", "print('Upper HSV range: ', upper_range) # Read in the file", "green) mask = ~mask # Extract the non-green parts of", "object_name) except botocore.exceptions.ClientError as e: logging.error(e) return False return True", "range: ', lower_range) print('Upper HSV range: ', upper_range) # Read", "green colors mask = cv2.inRange(hsv, lower_range, upper_range) # Invert the", "file to an S3 bucket :param file_name: File to upload", "def upload_file(file_name, bucket, object_name=None): \"\"\"Upload a file to an S3", "None: print(\"Error: No OUTPUT_BUCKET_NAME environment variable specified.\") return # set", "image target_height = 800 height, width, channels = _image.shape logger.info('Original", "upper_range) # Invert the mask (i.e. select everything not green)", "(i.e. select everything not green) mask = ~mask # Extract", "file_key.replace('.jpg', '.png') logger.info('Local input file: {}'.format(local_input_temp_file)) logger.info('Local output file: {}'.format(local_output_temp_file))", "(70, 255, 255) - default upper_range = eval(os.environ[\"HSV_UPPER\"]) print('Lower HSV", "# get the object s3.download_file(input_bucket_name, file_key, local_input_temp_file) # HSV range", "~mask # Extract the non-green parts of the image result", "cv2.resize(image, (int(width/scale), int(height/scale))) height, width, channels = image.shape logger.info('New size:", "logging import boto3 import botocore s3 = boto3.client('s3') logger =", "image_alpha, mask=mask) #Save the result cv2.imwrite(local_output_temp_file,result) #Save to S3 if", "100, 100) - relaxed lower_range = eval(os.environ[\"HSV_LOWER\"]) # (70, 255,", "{}'.format(local_output_temp_file)) # get the object s3.download_file(input_bucket_name, file_key, local_input_temp_file) # HSV", "HSV color space hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV) # convert to", "S3 object_name was not specified, use file_name if object_name is", "file: {}'.format(local_output_temp_file)) # get the object s3.download_file(input_bucket_name, file_key, local_input_temp_file) #", "Extract the non-green parts of the image result = cv2.bitwise_and(image_alpha,", "upload to :param object_name: S3 object name. If not specified", "Convert BGR to HSV color space hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)", "output_bucket_name) if output_bucket_name is None: print(\"Error: No OUTPUT_BUCKET_NAME environment variable", "= cv2.resize(image, (int(width/scale), int(height/scale))) height, width, channels = image.shape logger.info('New", "cv2.COLOR_BGR2RGB) # Convert BGR to HSV color space hsv =", "event['Records'][0]['s3']['bucket']['name'] file_key = event['Records'][0]['s3']['object']['key'] output_bucket_name = os.environ['OUTPUT_BUCKET_NAME'] output_file_key = file_key.<KEY>')", "s3 try: response = s3_client.upload_file(file_name, bucket, object_name) except botocore.exceptions.ClientError as", "import boto3 import botocore s3 = boto3.client('s3') logger = logging.getLogger()", ":return: True if file was uploaded, else False \"\"\" #", "= os.environ['OUTPUT_BUCKET_NAME'] output_file_key = file_key.<KEY>') print(\"Input bucket: \", input_bucket_name) print(\"Output", "space hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV) # convert to RGBA image_alpha", "file_key, local_input_temp_file) # HSV range # (36, 25, 25) -", "if file was uploaded, else False \"\"\" # If S3", "to RGBA image_alpha = cv2.cvtColor(image, cv2.COLOR_BGR2RGBA) # Threshold the HSV", "image = scale_image(image) # Flip from RGB of JPEG to", "= s3 try: response = s3_client.upload_file(file_name, bucket, object_name) except botocore.exceptions.ClientError", "bucket, object_name) except botocore.exceptions.ClientError as e: logging.error(e) return False return", "HSV range: ', upper_range) # Read in the file image", "width, channels = image.shape logger.info('New size: {}h x {}w'.format(int(height/scale), int(width/scale)))", "Upload the file s3_client = s3 try: response = s3_client.upload_file(file_name,", "BGR of OpenCV image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) # Convert BGR", "No OUTPUT_BUCKET_NAME environment variable specified.\") return # set up local", "print(\"Input bucket: \", input_bucket_name) print(\"Output bucket: \", output_bucket_name) if output_bucket_name", "handler\") # get object metadata from event input_bucket_name = event['Records'][0]['s3']['bucket']['name']", "result cv2.imwrite(local_output_temp_file,result) #Save to S3 if upload_file(local_output_temp_file, output_bucket_name, output_file_key): print('Processed", "e: logging.error(e) return False return True def scale_image(image): _image =", "image.shape logger.info('New size: {}h x {}w'.format(int(height/scale), int(width/scale))) return _image def", "{}h x {}w'.format(height, width)) scale = height/target_height if scale >", "image = cv2.imread(local_input_temp_file) # Resize the image if larger than", "If not specified then same as file_name :return: True if", "# If S3 object_name was not specified, use file_name if", "as file_name :return: True if file was uploaded, else False", "True def scale_image(image): _image = image target_height = 800 height,", "= event['Records'][0]['s3']['bucket']['name'] file_key = event['Records'][0]['s3']['object']['key'] output_bucket_name = os.environ['OUTPUT_BUCKET_NAME'] output_file_key =", "to S3 if upload_file(local_output_temp_file, output_bucket_name, output_file_key): print('Processed file uploaded.') return", "mask = cv2.inRange(hsv, lower_range, upper_range) # Invert the mask (i.e.", "file image = cv2.imread(local_input_temp_file) # Resize the image if larger", "Flip from RGB of JPEG to BGR of OpenCV image", "= cv2.cvtColor(image, cv2.COLOR_BGR2RGBA) # Threshold the HSV image to only", "to BGR of OpenCV image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) # Convert", "# Read in the file image = cv2.imread(local_input_temp_file) # Resize", "the file image = cv2.imread(local_input_temp_file) # Resize the image if", "= image.shape logger.info('New size: {}h x {}w'.format(int(height/scale), int(width/scale))) return _image", "100) - relaxed lower_range = eval(os.environ[\"HSV_LOWER\"]) # (70, 255, 255)", "False \"\"\" # If S3 object_name was not specified, use", "image_alpha = cv2.cvtColor(image, cv2.COLOR_BGR2RGBA) # Threshold the HSV image to", "the result cv2.imwrite(local_output_temp_file,result) #Save to S3 if upload_file(local_output_temp_file, output_bucket_name, output_file_key):", "lower_range = eval(os.environ[\"HSV_LOWER\"]) # (70, 255, 255) - default upper_range", "#Save to S3 if upload_file(local_output_temp_file, output_bucket_name, output_file_key): print('Processed file uploaded.')", "255) - default upper_range = eval(os.environ[\"HSV_UPPER\"]) print('Lower HSV range: ',", "object metadata from event input_bucket_name = event['Records'][0]['s3']['bucket']['name'] file_key = event['Records'][0]['s3']['object']['key']", "specified then same as file_name :return: True if file was", "cv2.COLOR_BGR2HSV) # convert to RGBA image_alpha = cv2.cvtColor(image, cv2.COLOR_BGR2RGBA) #", "specified.\") return # set up local temp file names local_input_temp_file", "= ~mask # Extract the non-green parts of the image", "int(width/scale))) return _image def lambda_handler(event, context): print (\"Starting handler\") #", "print (\"Starting handler\") # get object metadata from event input_bucket_name", "'/tmp/out_' + file_key.replace('.jpg', '.png') logger.info('Local input file: {}'.format(local_input_temp_file)) logger.info('Local output", "output_bucket_name = os.environ['OUTPUT_BUCKET_NAME'] output_file_key = file_key.<KEY>') print(\"Input bucket: \", input_bucket_name)", "not specified, use file_name if object_name is None: object_name =", "(36, 50, 50) - average # (36, 100, 100) -", "relaxed lower_range = eval(os.environ[\"HSV_LOWER\"]) # (70, 255, 255) - default", "is None: object_name = file_name # Upload the file s3_client", "if object_name is None: object_name = file_name # Upload the", "object_name = file_name # Upload the file s3_client = s3", "to HSV color space hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV) # convert", "width)) scale = height/target_height if scale > 1: _image =", "bucket :param file_name: File to upload :param bucket: Bucket to", "file s3_client = s3 try: response = s3_client.upload_file(file_name, bucket, object_name)", "object_name: S3 object name. If not specified then same as", "RGB of JPEG to BGR of OpenCV image = cv2.cvtColor(image,", "print(\"Error: No OUTPUT_BUCKET_NAME environment variable specified.\") return # set up", "= height/target_height if scale > 1: _image = cv2.resize(image, (int(width/scale),", "event['Records'][0]['s3']['object']['key'] output_bucket_name = os.environ['OUTPUT_BUCKET_NAME'] output_file_key = file_key.<KEY>') print(\"Input bucket: \",", "# Flip from RGB of JPEG to BGR of OpenCV", "\"\"\" # If S3 object_name was not specified, use file_name", "x {}w'.format(int(height/scale), int(width/scale))) return _image def lambda_handler(event, context): print (\"Starting", "HSV image to only green colors mask = cv2.inRange(hsv, lower_range,", "extreme # (36, 50, 50) - average # (36, 100,", "= '/tmp/' + file_key local_output_temp_file = '/tmp/out_' + file_key.replace('.jpg', '.png')", "- default upper_range = eval(os.environ[\"HSV_UPPER\"]) print('Lower HSV range: ', lower_range)", "= scale_image(image) # Flip from RGB of JPEG to BGR", "size: {}h x {}w'.format(int(height/scale), int(width/scale))) return _image def lambda_handler(event, context):", "<gh_stars>1-10 import os import json import cv2 import logging import", "return True def scale_image(image): _image = image target_height = 800", "_image = image target_height = 800 height, width, channels =", "# convert to RGBA image_alpha = cv2.cvtColor(image, cv2.COLOR_BGR2RGBA) # Threshold", "was not specified, use file_name if object_name is None: object_name", "boto3 import botocore s3 = boto3.client('s3') logger = logging.getLogger() logger.setLevel(logging.INFO)", "lower_range) print('Upper HSV range: ', upper_range) # Read in the", "# (36, 100, 100) - relaxed lower_range = eval(os.environ[\"HSV_LOWER\"]) #", "50, 50) - average # (36, 100, 100) - relaxed", "return # set up local temp file names local_input_temp_file =", "', upper_range) # Read in the file image = cv2.imread(local_input_temp_file)", "upper_range) # Read in the file image = cv2.imread(local_input_temp_file) #", "the file s3_client = s3 try: response = s3_client.upload_file(file_name, bucket,", "image result = cv2.bitwise_and(image_alpha, image_alpha, mask=mask) #Save the result cv2.imwrite(local_output_temp_file,result)", "mask = ~mask # Extract the non-green parts of the", "file_key.<KEY>') print(\"Input bucket: \", input_bucket_name) print(\"Output bucket: \", output_bucket_name) if", "bucket: \", output_bucket_name) if output_bucket_name is None: print(\"Error: No OUTPUT_BUCKET_NAME", "input_bucket_name) print(\"Output bucket: \", output_bucket_name) if output_bucket_name is None: print(\"Error:", "upload_file(file_name, bucket, object_name=None): \"\"\"Upload a file to an S3 bucket", "to only green colors mask = cv2.inRange(hsv, lower_range, upper_range) #", "\", input_bucket_name) print(\"Output bucket: \", output_bucket_name) if output_bucket_name is None:", "cv2 import logging import boto3 import botocore s3 = boto3.client('s3')", "response = s3_client.upload_file(file_name, bucket, object_name) except botocore.exceptions.ClientError as e: logging.error(e)", "25, 25) - most extreme # (36, 50, 50) -", "the non-green parts of the image result = cv2.bitwise_and(image_alpha, image_alpha,", "file names local_input_temp_file = '/tmp/' + file_key local_output_temp_file = '/tmp/out_'", "temp file names local_input_temp_file = '/tmp/' + file_key local_output_temp_file =", "height/target_height if scale > 1: _image = cv2.resize(image, (int(width/scale), int(height/scale)))", "cv2.COLOR_BGR2RGBA) # Threshold the HSV image to only green colors", "object_name was not specified, use file_name if object_name is None:", "RGBA image_alpha = cv2.cvtColor(image, cv2.COLOR_BGR2RGBA) # Threshold the HSV image", "eval(os.environ[\"HSV_UPPER\"]) print('Lower HSV range: ', lower_range) print('Upper HSV range: ',", "cv2.cvtColor(image, cv2.COLOR_BGR2RGB) # Convert BGR to HSV color space hsv", "s3_client = s3 try: response = s3_client.upload_file(file_name, bucket, object_name) except", "{}h x {}w'.format(int(height/scale), int(width/scale))) return _image def lambda_handler(event, context): print", "target size image = scale_image(image) # Flip from RGB of", "OpenCV image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) # Convert BGR to HSV", "up local temp file names local_input_temp_file = '/tmp/' + file_key", "botocore s3 = boto3.client('s3') logger = logging.getLogger() logger.setLevel(logging.INFO) def upload_file(file_name,", "= _image.shape logger.info('Original size: {}h x {}w'.format(height, width)) scale =", "_image.shape logger.info('Original size: {}h x {}w'.format(height, width)) scale = height/target_height", "boto3.client('s3') logger = logging.getLogger() logger.setLevel(logging.INFO) def upload_file(file_name, bucket, object_name=None): \"\"\"Upload", "print(\"Output bucket: \", output_bucket_name) if output_bucket_name is None: print(\"Error: No", "range: ', upper_range) # Read in the file image =", "import logging import boto3 import botocore s3 = boto3.client('s3') logger", "x {}w'.format(height, width)) scale = height/target_height if scale > 1:", "scale_image(image): _image = image target_height = 800 height, width, channels", "image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) # Convert BGR to HSV color", "If S3 object_name was not specified, use file_name if object_name" ]
[ "0 for x in range(1,100000): b += x return func(num", "import Profiler p = Profiler(use_signal=False) p.start() def func(num): if num", "b = 0 for x in range(1,100000): b += x", "= 0 for x in range(1,100000): b += x return", "in range(1,100000): b += x return func(num - 1) func(900)", "= Profiler(use_signal=False) p.start() def func(num): if num == 0: return", "b += x return func(num - 1) func(900) p.stop() print(p.output_text())", "func(num): if num == 0: return b = 0 for", "pyinstrument import Profiler p = Profiler(use_signal=False) p.start() def func(num): if", "range(1,100000): b += x return func(num - 1) func(900) p.stop()", "from pyinstrument import Profiler p = Profiler(use_signal=False) p.start() def func(num):", "p = Profiler(use_signal=False) p.start() def func(num): if num == 0:", "func(num - 1) func(900) p.stop() print(p.output_text()) with open('overflow_out.html', 'w') as", "+= x return func(num - 1) func(900) p.stop() print(p.output_text()) with", "x in range(1,100000): b += x return func(num - 1)", "return func(num - 1) func(900) p.stop() print(p.output_text()) with open('overflow_out.html', 'w')", "num == 0: return b = 0 for x in", "Profiler p = Profiler(use_signal=False) p.start() def func(num): if num ==", "def func(num): if num == 0: return b = 0", "== 0: return b = 0 for x in range(1,100000):", "if num == 0: return b = 0 for x", "p.start() def func(num): if num == 0: return b =", "for x in range(1,100000): b += x return func(num -", "return b = 0 for x in range(1,100000): b +=", "Profiler(use_signal=False) p.start() def func(num): if num == 0: return b", "- 1) func(900) p.stop() print(p.output_text()) with open('overflow_out.html', 'w') as f:", "0: return b = 0 for x in range(1,100000): b", "x return func(num - 1) func(900) p.stop() print(p.output_text()) with open('overflow_out.html',", "1) func(900) p.stop() print(p.output_text()) with open('overflow_out.html', 'w') as f: f.write(p.output_html())" ]
[ "a # string try: name = obj.name.decode() except (UnicodeDecodeError, AttributeError):", "lsyms_def.keys() and lsyms_def[name] > 1: eprint(\"Multiple definitions of local symbol", "parser.add_argument('--input', required=True, type=argparse.FileType('rb'), help='The input tee.elf') parser.add_argument('--out_tee_bin', required=False, type=argparse.FileType('wb'), help='The", "args.out_tee_bin: output_header_v1(elffile, args.out_tee_bin) if args.out_tee_pager_bin: output_pager_bin(elffile, args.out_tee_pager_bin) if args.out_tee_pageable_bin: output_pageable_bin(elffile,", "+---------------------------------------------------------+ # | uint32_t: Offset of relocations from beginning of", "import sys import struct import re import hashlib try: from", "# | Data of relocations + eventual padding | #", "of table | # +---------------------------------------------------------+ # | uint32_t: Length of", "for rel in section.iter_relocations(): if rel['r_info_type'] == 0: continue if", "== 0: bin_data = section.data() else: if section['sh_addr'] > last_end:", "help='The output tee_pageable.bin') parser.add_argument('--out_header_v2', required=False, type=argparse.FileType('wb'), help='The output tee_header_v2.bin') parser.add_argument('--out_pager_v2',", "SPDX-License-Identifier: BSD-2-Clause # # Copyright (c) 2019, Linaro Limited #", "tee_pageable_v2.bin') return parser.parse_args() def main(): args = get_args() elffile =", "Ubuntu. Or try to search for \"pyelftools\" or \"elftools\" in", "addrs.append(rel['r_offset'] - link_address) addrs.sort() data = bytearray() for a in", "'__get_tee_init_end')['st_value'] - get_symbol(elffile, '__text_start')['st_value'] + len(embdata_bin)) init_size = (pager_bin_size +", "= 0 nb_images = 1 if paged_size == 0 else", "addrs: data += struct.pack('<I', a) # Relocations has been reduced", "Probably it is not installed on your system. You can", "help='The input tee.elf') parser.add_argument('--out_tee_bin', required=False, type=argparse.FileType('wb'), help='The output tee.bin') parser.add_argument('--out_tee_pager_bin',", "2 hash_offs = 2 * 4 + num_entries * (2", "!= 0: eprint(\"pageable size not a multiple of 4K: \"", "re.compile(r'^\\..*_(pageable|init)$') tee_pageable_bin = get_sections(elffile, pad_to, dump_names) return tee_pageable_bin def get_pager_bin(elffile):", "tee_embdata_bin is None: hashes_bin = get_hashes_bin(elffile) reloc_bin = get_reloc_bin(elffile) num_entries", "reloc_offs + len(reloc_bin) + reloc_pad tee_embdata_bin = struct.pack('<IIIIII', total_len, num_entries,", "+ len(reloc_bin) + reloc_pad tee_embdata_bin = struct.pack('<IIIIII', total_len, num_entries, hash_offs,", "= 0x4554504f # 'OPTE' version = 2 flags = 0", "= dict() lsyms_def = dict() symbol_tables = [s for s", "file=sys.stderr, **kwargs) def round_up(n, m): if n == 0: return", "local symbol %s\" % name) sys.exit(1) if name not in", "None: pad_to = 0 dump_names = re.compile(r'^\\..*_(pageable|init)$') tee_pageable_bin = get_sections(elffile,", "Symbol or section .name might be a byte array or", "in lsyms_def.keys(): lsyms_def[symbol_name] = 1 else: lsyms_def[symbol_name] += 1 if", "num_entries * (2 * 4) hash_pad = round_up(len(hashes_bin), 8) -", "init_load_addr = get_symbol(elffile, '_start')['st_value'] init_load_addr_hi = init_load_addr >> 32 init_load_addr_lo", "def round_up(n, m): if n == 0: return 0 else:", "manager if you are using some other distribution. *** \"\"\")", "in elffile.iter_sections(): section_name = get_name(section) if (section['sh_type'] == 'SHT_NOBITS' or", "including this field | # +---------------------------------------------------------+ # | uint32_t: Number", "outf.write(pager_bin) outf.write(pageable_bin[:init_bin_size]) outf.write(embdata_bin) outf.write(pageable_bin[init_bin_size:]) def output_header_v2(elffile, outf): arch_id = get_arch_id(elffile)", "e_machine \"%s\"' % e_machine) sys.exit(1) def get_name(obj): # Symbol or", "section.iter_symbols(): symbol_name = get_name(symbol) if symbol['st_info']['bind'] == 'STB_GLOBAL': elffile_symbols[symbol_name] =", "help='The output tee_header_v2.bin') parser.add_argument('--out_pager_v2', required=False, type=argparse.FileType('wb'), help='The output tee_pager_v2.bin') parser.add_argument('--out_pageable_v2',", "r'^\\.(text|rodata|got|data|ARM\\.exidx|ARM\\.extab)$') tee_pager_bin = get_sections(elffile, pad_to, dump_names) return tee_pager_bin def get_reloc_bin(elffile):", "4 + num_entries * (2 * 4) hash_pad = round_up(len(hashes_bin),", "type=argparse.FileType('wb'), help='The output tee_pageable.bin') parser.add_argument('--out_header_v2', required=False, type=argparse.FileType('wb'), help='The output tee_header_v2.bin')", "rel['r_info_type'] == 0: continue if rel['r_info_type'] != exp_rel_type: eprint(\"Unexpected relocation", "- min(init_bin_size, paged_area_size) magic = 0x4554504f # 'OPTE' version =", "elftools.elf.sections import SymbolTableSection from elftools.elf.relocation import RelocationSection except ImportError: print(\"\"\"", "len(get_pageable_bin(elffile)) embdata_bin_size = len(get_embdata_bin(elffile)) init_size = (pager_bin_size + min(init_bin_size, paged_area_size)", "args = get_args() elffile = ELFFile(args.input) if args.out_tee_bin: output_header_v1(elffile, args.out_tee_bin)", "the address (r_offset) of relocation, that is, increase by #", "$ apt install python3-pyelftools if you are using Ubuntu. Or", "* 4 + num_entries * (2 * 4) hash_pad =", "field | # +---------------------------------------------------------+ # | uint32_t: Number of entries", "init_bin_size = get_symbol(elffile, '__init_size')['st_value'] outf.write(get_pageable_bin(elffile)[init_bin_size:]) def get_args(): parser = argparse.ArgumentParser()", "data = bytearray() for n in range(0, len(pageable_bin), small_page_size): page", "parser.add_argument('--out_header_v2', required=False, type=argparse.FileType('wb'), help='The output tee_header_v2.bin') parser.add_argument('--out_pager_v2', required=False, type=argparse.FileType('wb'), help='The", "# load_offset. The addresses (r_offset) are also sorted. The format", "division import argparse import sys import struct import re import", "name = obj.name.decode() except (UnicodeDecodeError, AttributeError): name = obj.name return", "ENUM_RELOC_TYPE_AARCH64['R_AARCH64_RELATIVE'] link_address = get_symbol(elffile, '__text_start')['st_value'] addrs = [] for section", "= get_sections(elffile, pad_to, dump_names) return tee_pager_bin def get_reloc_bin(elffile): if get_arch_id(elffile)", "= 0 bin_data = bytearray() for section in elffile.iter_sections(): section_name", "want a # string try: name = obj.name.decode() except (UnicodeDecodeError,", "relocation #1 # uint32_t: relocation #2 # ... # uint32_t:", "last_end: bin_data += bytearray(section['sh_addr'] - last_end) bin_data += section.data() last_end", "RelocationSection except ImportError: print(\"\"\" *** Can't find elftools module. Probably", "(((n - 1) // m) + 1) * m def", "import ENUM_RELOC_TYPE_AARCH64 from elftools.elf.sections import SymbolTableSection from elftools.elf.relocation import RelocationSection", "in section.iter_relocations(): if rel['r_info_type'] == 0: continue if rel['r_info_type'] !=", "install python3-pyelftools if you are using Ubuntu. Or try to", "rel['r_info_type'] != exp_rel_type: eprint(\"Unexpected relocation type 0x%x\" % rel['r_info_type']) sys.exit(1)", "= round_up(len(hashes_bin), 8) - len(hashes_bin) reloc_offs = hash_offs + len(hashes_bin)", "of relocations | # +---------------------------------------------------------+ # | Data of hashes", "embdata_bin_size = len(get_embdata_bin(elffile)) init_size = (pager_bin_size + min(init_bin_size, paged_area_size) +", "= paged_area_size - min(init_bin_size, paged_area_size) magic = 0x4554504f # 'OPTE'", "= 1 if paged_size == 0 else 2 outf.write(struct.pack('<IBBHI', magic,", "'SHT_NOBITS' or not (section['sh_flags'] & SH_FLAGS.SHF_ALLOC) or not dump_names.match(section_name)): continue", "output_pageable_bin(elffile, args.out_tee_pageable_bin) if args.out_header_v2: output_header_v2(elffile, args.out_header_v2) if args.out_pager_v2: output_pager_v2(elffile, args.out_pager_v2)", "sys.exit(1) addrs.append(rel['r_offset'] - link_address) addrs.sort() data = bytearray() for a", "addrs.sort() data = bytearray() for a in addrs: data +=", "distribution. *** \"\"\") raise small_page_size = 4 * 1024 elffile_symbols", "= None tee_pager_bin = None tee_embdata_bin = None def eprint(*args,", "**kwargs): print(*args, file=sys.stderr, **kwargs) def round_up(n, m): if n ==", "eprint(\"Cannot find symbol %s\" % name) sys.exit(1) return elffile_symbols[name] def", "a multiple of 4K: \" \"{}\".format(paged_area_size)) sys.exit(1) data = bytearray()", "reloc_pad = round_up(len(reloc_bin), 8) - len(reloc_bin) total_len = reloc_offs +", "Offset of relocations from beginning of table | # +---------------------------------------------------------+", "output tee_pager_v2.bin') parser.add_argument('--out_pageable_v2', required=False, type=argparse.FileType('wb'), help='The output tee_pageable_v2.bin') return parser.parse_args()", "= get_symbol(elffile, '__text_start')['st_value'] addrs = [] for section in elffile.iter_sections():", "+ min(init_bin_size, paged_area_size) + len(embdata_bin)) paged_size = paged_area_size - min(init_bin_size,", "= argparse.ArgumentParser() parser.add_argument('--input', required=True, type=argparse.FileType('rb'), help='The input tee.elf') parser.add_argument('--out_tee_bin', required=False,", "hashes_bin + bytearray(hash_pad) tee_embdata_bin += reloc_bin + bytearray(reloc_pad) # The", "tee_pageable_bin def get_pager_bin(elffile): global tee_pager_bin if tee_pager_bin is None: pad_to", "| uint32_t: Number of entries \"2\" | # +---------------------------------------------------------+ #", "import division import argparse import sys import struct import re", "data def get_embdata_bin(elffile): global tee_embdata_bin if tee_embdata_bin is None: hashes_bin", "package manager if you are using some other distribution. ***", "eprint(\"pageable size not a multiple of 4K: \" \"{}\".format(paged_area_size)) sys.exit(1)", ">> 32 init_load_addr_lo = init_load_addr & 0xffffffff return init_load_addr_hi, init_load_addr_lo", "output_header_v2(elffile, outf): arch_id = get_arch_id(elffile) init_load_addr = get_init_load_addr(elffile) init_bin_size =", "bytearray(pad_to - last_end) last_end = pad_to return bin_data def get_pageable_bin(elffile):", "table | # +---------------------------------------------------------+ # | uint32_t: Length of hashes", "init_load_addr & 0xffffffff return init_load_addr_hi, init_load_addr_lo def output_header_v1(elffile, outf): arch_id", "'EM_ARM': return 0 if e_machine == 'EM_AARCH64': return 1 eprint('Unknown", "0 dump_names = re.compile(r'^\\..*_(pageable|init)$') tee_pageable_bin = get_sections(elffile, pad_to, dump_names) return", "main(): args = get_args() elffile = ELFFile(args.input) if args.out_tee_bin: output_header_v1(elffile,", "sys.exit(1) if name not in elffile_symbols.keys(): eprint(\"Cannot find symbol %s\"", "bin_data = bytearray() for section in elffile.iter_sections(): section_name = get_name(section)", "your system. You can install this module with $ apt", "byte array or a string, we want a # string", "outf.write(pager_bin) outf.write(pageable_bin[:init_bin_size]) outf.write(embdata_bin) def output_pageable_v2(elffile, outf): init_bin_size = get_symbol(elffile, '__init_size')['st_value']", "= round_up(len(reloc_bin), 8) - len(reloc_bin) total_len = reloc_offs + len(reloc_bin)", "%s\" % name) sys.exit(1) return elffile_symbols[name] def get_sections(elffile, pad_to, dump_names):", "* 4) hash_pad = round_up(len(hashes_bin), 8) - len(hashes_bin) reloc_offs =", "args.out_pager_v2) if args.out_pageable_v2: output_pageable_v2(elffile, args.out_pageable_v2) if __name__ == \"__main__\": main()", "pageable_bin[n:n + small_page_size] data += hashlib.sha256(page).digest() return data def get_embdata_bin(elffile):", "get_sections(elffile, pad_to, dump_names): last_end = 0 bin_data = bytearray() for", "len(hashes_bin) + hash_pad reloc_pad = round_up(len(reloc_bin), 8) - len(reloc_bin) total_len", "# needed, it's formatted as: # +---------------------------------------------------------+ # | uint32_t:", "n == 0: return 0 else: return (((n - 1)", "1 eprint('Unknown e_machine \"%s\"' % e_machine) sys.exit(1) def get_name(obj): #", "embdata_bin_size) paged_size = paged_area_size - min(init_bin_size, paged_area_size) magic = 0x4554504f", "pad_to = get_symbol(elffile, '__data_end')['st_value'] dump_names = re.compile( r'^\\.(text|rodata|got|data|ARM\\.exidx|ARM\\.extab)$') tee_pager_bin =", "if args.out_tee_pageable_bin: output_pageable_bin(elffile, args.out_tee_pageable_bin) if args.out_header_v2: output_header_v2(elffile, args.out_header_v2) if args.out_pager_v2:", "args.out_header_v2: output_header_v2(elffile, args.out_header_v2) if args.out_pager_v2: output_pager_v2(elffile, args.out_pager_v2) if args.out_pageable_v2: output_pageable_v2(elffile,", "The format is # then: # uint32_t: relocation #1 #", "\"pyelftools\" or \"elftools\" in your package manager if you are", "+ bytearray(reloc_pad) # The embedded data region is designed to", "def get_pageable_bin(elffile): global tee_pageable_bin if tee_pageable_bin is None: pad_to =", "module with $ apt install python3-pyelftools if you are using", "init_bin_size = get_symbol(elffile, '__init_size')['st_value'] pager_bin_size = len(pager_bin) paged_area_size = len(pageable_bin)", "section.data() else: if section['sh_addr'] > last_end: bin_data += bytearray(section['sh_addr'] -", "section_name = get_name(section) if (section['sh_type'] == 'SHT_NOBITS' or not (section['sh_flags']", "init_bin_size = get_symbol(elffile, '__init_size')['st_value'] pager_bin_size = len(get_pager_bin(elffile)) paged_area_size = len(get_pageable_bin(elffile))", "if args.out_pager_v2: output_pager_v2(elffile, args.out_pager_v2) if args.out_pageable_v2: output_pageable_v2(elffile, args.out_pageable_v2) if __name__", "# addend at the address (r_offset) of relocation, that is,", "or not dump_names.match(section_name)): continue if last_end == 0: bin_data =", "page = pageable_bin[n:n + small_page_size] data += hashlib.sha256(page).digest() return data", "= re.compile(r'^\\..*_(pageable|init)$') tee_pageable_bin = get_sections(elffile, pad_to, dump_names) return tee_pageable_bin def", "Relocations has been reduced to only become the relative type", "is None: elffile_symbols = dict() lsyms_def = dict() symbol_tables =", "reloc_pad tee_embdata_bin = struct.pack('<IIIIII', total_len, num_entries, hash_offs, len(hashes_bin), reloc_offs, len(reloc_bin))", "uint32_t: Length of hashes | # +---------------------------------------------------------+ # | uint32_t:", "paged_area_size) + len(embdata_bin)) paged_size = paged_area_size - min(init_bin_size, paged_area_size) magic", "link_address) addrs.sort() data = bytearray() for a in addrs: data", "import struct import re import hashlib try: from elftools.elf.elffile import", "& SH_FLAGS.SHF_ALLOC) or not dump_names.match(section_name)): continue if last_end == 0:", "symbol_name not in lsyms_def.keys(): lsyms_def[symbol_name] = 1 else: lsyms_def[symbol_name] +=", "= get_symbol(elffile, '__init_size')['st_value'] pager_bin_size = len(get_pager_bin(elffile)) paged_area_size = len(get_pageable_bin(elffile)) embdata_bin_size", "= (pager_bin_size + min(init_bin_size, paged_area_size) + embdata_bin_size) paged_size = paged_area_size", "required=True, type=argparse.FileType('rb'), help='The input tee.elf') parser.add_argument('--out_tee_bin', required=False, type=argparse.FileType('wb'), help='The output", "'_start')['st_value'] init_load_addr_hi = init_load_addr >> 32 init_load_addr_lo = init_load_addr &", "+ section['sh_size'] if pad_to > last_end: bin_data += bytearray(pad_to -", "= get_embdata_bin(elffile) init_load_addr = get_init_load_addr(elffile) init_bin_size = get_symbol(elffile, '__init_size')['st_value'] pager_bin_size", "range(0, len(pageable_bin), small_page_size): page = pageable_bin[n:n + small_page_size] data +=", "'__init_size')['st_value'] pager_bin_size = len(pager_bin) paged_area_size = len(pageable_bin) init_mem_usage = (get_symbol(elffile,", "outf.write(embdata_bin) outf.write(pageable_bin[init_bin_size:]) def output_header_v2(elffile, outf): arch_id = get_arch_id(elffile) init_load_addr =", "= get_symbol(elffile, '__init_size')['st_value'] outf.write(get_pageable_bin(elffile)[init_bin_size:]) def get_args(): parser = argparse.ArgumentParser() parser.add_argument('--input',", "0xffffffff, 0xffffffff, 1, paged_size)) def output_pager_v2(elffile, outf): init_bin_size = get_symbol(elffile,", "(r_offset) are also sorted. The format is # then: #", "flags, init_size, init_load_addr[0], init_load_addr[1], init_mem_usage, paged_size)) outf.write(pager_bin) outf.write(pageable_bin[:init_bin_size]) outf.write(embdata_bin) outf.write(pageable_bin[init_bin_size:])", "type=argparse.FileType('wb'), help='The output tee_pager_v2.bin') parser.add_argument('--out_pageable_v2', required=False, type=argparse.FileType('wb'), help='The output tee_pageable_v2.bin')", "hash_offs, len(hashes_bin), reloc_offs, len(reloc_bin)) tee_embdata_bin += hashes_bin + bytearray(hash_pad) tee_embdata_bin", "flags = 0 outf.write(struct.pack('<IBBHIIIII', magic, version, arch_id, flags, init_size, init_load_addr[0],", "init_load_addr[0], init_load_addr[1], 0, init_size)) if nb_images == 2: outf.write(struct.pack('<IIII', 0xffffffff,", "if rel['r_info_type'] == 0: continue if rel['r_info_type'] != exp_rel_type: eprint(\"Unexpected", "get_embdata_bin(elffile) outf.write(pager_bin) outf.write(pageable_bin[:init_bin_size]) outf.write(embdata_bin) def output_pageable_v2(elffile, outf): init_bin_size = get_symbol(elffile,", "bin_data += section.data() last_end = section['sh_addr'] + section['sh_size'] if pad_to", "global tee_embdata_bin if tee_embdata_bin is None: hashes_bin = get_hashes_bin(elffile) reloc_bin", "from elftools.elf.elffile import ELFFile from elftools.elf.constants import SH_FLAGS from elftools.elf.enums", "== 0: return 0 else: return (((n - 1) //", "return 0 else: return (((n - 1) // m) +", "and lsyms_def[name] > 1: eprint(\"Multiple definitions of local symbol %s\"", "# uint32_t: relocation #n return data def get_hashes_bin(elffile): pageable_bin =", "for n in range(0, len(pageable_bin), small_page_size): page = pageable_bin[n:n +", "'STB_LOCAL': if symbol_name not in elffile_symbols.keys(): elffile_symbols[symbol_name] = symbol if", "outf.write(get_pager_bin(elffile)) def output_pageable_bin(elffile, outf): outf.write(get_pageable_bin(elffile)) def get_init_load_addr(elffile): init_load_addr = get_symbol(elffile,", "input tee.elf') parser.add_argument('--out_tee_bin', required=False, type=argparse.FileType('wb'), help='The output tee.bin') parser.add_argument('--out_tee_pager_bin', required=False,", "output tee_pageable.bin') parser.add_argument('--out_header_v2', required=False, type=argparse.FileType('wb'), help='The output tee_header_v2.bin') parser.add_argument('--out_pager_v2', required=False,", "for section in elffile.iter_sections(): if not isinstance(section, RelocationSection): continue for", "if you are using some other distribution. *** \"\"\") raise", "def get_arch_id(elffile): e_machine = elffile.header['e_machine'] if e_machine == 'EM_ARM': return", "for s in elffile.iter_sections() if isinstance(s, SymbolTableSection)] for section in", "lsyms_def if elffile_symbols is None: elffile_symbols = dict() lsyms_def =", "name) sys.exit(1) return elffile_symbols[name] def get_sections(elffile, pad_to, dump_names): last_end =", "= 0x4554504f # 'OPTE' version = 1 flags = 0", "paged_size = paged_area_size - min(init_bin_size, paged_area_size) magic = 0x4554504f #", "in lsyms_def.keys() and lsyms_def[name] > 1: eprint(\"Multiple definitions of local", "type with # addend at the address (r_offset) of relocation,", "get_symbol(elffile, '__text_start')['st_value'] addrs = [] for section in elffile.iter_sections(): if", "Can't find elftools module. Probably it is not installed on", "= symbol elif symbol['st_info']['bind'] == 'STB_LOCAL': if symbol_name not in", "# +---------------------------------------------------------+ # | Data of hashes + eventual padding", "0 else 2 outf.write(struct.pack('<IBBHI', magic, version, arch_id, flags, nb_images)) outf.write(struct.pack('<IIII',", "lsyms_def.keys(): lsyms_def[symbol_name] = 1 else: lsyms_def[symbol_name] += 1 if name", "help='The output tee_pager.bin') parser.add_argument('--out_tee_pageable_bin', required=False, type=argparse.FileType('wb'), help='The output tee_pageable.bin') parser.add_argument('--out_header_v2',", "argparse import sys import struct import re import hashlib try:", "Offset of hashes from beginning of table | # +---------------------------------------------------------+", "if args.out_tee_pager_bin: output_pager_bin(elffile, args.out_tee_pager_bin) if args.out_tee_pageable_bin: output_pageable_bin(elffile, args.out_tee_pageable_bin) if args.out_header_v2:", "try to search for \"pyelftools\" or \"elftools\" in your package", "in section.iter_symbols(): symbol_name = get_name(symbol) if symbol['st_info']['bind'] == 'STB_GLOBAL': elffile_symbols[symbol_name]", "%s\" % name) sys.exit(1) if name not in elffile_symbols.keys(): eprint(\"Cannot", "'__data_end')['st_value'] dump_names = re.compile( r'^\\.(text|rodata|got|data|ARM\\.exidx|ARM\\.extab)$') tee_pager_bin = get_sections(elffile, pad_to, dump_names)", "- last_end) last_end = pad_to return bin_data def get_pageable_bin(elffile): global", "parser.add_argument('--out_tee_pageable_bin', required=False, type=argparse.FileType('wb'), help='The output tee_pageable.bin') parser.add_argument('--out_header_v2', required=False, type=argparse.FileType('wb'), help='The", "or a string, we want a # string try: name", "tee_embdata_bin if tee_embdata_bin is None: hashes_bin = get_hashes_bin(elffile) reloc_bin =", "hashlib try: from elftools.elf.elffile import ELFFile from elftools.elf.constants import SH_FLAGS", "eventual padding | # +---------------------------------------------------------+ # | Data of relocations", "total_len, num_entries, hash_offs, len(hashes_bin), reloc_offs, len(reloc_bin)) tee_embdata_bin += hashes_bin +", "# uint32_t: relocation #2 # ... # uint32_t: relocation #n", "or \"elftools\" in your package manager if you are using", "multiple of 4K: \" \"{}\".format(paged_area_size)) sys.exit(1) data = bytearray() for", "init_load_addr[1], init_mem_usage, paged_size)) outf.write(pager_bin) outf.write(pageable_bin[:init_bin_size]) outf.write(embdata_bin) outf.write(pageable_bin[init_bin_size:]) def output_header_v2(elffile, outf):", "def get_name(obj): # Symbol or section .name might be a", "hash_pad = round_up(len(hashes_bin), 8) - len(hashes_bin) reloc_offs = hash_offs +", "eventual padding | # +---------------------------------------------------------+ return tee_embdata_bin def output_pager_bin(elffile, outf):", "name): global elffile_symbols global lsyms_def if elffile_symbols is None: elffile_symbols", "2 * 4 + num_entries * (2 * 4) hash_pad", "symbol['st_info']['bind'] == 'STB_LOCAL': if symbol_name not in elffile_symbols.keys(): elffile_symbols[symbol_name] =", "to only become the relative type with # addend at", "ENUM_RELOC_TYPE_ARM from elftools.elf.enums import ENUM_RELOC_TYPE_AARCH64 from elftools.elf.sections import SymbolTableSection from", "def output_pager_bin(elffile, outf): outf.write(get_pager_bin(elffile)) def output_pageable_bin(elffile, outf): outf.write(get_pageable_bin(elffile)) def get_init_load_addr(elffile):", "args.out_tee_pageable_bin: output_pageable_bin(elffile, args.out_tee_pageable_bin) if args.out_header_v2: output_header_v2(elffile, args.out_header_v2) if args.out_pager_v2: output_pager_v2(elffile,", "Data of hashes + eventual padding | # +---------------------------------------------------------+ #", "symbol_tables = [s for s in elffile.iter_sections() if isinstance(s, SymbolTableSection)]", "| uint32_t: Offset of hashes from beginning of table |", "pager_bin_size = len(pager_bin) paged_area_size = len(pageable_bin) init_mem_usage = (get_symbol(elffile, '__get_tee_init_end')['st_value']", "return 1 eprint('Unknown e_machine \"%s\"' % e_machine) sys.exit(1) def get_name(obj):", "= init_load_addr & 0xffffffff return init_load_addr_hi, init_load_addr_lo def output_header_v1(elffile, outf):", "== 'SHT_NOBITS' or not (section['sh_flags'] & SH_FLAGS.SHF_ALLOC) or not dump_names.match(section_name)):", "= get_pageable_bin(elffile) if len(pageable_bin) % small_page_size != 0: eprint(\"pageable size", "min(init_bin_size, paged_area_size) magic = 0x4554504f # 'OPTE' version = 2", "a string, we want a # string try: name =", "BSD-2-Clause # # Copyright (c) 2019, Linaro Limited # from", "struct.pack('<I', a) # Relocations has been reduced to only become", "0 else: return (((n - 1) // m) + 1)", "uint32_t: Length of entire area including this field | #", "parser.add_argument('--out_tee_bin', required=False, type=argparse.FileType('wb'), help='The output tee.bin') parser.add_argument('--out_tee_pager_bin', required=False, type=argparse.FileType('wb'), help='The", "args.out_tee_pager_bin: output_pager_bin(elffile, args.out_tee_pager_bin) if args.out_tee_pageable_bin: output_pageable_bin(elffile, args.out_tee_pageable_bin) if args.out_header_v2: output_header_v2(elffile,", "in symbol_tables: for symbol in section.iter_symbols(): symbol_name = get_name(symbol) if", "help='The output tee_pageable_v2.bin') return parser.parse_args() def main(): args = get_args()", "dict() lsyms_def = dict() symbol_tables = [s for s in", "exp_rel_type = ENUM_RELOC_TYPE_ARM['R_ARM_RELATIVE'] else: exp_rel_type = ENUM_RELOC_TYPE_AARCH64['R_AARCH64_RELATIVE'] link_address = get_symbol(elffile,", "is # then: # uint32_t: relocation #1 # uint32_t: relocation", "installed on your system. You can install this module with", "= bytearray() for n in range(0, len(pageable_bin), small_page_size): page =", "| # +---------------------------------------------------------+ # | uint32_t: Length of relocations |", "= 1 else: lsyms_def[symbol_name] += 1 if name in lsyms_def.keys()", "section.data() last_end = section['sh_addr'] + section['sh_size'] if pad_to > last_end:", "#2 # ... # uint32_t: relocation #n return data def", "small_page_size] data += hashlib.sha256(page).digest() return data def get_embdata_bin(elffile): global tee_embdata_bin", "# +---------------------------------------------------------+ # | uint32_t: Offset of relocations from beginning", "= get_pager_bin(elffile) pageable_bin = get_pageable_bin(elffile) embdata_bin = get_embdata_bin(elffile) init_load_addr =", "embedded data region is designed to be easy to extend", "python3-pyelftools if you are using Ubuntu. Or try to search", "import ELFFile from elftools.elf.constants import SH_FLAGS from elftools.elf.enums import ENUM_RELOC_TYPE_ARM", "== 'STB_LOCAL': if symbol_name not in elffile_symbols.keys(): elffile_symbols[symbol_name] = symbol", "find elftools module. Probably it is not installed on your", "get_symbol(elffile, '__data_end')['st_value'] dump_names = re.compile( r'^\\.(text|rodata|got|data|ARM\\.exidx|ARM\\.extab)$') tee_pager_bin = get_sections(elffile, pad_to,", "from elftools.elf.enums import ENUM_RELOC_TYPE_ARM from elftools.elf.enums import ENUM_RELOC_TYPE_AARCH64 from elftools.elf.sections", "# +---------------------------------------------------------+ # | uint32_t: Length of hashes | #", "return tee_pageable_bin def get_pager_bin(elffile): global tee_pager_bin if tee_pager_bin is None:", "python3 # SPDX-License-Identifier: BSD-2-Clause # # Copyright (c) 2019, Linaro", "lsyms_def[symbol_name] = 1 else: lsyms_def[symbol_name] += 1 if name in", "get_init_load_addr(elffile): init_load_addr = get_symbol(elffile, '_start')['st_value'] init_load_addr_hi = init_load_addr >> 32", "2 flags = 0 nb_images = 1 if paged_size ==", "= get_args() elffile = ELFFile(args.input) if args.out_tee_bin: output_header_v1(elffile, args.out_tee_bin) if", "continue if last_end == 0: bin_data = section.data() else: if", "by # load_offset. The addresses (r_offset) are also sorted. The", "dump_names.match(section_name)): continue if last_end == 0: bin_data = section.data() else:", "# Relocations has been reduced to only become the relative", "name in lsyms_def.keys() and lsyms_def[name] > 1: eprint(\"Multiple definitions of", "address (r_offset) of relocation, that is, increase by # load_offset.", "in elffile.iter_sections() if isinstance(s, SymbolTableSection)] for section in symbol_tables: for", "+ reloc_pad tee_embdata_bin = struct.pack('<IIIIII', total_len, num_entries, hash_offs, len(hashes_bin), reloc_offs,", "global tee_pager_bin if tee_pager_bin is None: pad_to = get_symbol(elffile, '__data_end')['st_value']", "args.out_tee_bin) if args.out_tee_pager_bin: output_pager_bin(elffile, args.out_tee_pager_bin) if args.out_tee_pageable_bin: output_pageable_bin(elffile, args.out_tee_pageable_bin) if", "relocation type 0x%x\" % rel['r_info_type']) sys.exit(1) addrs.append(rel['r_offset'] - link_address) addrs.sort()", "isinstance(section, RelocationSection): continue for rel in section.iter_relocations(): if rel['r_info_type'] ==", "of 4K: \" \"{}\".format(paged_area_size)) sys.exit(1) data = bytearray() for n", "= 2 hash_offs = 2 * 4 + num_entries *", "= obj.name return name def get_symbol(elffile, name): global elffile_symbols global", "None: elffile_symbols = dict() lsyms_def = dict() symbol_tables = [s", "RelocationSection): continue for rel in section.iter_relocations(): if rel['r_info_type'] == 0:", "# Copyright (c) 2019, Linaro Limited # from __future__ import", "if symbol_name not in lsyms_def.keys(): lsyms_def[symbol_name] = 1 else: lsyms_def[symbol_name]", "1) * m def get_arch_id(elffile): e_machine = elffile.header['e_machine'] if e_machine", "if get_arch_id(elffile) == 0: exp_rel_type = ENUM_RELOC_TYPE_ARM['R_ARM_RELATIVE'] else: exp_rel_type =", "+ hash_pad reloc_pad = round_up(len(reloc_bin), 8) - len(reloc_bin) total_len =", "get_symbol(elffile, '__init_size')['st_value'] outf.write(get_pageable_bin(elffile)[init_bin_size:]) def get_args(): parser = argparse.ArgumentParser() parser.add_argument('--input', required=True,", "if not isinstance(section, RelocationSection): continue for rel in section.iter_relocations(): if", "== 'EM_ARM': return 0 if e_machine == 'EM_AARCH64': return 1", "to extend when # needed, it's formatted as: # +---------------------------------------------------------+", "using Ubuntu. Or try to search for \"pyelftools\" or \"elftools\"", "args.out_tee_pager_bin) if args.out_tee_pageable_bin: output_pageable_bin(elffile, args.out_tee_pageable_bin) if args.out_header_v2: output_header_v2(elffile, args.out_header_v2) if", "addend at the address (r_offset) of relocation, that is, increase", "The embedded data region is designed to be easy to", "sorted. The format is # then: # uint32_t: relocation #1", "+---------------------------------------------------------+ # | Data of hashes + eventual padding |", "& 0xffffffff return init_load_addr_hi, init_load_addr_lo def output_header_v1(elffile, outf): arch_id =", "if tee_pager_bin is None: pad_to = get_symbol(elffile, '__data_end')['st_value'] dump_names =", "len(reloc_bin) + reloc_pad tee_embdata_bin = struct.pack('<IIIIII', total_len, num_entries, hash_offs, len(hashes_bin),", "2 outf.write(struct.pack('<IBBHI', magic, version, arch_id, flags, nb_images)) outf.write(struct.pack('<IIII', init_load_addr[0], init_load_addr[1],", "outf.write(get_pageable_bin(elffile)) def get_init_load_addr(elffile): init_load_addr = get_symbol(elffile, '_start')['st_value'] init_load_addr_hi = init_load_addr", "elftools.elf.constants import SH_FLAGS from elftools.elf.enums import ENUM_RELOC_TYPE_ARM from elftools.elf.enums import", "paged_area_size = len(get_pageable_bin(elffile)) embdata_bin_size = len(get_embdata_bin(elffile)) init_size = (pager_bin_size +", "nb_images)) outf.write(struct.pack('<IIII', init_load_addr[0], init_load_addr[1], 0, init_size)) if nb_images == 2:", "// m) + 1) * m def get_arch_id(elffile): e_machine =", "outf.write(struct.pack('<IBBHIIIII', magic, version, arch_id, flags, init_size, init_load_addr[0], init_load_addr[1], init_mem_usage, paged_size))", "*** \"\"\") raise small_page_size = 4 * 1024 elffile_symbols =", "symbol if symbol_name not in lsyms_def.keys(): lsyms_def[symbol_name] = 1 else:", "elffile.iter_sections(): if not isinstance(section, RelocationSection): continue for rel in section.iter_relocations():", "is, increase by # load_offset. The addresses (r_offset) are also", "for symbol in section.iter_symbols(): symbol_name = get_name(symbol) if symbol['st_info']['bind'] ==", "elffile.iter_sections(): section_name = get_name(section) if (section['sh_type'] == 'SHT_NOBITS' or not", "ENUM_RELOC_TYPE_ARM['R_ARM_RELATIVE'] else: exp_rel_type = ENUM_RELOC_TYPE_AARCH64['R_AARCH64_RELATIVE'] link_address = get_symbol(elffile, '__text_start')['st_value'] addrs", "get_arch_id(elffile) == 0: exp_rel_type = ENUM_RELOC_TYPE_ARM['R_ARM_RELATIVE'] else: exp_rel_type = ENUM_RELOC_TYPE_AARCH64['R_AARCH64_RELATIVE']", "1024 elffile_symbols = None tee_pageable_bin = None tee_pager_bin = None", "required=False, type=argparse.FileType('wb'), help='The output tee_pager_v2.bin') parser.add_argument('--out_pageable_v2', required=False, type=argparse.FileType('wb'), help='The output", "init_load_addr >> 32 init_load_addr_lo = init_load_addr & 0xffffffff return init_load_addr_hi,", "+ len(embdata_bin)) paged_size = paged_area_size - min(init_bin_size, paged_area_size) magic =", "elffile_symbols global lsyms_def if elffile_symbols is None: elffile_symbols = dict()", "= get_init_load_addr(elffile) init_bin_size = get_symbol(elffile, '__init_size')['st_value'] pager_bin_size = len(pager_bin) paged_area_size", "__future__ import print_function from __future__ import division import argparse import", "sys.exit(1) return elffile_symbols[name] def get_sections(elffile, pad_to, dump_names): last_end = 0", "last_end: bin_data += bytearray(pad_to - last_end) last_end = pad_to return", "reloc_bin = get_reloc_bin(elffile) num_entries = 2 hash_offs = 2 *", "> last_end: bin_data += bytearray(pad_to - last_end) last_end = pad_to", "'__text_start')['st_value'] addrs = [] for section in elffile.iter_sections(): if not", "def output_pageable_bin(elffile, outf): outf.write(get_pageable_bin(elffile)) def get_init_load_addr(elffile): init_load_addr = get_symbol(elffile, '_start')['st_value']", "from elftools.elf.relocation import RelocationSection except ImportError: print(\"\"\" *** Can't find", "arch_id = get_arch_id(elffile) init_load_addr = get_init_load_addr(elffile) init_bin_size = get_symbol(elffile, '__init_size')['st_value']", "type 0x%x\" % rel['r_info_type']) sys.exit(1) addrs.append(rel['r_offset'] - link_address) addrs.sort() data", "e_machine == 'EM_ARM': return 0 if e_machine == 'EM_AARCH64': return", "'__init_size')['st_value'] outf.write(get_pageable_bin(elffile)[init_bin_size:]) def get_args(): parser = argparse.ArgumentParser() parser.add_argument('--input', required=True, type=argparse.FileType('rb'),", "None tee_embdata_bin = None def eprint(*args, **kwargs): print(*args, file=sys.stderr, **kwargs)", "0: eprint(\"pageable size not a multiple of 4K: \" \"{}\".format(paged_area_size))", "- len(reloc_bin) total_len = reloc_offs + len(reloc_bin) + reloc_pad tee_embdata_bin", "relocations from beginning of table | # +---------------------------------------------------------+ # |", "region is designed to be easy to extend when #", "obj.name.decode() except (UnicodeDecodeError, AttributeError): name = obj.name return name def", "1 else: lsyms_def[symbol_name] += 1 if name in lsyms_def.keys() and", "pageable_bin = get_pageable_bin(elffile) if len(pageable_bin) % small_page_size != 0: eprint(\"pageable", "hash_pad reloc_pad = round_up(len(reloc_bin), 8) - len(reloc_bin) total_len = reloc_offs", "min(init_bin_size, paged_area_size) + len(embdata_bin)) paged_size = paged_area_size - min(init_bin_size, paged_area_size)", "parser.add_argument('--out_pageable_v2', required=False, type=argparse.FileType('wb'), help='The output tee_pageable_v2.bin') return parser.parse_args() def main():", "== 'EM_AARCH64': return 1 eprint('Unknown e_machine \"%s\"' % e_machine) sys.exit(1)", "* 1024 elffile_symbols = None tee_pageable_bin = None tee_pager_bin =", "needed, it's formatted as: # +---------------------------------------------------------+ # | uint32_t: Length", "0: return 0 else: return (((n - 1) // m)", "s in elffile.iter_sections() if isinstance(s, SymbolTableSection)] for section in symbol_tables:", "paged_size)) def output_pager_v2(elffile, outf): init_bin_size = get_symbol(elffile, '__init_size')['st_value'] pager_bin =", "required=False, type=argparse.FileType('wb'), help='The output tee_header_v2.bin') parser.add_argument('--out_pager_v2', required=False, type=argparse.FileType('wb'), help='The output", "from elftools.elf.constants import SH_FLAGS from elftools.elf.enums import ENUM_RELOC_TYPE_ARM from elftools.elf.enums", "sys.exit(1) def get_name(obj): # Symbol or section .name might be", "e_machine = elffile.header['e_machine'] if e_machine == 'EM_ARM': return 0 if", "get_name(symbol) if symbol['st_info']['bind'] == 'STB_GLOBAL': elffile_symbols[symbol_name] = symbol elif symbol['st_info']['bind']", "if pad_to > last_end: bin_data += bytearray(pad_to - last_end) last_end", "not isinstance(section, RelocationSection): continue for rel in section.iter_relocations(): if rel['r_info_type']", "You can install this module with $ apt install python3-pyelftools", "elftools.elf.enums import ENUM_RELOC_TYPE_AARCH64 from elftools.elf.sections import SymbolTableSection from elftools.elf.relocation import", "init_load_addr = get_init_load_addr(elffile) init_bin_size = get_symbol(elffile, '__init_size')['st_value'] pager_bin_size = len(pager_bin)", "embdata_bin = get_embdata_bin(elffile) outf.write(pager_bin) outf.write(pageable_bin[:init_bin_size]) outf.write(embdata_bin) def output_pageable_v2(elffile, outf): init_bin_size", "get_args() elffile = ELFFile(args.input) if args.out_tee_bin: output_header_v1(elffile, args.out_tee_bin) if args.out_tee_pager_bin:", "len(embdata_bin)) paged_size = paged_area_size - min(init_bin_size, paged_area_size) magic = 0x4554504f", "type=argparse.FileType('rb'), help='The input tee.elf') parser.add_argument('--out_tee_bin', required=False, type=argparse.FileType('wb'), help='The output tee.bin')", "last_end) last_end = pad_to return bin_data def get_pageable_bin(elffile): global tee_pageable_bin", "tee_pageable_bin is None: pad_to = 0 dump_names = re.compile(r'^\\..*_(pageable|init)$') tee_pageable_bin", "small_page_size): page = pageable_bin[n:n + small_page_size] data += hashlib.sha256(page).digest() return", "#n return data def get_hashes_bin(elffile): pageable_bin = get_pageable_bin(elffile) if len(pageable_bin)", "name not in elffile_symbols.keys(): eprint(\"Cannot find symbol %s\" % name)", "name = obj.name return name def get_symbol(elffile, name): global elffile_symbols", "**kwargs) def round_up(n, m): if n == 0: return 0", "if isinstance(s, SymbolTableSection)] for section in symbol_tables: for symbol in", "else: exp_rel_type = ENUM_RELOC_TYPE_AARCH64['R_AARCH64_RELATIVE'] link_address = get_symbol(elffile, '__text_start')['st_value'] addrs =", "0 if e_machine == 'EM_AARCH64': return 1 eprint('Unknown e_machine \"%s\"'", "4 * 1024 elffile_symbols = None tee_pageable_bin = None tee_pager_bin", "0x4554504f # 'OPTE' version = 2 flags = 0 nb_images", "dump_names = re.compile(r'^\\..*_(pageable|init)$') tee_pageable_bin = get_sections(elffile, pad_to, dump_names) return tee_pageable_bin", "def get_init_load_addr(elffile): init_load_addr = get_symbol(elffile, '_start')['st_value'] init_load_addr_hi = init_load_addr >>", "required=False, type=argparse.FileType('wb'), help='The output tee_pageable.bin') parser.add_argument('--out_header_v2', required=False, type=argparse.FileType('wb'), help='The output", "global lsyms_def if elffile_symbols is None: elffile_symbols = dict() lsyms_def", "== 'STB_GLOBAL': elffile_symbols[symbol_name] = symbol elif symbol['st_info']['bind'] == 'STB_LOCAL': if", "dump_names = re.compile( r'^\\.(text|rodata|got|data|ARM\\.exidx|ARM\\.extab)$') tee_pager_bin = get_sections(elffile, pad_to, dump_names) return", "obj.name return name def get_symbol(elffile, name): global elffile_symbols global lsyms_def", "[s for s in elffile.iter_sections() if isinstance(s, SymbolTableSection)] for section", "\"elftools\" in your package manager if you are using some", "argparse.ArgumentParser() parser.add_argument('--input', required=True, type=argparse.FileType('rb'), help='The input tee.elf') parser.add_argument('--out_tee_bin', required=False, type=argparse.FileType('wb'),", "to search for \"pyelftools\" or \"elftools\" in your package manager", "- get_symbol(elffile, '__text_start')['st_value'] + len(embdata_bin)) init_size = (pager_bin_size + min(init_bin_size,", "== 0: exp_rel_type = ENUM_RELOC_TYPE_ARM['R_ARM_RELATIVE'] else: exp_rel_type = ENUM_RELOC_TYPE_AARCH64['R_AARCH64_RELATIVE'] link_address", "continue if rel['r_info_type'] != exp_rel_type: eprint(\"Unexpected relocation type 0x%x\" %", "= [] for section in elffile.iter_sections(): if not isinstance(section, RelocationSection):", "m) + 1) * m def get_arch_id(elffile): e_machine = elffile.header['e_machine']", "in elffile_symbols.keys(): elffile_symbols[symbol_name] = symbol if symbol_name not in lsyms_def.keys():", "Length of hashes | # +---------------------------------------------------------+ # | uint32_t: Offset", "% name) sys.exit(1) if name not in elffile_symbols.keys(): eprint(\"Cannot find", "tee.elf') parser.add_argument('--out_tee_bin', required=False, type=argparse.FileType('wb'), help='The output tee.bin') parser.add_argument('--out_tee_pager_bin', required=False, type=argparse.FileType('wb'),", "return 0 if e_machine == 'EM_AARCH64': return 1 eprint('Unknown e_machine", "not in lsyms_def.keys(): lsyms_def[symbol_name] = 1 else: lsyms_def[symbol_name] += 1", "| Data of relocations + eventual padding | # +---------------------------------------------------------+", "args.out_pager_v2: output_pager_v2(elffile, args.out_pager_v2) if args.out_pageable_v2: output_pageable_v2(elffile, args.out_pageable_v2) if __name__ ==", "rel['r_info_type']) sys.exit(1) addrs.append(rel['r_offset'] - link_address) addrs.sort() data = bytearray() for", "| uint32_t: Length of hashes | # +---------------------------------------------------------+ # |", "0xffffffff return init_load_addr_hi, init_load_addr_lo def output_header_v1(elffile, outf): arch_id = get_arch_id(elffile)", "tee_pager_bin is None: pad_to = get_symbol(elffile, '__data_end')['st_value'] dump_names = re.compile(", "get_sections(elffile, pad_to, dump_names) return tee_pager_bin def get_reloc_bin(elffile): if get_arch_id(elffile) ==", "required=False, type=argparse.FileType('wb'), help='The output tee_pager.bin') parser.add_argument('--out_tee_pageable_bin', required=False, type=argparse.FileType('wb'), help='The output", "get_hashes_bin(elffile): pageable_bin = get_pageable_bin(elffile) if len(pageable_bin) % small_page_size != 0:", "in your package manager if you are using some other", "+ small_page_size] data += hashlib.sha256(page).digest() return data def get_embdata_bin(elffile): global", "len(get_embdata_bin(elffile)) init_size = (pager_bin_size + min(init_bin_size, paged_area_size) + embdata_bin_size) paged_size", "parser.add_argument('--out_tee_pager_bin', required=False, type=argparse.FileType('wb'), help='The output tee_pager.bin') parser.add_argument('--out_tee_pageable_bin', required=False, type=argparse.FileType('wb'), help='The", "import argparse import sys import struct import re import hashlib", "hash_offs = 2 * 4 + num_entries * (2 *", "init_mem_usage = (get_symbol(elffile, '__get_tee_init_end')['st_value'] - get_symbol(elffile, '__text_start')['st_value'] + len(embdata_bin)) init_size", "paged_size == 0 else 2 outf.write(struct.pack('<IBBHI', magic, version, arch_id, flags,", "dict() symbol_tables = [s for s in elffile.iter_sections() if isinstance(s,", "- len(hashes_bin) reloc_offs = hash_offs + len(hashes_bin) + hash_pad reloc_pad", "+= section.data() last_end = section['sh_addr'] + section['sh_size'] if pad_to >", "if you are using Ubuntu. Or try to search for", "load_offset. The addresses (r_offset) are also sorted. The format is", "len(embdata_bin)) init_size = (pager_bin_size + min(init_bin_size, paged_area_size) + len(embdata_bin)) paged_size", "1) // m) + 1) * m def get_arch_id(elffile): e_machine", "output_header_v1(elffile, args.out_tee_bin) if args.out_tee_pager_bin: output_pager_bin(elffile, args.out_tee_pager_bin) if args.out_tee_pageable_bin: output_pageable_bin(elffile, args.out_tee_pageable_bin)", "import print_function from __future__ import division import argparse import sys", "= hash_offs + len(hashes_bin) + hash_pad reloc_pad = round_up(len(reloc_bin), 8)", "Length of entire area including this field | # +---------------------------------------------------------+", "# +---------------------------------------------------------+ return tee_embdata_bin def output_pager_bin(elffile, outf): outf.write(get_pager_bin(elffile)) def output_pageable_bin(elffile,", "sys.exit(1) data = bytearray() for n in range(0, len(pageable_bin), small_page_size):", "bin_data += bytearray(pad_to - last_end) last_end = pad_to return bin_data", "of relocations + eventual padding | # +---------------------------------------------------------+ return tee_embdata_bin", "elffile_symbols = dict() lsyms_def = dict() symbol_tables = [s for", "tee_pageable.bin') parser.add_argument('--out_header_v2', required=False, type=argparse.FileType('wb'), help='The output tee_header_v2.bin') parser.add_argument('--out_pager_v2', required=False, type=argparse.FileType('wb'),", "% e_machine) sys.exit(1) def get_name(obj): # Symbol or section .name", "array or a string, we want a # string try:", "symbol elif symbol['st_info']['bind'] == 'STB_LOCAL': if symbol_name not in elffile_symbols.keys():", "or section .name might be a byte array or a", "= get_pageable_bin(elffile) embdata_bin = get_embdata_bin(elffile) outf.write(pager_bin) outf.write(pageable_bin[:init_bin_size]) outf.write(embdata_bin) def output_pageable_v2(elffile,", "1 if name in lsyms_def.keys() and lsyms_def[name] > 1: eprint(\"Multiple", "get_name(section) if (section['sh_type'] == 'SHT_NOBITS' or not (section['sh_flags'] & SH_FLAGS.SHF_ALLOC)", "= len(pager_bin) paged_area_size = len(pageable_bin) init_mem_usage = (get_symbol(elffile, '__get_tee_init_end')['st_value'] -", "'__init_size')['st_value'] pager_bin = get_pager_bin(elffile) pageable_bin = get_pageable_bin(elffile) embdata_bin = get_embdata_bin(elffile)", "relocation, that is, increase by # load_offset. The addresses (r_offset)", "= re.compile( r'^\\.(text|rodata|got|data|ARM\\.exidx|ARM\\.extab)$') tee_pager_bin = get_sections(elffile, pad_to, dump_names) return tee_pager_bin", "get_symbol(elffile, '_start')['st_value'] init_load_addr_hi = init_load_addr >> 32 init_load_addr_lo = init_load_addr", "string, we want a # string try: name = obj.name.decode()", "= ELFFile(args.input) if args.out_tee_bin: output_header_v1(elffile, args.out_tee_bin) if args.out_tee_pager_bin: output_pager_bin(elffile, args.out_tee_pager_bin)", "args.out_header_v2) if args.out_pager_v2: output_pager_v2(elffile, args.out_pager_v2) if args.out_pageable_v2: output_pageable_v2(elffile, args.out_pageable_v2) if", "1: eprint(\"Multiple definitions of local symbol %s\" % name) sys.exit(1)", "other distribution. *** \"\"\") raise small_page_size = 4 * 1024", "outf): outf.write(get_pageable_bin(elffile)) def get_init_load_addr(elffile): init_load_addr = get_symbol(elffile, '_start')['st_value'] init_load_addr_hi =", "AttributeError): name = obj.name return name def get_symbol(elffile, name): global", "dump_names) return tee_pager_bin def get_reloc_bin(elffile): if get_arch_id(elffile) == 0: exp_rel_type", "== 2: outf.write(struct.pack('<IIII', 0xffffffff, 0xffffffff, 1, paged_size)) def output_pager_v2(elffile, outf):", "None tee_pageable_bin = None tee_pager_bin = None tee_embdata_bin = None", "bin_data += bytearray(section['sh_addr'] - last_end) bin_data += section.data() last_end =", "# The embedded data region is designed to be easy", "(section['sh_flags'] & SH_FLAGS.SHF_ALLOC) or not dump_names.match(section_name)): continue if last_end ==", "def output_pageable_v2(elffile, outf): init_bin_size = get_symbol(elffile, '__init_size')['st_value'] outf.write(get_pageable_bin(elffile)[init_bin_size:]) def get_args():", "init_load_addr[0], init_load_addr[1], init_mem_usage, paged_size)) outf.write(pager_bin) outf.write(pageable_bin[:init_bin_size]) outf.write(embdata_bin) outf.write(pageable_bin[init_bin_size:]) def output_header_v2(elffile,", "= 4 * 1024 elffile_symbols = None tee_pageable_bin = None", "ELFFile from elftools.elf.constants import SH_FLAGS from elftools.elf.enums import ENUM_RELOC_TYPE_ARM from", "elif symbol['st_info']['bind'] == 'STB_LOCAL': if symbol_name not in elffile_symbols.keys(): elffile_symbols[symbol_name]", "data += struct.pack('<I', a) # Relocations has been reduced to", "+ eventual padding | # +---------------------------------------------------------+ return tee_embdata_bin def output_pager_bin(elffile,", "magic, version, arch_id, flags, nb_images)) outf.write(struct.pack('<IIII', init_load_addr[0], init_load_addr[1], 0, init_size))", "except ImportError: print(\"\"\" *** Can't find elftools module. Probably it", "struct import re import hashlib try: from elftools.elf.elffile import ELFFile", "from __future__ import division import argparse import sys import struct", "# then: # uint32_t: relocation #1 # uint32_t: relocation #2", "or not (section['sh_flags'] & SH_FLAGS.SHF_ALLOC) or not dump_names.match(section_name)): continue if", "return elffile_symbols[name] def get_sections(elffile, pad_to, dump_names): last_end = 0 bin_data", "it's formatted as: # +---------------------------------------------------------+ # | uint32_t: Length of", "+= reloc_bin + bytearray(reloc_pad) # The embedded data region is", "= 2 flags = 0 nb_images = 1 if paged_size", "link_address = get_symbol(elffile, '__text_start')['st_value'] addrs = [] for section in", "data region is designed to be easy to extend when", "= 1 flags = 0 outf.write(struct.pack('<IBBHIIIII', magic, version, arch_id, flags,", "return name def get_symbol(elffile, name): global elffile_symbols global lsyms_def if", "4) hash_pad = round_up(len(hashes_bin), 8) - len(hashes_bin) reloc_offs = hash_offs", "hashes_bin = get_hashes_bin(elffile) reloc_bin = get_reloc_bin(elffile) num_entries = 2 hash_offs", "elffile.header['e_machine'] if e_machine == 'EM_ARM': return 0 if e_machine ==", "if n == 0: return 0 else: return (((n -", "symbol in section.iter_symbols(): symbol_name = get_name(symbol) if symbol['st_info']['bind'] == 'STB_GLOBAL':", "name) sys.exit(1) if name not in elffile_symbols.keys(): eprint(\"Cannot find symbol", "8) - len(reloc_bin) total_len = reloc_offs + len(reloc_bin) + reloc_pad", "= (get_symbol(elffile, '__get_tee_init_end')['st_value'] - get_symbol(elffile, '__text_start')['st_value'] + len(embdata_bin)) init_size =", "def get_symbol(elffile, name): global elffile_symbols global lsyms_def if elffile_symbols is", "get_embdata_bin(elffile) init_load_addr = get_init_load_addr(elffile) init_bin_size = get_symbol(elffile, '__init_size')['st_value'] pager_bin_size =", "section in elffile.iter_sections(): if not isinstance(section, RelocationSection): continue for rel", "32 init_load_addr_lo = init_load_addr & 0xffffffff return init_load_addr_hi, init_load_addr_lo def", "= get_pager_bin(elffile) pageable_bin = get_pageable_bin(elffile) embdata_bin = get_embdata_bin(elffile) outf.write(pager_bin) outf.write(pageable_bin[:init_bin_size])", "len(reloc_bin) total_len = reloc_offs + len(reloc_bin) + reloc_pad tee_embdata_bin =", "might be a byte array or a string, we want", "beginning of table | # +---------------------------------------------------------+ # | uint32_t: Length", "elffile_symbols[name] def get_sections(elffile, pad_to, dump_names): last_end = 0 bin_data =", "+ 1) * m def get_arch_id(elffile): e_machine = elffile.header['e_machine'] if", "relocations | # +---------------------------------------------------------+ # | Data of hashes +", "padding | # +---------------------------------------------------------+ # | Data of relocations +", "Linaro Limited # from __future__ import print_function from __future__ import", "last_end) bin_data += section.data() last_end = section['sh_addr'] + section['sh_size'] if", "apt install python3-pyelftools if you are using Ubuntu. Or try", "version, arch_id, flags, nb_images)) outf.write(struct.pack('<IIII', init_load_addr[0], init_load_addr[1], 0, init_size)) if", "in addrs: data += struct.pack('<I', a) # Relocations has been", "bytearray() for n in range(0, len(pageable_bin), small_page_size): page = pageable_bin[n:n", "len(hashes_bin), reloc_offs, len(reloc_bin)) tee_embdata_bin += hashes_bin + bytearray(hash_pad) tee_embdata_bin +=", "symbol %s\" % name) sys.exit(1) return elffile_symbols[name] def get_sections(elffile, pad_to,", "if tee_embdata_bin is None: hashes_bin = get_hashes_bin(elffile) reloc_bin = get_reloc_bin(elffile)", "= get_symbol(elffile, '__init_size')['st_value'] pager_bin_size = len(pager_bin) paged_area_size = len(pageable_bin) init_mem_usage", "\"\"\") raise small_page_size = 4 * 1024 elffile_symbols = None", "tee_pageable_bin = get_sections(elffile, pad_to, dump_names) return tee_pageable_bin def get_pager_bin(elffile): global", "min(init_bin_size, paged_area_size) magic = 0x4554504f # 'OPTE' version = 1", "= len(pageable_bin) init_mem_usage = (get_symbol(elffile, '__get_tee_init_end')['st_value'] - get_symbol(elffile, '__text_start')['st_value'] +", "global elffile_symbols global lsyms_def if elffile_symbols is None: elffile_symbols =", "= elffile.header['e_machine'] if e_machine == 'EM_ARM': return 0 if e_machine", "tee_pageable_bin if tee_pageable_bin is None: pad_to = 0 dump_names =", "+---------------------------------------------------------+ return tee_embdata_bin def output_pager_bin(elffile, outf): outf.write(get_pager_bin(elffile)) def output_pageable_bin(elffile, outf):", "relocation #2 # ... # uint32_t: relocation #n return data", "| uint32_t: Offset of relocations from beginning of table |", "section in symbol_tables: for symbol in section.iter_symbols(): symbol_name = get_name(symbol)", "= get_name(symbol) if symbol['st_info']['bind'] == 'STB_GLOBAL': elffile_symbols[symbol_name] = symbol elif", "= (pager_bin_size + min(init_bin_size, paged_area_size) + len(embdata_bin)) paged_size = paged_area_size", "of entire area including this field | # +---------------------------------------------------------+ #", "if section['sh_addr'] > last_end: bin_data += bytearray(section['sh_addr'] - last_end) bin_data", "init_load_addr_hi, init_load_addr_lo def output_header_v1(elffile, outf): arch_id = get_arch_id(elffile) pager_bin =", "is None: pad_to = 0 dump_names = re.compile(r'^\\..*_(pageable|init)$') tee_pageable_bin =", "tee_embdata_bin def output_pager_bin(elffile, outf): outf.write(get_pager_bin(elffile)) def output_pageable_bin(elffile, outf): outf.write(get_pageable_bin(elffile)) def", "+ min(init_bin_size, paged_area_size) + embdata_bin_size) paged_size = paged_area_size - min(init_bin_size,", "+= hashes_bin + bytearray(hash_pad) tee_embdata_bin += reloc_bin + bytearray(reloc_pad) #", "= [s for s in elffile.iter_sections() if isinstance(s, SymbolTableSection)] for", "type=argparse.FileType('wb'), help='The output tee.bin') parser.add_argument('--out_tee_pager_bin', required=False, type=argparse.FileType('wb'), help='The output tee_pager.bin')", "else: return (((n - 1) // m) + 1) *", "area including this field | # +---------------------------------------------------------+ # | uint32_t:", "output_pager_v2(elffile, outf): init_bin_size = get_symbol(elffile, '__init_size')['st_value'] pager_bin = get_pager_bin(elffile) pageable_bin", "module. Probably it is not installed on your system. You", "this module with $ apt install python3-pyelftools if you are", "num_entries = 2 hash_offs = 2 * 4 + num_entries", "+---------------------------------------------------------+ # | uint32_t: Length of entire area including this", "- last_end) bin_data += section.data() last_end = section['sh_addr'] + section['sh_size']", "the relative type with # addend at the address (r_offset)", "+ len(hashes_bin) + hash_pad reloc_pad = round_up(len(reloc_bin), 8) - len(reloc_bin)", "| uint32_t: Length of entire area including this field |", "type=argparse.FileType('wb'), help='The output tee_header_v2.bin') parser.add_argument('--out_pager_v2', required=False, type=argparse.FileType('wb'), help='The output tee_pager_v2.bin')", "1, paged_size)) def output_pager_v2(elffile, outf): init_bin_size = get_symbol(elffile, '__init_size')['st_value'] pager_bin", "last_end = 0 bin_data = bytearray() for section in elffile.iter_sections():", "when # needed, it's formatted as: # +---------------------------------------------------------+ # |", "# SPDX-License-Identifier: BSD-2-Clause # # Copyright (c) 2019, Linaro Limited", "init_load_addr_lo = init_load_addr & 0xffffffff return init_load_addr_hi, init_load_addr_lo def output_header_v1(elffile,", "= section['sh_addr'] + section['sh_size'] if pad_to > last_end: bin_data +=", "None def eprint(*args, **kwargs): print(*args, file=sys.stderr, **kwargs) def round_up(n, m):", "# +---------------------------------------------------------+ # | uint32_t: Length of relocations | #", "of relocations from beginning of table | # +---------------------------------------------------------+ #", "return init_load_addr_hi, init_load_addr_lo def output_header_v1(elffile, outf): arch_id = get_arch_id(elffile) pager_bin", "+---------------------------------------------------------+ # | uint32_t: Length of relocations | # +---------------------------------------------------------+", "| # +---------------------------------------------------------+ # | uint32_t: Length of hashes |", "def get_hashes_bin(elffile): pageable_bin = get_pageable_bin(elffile) if len(pageable_bin) % small_page_size !=", "bytearray(section['sh_addr'] - last_end) bin_data += section.data() last_end = section['sh_addr'] +", "a) # Relocations has been reduced to only become the", "= len(get_embdata_bin(elffile)) init_size = (pager_bin_size + min(init_bin_size, paged_area_size) + embdata_bin_size)", "len(hashes_bin) reloc_offs = hash_offs + len(hashes_bin) + hash_pad reloc_pad =", "paged_area_size - min(init_bin_size, paged_area_size) magic = 0x4554504f # 'OPTE' version", "output_pageable_bin(elffile, outf): outf.write(get_pageable_bin(elffile)) def get_init_load_addr(elffile): init_load_addr = get_symbol(elffile, '_start')['st_value'] init_load_addr_hi", "init_bin_size = get_symbol(elffile, '__init_size')['st_value'] pager_bin = get_pager_bin(elffile) pageable_bin = get_pageable_bin(elffile)", "if paged_size == 0 else 2 outf.write(struct.pack('<IBBHI', magic, version, arch_id,", "some other distribution. *** \"\"\") raise small_page_size = 4 *", "def get_embdata_bin(elffile): global tee_embdata_bin if tee_embdata_bin is None: hashes_bin =", "reloc_bin + bytearray(reloc_pad) # The embedded data region is designed", "elffile_symbols[symbol_name] = symbol elif symbol['st_info']['bind'] == 'STB_LOCAL': if symbol_name not", "m def get_arch_id(elffile): e_machine = elffile.header['e_machine'] if e_machine == 'EM_ARM':", "for section in elffile.iter_sections(): section_name = get_name(section) if (section['sh_type'] ==", "format is # then: # uint32_t: relocation #1 # uint32_t:", "data def get_hashes_bin(elffile): pageable_bin = get_pageable_bin(elffile) if len(pageable_bin) % small_page_size", "outf.write(struct.pack('<IBBHI', magic, version, arch_id, flags, nb_images)) outf.write(struct.pack('<IIII', init_load_addr[0], init_load_addr[1], 0,", "+---------------------------------------------------------+ # | uint32_t: Offset of hashes from beginning of", "== 0 else 2 outf.write(struct.pack('<IBBHI', magic, version, arch_id, flags, nb_images))", "that is, increase by # load_offset. The addresses (r_offset) are", "Or try to search for \"pyelftools\" or \"elftools\" in your", "for section in symbol_tables: for symbol in section.iter_symbols(): symbol_name =", "if symbol['st_info']['bind'] == 'STB_GLOBAL': elffile_symbols[symbol_name] = symbol elif symbol['st_info']['bind'] ==", "if rel['r_info_type'] != exp_rel_type: eprint(\"Unexpected relocation type 0x%x\" % rel['r_info_type'])", "parser = argparse.ArgumentParser() parser.add_argument('--input', required=True, type=argparse.FileType('rb'), help='The input tee.elf') parser.add_argument('--out_tee_bin',", "section in elffile.iter_sections(): section_name = get_name(section) if (section['sh_type'] == 'SHT_NOBITS'", "help='The output tee.bin') parser.add_argument('--out_tee_pager_bin', required=False, type=argparse.FileType('wb'), help='The output tee_pager.bin') parser.add_argument('--out_tee_pageable_bin',", "output tee_header_v2.bin') parser.add_argument('--out_pager_v2', required=False, type=argparse.FileType('wb'), help='The output tee_pager_v2.bin') parser.add_argument('--out_pageable_v2', required=False,", "output_header_v2(elffile, args.out_header_v2) if args.out_pager_v2: output_pager_v2(elffile, args.out_pager_v2) if args.out_pageable_v2: output_pageable_v2(elffile, args.out_pageable_v2)", "ImportError: print(\"\"\" *** Can't find elftools module. Probably it is", "hashes + eventual padding | # +---------------------------------------------------------+ # | Data", "isinstance(s, SymbolTableSection)] for section in symbol_tables: for symbol in section.iter_symbols():", "0, init_size)) if nb_images == 2: outf.write(struct.pack('<IIII', 0xffffffff, 0xffffffff, 1,", "not in elffile_symbols.keys(): eprint(\"Cannot find symbol %s\" % name) sys.exit(1)", "if name not in elffile_symbols.keys(): eprint(\"Cannot find symbol %s\" %", "#!/usr/bin/env python3 # SPDX-License-Identifier: BSD-2-Clause # # Copyright (c) 2019,", "8) - len(hashes_bin) reloc_offs = hash_offs + len(hashes_bin) + hash_pad", "version = 1 flags = 0 outf.write(struct.pack('<IBBHIIIII', magic, version, arch_id,", "- link_address) addrs.sort() data = bytearray() for a in addrs:", "of hashes | # +---------------------------------------------------------+ # | uint32_t: Offset of", "as: # +---------------------------------------------------------+ # | uint32_t: Length of entire area", "= dict() symbol_tables = [s for s in elffile.iter_sections() if", "get_reloc_bin(elffile) num_entries = 2 hash_offs = 2 * 4 +", "= len(get_pageable_bin(elffile)) embdata_bin_size = len(get_embdata_bin(elffile)) init_size = (pager_bin_size + min(init_bin_size,", "uint32_t: Offset of hashes from beginning of table | #", "re import hashlib try: from elftools.elf.elffile import ELFFile from elftools.elf.constants", "n in range(0, len(pageable_bin), small_page_size): page = pageable_bin[n:n + small_page_size]", "= get_init_load_addr(elffile) init_bin_size = get_symbol(elffile, '__init_size')['st_value'] pager_bin_size = len(get_pager_bin(elffile)) paged_area_size", "== 0: continue if rel['r_info_type'] != exp_rel_type: eprint(\"Unexpected relocation type", "get_arch_id(elffile) pager_bin = get_pager_bin(elffile) pageable_bin = get_pageable_bin(elffile) embdata_bin = get_embdata_bin(elffile)", "is designed to be easy to extend when # needed,", "def get_reloc_bin(elffile): if get_arch_id(elffile) == 0: exp_rel_type = ENUM_RELOC_TYPE_ARM['R_ARM_RELATIVE'] else:", "elffile_symbols[symbol_name] = symbol if symbol_name not in lsyms_def.keys(): lsyms_def[symbol_name] =", "get_embdata_bin(elffile): global tee_embdata_bin if tee_embdata_bin is None: hashes_bin = get_hashes_bin(elffile)", "to be easy to extend when # needed, it's formatted", "+---------------------------------------------------------+ # | uint32_t: Number of entries \"2\" | #", "return data def get_embdata_bin(elffile): global tee_embdata_bin if tee_embdata_bin is None:", "magic, version, arch_id, flags, init_size, init_load_addr[0], init_load_addr[1], init_mem_usage, paged_size)) outf.write(pager_bin)", "(r_offset) of relocation, that is, increase by # load_offset. The", "definitions of local symbol %s\" % name) sys.exit(1) if name", "None: pad_to = get_symbol(elffile, '__data_end')['st_value'] dump_names = re.compile( r'^\\.(text|rodata|got|data|ARM\\.exidx|ARM\\.extab)$') tee_pager_bin", "outf.write(pageable_bin[init_bin_size:]) def output_header_v2(elffile, outf): arch_id = get_arch_id(elffile) init_load_addr = get_init_load_addr(elffile)", "at the address (r_offset) of relocation, that is, increase by", "1 if paged_size == 0 else 2 outf.write(struct.pack('<IBBHI', magic, version,", "uint32_t: Number of entries \"2\" | # +---------------------------------------------------------+ # |", "you are using some other distribution. *** \"\"\") raise small_page_size", "string try: name = obj.name.decode() except (UnicodeDecodeError, AttributeError): name =", "0 bin_data = bytearray() for section in elffile.iter_sections(): section_name =", "with $ apt install python3-pyelftools if you are using Ubuntu.", "type=argparse.FileType('wb'), help='The output tee_pager.bin') parser.add_argument('--out_tee_pageable_bin', required=False, type=argparse.FileType('wb'), help='The output tee_pageable.bin')", "+ embdata_bin_size) paged_size = paged_area_size - min(init_bin_size, paged_area_size) magic =", "import SymbolTableSection from elftools.elf.relocation import RelocationSection except ImportError: print(\"\"\" ***", "# string try: name = obj.name.decode() except (UnicodeDecodeError, AttributeError): name", "try: name = obj.name.decode() except (UnicodeDecodeError, AttributeError): name = obj.name", "(pager_bin_size + min(init_bin_size, paged_area_size) + len(embdata_bin)) paged_size = paged_area_size -", "\"%s\"' % e_machine) sys.exit(1) def get_name(obj): # Symbol or section", "pad_to = 0 dump_names = re.compile(r'^\\..*_(pageable|init)$') tee_pageable_bin = get_sections(elffile, pad_to,", "in range(0, len(pageable_bin), small_page_size): page = pageable_bin[n:n + small_page_size] data", "on your system. You can install this module with $", "we want a # string try: name = obj.name.decode() except", "addresses (r_offset) are also sorted. The format is # then:", "symbol['st_info']['bind'] == 'STB_GLOBAL': elffile_symbols[symbol_name] = symbol elif symbol['st_info']['bind'] == 'STB_LOCAL':", "get_pageable_bin(elffile) if len(pageable_bin) % small_page_size != 0: eprint(\"pageable size not", "outf.write(pageable_bin[:init_bin_size]) outf.write(embdata_bin) def output_pageable_v2(elffile, outf): init_bin_size = get_symbol(elffile, '__init_size')['st_value'] outf.write(get_pageable_bin(elffile)[init_bin_size:])", "# | Data of hashes + eventual padding | #", "elftools.elf.relocation import RelocationSection except ImportError: print(\"\"\" *** Can't find elftools", "0: bin_data = section.data() else: if section['sh_addr'] > last_end: bin_data", "= len(get_pager_bin(elffile)) paged_area_size = len(get_pageable_bin(elffile)) embdata_bin_size = len(get_embdata_bin(elffile)) init_size =", "import re import hashlib try: from elftools.elf.elffile import ELFFile from", "output tee_pager.bin') parser.add_argument('--out_tee_pageable_bin', required=False, type=argparse.FileType('wb'), help='The output tee_pageable.bin') parser.add_argument('--out_header_v2', required=False,", "= section.data() else: if section['sh_addr'] > last_end: bin_data += bytearray(section['sh_addr']", "else: if section['sh_addr'] > last_end: bin_data += bytearray(section['sh_addr'] - last_end)", "+ eventual padding | # +---------------------------------------------------------+ # | Data of", "outf): outf.write(get_pager_bin(elffile)) def output_pageable_bin(elffile, outf): outf.write(get_pageable_bin(elffile)) def get_init_load_addr(elffile): init_load_addr =", "symbol %s\" % name) sys.exit(1) if name not in elffile_symbols.keys():", "it is not installed on your system. You can install", "return tee_embdata_bin def output_pager_bin(elffile, outf): outf.write(get_pager_bin(elffile)) def output_pageable_bin(elffile, outf): outf.write(get_pageable_bin(elffile))", "tee_pager_bin = get_sections(elffile, pad_to, dump_names) return tee_pager_bin def get_reloc_bin(elffile): if", "in elffile_symbols.keys(): eprint(\"Cannot find symbol %s\" % name) sys.exit(1) return", "SymbolTableSection from elftools.elf.relocation import RelocationSection except ImportError: print(\"\"\" *** Can't", "has been reduced to only become the relative type with", "output_pager_bin(elffile, outf): outf.write(get_pager_bin(elffile)) def output_pageable_bin(elffile, outf): outf.write(get_pageable_bin(elffile)) def get_init_load_addr(elffile): init_load_addr", "a byte array or a string, we want a #", "def output_header_v2(elffile, outf): arch_id = get_arch_id(elffile) init_load_addr = get_init_load_addr(elffile) init_bin_size", "tee_embdata_bin = None def eprint(*args, **kwargs): print(*args, file=sys.stderr, **kwargs) def", "elffile_symbols.keys(): elffile_symbols[symbol_name] = symbol if symbol_name not in lsyms_def.keys(): lsyms_def[symbol_name]", "The addresses (r_offset) are also sorted. The format is #", "def output_pager_v2(elffile, outf): init_bin_size = get_symbol(elffile, '__init_size')['st_value'] pager_bin = get_pager_bin(elffile)", "outf): init_bin_size = get_symbol(elffile, '__init_size')['st_value'] pager_bin = get_pager_bin(elffile) pageable_bin =", "!= exp_rel_type: eprint(\"Unexpected relocation type 0x%x\" % rel['r_info_type']) sys.exit(1) addrs.append(rel['r_offset']", "*** Can't find elftools module. Probably it is not installed", "import hashlib try: from elftools.elf.elffile import ELFFile from elftools.elf.constants import", "arch_id, flags, nb_images)) outf.write(struct.pack('<IIII', init_load_addr[0], init_load_addr[1], 0, init_size)) if nb_images", "uint32_t: relocation #2 # ... # uint32_t: relocation #n return", "hashlib.sha256(page).digest() return data def get_embdata_bin(elffile): global tee_embdata_bin if tee_embdata_bin is", "entire area including this field | # +---------------------------------------------------------+ # |", "elffile = ELFFile(args.input) if args.out_tee_bin: output_header_v1(elffile, args.out_tee_bin) if args.out_tee_pager_bin: output_pager_bin(elffile,", "Data of relocations + eventual padding | # +---------------------------------------------------------+ return", "outf.write(pageable_bin[:init_bin_size]) outf.write(embdata_bin) outf.write(pageable_bin[init_bin_size:]) def output_header_v2(elffile, outf): arch_id = get_arch_id(elffile) init_load_addr", "increase by # load_offset. The addresses (r_offset) are also sorted.", "raise small_page_size = 4 * 1024 elffile_symbols = None tee_pageable_bin", "from elftools.elf.enums import ENUM_RELOC_TYPE_AARCH64 from elftools.elf.sections import SymbolTableSection from elftools.elf.relocation", "+= struct.pack('<I', a) # Relocations has been reduced to only", "padding | # +---------------------------------------------------------+ return tee_embdata_bin def output_pager_bin(elffile, outf): outf.write(get_pager_bin(elffile))", "elftools.elf.enums import ENUM_RELOC_TYPE_ARM from elftools.elf.enums import ENUM_RELOC_TYPE_AARCH64 from elftools.elf.sections import", "section['sh_addr'] > last_end: bin_data += bytearray(section['sh_addr'] - last_end) bin_data +=", "len(pager_bin) paged_area_size = len(pageable_bin) init_mem_usage = (get_symbol(elffile, '__get_tee_init_end')['st_value'] - get_symbol(elffile,", "nb_images = 1 if paged_size == 0 else 2 outf.write(struct.pack('<IBBHI',", "exp_rel_type: eprint(\"Unexpected relocation type 0x%x\" % rel['r_info_type']) sys.exit(1) addrs.append(rel['r_offset'] -", "get_pager_bin(elffile) pageable_bin = get_pageable_bin(elffile) embdata_bin = get_embdata_bin(elffile) outf.write(pager_bin) outf.write(pageable_bin[:init_bin_size]) outf.write(embdata_bin)", "outf): init_bin_size = get_symbol(elffile, '__init_size')['st_value'] outf.write(get_pageable_bin(elffile)[init_bin_size:]) def get_args(): parser =", "def get_sections(elffile, pad_to, dump_names): last_end = 0 bin_data = bytearray()", "| # +---------------------------------------------------------+ # | Data of hashes + eventual", "pad_to, dump_names) return tee_pageable_bin def get_pager_bin(elffile): global tee_pager_bin if tee_pager_bin", "lsyms_def[name] > 1: eprint(\"Multiple definitions of local symbol %s\" %", "SH_FLAGS from elftools.elf.enums import ENUM_RELOC_TYPE_ARM from elftools.elf.enums import ENUM_RELOC_TYPE_AARCH64 from", "get_symbol(elffile, name): global elffile_symbols global lsyms_def if elffile_symbols is None:", ".name might be a byte array or a string, we", "small_page_size != 0: eprint(\"pageable size not a multiple of 4K:", "= reloc_offs + len(reloc_bin) + reloc_pad tee_embdata_bin = struct.pack('<IIIIII', total_len,", "if len(pageable_bin) % small_page_size != 0: eprint(\"pageable size not a", "relocations + eventual padding | # +---------------------------------------------------------+ return tee_embdata_bin def", "tee_embdata_bin = struct.pack('<IIIIII', total_len, num_entries, hash_offs, len(hashes_bin), reloc_offs, len(reloc_bin)) tee_embdata_bin", "paged_area_size) magic = 0x4554504f # 'OPTE' version = 2 flags", "'EM_AARCH64': return 1 eprint('Unknown e_machine \"%s\"' % e_machine) sys.exit(1) def", "lsyms_def[symbol_name] += 1 if name in lsyms_def.keys() and lsyms_def[name] >", "4K: \" \"{}\".format(paged_area_size)) sys.exit(1) data = bytearray() for n in", "= bytearray() for section in elffile.iter_sections(): section_name = get_name(section) if", "tee_embdata_bin += hashes_bin + bytearray(hash_pad) tee_embdata_bin += reloc_bin + bytearray(reloc_pad)", "# +---------------------------------------------------------+ # | Data of relocations + eventual padding", "pager_bin_size = len(get_pager_bin(elffile)) paged_area_size = len(get_pageable_bin(elffile)) embdata_bin_size = len(get_embdata_bin(elffile)) init_size", "0 nb_images = 1 if paged_size == 0 else 2", "len(get_pager_bin(elffile)) paged_area_size = len(get_pageable_bin(elffile)) embdata_bin_size = len(get_embdata_bin(elffile)) init_size = (pager_bin_size", "embdata_bin = get_embdata_bin(elffile) init_load_addr = get_init_load_addr(elffile) init_bin_size = get_symbol(elffile, '__init_size')['st_value']", "ENUM_RELOC_TYPE_AARCH64 from elftools.elf.sections import SymbolTableSection from elftools.elf.relocation import RelocationSection except", "+= bytearray(pad_to - last_end) last_end = pad_to return bin_data def", "# +---------------------------------------------------------+ # | uint32_t: Length of entire area including", "easy to extend when # needed, it's formatted as: #", "pad_to return bin_data def get_pageable_bin(elffile): global tee_pageable_bin if tee_pageable_bin is", "pageable_bin = get_pageable_bin(elffile) embdata_bin = get_embdata_bin(elffile) init_load_addr = get_init_load_addr(elffile) init_bin_size", "if elffile_symbols is None: elffile_symbols = dict() lsyms_def = dict()", "of entries \"2\" | # +---------------------------------------------------------+ # | uint32_t: Offset", "SymbolTableSection)] for section in symbol_tables: for symbol in section.iter_symbols(): symbol_name", "extend when # needed, it's formatted as: # +---------------------------------------------------------+ #", "init_load_addr = get_init_load_addr(elffile) init_bin_size = get_symbol(elffile, '__init_size')['st_value'] pager_bin_size = len(get_pager_bin(elffile))", "= None tee_embdata_bin = None def eprint(*args, **kwargs): print(*args, file=sys.stderr,", "tee_pager_v2.bin') parser.add_argument('--out_pageable_v2', required=False, type=argparse.FileType('wb'), help='The output tee_pageable_v2.bin') return parser.parse_args() def", "len(reloc_bin)) tee_embdata_bin += hashes_bin + bytearray(hash_pad) tee_embdata_bin += reloc_bin +", "if args.out_header_v2: output_header_v2(elffile, args.out_header_v2) if args.out_pager_v2: output_pager_v2(elffile, args.out_pager_v2) if args.out_pageable_v2:", "# | uint32_t: Offset of relocations from beginning of table", "install this module with $ apt install python3-pyelftools if you", "tee_embdata_bin += reloc_bin + bytearray(reloc_pad) # The embedded data region", "# +---------------------------------------------------------+ # | uint32_t: Number of entries \"2\" |", "Number of entries \"2\" | # +---------------------------------------------------------+ # | uint32_t:", "tee_header_v2.bin') parser.add_argument('--out_pager_v2', required=False, type=argparse.FileType('wb'), help='The output tee_pager_v2.bin') parser.add_argument('--out_pageable_v2', required=False, type=argparse.FileType('wb'),", "section['sh_addr'] + section['sh_size'] if pad_to > last_end: bin_data += bytearray(pad_to", "version = 2 flags = 0 nb_images = 1 if", "elffile_symbols = None tee_pageable_bin = None tee_pager_bin = None tee_embdata_bin", "bytearray(reloc_pad) # The embedded data region is designed to be", "args.out_tee_pageable_bin) if args.out_header_v2: output_header_v2(elffile, args.out_header_v2) if args.out_pager_v2: output_pager_v2(elffile, args.out_pager_v2) if", "get_arch_id(elffile): e_machine = elffile.header['e_machine'] if e_machine == 'EM_ARM': return 0", "symbol_name not in elffile_symbols.keys(): elffile_symbols[symbol_name] = symbol if symbol_name not", "last_end = pad_to return bin_data def get_pageable_bin(elffile): global tee_pageable_bin if", "0: exp_rel_type = ENUM_RELOC_TYPE_ARM['R_ARM_RELATIVE'] else: exp_rel_type = ENUM_RELOC_TYPE_AARCH64['R_AARCH64_RELATIVE'] link_address =", "magic = 0x4554504f # 'OPTE' version = 1 flags =", "of local symbol %s\" % name) sys.exit(1) if name not", "| # +---------------------------------------------------------+ # | uint32_t: Offset of hashes from", "| # +---------------------------------------------------------+ # | Data of relocations + eventual", "outf.write(struct.pack('<IIII', init_load_addr[0], init_load_addr[1], 0, init_size)) if nb_images == 2: outf.write(struct.pack('<IIII',", "+ bytearray(hash_pad) tee_embdata_bin += reloc_bin + bytearray(reloc_pad) # The embedded", "if nb_images == 2: outf.write(struct.pack('<IIII', 0xffffffff, 0xffffffff, 1, paged_size)) def", "hashes | # +---------------------------------------------------------+ # | uint32_t: Offset of relocations", "total_len = reloc_offs + len(reloc_bin) + reloc_pad tee_embdata_bin = struct.pack('<IIIIII',", "eprint(\"Multiple definitions of local symbol %s\" % name) sys.exit(1) if", "# ... # uint32_t: relocation #n return data def get_hashes_bin(elffile):", "= ENUM_RELOC_TYPE_AARCH64['R_AARCH64_RELATIVE'] link_address = get_symbol(elffile, '__text_start')['st_value'] addrs = [] for", "= bytearray() for a in addrs: data += struct.pack('<I', a)", "print(*args, file=sys.stderr, **kwargs) def round_up(n, m): if n == 0:", "elffile.iter_sections() if isinstance(s, SymbolTableSection)] for section in symbol_tables: for symbol", "be easy to extend when # needed, it's formatted as:", "paged_area_size) magic = 0x4554504f # 'OPTE' version = 1 flags", "required=False, type=argparse.FileType('wb'), help='The output tee_pageable_v2.bin') return parser.parse_args() def main(): args", "sys import struct import re import hashlib try: from elftools.elf.elffile", "e_machine == 'EM_AARCH64': return 1 eprint('Unknown e_machine \"%s\"' % e_machine)", "2019, Linaro Limited # from __future__ import print_function from __future__", "output tee.bin') parser.add_argument('--out_tee_pager_bin', required=False, type=argparse.FileType('wb'), help='The output tee_pager.bin') parser.add_argument('--out_tee_pageable_bin', required=False,", "= struct.pack('<IIIIII', total_len, num_entries, hash_offs, len(hashes_bin), reloc_offs, len(reloc_bin)) tee_embdata_bin +=", "designed to be easy to extend when # needed, it's", "if last_end == 0: bin_data = section.data() else: if section['sh_addr']", "using some other distribution. *** \"\"\") raise small_page_size = 4", "of relocation, that is, increase by # load_offset. The addresses", "system. You can install this module with $ apt install", "be a byte array or a string, we want a", "elffile_symbols.keys(): eprint(\"Cannot find symbol %s\" % name) sys.exit(1) return elffile_symbols[name]", "help='The output tee_pager_v2.bin') parser.add_argument('--out_pageable_v2', required=False, type=argparse.FileType('wb'), help='The output tee_pageable_v2.bin') return", "bytearray(hash_pad) tee_embdata_bin += reloc_bin + bytearray(reloc_pad) # The embedded data", "e_machine) sys.exit(1) def get_name(obj): # Symbol or section .name might", "2: outf.write(struct.pack('<IIII', 0xffffffff, 0xffffffff, 1, paged_size)) def output_pager_v2(elffile, outf): init_bin_size", "if args.out_tee_bin: output_header_v1(elffile, args.out_tee_bin) if args.out_tee_pager_bin: output_pager_bin(elffile, args.out_tee_pager_bin) if args.out_tee_pageable_bin:", "get_symbol(elffile, '__text_start')['st_value'] + len(embdata_bin)) init_size = (pager_bin_size + min(init_bin_size, paged_area_size)", "nb_images == 2: outf.write(struct.pack('<IIII', 0xffffffff, 0xffffffff, 1, paged_size)) def output_pager_v2(elffile,", "flags, nb_images)) outf.write(struct.pack('<IIII', init_load_addr[0], init_load_addr[1], 0, init_size)) if nb_images ==", "= get_arch_id(elffile) pager_bin = get_pager_bin(elffile) pageable_bin = get_pageable_bin(elffile) embdata_bin =", "(c) 2019, Linaro Limited # from __future__ import print_function from", "search for \"pyelftools\" or \"elftools\" in your package manager if", "init_size = (pager_bin_size + min(init_bin_size, paged_area_size) + len(embdata_bin)) paged_size =", "exp_rel_type = ENUM_RELOC_TYPE_AARCH64['R_AARCH64_RELATIVE'] link_address = get_symbol(elffile, '__text_start')['st_value'] addrs = []", "return bin_data def get_pageable_bin(elffile): global tee_pageable_bin if tee_pageable_bin is None:", "with # addend at the address (r_offset) of relocation, that", "outf.write(get_pageable_bin(elffile)[init_bin_size:]) def get_args(): parser = argparse.ArgumentParser() parser.add_argument('--input', required=True, type=argparse.FileType('rb'), help='The", "'__init_size')['st_value'] pager_bin_size = len(get_pager_bin(elffile)) paged_area_size = len(get_pageable_bin(elffile)) embdata_bin_size = len(get_embdata_bin(elffile))", "not dump_names.match(section_name)): continue if last_end == 0: bin_data = section.data()", "try: from elftools.elf.elffile import ELFFile from elftools.elf.constants import SH_FLAGS from", "version, arch_id, flags, init_size, init_load_addr[0], init_load_addr[1], init_mem_usage, paged_size)) outf.write(pager_bin) outf.write(pageable_bin[:init_bin_size])", "section['sh_size'] if pad_to > last_end: bin_data += bytearray(pad_to - last_end)", "pad_to, dump_names): last_end = 0 bin_data = bytearray() for section", "get_pager_bin(elffile): global tee_pager_bin if tee_pager_bin is None: pad_to = get_symbol(elffile,", "small_page_size = 4 * 1024 elffile_symbols = None tee_pageable_bin =", "= get_name(section) if (section['sh_type'] == 'SHT_NOBITS' or not (section['sh_flags'] &", "bytearray() for a in addrs: data += struct.pack('<I', a) #", "section .name might be a byte array or a string,", "= 0 outf.write(struct.pack('<IBBHIIIII', magic, version, arch_id, flags, init_size, init_load_addr[0], init_load_addr[1],", "get_init_load_addr(elffile) init_bin_size = get_symbol(elffile, '__init_size')['st_value'] pager_bin_size = len(pager_bin) paged_area_size =", "tee_pageable_bin = None tee_pager_bin = None tee_embdata_bin = None def", "= 0 dump_names = re.compile(r'^\\..*_(pageable|init)$') tee_pageable_bin = get_sections(elffile, pad_to, dump_names)", "get_symbol(elffile, '__init_size')['st_value'] pager_bin_size = len(pager_bin) paged_area_size = len(pageable_bin) init_mem_usage =", "of hashes from beginning of table | # +---------------------------------------------------------+ #", "rel in section.iter_relocations(): if rel['r_info_type'] == 0: continue if rel['r_info_type']", "been reduced to only become the relative type with #", "# 'OPTE' version = 2 flags = 0 nb_images =", "init_size)) if nb_images == 2: outf.write(struct.pack('<IIII', 0xffffffff, 0xffffffff, 1, paged_size))", "output tee_pageable_v2.bin') return parser.parse_args() def main(): args = get_args() elffile", "= 2 * 4 + num_entries * (2 * 4)", "if tee_pageable_bin is None: pad_to = 0 dump_names = re.compile(r'^\\..*_(pageable|init)$')", "reloc_offs, len(reloc_bin)) tee_embdata_bin += hashes_bin + bytearray(hash_pad) tee_embdata_bin += reloc_bin", "num_entries, hash_offs, len(hashes_bin), reloc_offs, len(reloc_bin)) tee_embdata_bin += hashes_bin + bytearray(hash_pad)", "+---------------------------------------------------------+ # | Data of relocations + eventual padding |", "'OPTE' version = 1 flags = 0 outf.write(struct.pack('<IBBHIIIII', magic, version,", "ELFFile(args.input) if args.out_tee_bin: output_header_v1(elffile, args.out_tee_bin) if args.out_tee_pager_bin: output_pager_bin(elffile, args.out_tee_pager_bin) if", "def get_args(): parser = argparse.ArgumentParser() parser.add_argument('--input', required=True, type=argparse.FileType('rb'), help='The input", "# | uint32_t: Length of relocations | # +---------------------------------------------------------+ #", "0x4554504f # 'OPTE' version = 1 flags = 0 outf.write(struct.pack('<IBBHIIIII',", "not in elffile_symbols.keys(): elffile_symbols[symbol_name] = symbol if symbol_name not in", "get_sections(elffile, pad_to, dump_names) return tee_pageable_bin def get_pager_bin(elffile): global tee_pager_bin if", "reduced to only become the relative type with # addend", "get_args(): parser = argparse.ArgumentParser() parser.add_argument('--input', required=True, type=argparse.FileType('rb'), help='The input tee.elf')", "tee.bin') parser.add_argument('--out_tee_pager_bin', required=False, type=argparse.FileType('wb'), help='The output tee_pager.bin') parser.add_argument('--out_tee_pageable_bin', required=False, type=argparse.FileType('wb'),", "0 outf.write(struct.pack('<IBBHIIIII', magic, version, arch_id, flags, init_size, init_load_addr[0], init_load_addr[1], init_mem_usage,", "struct.pack('<IIIIII', total_len, num_entries, hash_offs, len(hashes_bin), reloc_offs, len(reloc_bin)) tee_embdata_bin += hashes_bin", "return parser.parse_args() def main(): args = get_args() elffile = ELFFile(args.input)", "only become the relative type with # addend at the", "parser.parse_args() def main(): args = get_args() elffile = ELFFile(args.input) if", "entries \"2\" | # +---------------------------------------------------------+ # | uint32_t: Offset of", "flags = 0 nb_images = 1 if paged_size == 0", "#1 # uint32_t: relocation #2 # ... # uint32_t: relocation", "Copyright (c) 2019, Linaro Limited # from __future__ import print_function", "tee_pager_bin if tee_pager_bin is None: pad_to = get_symbol(elffile, '__data_end')['st_value'] dump_names", "| uint32_t: Length of relocations | # +---------------------------------------------------------+ # |", "eprint('Unknown e_machine \"%s\"' % e_machine) sys.exit(1) def get_name(obj): # Symbol", "len(pageable_bin) init_mem_usage = (get_symbol(elffile, '__get_tee_init_end')['st_value'] - get_symbol(elffile, '__text_start')['st_value'] + len(embdata_bin))", "= init_load_addr >> 32 init_load_addr_lo = init_load_addr & 0xffffffff return", "type=argparse.FileType('wb'), help='The output tee_pageable_v2.bin') return parser.parse_args() def main(): args =", "# +---------------------------------------------------------+ # | uint32_t: Offset of hashes from beginning", "outf.write(struct.pack('<IIII', 0xffffffff, 0xffffffff, 1, paged_size)) def output_pager_v2(elffile, outf): init_bin_size =", "'__text_start')['st_value'] + len(embdata_bin)) init_size = (pager_bin_size + min(init_bin_size, paged_area_size) +", "import ENUM_RELOC_TYPE_ARM from elftools.elf.enums import ENUM_RELOC_TYPE_AARCH64 from elftools.elf.sections import SymbolTableSection", "+---------------------------------------------------------+ # | uint32_t: Length of hashes | # +---------------------------------------------------------+", "uint32_t: Length of relocations | # +---------------------------------------------------------+ # | Data", "get_pageable_bin(elffile): global tee_pageable_bin if tee_pageable_bin is None: pad_to = 0", "eprint(\"Unexpected relocation type 0x%x\" % rel['r_info_type']) sys.exit(1) addrs.append(rel['r_offset'] - link_address)", "+ num_entries * (2 * 4) hash_pad = round_up(len(hashes_bin), 8)", "this field | # +---------------------------------------------------------+ # | uint32_t: Number of", "outf.write(embdata_bin) def output_pageable_v2(elffile, outf): init_bin_size = get_symbol(elffile, '__init_size')['st_value'] outf.write(get_pageable_bin(elffile)[init_bin_size:]) def", "tee_pager.bin') parser.add_argument('--out_tee_pageable_bin', required=False, type=argparse.FileType('wb'), help='The output tee_pageable.bin') parser.add_argument('--out_header_v2', required=False, type=argparse.FileType('wb'),", "outf): arch_id = get_arch_id(elffile) pager_bin = get_pager_bin(elffile) pageable_bin = get_pageable_bin(elffile)", "= ENUM_RELOC_TYPE_ARM['R_ARM_RELATIVE'] else: exp_rel_type = ENUM_RELOC_TYPE_AARCH64['R_AARCH64_RELATIVE'] link_address = get_symbol(elffile, '__text_start')['st_value']", "get_hashes_bin(elffile) reloc_bin = get_reloc_bin(elffile) num_entries = 2 hash_offs = 2", "m): if n == 0: return 0 else: return (((n", "import SH_FLAGS from elftools.elf.enums import ENUM_RELOC_TYPE_ARM from elftools.elf.enums import ENUM_RELOC_TYPE_AARCH64", "% name) sys.exit(1) return elffile_symbols[name] def get_sections(elffile, pad_to, dump_names): last_end", "a in addrs: data += struct.pack('<I', a) # Relocations has", "def eprint(*args, **kwargs): print(*args, file=sys.stderr, **kwargs) def round_up(n, m): if", "= None tee_pageable_bin = None tee_pager_bin = None tee_embdata_bin =", "= get_hashes_bin(elffile) reloc_bin = get_reloc_bin(elffile) num_entries = 2 hash_offs =", "= None def eprint(*args, **kwargs): print(*args, file=sys.stderr, **kwargs) def round_up(n,", "= get_pageable_bin(elffile) embdata_bin = get_embdata_bin(elffile) init_load_addr = get_init_load_addr(elffile) init_bin_size =", "parser.add_argument('--out_pager_v2', required=False, type=argparse.FileType('wb'), help='The output tee_pager_v2.bin') parser.add_argument('--out_pageable_v2', required=False, type=argparse.FileType('wb'), help='The", "pager_bin = get_pager_bin(elffile) pageable_bin = get_pageable_bin(elffile) embdata_bin = get_embdata_bin(elffile) init_load_addr", "print_function from __future__ import division import argparse import sys import", "# | uint32_t: Number of entries \"2\" | # +---------------------------------------------------------+", "get_arch_id(elffile) init_load_addr = get_init_load_addr(elffile) init_bin_size = get_symbol(elffile, '__init_size')['st_value'] pager_bin_size =", "is not installed on your system. You can install this", "then: # uint32_t: relocation #1 # uint32_t: relocation #2 #", "symbol_name = get_name(symbol) if symbol['st_info']['bind'] == 'STB_GLOBAL': elffile_symbols[symbol_name] = symbol", "pager_bin = get_pager_bin(elffile) pageable_bin = get_pageable_bin(elffile) embdata_bin = get_embdata_bin(elffile) outf.write(pager_bin)", "# Symbol or section .name might be a byte array", "def get_pager_bin(elffile): global tee_pager_bin if tee_pager_bin is None: pad_to =", "formatted as: # +---------------------------------------------------------+ # | uint32_t: Length of entire", "lsyms_def = dict() symbol_tables = [s for s in elffile.iter_sections()", "# # Copyright (c) 2019, Linaro Limited # from __future__", "round_up(len(hashes_bin), 8) - len(hashes_bin) reloc_offs = hash_offs + len(hashes_bin) +", "hash_offs + len(hashes_bin) + hash_pad reloc_pad = round_up(len(reloc_bin), 8) -", "% small_page_size != 0: eprint(\"pageable size not a multiple of", "output_pager_bin(elffile, args.out_tee_pager_bin) if args.out_tee_pageable_bin: output_pageable_bin(elffile, args.out_tee_pageable_bin) if args.out_header_v2: output_header_v2(elffile, args.out_header_v2)", "tee_pager_bin def get_reloc_bin(elffile): if get_arch_id(elffile) == 0: exp_rel_type = ENUM_RELOC_TYPE_ARM['R_ARM_RELATIVE']", "init_mem_usage, paged_size)) outf.write(pager_bin) outf.write(pageable_bin[:init_bin_size]) outf.write(embdata_bin) outf.write(pageable_bin[init_bin_size:]) def output_header_v2(elffile, outf): arch_id", "hashes from beginning of table | # +---------------------------------------------------------+ # |", "dump_names): last_end = 0 bin_data = bytearray() for section in", "relocation #n return data def get_hashes_bin(elffile): pageable_bin = get_pageable_bin(elffile) if", "None: hashes_bin = get_hashes_bin(elffile) reloc_bin = get_reloc_bin(elffile) num_entries = 2", "% rel['r_info_type']) sys.exit(1) addrs.append(rel['r_offset'] - link_address) addrs.sort() data = bytearray()", "are also sorted. The format is # then: # uint32_t:", "except (UnicodeDecodeError, AttributeError): name = obj.name return name def get_symbol(elffile,", "for a in addrs: data += struct.pack('<I', a) # Relocations", "get_symbol(elffile, '__init_size')['st_value'] pager_bin_size = len(get_pager_bin(elffile)) paged_area_size = len(get_pageable_bin(elffile)) embdata_bin_size =", "+= bytearray(section['sh_addr'] - last_end) bin_data += section.data() last_end = section['sh_addr']", "table | # +---------------------------------------------------------+ # | uint32_t: Length of relocations", "from beginning of table | # +---------------------------------------------------------+ # | uint32_t:", "1 flags = 0 outf.write(struct.pack('<IBBHIIIII', magic, version, arch_id, flags, init_size,", "return data def get_hashes_bin(elffile): pageable_bin = get_pageable_bin(elffile) if len(pageable_bin) %", "not installed on your system. You can install this module", "last_end = section['sh_addr'] + section['sh_size'] if pad_to > last_end: bin_data", "get_pageable_bin(elffile) embdata_bin = get_embdata_bin(elffile) outf.write(pager_bin) outf.write(pageable_bin[:init_bin_size]) outf.write(embdata_bin) def output_pageable_v2(elffile, outf):", "# from __future__ import print_function from __future__ import division import", "= get_symbol(elffile, '__data_end')['st_value'] dump_names = re.compile( r'^\\.(text|rodata|got|data|ARM\\.exidx|ARM\\.extab)$') tee_pager_bin = get_sections(elffile,", "get_symbol(elffile, '__init_size')['st_value'] pager_bin = get_pager_bin(elffile) pageable_bin = get_pageable_bin(elffile) embdata_bin =", "can install this module with $ apt install python3-pyelftools if", "is None: pad_to = get_symbol(elffile, '__data_end')['st_value'] dump_names = re.compile( r'^\\.(text|rodata|got|data|ARM\\.exidx|ARM\\.extab)$')", "elftools.elf.elffile import ELFFile from elftools.elf.constants import SH_FLAGS from elftools.elf.enums import", "section.iter_relocations(): if rel['r_info_type'] == 0: continue if rel['r_info_type'] != exp_rel_type:", "0x%x\" % rel['r_info_type']) sys.exit(1) addrs.append(rel['r_offset'] - link_address) addrs.sort() data =", "else: lsyms_def[symbol_name] += 1 if name in lsyms_def.keys() and lsyms_def[name]", "\"{}\".format(paged_area_size)) sys.exit(1) data = bytearray() for n in range(0, len(pageable_bin),", "= symbol if symbol_name not in lsyms_def.keys(): lsyms_def[symbol_name] = 1", "reloc_offs = hash_offs + len(hashes_bin) + hash_pad reloc_pad = round_up(len(reloc_bin),", "round_up(len(reloc_bin), 8) - len(reloc_bin) total_len = reloc_offs + len(reloc_bin) +", "init_size, init_load_addr[0], init_load_addr[1], init_mem_usage, paged_size)) outf.write(pager_bin) outf.write(pageable_bin[:init_bin_size]) outf.write(embdata_bin) outf.write(pageable_bin[init_bin_size:]) def", "SH_FLAGS.SHF_ALLOC) or not dump_names.match(section_name)): continue if last_end == 0: bin_data", "in elffile.iter_sections(): if not isinstance(section, RelocationSection): continue for rel in", "data += hashlib.sha256(page).digest() return data def get_embdata_bin(elffile): global tee_embdata_bin if", "len(pageable_bin) % small_page_size != 0: eprint(\"pageable size not a multiple", "= get_symbol(elffile, '__init_size')['st_value'] pager_bin = get_pager_bin(elffile) pageable_bin = get_pageable_bin(elffile) embdata_bin", "pageable_bin = get_pageable_bin(elffile) embdata_bin = get_embdata_bin(elffile) outf.write(pager_bin) outf.write(pageable_bin[:init_bin_size]) outf.write(embdata_bin) def", "elftools module. Probably it is not installed on your system.", "eprint(*args, **kwargs): print(*args, file=sys.stderr, **kwargs) def round_up(n, m): if n", "= get_symbol(elffile, '_start')['st_value'] init_load_addr_hi = init_load_addr >> 32 init_load_addr_lo =", "0xffffffff, 1, paged_size)) def output_pager_v2(elffile, outf): init_bin_size = get_symbol(elffile, '__init_size')['st_value']", "pad_to, dump_names) return tee_pager_bin def get_reloc_bin(elffile): if get_arch_id(elffile) == 0:", "also sorted. The format is # then: # uint32_t: relocation", "return tee_pager_bin def get_reloc_bin(elffile): if get_arch_id(elffile) == 0: exp_rel_type =", "# | uint32_t: Length of hashes | # +---------------------------------------------------------+ #", "def output_header_v1(elffile, outf): arch_id = get_arch_id(elffile) pager_bin = get_pager_bin(elffile) pageable_bin", "output_header_v1(elffile, outf): arch_id = get_arch_id(elffile) pager_bin = get_pager_bin(elffile) pageable_bin =", "magic = 0x4554504f # 'OPTE' version = 2 flags =", "... # uint32_t: relocation #n return data def get_hashes_bin(elffile): pageable_bin", "your package manager if you are using some other distribution.", "Limited # from __future__ import print_function from __future__ import division", "len(pageable_bin), small_page_size): page = pageable_bin[n:n + small_page_size] data += hashlib.sha256(page).digest()", "| # +---------------------------------------------------------+ # | uint32_t: Offset of relocations from", "get_reloc_bin(elffile): if get_arch_id(elffile) == 0: exp_rel_type = ENUM_RELOC_TYPE_ARM['R_ARM_RELATIVE'] else: exp_rel_type", "not (section['sh_flags'] & SH_FLAGS.SHF_ALLOC) or not dump_names.match(section_name)): continue if last_end", "init_load_addr[1], 0, init_size)) if nb_images == 2: outf.write(struct.pack('<IIII', 0xffffffff, 0xffffffff,", "__future__ import division import argparse import sys import struct import", "get_pager_bin(elffile) pageable_bin = get_pageable_bin(elffile) embdata_bin = get_embdata_bin(elffile) init_load_addr = get_init_load_addr(elffile)", "bin_data = section.data() else: if section['sh_addr'] > last_end: bin_data +=", "global tee_pageable_bin if tee_pageable_bin is None: pad_to = 0 dump_names", "init_load_addr_hi = init_load_addr >> 32 init_load_addr_lo = init_load_addr & 0xffffffff", "bin_data def get_pageable_bin(elffile): global tee_pageable_bin if tee_pageable_bin is None: pad_to", "\" \"{}\".format(paged_area_size)) sys.exit(1) data = bytearray() for n in range(0,", "> 1: eprint(\"Multiple definitions of local symbol %s\" % name)", "output_pageable_v2(elffile, outf): init_bin_size = get_symbol(elffile, '__init_size')['st_value'] outf.write(get_pageable_bin(elffile)[init_bin_size:]) def get_args(): parser", "import RelocationSection except ImportError: print(\"\"\" *** Can't find elftools module.", "continue for rel in section.iter_relocations(): if rel['r_info_type'] == 0: continue", "find symbol %s\" % name) sys.exit(1) return elffile_symbols[name] def get_sections(elffile,", "# uint32_t: relocation #1 # uint32_t: relocation #2 # ...", "'OPTE' version = 2 flags = 0 nb_images = 1", "# 'OPTE' version = 1 flags = 0 outf.write(struct.pack('<IBBHIIIII', magic,", "paged_area_size) + embdata_bin_size) paged_size = paged_area_size - min(init_bin_size, paged_area_size) magic", "(UnicodeDecodeError, AttributeError): name = obj.name return name def get_symbol(elffile, name):", "relative type with # addend at the address (r_offset) of", "required=False, type=argparse.FileType('wb'), help='The output tee.bin') parser.add_argument('--out_tee_pager_bin', required=False, type=argparse.FileType('wb'), help='The output", "'STB_GLOBAL': elffile_symbols[symbol_name] = symbol elif symbol['st_info']['bind'] == 'STB_LOCAL': if symbol_name", "if name in lsyms_def.keys() and lsyms_def[name] > 1: eprint(\"Multiple definitions", "are using some other distribution. *** \"\"\") raise small_page_size =", "min(init_bin_size, paged_area_size) + embdata_bin_size) paged_size = paged_area_size - min(init_bin_size, paged_area_size)", "uint32_t: Offset of relocations from beginning of table | #", "return (((n - 1) // m) + 1) * m", "elffile_symbols is None: elffile_symbols = dict() lsyms_def = dict() symbol_tables", "round_up(n, m): if n == 0: return 0 else: return", "dump_names) return tee_pageable_bin def get_pager_bin(elffile): global tee_pager_bin if tee_pager_bin is", "if e_machine == 'EM_ARM': return 0 if e_machine == 'EM_AARCH64':", "arch_id, flags, init_size, init_load_addr[0], init_load_addr[1], init_mem_usage, paged_size)) outf.write(pager_bin) outf.write(pageable_bin[:init_bin_size]) outf.write(embdata_bin)", "else 2 outf.write(struct.pack('<IBBHI', magic, version, arch_id, flags, nb_images)) outf.write(struct.pack('<IIII', init_load_addr[0],", "+= 1 if name in lsyms_def.keys() and lsyms_def[name] > 1:", "size not a multiple of 4K: \" \"{}\".format(paged_area_size)) sys.exit(1) data", "paged_size)) outf.write(pager_bin) outf.write(pageable_bin[:init_bin_size]) outf.write(embdata_bin) outf.write(pageable_bin[init_bin_size:]) def output_header_v2(elffile, outf): arch_id =", "+= hashlib.sha256(page).digest() return data def get_embdata_bin(elffile): global tee_embdata_bin if tee_embdata_bin", "= get_sections(elffile, pad_to, dump_names) return tee_pageable_bin def get_pager_bin(elffile): global tee_pager_bin", "you are using Ubuntu. Or try to search for \"pyelftools\"", "if e_machine == 'EM_AARCH64': return 1 eprint('Unknown e_machine \"%s\"' %", "name def get_symbol(elffile, name): global elffile_symbols global lsyms_def if elffile_symbols", "if (section['sh_type'] == 'SHT_NOBITS' or not (section['sh_flags'] & SH_FLAGS.SHF_ALLOC) or", "0: continue if rel['r_info_type'] != exp_rel_type: eprint(\"Unexpected relocation type 0x%x\"", "* (2 * 4) hash_pad = round_up(len(hashes_bin), 8) - len(hashes_bin)", "[] for section in elffile.iter_sections(): if not isinstance(section, RelocationSection): continue", "become the relative type with # addend at the address", "# | uint32_t: Length of entire area including this field", "None tee_pager_bin = None tee_embdata_bin = None def eprint(*args, **kwargs):", "is None: hashes_bin = get_hashes_bin(elffile) reloc_bin = get_reloc_bin(elffile) num_entries =", "def main(): args = get_args() elffile = ELFFile(args.input) if args.out_tee_bin:", "from __future__ import print_function from __future__ import division import argparse", "re.compile( r'^\\.(text|rodata|got|data|ARM\\.exidx|ARM\\.extab)$') tee_pager_bin = get_sections(elffile, pad_to, dump_names) return tee_pager_bin def", "= get_arch_id(elffile) init_load_addr = get_init_load_addr(elffile) init_bin_size = get_symbol(elffile, '__init_size')['st_value'] pager_bin_size", "# | uint32_t: Offset of hashes from beginning of table", "(section['sh_type'] == 'SHT_NOBITS' or not (section['sh_flags'] & SH_FLAGS.SHF_ALLOC) or not", "| # +---------------------------------------------------------+ # | uint32_t: Number of entries \"2\"", "uint32_t: relocation #n return data def get_hashes_bin(elffile): pageable_bin = get_pageable_bin(elffile)", "tee_pager_bin = None tee_embdata_bin = None def eprint(*args, **kwargs): print(*args,", "last_end == 0: bin_data = section.data() else: if section['sh_addr'] >", "if symbol_name not in elffile_symbols.keys(): elffile_symbols[symbol_name] = symbol if symbol_name", "from elftools.elf.sections import SymbolTableSection from elftools.elf.relocation import RelocationSection except ImportError:", "init_load_addr_lo def output_header_v1(elffile, outf): arch_id = get_arch_id(elffile) pager_bin = get_pager_bin(elffile)", "outf): arch_id = get_arch_id(elffile) init_load_addr = get_init_load_addr(elffile) init_bin_size = get_symbol(elffile,", "arch_id = get_arch_id(elffile) pager_bin = get_pager_bin(elffile) pageable_bin = get_pageable_bin(elffile) embdata_bin", "* m def get_arch_id(elffile): e_machine = elffile.header['e_machine'] if e_machine ==", "+ len(embdata_bin)) init_size = (pager_bin_size + min(init_bin_size, paged_area_size) + len(embdata_bin))", "are using Ubuntu. Or try to search for \"pyelftools\" or", "print(\"\"\" *** Can't find elftools module. Probably it is not", "> last_end: bin_data += bytearray(section['sh_addr'] - last_end) bin_data += section.data()", "output_pager_v2(elffile, args.out_pager_v2) if args.out_pageable_v2: output_pageable_v2(elffile, args.out_pageable_v2) if __name__ == \"__main__\":", "(pager_bin_size + min(init_bin_size, paged_area_size) + embdata_bin_size) paged_size = paged_area_size -", "not a multiple of 4K: \" \"{}\".format(paged_area_size)) sys.exit(1) data =", "= obj.name.decode() except (UnicodeDecodeError, AttributeError): name = obj.name return name", "addrs = [] for section in elffile.iter_sections(): if not isinstance(section,", "= pageable_bin[n:n + small_page_size] data += hashlib.sha256(page).digest() return data def", "get_pageable_bin(elffile) embdata_bin = get_embdata_bin(elffile) init_load_addr = get_init_load_addr(elffile) init_bin_size = get_symbol(elffile,", "\"2\" | # +---------------------------------------------------------+ # | uint32_t: Offset of hashes", "symbol_tables: for symbol in section.iter_symbols(): symbol_name = get_name(symbol) if symbol['st_info']['bind']", "pad_to > last_end: bin_data += bytearray(pad_to - last_end) last_end =", "Length of relocations | # +---------------------------------------------------------+ # | Data of", "| Data of hashes + eventual padding | # +---------------------------------------------------------+", "get_init_load_addr(elffile) init_bin_size = get_symbol(elffile, '__init_size')['st_value'] pager_bin_size = len(get_pager_bin(elffile)) paged_area_size =", "data = bytearray() for a in addrs: data += struct.pack('<I',", "uint32_t: relocation #1 # uint32_t: relocation #2 # ... #", "= get_reloc_bin(elffile) num_entries = 2 hash_offs = 2 * 4", "paged_area_size = len(pageable_bin) init_mem_usage = (get_symbol(elffile, '__get_tee_init_end')['st_value'] - get_symbol(elffile, '__text_start')['st_value']", "init_size = (pager_bin_size + min(init_bin_size, paged_area_size) + embdata_bin_size) paged_size =", "for \"pyelftools\" or \"elftools\" in your package manager if you", "| # +---------------------------------------------------------+ return tee_embdata_bin def output_pager_bin(elffile, outf): outf.write(get_pager_bin(elffile)) def", "(2 * 4) hash_pad = round_up(len(hashes_bin), 8) - len(hashes_bin) reloc_offs", "get_name(obj): # Symbol or section .name might be a byte", "= pad_to return bin_data def get_pageable_bin(elffile): global tee_pageable_bin if tee_pageable_bin", "= get_embdata_bin(elffile) outf.write(pager_bin) outf.write(pageable_bin[:init_bin_size]) outf.write(embdata_bin) def output_pageable_v2(elffile, outf): init_bin_size =", "bytearray() for section in elffile.iter_sections(): section_name = get_name(section) if (section['sh_type']", "of hashes + eventual padding | # +---------------------------------------------------------+ # |", "- 1) // m) + 1) * m def get_arch_id(elffile):", "(get_symbol(elffile, '__get_tee_init_end')['st_value'] - get_symbol(elffile, '__text_start')['st_value'] + len(embdata_bin)) init_size = (pager_bin_size" ]
[ "# # Copyright (c) 2020 <NAME> for Adafruit Industries LLC", "conditions: # # The above copyright notice and this permission", "Adafruit Industries LLC # # Permission is hereby granted, free", "every 'rate' seconds thereafter\"\"\" state = self.getter() if not state:", "charge, to any person obtaining a copy # of this", "permit persons to whom the Software is # furnished to", "to use, copy, modify, merge, publish, distribute, sublicense, and/or sell", "LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A", "the state of a button and, while it is held,", "IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS", "= -1 return False now = time.monotonic_ns() if state and", "the Software, and to permit persons to whom the Software", "THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE", "the Software is # furnished to do so, subject to", "THE USE OR OTHER DEALINGS IN # THE SOFTWARE. \"\"\"", "above copyright notice and this permission notice shall be included", "IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED,", "FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN", "output a press every 'rate' seconds\"\"\" def __init__(self, getter, rate=0.5):", "<gh_stars>100-1000 # The MIT License (MIT) # # Copyright (c)", "limitation the rights # to use, copy, modify, merge, publish,", "this permission notice shall be included in # all copies", "A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE", "seconds thereafter\"\"\" state = self.getter() if not state: self.next =", "if state and now > self.next: self.next = now +", "def value(self): \"\"\"True when a button is first pressed, or", "and, while it is held, output a press every 'rate'", "(button) repeat when held down \"\"\" import time class KeyRepeat:", "PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE #", "in # all copies or substantial portions of the Software.", "without limitation the rights # to use, copy, modify, merge,", "FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT", "while it is held, output a press every 'rate' seconds\"\"\"", "TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR", "persons to whom the Software is # furnished to do", "self.getter = getter self.rate_ns = round(rate * 1e9) self.next =", "a button is first pressed, or once every 'rate' seconds", "EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE", "rights # to use, copy, modify, merge, publish, distribute, sublicense,", "OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE.", "associated documentation files (the \"Software\"), to deal # in the", "OTHER DEALINGS IN # THE SOFTWARE. \"\"\" Make a key", "# in the Software without restriction, including without limitation the", "thereafter\"\"\" state = self.getter() if not state: self.next = -1", "documentation files (the \"Software\"), to deal # in the Software", "if not state: self.next = -1 return False now =", "and/or sell # copies of the Software, and to permit", "permission notice shall be included in # all copies or", "-1 @property def value(self): \"\"\"True when a button is first", "-1 return False now = time.monotonic_ns() if state and now", "copies or substantial portions of the Software. # # THE", "the rights # to use, copy, modify, merge, publish, distribute,", "MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN", "Software. # # THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT", "every 'rate' seconds\"\"\" def __init__(self, getter, rate=0.5): self.getter = getter", "to any person obtaining a copy # of this software", "False now = time.monotonic_ns() if state and now > self.next:", "pressed, or once every 'rate' seconds thereafter\"\"\" state = self.getter()", "or once every 'rate' seconds thereafter\"\"\" state = self.getter() if", "portions of the Software. # # THE SOFTWARE IS PROVIDED", "* 1e9) self.next = -1 @property def value(self): \"\"\"True when", "is held, output a press every 'rate' seconds\"\"\" def __init__(self,", "Copyright (c) 2020 <NAME> for Adafruit Industries LLC # #", "a press every 'rate' seconds\"\"\" def __init__(self, getter, rate=0.5): self.getter", "be included in # all copies or substantial portions of", "this software and associated documentation files (the \"Software\"), to deal", "of the Software, and to permit persons to whom the", "state of a button and, while it is held, output", "ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN", "is hereby granted, free of charge, to any person obtaining", "# # The above copyright notice and this permission notice", "state: self.next = -1 return False now = time.monotonic_ns() if", "BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY,", "return False now = time.monotonic_ns() if state and now >", "ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT", "sell # copies of the Software, and to permit persons", "2020 <NAME> for Adafruit Industries LLC # # Permission is", "OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT", "KeyRepeat: \"\"\"Track the state of a button and, while it", "Software is # furnished to do so, subject to the", "and associated documentation files (the \"Software\"), to deal # in", "Software without restriction, including without limitation the rights # to", "and to permit persons to whom the Software is #", "CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR", "a key (button) repeat when held down \"\"\" import time", "PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR", "= time.monotonic_ns() if state and now > self.next: self.next =", "copies of the Software, and to permit persons to whom", "OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT,", "hereby granted, free of charge, to any person obtaining a", "THE SOFTWARE OR THE USE OR OTHER DEALINGS IN #", "Make a key (button) repeat when held down \"\"\" import", "whom the Software is # furnished to do so, subject", "publish, distribute, sublicense, and/or sell # copies of the Software,", "\"\"\"Track the state of a button and, while it is", "self.next: self.next = now + self.rate_ns return True return False", "person obtaining a copy # of this software and associated", "# # Permission is hereby granted, free of charge, to", "without restriction, including without limitation the rights # to use,", "sublicense, and/or sell # copies of the Software, and to", "to the following conditions: # # The above copyright notice", "distribute, sublicense, and/or sell # copies of the Software, and", "OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE", "press every 'rate' seconds\"\"\" def __init__(self, getter, rate=0.5): self.getter =", "THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY", "when a button is first pressed, or once every 'rate'", "(MIT) # # Copyright (c) 2020 <NAME> for Adafruit Industries", "subject to the following conditions: # # The above copyright", "substantial portions of the Software. # # THE SOFTWARE IS", "= -1 @property def value(self): \"\"\"True when a button is", "# all copies or substantial portions of the Software. #", "OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.", "DEALINGS IN # THE SOFTWARE. \"\"\" Make a key (button)", "do so, subject to the following conditions: # # The", "Industries LLC # # Permission is hereby granted, free of", "WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING", "HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER #", "LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,", "of a button and, while it is held, output a", "and now > self.next: self.next = now + self.rate_ns return", "in the Software without restriction, including without limitation the rights", "time class KeyRepeat: \"\"\"Track the state of a button and,", "held, output a press every 'rate' seconds\"\"\" def __init__(self, getter,", "included in # all copies or substantial portions of the", "= getter self.rate_ns = round(rate * 1e9) self.next = -1", "state = self.getter() if not state: self.next = -1 return", "first pressed, or once every 'rate' seconds thereafter\"\"\" state =", "# furnished to do so, subject to the following conditions:", "(c) 2020 <NAME> for Adafruit Industries LLC # # Permission", "modify, merge, publish, distribute, sublicense, and/or sell # copies of", "WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN", "any person obtaining a copy # of this software and", "seconds\"\"\" def __init__(self, getter, rate=0.5): self.getter = getter self.rate_ns =", "OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION", "ARISING FROM, # OUT OF OR IN CONNECTION WITH THE", "SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,", "time.monotonic_ns() if state and now > self.next: self.next = now", "IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,", "shall be included in # all copies or substantial portions", "KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO", "Software, and to permit persons to whom the Software is", "held down \"\"\" import time class KeyRepeat: \"\"\"Track the state", "key (button) repeat when held down \"\"\" import time class", "<NAME> for Adafruit Industries LLC # # Permission is hereby", "OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES", "OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH", "# to use, copy, modify, merge, publish, distribute, sublicense, and/or", "> self.next: self.next = now + self.rate_ns return True return", "# The MIT License (MIT) # # Copyright (c) 2020", "License (MIT) # # Copyright (c) 2020 <NAME> for Adafruit", "restriction, including without limitation the rights # to use, copy,", "deal # in the Software without restriction, including without limitation", "\"\"\"True when a button is first pressed, or once every", "OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT", "use, copy, modify, merge, publish, distribute, sublicense, and/or sell #", "now = time.monotonic_ns() if state and now > self.next: self.next", "or substantial portions of the Software. # # THE SOFTWARE", "self.next = -1 @property def value(self): \"\"\"True when a button", "BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS", "LLC # # Permission is hereby granted, free of charge,", "notice and this permission notice shall be included in #", "FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL", "__init__(self, getter, rate=0.5): self.getter = getter self.rate_ns = round(rate *", "including without limitation the rights # to use, copy, modify,", "the Software. # # THE SOFTWARE IS PROVIDED \"AS IS\",", "OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR", "The MIT License (MIT) # # Copyright (c) 2020 <NAME>", "copyright notice and this permission notice shall be included in", "\"Software\"), to deal # in the Software without restriction, including", "copy, modify, merge, publish, distribute, sublicense, and/or sell # copies", "# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR", "getter, rate=0.5): self.getter = getter self.rate_ns = round(rate * 1e9)", "ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED", "free of charge, to any person obtaining a copy #", "MIT License (MIT) # # Copyright (c) 2020 <NAME> for", "files (the \"Software\"), to deal # in the Software without", "IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER", "CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS", "# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR", "# THE SOFTWARE. \"\"\" Make a key (button) repeat when", "it is held, output a press every 'rate' seconds\"\"\" def", "CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION", "round(rate * 1e9) self.next = -1 @property def value(self): \"\"\"True", "def __init__(self, getter, rate=0.5): self.getter = getter self.rate_ns = round(rate", "button and, while it is held, output a press every", "is first pressed, or once every 'rate' seconds thereafter\"\"\" state", "now > self.next: self.next = now + self.rate_ns return True", "all copies or substantial portions of the Software. # #", "self.rate_ns = round(rate * 1e9) self.next = -1 @property def", "getter self.rate_ns = round(rate * 1e9) self.next = -1 @property", "# Permission is hereby granted, free of charge, to any", "of charge, to any person obtaining a copy # of", "software and associated documentation files (the \"Software\"), to deal #", "COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER", "INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, #", "merge, publish, distribute, sublicense, and/or sell # copies of the", "state and now > self.next: self.next = now + self.rate_ns", "OR OTHER DEALINGS IN # THE SOFTWARE. \"\"\" Make a", "# # THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY", "SOFTWARE. \"\"\" Make a key (button) repeat when held down", "# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF", "IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,", "AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR", "the Software without restriction, including without limitation the rights #", "NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT", "# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF", "# copies of the Software, and to permit persons to", "SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE", "of the Software. # # THE SOFTWARE IS PROVIDED \"AS", "\"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR #", "NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR", "\"\"\" import time class KeyRepeat: \"\"\"Track the state of a", "@property def value(self): \"\"\"True when a button is first pressed,", "= round(rate * 1e9) self.next = -1 @property def value(self):", "granted, free of charge, to any person obtaining a copy", "not state: self.next = -1 return False now = time.monotonic_ns()", "button is first pressed, or once every 'rate' seconds thereafter\"\"\"", "# Copyright (c) 2020 <NAME> for Adafruit Industries LLC #", "repeat when held down \"\"\" import time class KeyRepeat: \"\"\"Track", "once every 'rate' seconds thereafter\"\"\" state = self.getter() if not", "obtaining a copy # of this software and associated documentation", "TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN", "is # furnished to do so, subject to the following", "to whom the Software is # furnished to do so,", "for Adafruit Industries LLC # # Permission is hereby granted,", "copy # of this software and associated documentation files (the", "THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY", "LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER", "Permission is hereby granted, free of charge, to any person", "# of this software and associated documentation files (the \"Software\"),", "furnished to do so, subject to the following conditions: #", "to do so, subject to the following conditions: # #", "THE SOFTWARE. \"\"\" Make a key (button) repeat when held", "# The above copyright notice and this permission notice shall", "self.getter() if not state: self.next = -1 return False now", "SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR", "so, subject to the following conditions: # # The above", "a button and, while it is held, output a press", "a copy # of this software and associated documentation files", "OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF", "'rate' seconds thereafter\"\"\" state = self.getter() if not state: self.next", "USE OR OTHER DEALINGS IN # THE SOFTWARE. \"\"\" Make", "when held down \"\"\" import time class KeyRepeat: \"\"\"Track the", "of this software and associated documentation files (the \"Software\"), to", "OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR", "OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE", "'rate' seconds\"\"\" def __init__(self, getter, rate=0.5): self.getter = getter self.rate_ns", "The above copyright notice and this permission notice shall be", "AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, #", "notice shall be included in # all copies or substantial", "EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE", "down \"\"\" import time class KeyRepeat: \"\"\"Track the state of", "\"\"\" Make a key (button) repeat when held down \"\"\"", "IN # THE SOFTWARE. \"\"\" Make a key (button) repeat", "DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF", "import time class KeyRepeat: \"\"\"Track the state of a button", "value(self): \"\"\"True when a button is first pressed, or once", "self.next = -1 return False now = time.monotonic_ns() if state", "class KeyRepeat: \"\"\"Track the state of a button and, while", "rate=0.5): self.getter = getter self.rate_ns = round(rate * 1e9) self.next", "# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO", "# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,", "PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS", "and this permission notice shall be included in # all", "IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS", "the following conditions: # # The above copyright notice and", "WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT", "FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE", "NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE", "(the \"Software\"), to deal # in the Software without restriction,", "AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES", "= self.getter() if not state: self.next = -1 return False", "1e9) self.next = -1 @property def value(self): \"\"\"True when a", "following conditions: # # The above copyright notice and this", "to permit persons to whom the Software is # furnished", "to deal # in the Software without restriction, including without", "WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING", "WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND" ]
[ "ein _privates_ Attribut --- # # Auskommentiert, da es einen", "das Instanz-Dictionary, um die Inhalte jener Instanz zu erhalten. ---", "# class PC: def __init__(self, cpu, gpu, ram): self.cpu =", "# --- Zugriff auf das Instanz-Dictionary, um die Inhalte jener", "Attribut --- # # Auskommentiert, da es einen AttributeError schmeißt.", "= ram # --- Instanziierung einer Klasse ---# # ---", "--- # print(pc_instanz.cpu) print(pc_instanz.gpu) # --- Zugriff auf ein _privates_", "jener Instanz zu erhalten. --- # print(pc_instanz.__dict__) # --- Zugriff", "_public_ Attribute --- # print(pc_instanz.cpu) print(pc_instanz.gpu) # --- Zugriff auf", "def __init__(self, cpu, gpu, ram): self.cpu = cpu self.gpu =", "cpu self.gpu = gpu self.__ram = ram # --- Instanziierung", "# Auskommentiert, da es einen AttributeError schmeißt. # print(pc_instanz.__ram) #", "einen AttributeError schmeißt. # print(pc_instanz.__ram) # --- Zugriff auf das", "--- Zugriff auf das Instanz-Dictionary, um die Inhalte jener Instanz", "schmeißt. # print(pc_instanz.__ram) # --- Zugriff auf das Instanz-Dictionary, um", "--- # # Auskommentiert, da es einen AttributeError schmeißt. #", "--- # print(pc_instanz.__dict__) # --- Zugriff auf das eigentlich _private_", "class PC: def __init__(self, cpu, gpu, ram): self.cpu = cpu", "Instanz zu erhalten. --- # print(pc_instanz.__dict__) # --- Zugriff auf", "# # Auskommentiert, da es einen AttributeError schmeißt. # print(pc_instanz.__ram)", "self.gpu = gpu self.__ram = ram # --- Instanziierung einer", "# print(pc_instanz.__dict__) # --- Zugriff auf das eigentlich _private_ Attribut.", "PC(cpu='Ryzen 7', gpu='RTX2070Super', ram='GSkill') # --- Zugriff auf normale _public_", "die Initialisierung mit den Keywords --- # pc_instanz = PC(cpu='Ryzen", "cpu, gpu, ram): self.cpu = cpu self.gpu = gpu self.__ram", "--- Zugriff auf das eigentlich _private_ Attribut. --- # print(pc_instanz._PC__ram)", "# --- Klassendeklaration mit Konstruktor --- # class PC: def", "__init__(self, cpu, gpu, ram): self.cpu = cpu self.gpu = gpu", "mit Konstruktor --- # class PC: def __init__(self, cpu, gpu,", "# --- Zugriff auf normale _public_ Attribute --- # print(pc_instanz.cpu)", "gpu self.__ram = ram # --- Instanziierung einer Klasse ---#", "bevorzuge die Initialisierung mit den Keywords --- # pc_instanz =", "# print(pc_instanz.__ram) # --- Zugriff auf das Instanz-Dictionary, um die", "--- Instanziierung einer Klasse ---# # --- Ich bevorzuge die", "_privates_ Attribut --- # # Auskommentiert, da es einen AttributeError", "gpu='RTX2070Super', ram='GSkill') # --- Zugriff auf normale _public_ Attribute ---", "Instanz-Dictionary, um die Inhalte jener Instanz zu erhalten. --- #", "# --- Instanziierung einer Klasse ---# # --- Ich bevorzuge", "den Keywords --- # pc_instanz = PC(cpu='Ryzen 7', gpu='RTX2070Super', ram='GSkill')", "pc_instanz = PC(cpu='Ryzen 7', gpu='RTX2070Super', ram='GSkill') # --- Zugriff auf", "self.__ram = ram # --- Instanziierung einer Klasse ---# #", "um die Inhalte jener Instanz zu erhalten. --- # print(pc_instanz.__dict__)", "= PC(cpu='Ryzen 7', gpu='RTX2070Super', ram='GSkill') # --- Zugriff auf normale", "Instanziierung einer Klasse ---# # --- Ich bevorzuge die Initialisierung", "--- Klassendeklaration mit Konstruktor --- # class PC: def __init__(self,", "PC: def __init__(self, cpu, gpu, ram): self.cpu = cpu self.gpu", "# pc_instanz = PC(cpu='Ryzen 7', gpu='RTX2070Super', ram='GSkill') # --- Zugriff", "self.cpu = cpu self.gpu = gpu self.__ram = ram #", "--- Ich bevorzuge die Initialisierung mit den Keywords --- #", "--- Zugriff auf normale _public_ Attribute --- # print(pc_instanz.cpu) print(pc_instanz.gpu)", "Ich bevorzuge die Initialisierung mit den Keywords --- # pc_instanz", "mit den Keywords --- # pc_instanz = PC(cpu='Ryzen 7', gpu='RTX2070Super',", "# --- Zugriff auf ein _privates_ Attribut --- # #", "---# # --- Ich bevorzuge die Initialisierung mit den Keywords", "auf das Instanz-Dictionary, um die Inhalte jener Instanz zu erhalten.", "print(pc_instanz.__ram) # --- Zugriff auf das Instanz-Dictionary, um die Inhalte", "Konstruktor --- # class PC: def __init__(self, cpu, gpu, ram):", "--- # class PC: def __init__(self, cpu, gpu, ram): self.cpu", "erhalten. --- # print(pc_instanz.__dict__) # --- Zugriff auf das eigentlich", "Zugriff auf das Instanz-Dictionary, um die Inhalte jener Instanz zu", "print(pc_instanz.gpu) # --- Zugriff auf ein _privates_ Attribut --- #", "= gpu self.__ram = ram # --- Instanziierung einer Klasse", "die Inhalte jener Instanz zu erhalten. --- # print(pc_instanz.__dict__) #", "Inhalte jener Instanz zu erhalten. --- # print(pc_instanz.__dict__) # ---", "# print(pc_instanz.cpu) print(pc_instanz.gpu) # --- Zugriff auf ein _privates_ Attribut", "ram # --- Instanziierung einer Klasse ---# # --- Ich", "AttributeError schmeißt. # print(pc_instanz.__ram) # --- Zugriff auf das Instanz-Dictionary,", "ram='GSkill') # --- Zugriff auf normale _public_ Attribute --- #", "Klasse ---# # --- Ich bevorzuge die Initialisierung mit den", "# --- Zugriff auf das eigentlich _private_ Attribut. --- #", "# --- Ich bevorzuge die Initialisierung mit den Keywords ---", "--- Zugriff auf ein _privates_ Attribut --- # # Auskommentiert,", "print(pc_instanz.cpu) print(pc_instanz.gpu) # --- Zugriff auf ein _privates_ Attribut ---", "auf normale _public_ Attribute --- # print(pc_instanz.cpu) print(pc_instanz.gpu) # ---", "Klassendeklaration mit Konstruktor --- # class PC: def __init__(self, cpu,", "da es einen AttributeError schmeißt. # print(pc_instanz.__ram) # --- Zugriff", "Auskommentiert, da es einen AttributeError schmeißt. # print(pc_instanz.__ram) # ---", "auf ein _privates_ Attribut --- # # Auskommentiert, da es", "zu erhalten. --- # print(pc_instanz.__dict__) # --- Zugriff auf das", "Zugriff auf ein _privates_ Attribut --- # # Auskommentiert, da", "Initialisierung mit den Keywords --- # pc_instanz = PC(cpu='Ryzen 7',", "Keywords --- # pc_instanz = PC(cpu='Ryzen 7', gpu='RTX2070Super', ram='GSkill') #", "= cpu self.gpu = gpu self.__ram = ram # ---", "Attribute --- # print(pc_instanz.cpu) print(pc_instanz.gpu) # --- Zugriff auf ein", "es einen AttributeError schmeißt. # print(pc_instanz.__ram) # --- Zugriff auf", "--- # pc_instanz = PC(cpu='Ryzen 7', gpu='RTX2070Super', ram='GSkill') # ---", "normale _public_ Attribute --- # print(pc_instanz.cpu) print(pc_instanz.gpu) # --- Zugriff", "7', gpu='RTX2070Super', ram='GSkill') # --- Zugriff auf normale _public_ Attribute", "Zugriff auf normale _public_ Attribute --- # print(pc_instanz.cpu) print(pc_instanz.gpu) #", "<reponame>Geralonx/Classes_Tutorial # --- Klassendeklaration mit Konstruktor --- # class PC:", "print(pc_instanz.__dict__) # --- Zugriff auf das eigentlich _private_ Attribut. ---", "einer Klasse ---# # --- Ich bevorzuge die Initialisierung mit", "ram): self.cpu = cpu self.gpu = gpu self.__ram = ram", "gpu, ram): self.cpu = cpu self.gpu = gpu self.__ram =" ]
[ "\"\"\" from typing import List def count_ways(amount: int, coins: List[int])", "to ``amount`` with values ``coins``.\"\"\" ways = [1] + [0]", "``coins``.\"\"\" ways = [1] + [0] * amount for coin", "ways we can count to ``amount`` with values ``coins``.\"\"\" ways", "coins: for val in range(coin, amount + 1): ways[val] +=", "+ [0] * amount for coin in coins: for val", "count_ways(amount: int, coins: List[int]) -> int: \"\"\"Return the number of", "int: \"\"\"Return the number of ways we can count to", "in range(coin, amount + 1): ways[val] += ways[val - coin]", "<gh_stars>1-10 #!/usr/bin/env python3 \"\"\" The Coin Change Problem :author: <NAME>", "def count_ways(amount: int, coins: List[int]) -> int: \"\"\"Return the number", "ways[val] += ways[val - coin] return ways[-1] def main(): m,", "with values ``coins``.\"\"\" ways = [1] + [0] * amount", "List[int]) -> int: \"\"\"Return the number of ways we can", "- coin] return ways[-1] def main(): m, n = [int(x)", "ways[val - coin] return ways[-1] def main(): m, n =", ":problem: https://www.hackerrank.com/challenges/coin-change/problem \"\"\" from typing import List def count_ways(amount: int,", "coins = sorted({int(x) for x in input().strip().split()}) print(count_ways(m, coins)) if", "x in input().strip().split()}) print(count_ways(m, coins)) if __name__ == '__main__': main()", "def main(): m, n = [int(x) for x in input().strip().split()]", "python3 \"\"\" The Coin Change Problem :author: <NAME> :hackerrank: https://hackerrank.com/delaanthonio", "+= ways[val - coin] return ways[-1] def main(): m, n", "in coins: for val in range(coin, amount + 1): ways[val]", "of ways we can count to ``amount`` with values ``coins``.\"\"\"", "for x in input().strip().split()}) print(count_ways(m, coins)) if __name__ == '__main__':", "[int(x) for x in input().strip().split()] coins = sorted({int(x) for x", "int, coins: List[int]) -> int: \"\"\"Return the number of ways", "= [int(x) for x in input().strip().split()] coins = sorted({int(x) for", "range(coin, amount + 1): ways[val] += ways[val - coin] return", "typing import List def count_ways(amount: int, coins: List[int]) -> int:", "+ 1): ways[val] += ways[val - coin] return ways[-1] def", "number of ways we can count to ``amount`` with values", "we can count to ``amount`` with values ``coins``.\"\"\" ways =", "from typing import List def count_ways(amount: int, coins: List[int]) ->", "val in range(coin, amount + 1): ways[val] += ways[val -", "input().strip().split()] coins = sorted({int(x) for x in input().strip().split()}) print(count_ways(m, coins))", "values ``coins``.\"\"\" ways = [1] + [0] * amount for", "[0] * amount for coin in coins: for val in", "Coin Change Problem :author: <NAME> :hackerrank: https://hackerrank.com/delaanthonio :problem: https://www.hackerrank.com/challenges/coin-change/problem \"\"\"", "in input().strip().split()] coins = sorted({int(x) for x in input().strip().split()}) print(count_ways(m,", "The Coin Change Problem :author: <NAME> :hackerrank: https://hackerrank.com/delaanthonio :problem: https://www.hackerrank.com/challenges/coin-change/problem", "coin] return ways[-1] def main(): m, n = [int(x) for", "import List def count_ways(amount: int, coins: List[int]) -> int: \"\"\"Return", "https://www.hackerrank.com/challenges/coin-change/problem \"\"\" from typing import List def count_ways(amount: int, coins:", "amount for coin in coins: for val in range(coin, amount", "main(): m, n = [int(x) for x in input().strip().split()] coins", "<NAME> :hackerrank: https://hackerrank.com/delaanthonio :problem: https://www.hackerrank.com/challenges/coin-change/problem \"\"\" from typing import List", "return ways[-1] def main(): m, n = [int(x) for x", "https://hackerrank.com/delaanthonio :problem: https://www.hackerrank.com/challenges/coin-change/problem \"\"\" from typing import List def count_ways(amount:", "x in input().strip().split()] coins = sorted({int(x) for x in input().strip().split()})", "ways = [1] + [0] * amount for coin in", "-> int: \"\"\"Return the number of ways we can count", "for coin in coins: for val in range(coin, amount +", "the number of ways we can count to ``amount`` with", "coin in coins: for val in range(coin, amount + 1):", "for x in input().strip().split()] coins = sorted({int(x) for x in", "count to ``amount`` with values ``coins``.\"\"\" ways = [1] +", "m, n = [int(x) for x in input().strip().split()] coins =", "ways[-1] def main(): m, n = [int(x) for x in", "n = [int(x) for x in input().strip().split()] coins = sorted({int(x)", ":hackerrank: https://hackerrank.com/delaanthonio :problem: https://www.hackerrank.com/challenges/coin-change/problem \"\"\" from typing import List def", "* amount for coin in coins: for val in range(coin,", "[1] + [0] * amount for coin in coins: for", "1): ways[val] += ways[val - coin] return ways[-1] def main():", "Change Problem :author: <NAME> :hackerrank: https://hackerrank.com/delaanthonio :problem: https://www.hackerrank.com/challenges/coin-change/problem \"\"\" from", "= [1] + [0] * amount for coin in coins:", "\"\"\" The Coin Change Problem :author: <NAME> :hackerrank: https://hackerrank.com/delaanthonio :problem:", "coins: List[int]) -> int: \"\"\"Return the number of ways we", "sorted({int(x) for x in input().strip().split()}) print(count_ways(m, coins)) if __name__ ==", "List def count_ways(amount: int, coins: List[int]) -> int: \"\"\"Return the", "= sorted({int(x) for x in input().strip().split()}) print(count_ways(m, coins)) if __name__", "\"\"\"Return the number of ways we can count to ``amount``", ":author: <NAME> :hackerrank: https://hackerrank.com/delaanthonio :problem: https://www.hackerrank.com/challenges/coin-change/problem \"\"\" from typing import", "amount + 1): ways[val] += ways[val - coin] return ways[-1]", "can count to ``amount`` with values ``coins``.\"\"\" ways = [1]", "``amount`` with values ``coins``.\"\"\" ways = [1] + [0] *", "for val in range(coin, amount + 1): ways[val] += ways[val", "#!/usr/bin/env python3 \"\"\" The Coin Change Problem :author: <NAME> :hackerrank:", "Problem :author: <NAME> :hackerrank: https://hackerrank.com/delaanthonio :problem: https://www.hackerrank.com/challenges/coin-change/problem \"\"\" from typing" ]
[ "* from . import models # Register your models here.", "django.contrib import admin #from .models import * from . import", ".models import * from . import models # Register your", "import admin #from .models import * from . import models", "from django.contrib import admin #from .models import * from .", "admin #from .models import * from . import models #", "#from .models import * from . import models # Register", "from . import models # Register your models here. admin.site.register(models.ClimbModel)", "import * from . import models # Register your models" ]
[ "System :: OS Independent\", \"Programming Language :: Python\", \"Programming Language", "import setup # Get the version from the relevant file", "setuptools import setup # Get the version from the relevant", "\"Programming Language :: Python\", \"Programming Language :: Python :: 3\",", "file d = run_path('skaero/version.py') __version__ = d['__version__'] setup( name=\"scikit-aero\", version=__version__,", ":: Python\", \"Programming Language :: Python :: 3\", \"Programming Language", "\"gas\" ], requires=[\"numpy\", \"scipy\"], packages=[ \"skaero\", \"skaero.atmosphere\", \"skaero.gasdynamics\", \"skaero.util\" ],", "Language :: Python :: 3\", \"Programming Language :: Python ::", "- Pre-Alpha\", \"Intended Audience :: Education\", \"Intended Audience :: Science/Research\",", "\"scipy\"], packages=[ \"skaero\", \"skaero.atmosphere\", \"skaero.gasdynamics\", \"skaero.util\" ], classifiers=[ \"Development Status", "\"Topic :: Scientific/Engineering\", \"Topic :: Scientific/Engineering :: Physics\" ], long_description=open('README.rst').read()", "utf-8 from runpy import run_path from setuptools import setup #", "author_email=\"<EMAIL>\", url=\"https://github.com/Juanlu001/scikit-aero\", license=\"BSD\", keywords=[ \"aero\", \"aeronautical\", \"aerospace\", \"engineering\", \"atmosphere\", \"gas\"", "classifiers=[ \"Development Status :: 2 - Pre-Alpha\", \"Intended Audience ::", ":: 3\", \"Programming Language :: Python :: Implementation :: CPython\",", "], requires=[\"numpy\", \"scipy\"], packages=[ \"skaero\", \"skaero.atmosphere\", \"skaero.gasdynamics\", \"skaero.util\" ], classifiers=[", ":: Python :: Implementation :: CPython\", \"Topic :: Scientific/Engineering\", \"Topic", "the relevant file d = run_path('skaero/version.py') __version__ = d['__version__'] setup(", "\"Operating System :: OS Independent\", \"Programming Language :: Python\", \"Programming", "from the relevant file d = run_path('skaero/version.py') __version__ = d['__version__']", "\"Programming Language :: Python :: 3\", \"Programming Language :: Python", "3\", \"Programming Language :: Python :: Implementation :: CPython\", \"Topic", "keywords=[ \"aero\", \"aeronautical\", \"aerospace\", \"engineering\", \"atmosphere\", \"gas\" ], requires=[\"numpy\", \"scipy\"],", ":: BSD License\", \"Operating System :: OS Independent\", \"Programming Language", "\"skaero.util\" ], classifiers=[ \"Development Status :: 2 - Pre-Alpha\", \"Intended", "\"Programming Language :: Python :: Implementation :: CPython\", \"Topic ::", "setup # Get the version from the relevant file d", "runpy import run_path from setuptools import setup # Get the", "Language :: Python\", \"Programming Language :: Python :: 3\", \"Programming", "= run_path('skaero/version.py') __version__ = d['__version__'] setup( name=\"scikit-aero\", version=__version__, description=\"Aeronautical engineering", "d['__version__'] setup( name=\"scikit-aero\", version=__version__, description=\"Aeronautical engineering calculations in Python.\", author=\"<NAME>\",", ":: Python :: 3\", \"Programming Language :: Python :: Implementation", "name=\"scikit-aero\", version=__version__, description=\"Aeronautical engineering calculations in Python.\", author=\"<NAME>\", author_email=\"<EMAIL>\", url=\"https://github.com/Juanlu001/scikit-aero\",", "relevant file d = run_path('skaero/version.py') __version__ = d['__version__'] setup( name=\"scikit-aero\",", ":: Education\", \"Intended Audience :: Science/Research\", \"License :: OSI Approved", "run_path from setuptools import setup # Get the version from", "url=\"https://github.com/Juanlu001/scikit-aero\", license=\"BSD\", keywords=[ \"aero\", \"aeronautical\", \"aerospace\", \"engineering\", \"atmosphere\", \"gas\" ],", "__version__ = d['__version__'] setup( name=\"scikit-aero\", version=__version__, description=\"Aeronautical engineering calculations in", "= d['__version__'] setup( name=\"scikit-aero\", version=__version__, description=\"Aeronautical engineering calculations in Python.\",", "Get the version from the relevant file d = run_path('skaero/version.py')", "Python\", \"Programming Language :: Python :: 3\", \"Programming Language ::", "BSD License\", \"Operating System :: OS Independent\", \"Programming Language ::", ":: CPython\", \"Topic :: Scientific/Engineering\", \"Topic :: Scientific/Engineering :: Physics\"", "version=__version__, description=\"Aeronautical engineering calculations in Python.\", author=\"<NAME>\", author_email=\"<EMAIL>\", url=\"https://github.com/Juanlu001/scikit-aero\", license=\"BSD\",", "\"skaero\", \"skaero.atmosphere\", \"skaero.gasdynamics\", \"skaero.util\" ], classifiers=[ \"Development Status :: 2", "engineering calculations in Python.\", author=\"<NAME>\", author_email=\"<EMAIL>\", url=\"https://github.com/Juanlu001/scikit-aero\", license=\"BSD\", keywords=[ \"aero\",", "\"aeronautical\", \"aerospace\", \"engineering\", \"atmosphere\", \"gas\" ], requires=[\"numpy\", \"scipy\"], packages=[ \"skaero\",", "\"License :: OSI Approved :: BSD License\", \"Operating System ::", "\"atmosphere\", \"gas\" ], requires=[\"numpy\", \"scipy\"], packages=[ \"skaero\", \"skaero.atmosphere\", \"skaero.gasdynamics\", \"skaero.util\"", "\"engineering\", \"atmosphere\", \"gas\" ], requires=[\"numpy\", \"scipy\"], packages=[ \"skaero\", \"skaero.atmosphere\", \"skaero.gasdynamics\",", "author=\"<NAME>\", author_email=\"<EMAIL>\", url=\"https://github.com/Juanlu001/scikit-aero\", license=\"BSD\", keywords=[ \"aero\", \"aeronautical\", \"aerospace\", \"engineering\", \"atmosphere\",", "Pre-Alpha\", \"Intended Audience :: Education\", \"Intended Audience :: Science/Research\", \"License", ":: Science/Research\", \"License :: OSI Approved :: BSD License\", \"Operating", "\"aerospace\", \"engineering\", \"atmosphere\", \"gas\" ], requires=[\"numpy\", \"scipy\"], packages=[ \"skaero\", \"skaero.atmosphere\",", "Python :: Implementation :: CPython\", \"Topic :: Scientific/Engineering\", \"Topic ::", "\"Development Status :: 2 - Pre-Alpha\", \"Intended Audience :: Education\",", "\"Intended Audience :: Science/Research\", \"License :: OSI Approved :: BSD", "Science/Research\", \"License :: OSI Approved :: BSD License\", \"Operating System", "the version from the relevant file d = run_path('skaero/version.py') __version__", "in Python.\", author=\"<NAME>\", author_email=\"<EMAIL>\", url=\"https://github.com/Juanlu001/scikit-aero\", license=\"BSD\", keywords=[ \"aero\", \"aeronautical\", \"aerospace\",", "version from the relevant file d = run_path('skaero/version.py') __version__ =", "d = run_path('skaero/version.py') __version__ = d['__version__'] setup( name=\"scikit-aero\", version=__version__, description=\"Aeronautical", "requires=[\"numpy\", \"scipy\"], packages=[ \"skaero\", \"skaero.atmosphere\", \"skaero.gasdynamics\", \"skaero.util\" ], classifiers=[ \"Development", "Independent\", \"Programming Language :: Python\", \"Programming Language :: Python ::", "# Get the version from the relevant file d =", ":: 2 - Pre-Alpha\", \"Intended Audience :: Education\", \"Intended Audience", "Approved :: BSD License\", \"Operating System :: OS Independent\", \"Programming", "License\", \"Operating System :: OS Independent\", \"Programming Language :: Python\",", "# coding: utf-8 from runpy import run_path from setuptools import", "\"skaero.gasdynamics\", \"skaero.util\" ], classifiers=[ \"Development Status :: 2 - Pre-Alpha\",", ":: OSI Approved :: BSD License\", \"Operating System :: OS", "from runpy import run_path from setuptools import setup # Get", "\"aero\", \"aeronautical\", \"aerospace\", \"engineering\", \"atmosphere\", \"gas\" ], requires=[\"numpy\", \"scipy\"], packages=[", "], classifiers=[ \"Development Status :: 2 - Pre-Alpha\", \"Intended Audience", "Language :: Python :: Implementation :: CPython\", \"Topic :: Scientific/Engineering\",", "description=\"Aeronautical engineering calculations in Python.\", author=\"<NAME>\", author_email=\"<EMAIL>\", url=\"https://github.com/Juanlu001/scikit-aero\", license=\"BSD\", keywords=[", "OSI Approved :: BSD License\", \"Operating System :: OS Independent\",", "Implementation :: CPython\", \"Topic :: Scientific/Engineering\", \"Topic :: Scientific/Engineering ::", "CPython\", \"Topic :: Scientific/Engineering\", \"Topic :: Scientific/Engineering :: Physics\" ],", "run_path('skaero/version.py') __version__ = d['__version__'] setup( name=\"scikit-aero\", version=__version__, description=\"Aeronautical engineering calculations", "Python.\", author=\"<NAME>\", author_email=\"<EMAIL>\", url=\"https://github.com/Juanlu001/scikit-aero\", license=\"BSD\", keywords=[ \"aero\", \"aeronautical\", \"aerospace\", \"engineering\",", "\"Intended Audience :: Education\", \"Intended Audience :: Science/Research\", \"License ::", "import run_path from setuptools import setup # Get the version", "\"skaero.atmosphere\", \"skaero.gasdynamics\", \"skaero.util\" ], classifiers=[ \"Development Status :: 2 -", "Education\", \"Intended Audience :: Science/Research\", \"License :: OSI Approved ::", "Python :: 3\", \"Programming Language :: Python :: Implementation ::", "from setuptools import setup # Get the version from the", "coding: utf-8 from runpy import run_path from setuptools import setup", ":: OS Independent\", \"Programming Language :: Python\", \"Programming Language ::", "calculations in Python.\", author=\"<NAME>\", author_email=\"<EMAIL>\", url=\"https://github.com/Juanlu001/scikit-aero\", license=\"BSD\", keywords=[ \"aero\", \"aeronautical\",", "Audience :: Education\", \"Intended Audience :: Science/Research\", \"License :: OSI", "packages=[ \"skaero\", \"skaero.atmosphere\", \"skaero.gasdynamics\", \"skaero.util\" ], classifiers=[ \"Development Status ::", "2 - Pre-Alpha\", \"Intended Audience :: Education\", \"Intended Audience ::", ":: Scientific/Engineering\", \"Topic :: Scientific/Engineering :: Physics\" ], long_description=open('README.rst').read() )", "license=\"BSD\", keywords=[ \"aero\", \"aeronautical\", \"aerospace\", \"engineering\", \"atmosphere\", \"gas\" ], requires=[\"numpy\",", "Status :: 2 - Pre-Alpha\", \"Intended Audience :: Education\", \"Intended", "Audience :: Science/Research\", \"License :: OSI Approved :: BSD License\",", ":: Implementation :: CPython\", \"Topic :: Scientific/Engineering\", \"Topic :: Scientific/Engineering", "OS Independent\", \"Programming Language :: Python\", \"Programming Language :: Python", "setup( name=\"scikit-aero\", version=__version__, description=\"Aeronautical engineering calculations in Python.\", author=\"<NAME>\", author_email=\"<EMAIL>\",", "<reponame>TheMagicNacho/artemis-nozzle<gh_stars>0 # coding: utf-8 from runpy import run_path from setuptools" ]
[ "= 0 def queen(n): try_queen(1,n) n=int(input(\"请输入n:\")) queens = [0]*(n+1) #", "range(1,n+1): if queens[i] == j: print(\"Q \",end=\"\") else: print(\" \",end=\"\")", "queens[i], n) i+=1 queens[i] = 0 def queen(n): try_queen(1,n) n=int(input(\"请输入n:\"))", "print(\" \",end=\"\") print() def set_flags(i,j,n): col_flags[j]=1 diag_flags[i+j-1]=1 diag2_flags[n+i-j]=1 def clear_flags(i,j,n):", "diag_flags[i+j-1]=0 diag2_flags[n+i-j]=0 def can_stay(i,j,n): if col_flags[j]==1: return False if diag_flags[i+j-1]==1:", "True def try_queen(i,n): global count i=1 while True: queens[i]+=1 if", "i-=1 if i<1: # all possible solutions have been tried,", "\"\"\" 8皇后问题 使用栈实现回溯法 \"\"\" def print_board(n,count): print(f\"------解.{count}------\") print(\" \",end=\"\") for", "count += 1 print_board(n, count) else: set_flags(i, queens[i], n) i+=1", "been tried, quit searching break clear_flags(i,queens[i],n) elif can_stay(i,queens[i],n): if i==n:", "print() def set_flags(i,j,n): col_flags[j]=1 diag_flags[i+j-1]=1 diag2_flags[n+i-j]=1 def clear_flags(i,j,n): col_flags[j]=0 diag_flags[i+j-1]=0", "searching break clear_flags(i,queens[i],n) elif can_stay(i,queens[i],n): if i==n: count += 1", "# all possible solutions have been tried, quit searching break", "have been tried, quit searching break clear_flags(i,queens[i],n) elif can_stay(i,queens[i],n): if", "count) else: set_flags(i, queens[i], n) i+=1 queens[i] = 0 def", "print_board(n,count): print(f\"------解.{count}------\") print(\" \",end=\"\") for j in range(n): print(f\"{j:<2}\" ,end=\"\")", "range(1,n+1): print(f\"{i:<2}\",end=\"\") for j in range(1,n+1): if queens[i] == j:", "print(f\"------解.{count}------\") print(\" \",end=\"\") for j in range(n): print(f\"{j:<2}\" ,end=\"\") print()", "try_queen(i,n): global count i=1 while True: queens[i]+=1 if queens[i]>n: #", "diag2_flags[n+i-j]=0 def can_stay(i,j,n): if col_flags[j]==1: return False if diag_flags[i+j-1]==1: return", "主对角线标志 diag_flags = [0]*(2*n) # 副对角线标志 diag2_flags = [0] *", "使用栈实现回溯法 \"\"\" def print_board(n,count): print(f\"------解.{count}------\") print(\" \",end=\"\") for j in", "possible solutions have been tried, quit searching break clear_flags(i,queens[i],n) elif", "return True def try_queen(i,n): global count i=1 while True: queens[i]+=1", "8皇后问题 使用栈实现回溯法 \"\"\" def print_board(n,count): print(f\"------解.{count}------\") print(\" \",end=\"\") for j", "while True: queens[i]+=1 if queens[i]>n: # backtracking i-=1 if i<1:", "i in range(1,n+1): print(f\"{i:<2}\",end=\"\") for j in range(1,n+1): if queens[i]", "queens = [0]*(n+1) # 列标志 col_flags=[0]*(n+1) # 主对角线标志 diag_flags =", "== j: print(\"Q \",end=\"\") else: print(\" \",end=\"\") print() def set_flags(i,j,n):", "\",end=\"\") print() def set_flags(i,j,n): col_flags[j]=1 diag_flags[i+j-1]=1 diag2_flags[n+i-j]=1 def clear_flags(i,j,n): col_flags[j]=0", "diag2_flags[n+i-j]==1: return False return True def try_queen(i,n): global count i=1", "副对角线标志 diag2_flags = [0] * (2*n) count = 0 queen(n)", "True: queens[i]+=1 if queens[i]>n: # backtracking i-=1 if i<1: #", "i=1 while True: queens[i]+=1 if queens[i]>n: # backtracking i-=1 if", "print(\"Q \",end=\"\") else: print(\" \",end=\"\") print() def set_flags(i,j,n): col_flags[j]=1 diag_flags[i+j-1]=1", "# 列标志 col_flags=[0]*(n+1) # 主对角线标志 diag_flags = [0]*(2*n) # 副对角线标志", "if queens[i] == j: print(\"Q \",end=\"\") else: print(\" \",end=\"\") print()", "elif can_stay(i,queens[i],n): if i==n: count += 1 print_board(n, count) else:", "# 副对角线标志 diag2_flags = [0] * (2*n) count = 0", "False return True def try_queen(i,n): global count i=1 while True:", "else: print(\" \",end=\"\") print() def set_flags(i,j,n): col_flags[j]=1 diag_flags[i+j-1]=1 diag2_flags[n+i-j]=1 def", "can_stay(i,j,n): if col_flags[j]==1: return False if diag_flags[i+j-1]==1: return False if", "return False if diag_flags[i+j-1]==1: return False if diag2_flags[n+i-j]==1: return False", ",end=\"\") print() for i in range(1,n+1): print(f\"{i:<2}\",end=\"\") for j in", "i+=1 queens[i] = 0 def queen(n): try_queen(1,n) n=int(input(\"请输入n:\")) queens =", "all possible solutions have been tried, quit searching break clear_flags(i,queens[i],n)", "break clear_flags(i,queens[i],n) elif can_stay(i,queens[i],n): if i==n: count += 1 print_board(n,", "+= 1 print_board(n, count) else: set_flags(i, queens[i], n) i+=1 queens[i]", "print(f\"{j:<2}\" ,end=\"\") print() for i in range(1,n+1): print(f\"{i:<2}\",end=\"\") for j", "solutions have been tried, quit searching break clear_flags(i,queens[i],n) elif can_stay(i,queens[i],n):", "j: print(\"Q \",end=\"\") else: print(\" \",end=\"\") print() def set_flags(i,j,n): col_flags[j]=1", "global count i=1 while True: queens[i]+=1 if queens[i]>n: # backtracking", "queens[i] == j: print(\"Q \",end=\"\") else: print(\" \",end=\"\") print() def", "try_queen(1,n) n=int(input(\"请输入n:\")) queens = [0]*(n+1) # 列标志 col_flags=[0]*(n+1) # 主对角线标志", "0 def queen(n): try_queen(1,n) n=int(input(\"请输入n:\")) queens = [0]*(n+1) # 列标志", "tried, quit searching break clear_flags(i,queens[i],n) elif can_stay(i,queens[i],n): if i==n: count", "if col_flags[j]==1: return False if diag_flags[i+j-1]==1: return False if diag2_flags[n+i-j]==1:", "col_flags[j]=0 diag_flags[i+j-1]=0 diag2_flags[n+i-j]=0 def can_stay(i,j,n): if col_flags[j]==1: return False if", "False if diag2_flags[n+i-j]==1: return False return True def try_queen(i,n): global", "\",end=\"\") else: print(\" \",end=\"\") print() def set_flags(i,j,n): col_flags[j]=1 diag_flags[i+j-1]=1 diag2_flags[n+i-j]=1", "# backtracking i-=1 if i<1: # all possible solutions have", "def queen(n): try_queen(1,n) n=int(input(\"请输入n:\")) queens = [0]*(n+1) # 列标志 col_flags=[0]*(n+1)", "diag_flags[i+j-1]=1 diag2_flags[n+i-j]=1 def clear_flags(i,j,n): col_flags[j]=0 diag_flags[i+j-1]=0 diag2_flags[n+i-j]=0 def can_stay(i,j,n): if", "列标志 col_flags=[0]*(n+1) # 主对角线标志 diag_flags = [0]*(2*n) # 副对角线标志 diag2_flags", "col_flags[j]==1: return False if diag_flags[i+j-1]==1: return False if diag2_flags[n+i-j]==1: return", "col_flags=[0]*(n+1) # 主对角线标志 diag_flags = [0]*(2*n) # 副对角线标志 diag2_flags =", "if i<1: # all possible solutions have been tried, quit", "return False if diag2_flags[n+i-j]==1: return False return True def try_queen(i,n):", "print(f\"{i:<2}\",end=\"\") for j in range(1,n+1): if queens[i] == j: print(\"Q", "\",end=\"\") for j in range(n): print(f\"{j:<2}\" ,end=\"\") print() for i", "queens[i]+=1 if queens[i]>n: # backtracking i-=1 if i<1: # all", "range(n): print(f\"{j:<2}\" ,end=\"\") print() for i in range(1,n+1): print(f\"{i:<2}\",end=\"\") for", "if diag2_flags[n+i-j]==1: return False return True def try_queen(i,n): global count", "i<1: # all possible solutions have been tried, quit searching", "if diag_flags[i+j-1]==1: return False if diag2_flags[n+i-j]==1: return False return True", "queens[i]>n: # backtracking i-=1 if i<1: # all possible solutions", "print_board(n, count) else: set_flags(i, queens[i], n) i+=1 queens[i] = 0", "for i in range(1,n+1): print(f\"{i:<2}\",end=\"\") for j in range(1,n+1): if", "can_stay(i,queens[i],n): if i==n: count += 1 print_board(n, count) else: set_flags(i,", "diag2_flags = [0] * (2*n) count = 0 queen(n) print(f\"共有{count}种解法\\n\")", "diag2_flags[n+i-j]=1 def clear_flags(i,j,n): col_flags[j]=0 diag_flags[i+j-1]=0 diag2_flags[n+i-j]=0 def can_stay(i,j,n): if col_flags[j]==1:", "queens[i] = 0 def queen(n): try_queen(1,n) n=int(input(\"请输入n:\")) queens = [0]*(n+1)", "def set_flags(i,j,n): col_flags[j]=1 diag_flags[i+j-1]=1 diag2_flags[n+i-j]=1 def clear_flags(i,j,n): col_flags[j]=0 diag_flags[i+j-1]=0 diag2_flags[n+i-j]=0", "\"\"\" def print_board(n,count): print(f\"------解.{count}------\") print(\" \",end=\"\") for j in range(n):", "i==n: count += 1 print_board(n, count) else: set_flags(i, queens[i], n)", "[0]*(n+1) # 列标志 col_flags=[0]*(n+1) # 主对角线标志 diag_flags = [0]*(2*n) #", "quit searching break clear_flags(i,queens[i],n) elif can_stay(i,queens[i],n): if i==n: count +=", "for j in range(1,n+1): if queens[i] == j: print(\"Q \",end=\"\")", "print() for i in range(1,n+1): print(f\"{i:<2}\",end=\"\") for j in range(1,n+1):", "1 print_board(n, count) else: set_flags(i, queens[i], n) i+=1 queens[i] =", "j in range(n): print(f\"{j:<2}\" ,end=\"\") print() for i in range(1,n+1):", "clear_flags(i,j,n): col_flags[j]=0 diag_flags[i+j-1]=0 diag2_flags[n+i-j]=0 def can_stay(i,j,n): if col_flags[j]==1: return False", "= [0]*(n+1) # 列标志 col_flags=[0]*(n+1) # 主对角线标志 diag_flags = [0]*(2*n)", "j in range(1,n+1): if queens[i] == j: print(\"Q \",end=\"\") else:", "count i=1 while True: queens[i]+=1 if queens[i]>n: # backtracking i-=1", "def print_board(n,count): print(f\"------解.{count}------\") print(\" \",end=\"\") for j in range(n): print(f\"{j:<2}\"", "if queens[i]>n: # backtracking i-=1 if i<1: # all possible", "= [0]*(2*n) # 副对角线标志 diag2_flags = [0] * (2*n) count", "print(\" \",end=\"\") for j in range(n): print(f\"{j:<2}\" ,end=\"\") print() for", "n) i+=1 queens[i] = 0 def queen(n): try_queen(1,n) n=int(input(\"请输入n:\")) queens", "n=int(input(\"请输入n:\")) queens = [0]*(n+1) # 列标志 col_flags=[0]*(n+1) # 主对角线标志 diag_flags", "clear_flags(i,queens[i],n) elif can_stay(i,queens[i],n): if i==n: count += 1 print_board(n, count)", "else: set_flags(i, queens[i], n) i+=1 queens[i] = 0 def queen(n):", "in range(1,n+1): if queens[i] == j: print(\"Q \",end=\"\") else: print(\"", "if i==n: count += 1 print_board(n, count) else: set_flags(i, queens[i],", "[0]*(2*n) # 副对角线标志 diag2_flags = [0] * (2*n) count =", "def clear_flags(i,j,n): col_flags[j]=0 diag_flags[i+j-1]=0 diag2_flags[n+i-j]=0 def can_stay(i,j,n): if col_flags[j]==1: return", "diag_flags = [0]*(2*n) # 副对角线标志 diag2_flags = [0] * (2*n)", "backtracking i-=1 if i<1: # all possible solutions have been", "set_flags(i,j,n): col_flags[j]=1 diag_flags[i+j-1]=1 diag2_flags[n+i-j]=1 def clear_flags(i,j,n): col_flags[j]=0 diag_flags[i+j-1]=0 diag2_flags[n+i-j]=0 def", "def can_stay(i,j,n): if col_flags[j]==1: return False if diag_flags[i+j-1]==1: return False", "queen(n): try_queen(1,n) n=int(input(\"请输入n:\")) queens = [0]*(n+1) # 列标志 col_flags=[0]*(n+1) #", "diag_flags[i+j-1]==1: return False if diag2_flags[n+i-j]==1: return False return True def", "col_flags[j]=1 diag_flags[i+j-1]=1 diag2_flags[n+i-j]=1 def clear_flags(i,j,n): col_flags[j]=0 diag_flags[i+j-1]=0 diag2_flags[n+i-j]=0 def can_stay(i,j,n):", "def try_queen(i,n): global count i=1 while True: queens[i]+=1 if queens[i]>n:", "set_flags(i, queens[i], n) i+=1 queens[i] = 0 def queen(n): try_queen(1,n)", "return False return True def try_queen(i,n): global count i=1 while", "# 主对角线标志 diag_flags = [0]*(2*n) # 副对角线标志 diag2_flags = [0]", "in range(n): print(f\"{j:<2}\" ,end=\"\") print() for i in range(1,n+1): print(f\"{i:<2}\",end=\"\")", "for j in range(n): print(f\"{j:<2}\" ,end=\"\") print() for i in", "False if diag_flags[i+j-1]==1: return False if diag2_flags[n+i-j]==1: return False return", "in range(1,n+1): print(f\"{i:<2}\",end=\"\") for j in range(1,n+1): if queens[i] ==" ]
[ "= [word_to_color[word] for word in words] # Initially empty, the", "set_idx, entities_set in enumerate(entity_sets): face_color = face_colors[set_idx] edge_color = edge_colors[set_idx]", "+ '_pca.png')) plt.close(fig) @staticmethod def _find_k_furthest_words_per_cluster(document, embeddings_2d, k=3): \"\"\" Greedy", "def animate_pca_embedding_space_for_clusters(document, output_path, embeddings_history, colors_palette=None): \"\"\" Plot 2d PCA visualization", "indices_to_crops.items(): extent = indices_to_extents[point_index] rect = patches.Rectangle((extent.left, extent.top), extent.right-extent.left, extent.bottom-extent.top,", "indices_to_extents[point_index] rect = patches.Rectangle((extent.left, extent.top), extent.right-extent.left, extent.bottom-extent.top, linewidth=0.5, edgecolor=\"black\", facecolor=\"none\",", "for word in words] chosen_embedding = normalized_embeddings elif len(unnormalized_embeddings_dict) >", "in enumerate(self.document.get_words()): cluster_id = clustering_labels[word_idx] if cluster_id == -1: #", "< e2.top) is_extent_intersect = lambda e1, e2: is_extent_x_intersect(e1, e2) and", "with_title=True, colors_list=None): \"\"\" :param document: :param set_of_clusters: list of list", "from random import randrange import numpy as np from sklearn.decomposition", "not (e1.right < e2.left or e1.left > e2.right) is_extent_y_intersect =", "crops for each selected word in k-furthest neighbours solution :param", "words] chosen_embedding = normalized_embeddings elif len(unnormalized_embeddings_dict) > 0: unnormalized_embeddings =", "VisHandler.generate_colors_list(amount=len(entity_sets)) face_colors = colors_list edge_colors = VisHandler.generate_darker_palette(colors_list) output_img = bg_img.copy()", "solution :param document: :param solution_per_cluster: Solution of k-furthest neighbours :return:", "e2) min_x, max_x = min(x_list), max(x_list) min_y, max_y = min(y_list),", "for word in words] embeddings_array = np.array(embeddings).squeeze() num_pca_comp = 2", "& accumulator distances_matrix[:, random_index] = 0 distances_matrix[random_index, :] = 0", "embedding_property: Embedding property of words - normally 'embedding' or 'unprojected_embedding'", "= 120 mpl.rcParams['figure.dpi'] = dpi height = self.img.shape[0] width =", "1000) and performs a naive linear comparison for each crop.", "cluster_solution.words): bbox = word.get_bbox() # left, top, width, height y_min", "List of words :param x_list: List of corresponding pt x", "labels to list of list of words (clusters) set_of_clusters =", "for i in range(embeddings_2d.shape[0])] fig, ax = plt.subplots(1) if crops_per_cluster", "far distances_accumulator = np.zeros(len(cluster.words)) # Sample first point random_index =", "if len(normalized_embeddings_dict) > 0: normalized_embeddings = [normalized_embeddings_dict[word].detach().cpu().numpy() for word in", "x_list, y_list, push_pull_ratio in scatter_data: fig, ax = plt.subplots(1) ax.set_xlim(min_x,", "= document.get_words() clusters = document.get_clusters() if len(words) == 0 or", "= patches.Rectangle((extent.left, extent.top), extent.right-extent.left, extent.bottom-extent.top, linewidth=0.5, edgecolor=\"black\", facecolor=\"none\", zorder=5) ax.imshow(crop,", ":param embedding_property: Embedding property of words - normally 'embedding' or", "output_path, embedding_property='embedding', title=''): \"\"\" Plot 2d PCA visualization of the", "self.document.basename + '_phrase_detection.png')) plt.close(fig) def save_clustering_results(self, with_title=True, colors_list=None): set_of_clusters =", "@staticmethod def _draw_entity_bounding_boxes_opencv(bg_img, entity_sets, colors_list=None): img_height = bg_img.shape[0] img_width =", "<= top <= other_top: top = other_bottom + spaceout_margin bottom", "{word: colors_palette[cluster_idx] for cluster_idx, cluster in enumerate(clusters) for word in", "1 - alpha, 0) return output_img @staticmethod def _draw_entity_bounding_boxes(fig, ax,", "def plot_word_boxes_on_image(self): set_of_words = [[word] for word in self.document.get_words()] #", "for embedding_property in embedding_properties]): return colors_palette = VisHandler.generate_colors_list(amount=len(clusters)) word_to_color =", "= lambda e1, e2: not (e1.top > e2.bottom or e1.bottom", "and returning it rgb_color = rgb_hex_to_tuple(face_color) cv2.rectangle(output_img, (int(x), int(y)), (int(x", "min_y) * padding_factor frames = [] for epoch, x_list, y_list,", "unprojected_embedding = torch.cat(word.unprojected_embedding['embeddings'], dim=1) unprojected_embedding = unprojected_embedding.detach().cpu().numpy() embeddings.append(unprojected_embedding) else: embeddings", "== 'unprojected_embedding': plot_title = 'Initial unprojected embeddings, pre training (PCA)'", "x = entity.geometry.left * img_width y = entity.geometry.top * img_height", "if embedding_property == 'unprojected_embedding': embeddings = [] for word in", "(clusters) :return: \"\"\" output_img = self._draw_entity_bounding_boxes_opencv(bg_img=self.img_opencv, entity_sets=set_of_clusters, colors_list=colors_list) cv2.imwrite(os.path.join(self.output_path, self.document.basename", "= [[phrase] for phrase in self.document.get_phrases()] # list of singleton", "import torch import matplotlib matplotlib.use('Agg') # Required for gif animations", "None: plot_title = 'Projected embeddings, post training (PCA)' else: plot_title", "word in words] chosen_embedding = unnormalized_embeddings else: return embeddings_array =", "i in range(embeddings_2d.shape[0])] y_list = [embeddings_2d[i, 1] for i in", "None and indices_to_crops is None: # Calculate per first attribute", "width), int(y + height)), (rgb_color[2], rgb_color[1], rgb_color[0]), cv2.FILLED) output_img =", "distances_accumulator = np.zeros(len(cluster.words)) # Sample first point random_index = randrange(len(cluster.words))", "Calculate per first attribute selected_word_crops_per_cluster = PlotsProducer._find_k_furthest_words_per_cluster(document, embeddings_2d, k=crops_per_cluster) indices_to_crops", "embedding_properties=['embedding', 'unprojected_embedding'], unprojected_caption=None): \"\"\" Plot 2d PCA visualization of the", "unprojected embeddings, pre training (PCA)' else: if unprojected_caption is None:", "@staticmethod def _draw_entity_bounding_boxes(fig, ax, bg_img, title, entity_sets, colors_list=None): ax.set_title(title) plt.tick_params(axis='both',", "List of corresponding pt y positions :param dist_from_pt: How far", "squareform import torch import matplotlib matplotlib.use('Agg') # Required for gif", "img_height = bg_img.shape[0] img_width = bg_img.shape[1] if colors_list is None:", "- spaceout_margin top = bottom - height continue indices_to_extents[point_index] =", "overlap = False extent = MatplotExtent(left, right, bottom, top) for", "indices_to_extents: dict of word index to extens describing position and", "selected_word_crops_per_cluster = None indices_to_crops = None for embedding_property in embedding_properties:", "plt.subplots(1) ax.set_xlim(min_x, max_x) ax.set_ylim(min_y, max_y) plot_title = 'Projected embeddings at", "distances_matrix[last_point_selected] # Eliminate last point selected from distance matrix &", "in cluster.words] all_cluster_embeddings = np.take(embeddings_2d, all_cluster_embeddings_indices, axis=0) pairwise_distances = pdist(all_cluster_embeddings,", "distances matrix all_cluster_embeddings_indices = [word_to_embedding_2d_idx[word] for word in cluster.words] all_cluster_embeddings", "0) return output_img @staticmethod def _draw_entity_bounding_boxes(fig, ax, bg_img, title, entity_sets,", "enumerate(clusters) for word in cluster.words} colors = [word_to_color[word] for word", "padding_factor max_y += (max_y - min_y) * padding_factor frames =", "word in enumerate(self.document.get_words()): cluster_id = clustering_labels[word_idx] if cluster_id == -1:", "set so far distances_accumulator = np.zeros(len(cluster.words)) # Sample first point", "a small number of crops (< 1000) and performs a", "indices_to_crops = PlotsProducer._extract_crops_per_cluster_solution(document, selected_word_crops_per_cluster) indices_to_extents = PlotsProducer._space_out_crops(indices_to_crops, words, x_list, y_list,", "far in (x-y) coords the crop should be placed from", "2 embeddings_2d = PCA(n_components=num_pca_comp).fit_transform(embeddings_array) x_list = [embeddings_2d[i, 0] for i", "x_list, y_list, dist_from_pt=0.02, height=0.04) # Plot crop images for point_index,", "left, right = x_list[point_index] + dist_from_pt, x_list[point_index] + dist_from_pt +", "= [getattr(word, embedding_property).detach().cpu().numpy() for word in words] embeddings_array = np.array(embeddings).squeeze()", "= state_idx + 1 normalized_embeddings_dict = embeddings_state['normalized'] unnormalized_embeddings_dict = embeddings_state['unnormalized']", "positions :param dist_from_pt: How far in (x-y) coords the crop", "linewidth=1.0, zorder=3) plt.tick_params(axis='both', which='both', bottom='off', top='off', labelbottom='off', right='off', left='off', labelleft='off')", "save_clustering_results(self, with_title=True, colors_list=None): set_of_clusters = [cluster.words for cluster in self.document.get_clusters()]", "fig, ax = plt.subplots(1) plot_title = embedding_property if plot_title !=", "return colors_palette = VisHandler.generate_colors_list(amount=len(clusters)) word_to_color = {word: colors_palette[cluster_idx] for cluster_idx,", "process will set those for all figures selected_word_crops_per_cluster = None", "if unprojected_caption is None: plot_title = 'Projected embeddings, post training", "Plot points if embedding_property == 'unprojected_embedding': plot_title = 'Initial unprojected", "= patches.Rectangle((x, y), width, height, linewidth=2, edgecolor=edge_color, facecolor=face_color, alpha=0.4) ax.add_patch(rect)", "['word_indices', 'words']) for cluster in clusters: # Generate cluster pairwise", "non-clustered words continue cluster_idx = cluster_id_to_cluster_idx[cluster_id] set_of_clusters[cluster_idx].append(word) self._save_set_of_clusters(set_of_clusters, colors_list) def", "word_index, word in zip(cluster_solution.word_indices, cluster_solution.words): bbox = word.get_bbox() # left,", "y_list, c=colors, s=18, alpha=1.0, edgecolors='black', linewidth=1.0, zorder=3) plt.tick_params(axis='both', which='both', bottom='off',", "VisHandler.generate_colors_list(amount=len(entity_sets)) face_colors = colors_list edge_colors = VisHandler.generate_darker_palette(colors_list) for set_idx, entities_set", "rgb_hex_to_tuple class PlotsProducer: def __init__(self, document, output_path): # Load background", "import imageio from PIL import Image from random import randrange", "= {cluster_id: idx for idx, cluster_id in enumerate(cluster_ids)} # Converts", "+ dist_from_pt + width bottom, top = y_list[point_index] + dist_from_pt", "# writing the text onto the image and returning it", "bg_img.shape[1] if colors_list is None: colors_list = VisHandler.generate_colors_list(amount=len(entity_sets)) face_colors =", "> e2.bottom or e1.bottom < e2.top) is_extent_intersect = lambda e1,", "Rights Reserved. # SPDX-License-Identifier: CC-BY-4.0 import os import cv2 from", "e2.bottom or e1.bottom < e2.top) is_extent_intersect = lambda e1, e2:", "k-furthest neighbours :return: \"\"\" word_indices_to_crops = {} for cluster, cluster_solution", "of the embedding space according to cluster colors. :param document:", "the image and returning it rgb_color = rgb_hex_to_tuple(face_color) cv2.rectangle(output_img, (int(x),", "height=0.02): \"\"\" Calculates the positions and dimensions of crop images", "= top + height else: # shift above bottom =", "dist_from_pt=0.02, height=0.04) # Plot crop images for point_index, crop in", "in doc) to PIL crop :param words: List of words", "colors_list=colors_palette) return colors_palette @staticmethod def animate_pca_embedding_space_for_clusters(document, output_path, embeddings_history, colors_palette=None): \"\"\"", "document.height)) x_min = int(round(bbox[0] * document.width)) x_max = int(round((bbox[0] +", "embedding space according to cluster colors. :param document: Document with", "= document.get_clusters() solution_per_cluster = {} ClusterSolution = namedtuple('ClusterSolution', ['word_indices', 'words'])", "key=lambda entry: max(entry[2]))[2]) padding_factor = 0.1 min_x -= (max_x -", "{} ClusterSolution = namedtuple('ClusterSolution', ['word_indices', 'words']) for cluster in clusters:", "of words - normally 'embedding' or 'unprojected_embedding' :return: \"\"\" if", "getattr(words[0], embedding_property) is None: return if embedding_property == 'unprojected_embedding': embeddings", "e2: is_extent_x_intersect(e1, e2) and is_extent_y_intersect(e1, e2) min_x, max_x = min(x_list),", "(max_x - min_x) * padding_factor max_x += (max_x - min_x)", "colors_list=None): img_height = bg_img.shape[0] img_width = bg_img.shape[1] if colors_list is", "all_cluster_embeddings = np.take(embeddings_2d, all_cluster_embeddings_indices, axis=0) pairwise_distances = pdist(all_cluster_embeddings, metric='euclidean') distances_matrix", "performs a naive linear comparison for each crop. :param indices_to_crops:", "height = entity.geometry.height * img_height rect = patches.Rectangle((x, y), width,", "embedding property we process will set those for all figures", "is_extent_y_intersect = lambda e1, e2: not (e1.top > e2.bottom or", "embedding_property in embedding_properties: if embedding_property == 'unprojected_embedding': # Can't handle", "dist_from_pt for point_index, crop in indices_to_crops.items(): word_aspect_ratio = words[point_index].geometry.width /", "cv2 from collections import namedtuple import imageio from PIL import", "top = bottom - height continue indices_to_extents[point_index] = extent return", "if crops_per_cluster > 0: if selected_word_crops_per_cluster is None and indices_to_crops", "100) \"\"\" words = document.get_words() word_to_embedding_2d_idx = {word: idx for", "import resize_image from multimodal_affinities.visualization.colors_util import rgb_hex_to_tuple class PlotsProducer: def __init__(self,", "# SPDX-License-Identifier: CC-BY-4.0 import os import cv2 from collections import", "= 0.8 for set_idx, entities_set in enumerate(entity_sets): face_color = face_colors[set_idx]", "height: Height of the crop, in figure axes dimensions (note:", "is None: plot_title = 'Projected embeddings, post training (PCA)' else:", "for i in range(embeddings_2d.shape[0])] fig, ax = plt.subplots(1) plot_title =", "or \\ all([getattr(words[0], embedding_property) is None for embedding_property in embedding_properties]):", "matplotlib.image as image import matplotlib.patches as patches from multimodal_affinities.visualization.vis_handler import", ":return: indices_to_extents: dict of word index to extens describing position", "= int(round((bbox[0] + bbox[2]) * document.width)) image_of_crop = document.image[max(0, y_min):min(y_max,", "= [unnormalized_embeddings_dict[word].detach().cpu().numpy() for word in words] chosen_embedding = unnormalized_embeddings else:", "pil_image return word_indices_to_crops @staticmethod def _space_out_crops(indices_to_crops, words, x_list, y_list, dist_from_pt=0.01,", "cv2.imwrite(os.path.join(self.output_path, self.document.basename + '_clustering.png'), output_img) @staticmethod def _draw_entity_bounding_boxes_opencv(bg_img, entity_sets, colors_list=None):", "bottom='off', top='off', labelbottom='off', right='off', left='off', labelleft='off') plt.imshow(bg_img) img_height = bg_img.shape[0]", "+ title plt.title(plot_title) plt.scatter(x_list, y_list, c=colors, s=1, alpha=0.8) fig.tight_layout() fig.savefig(os.path.join(output_path,", "e2.top) is_extent_intersect = lambda e1, e2: is_extent_x_intersect(e1, e2) and is_extent_y_intersect(e1,", "import matplotlib as mpl import matplotlib.pyplot as plt import matplotlib.image", "edge_colors[set_idx] for entity in entities_set: x = entity.geometry.left * img_width", "+ embedding_property + '_pca.png')) plt.close(fig) @staticmethod def _find_k_furthest_words_per_cluster(document, embeddings_2d, k=3):", "each selected word in k-furthest neighbours solution :param document: :param", "= plt.imread(self.image_path) self.img_opencv = cv2.imread(self.image_path) dpi = 120 mpl.rcParams['figure.dpi'] =", "unprojected_caption is None: plot_title = 'Projected embeddings, post training (PCA)'", "normalized_embeddings = [normalized_embeddings_dict[word].detach().cpu().numpy() for word in words] chosen_embedding = normalized_embeddings", "PCA(n_components=num_pca_comp).fit_transform(embeddings_array) x_list = [embeddings_2d[i, 0] for i in range(embeddings_2d.shape[0])] y_list", "0: if selected_word_crops_per_cluster is None and indices_to_crops is None: #", "cluster in clusters: # Generate cluster pairwise distances matrix all_cluster_embeddings_indices", "top, width, height y_min = int(round(bbox[1] * document.height)) y_max =", "= height * word_aspect_ratio * axis_ratio left, right = x_list[point_index]", "k is expected to be relatively small (< 100) \"\"\"", "pil_image.convert('RGB') word_indices_to_crops[word_index] = pil_image return word_indices_to_crops @staticmethod def _space_out_crops(indices_to_crops, words,", "list of words (clusters) self._save_set_of_clusters(set_of_clusters, with_title, colors_list) def save_clustering_labels(self, clustering_labels,", "return embeddings_array = np.array(chosen_embedding).squeeze() num_pca_comp = 2 embeddings_2d = PCA(n_components=num_pca_comp).fit_transform(embeddings_array)", "y_list, push_pull_ratio in scatter_data: fig, ax = plt.subplots(1) ax.set_xlim(min_x, max_x)", "0: return if colors_palette is None: colors_palette = VisHandler.generate_colors_list(amount=len(clusters)) word_to_color", "= document.get_clusters() if len(words) == 0 or embeddings_history is None", "{word: idx for idx, word in enumerate(words)} clusters = document.get_clusters()", "colors_list edge_colors = VisHandler.generate_darker_palette(colors_list) for set_idx, entities_set in enumerate(entity_sets): face_color", "words: List of words :param x_list: List of corresponding pt", "mpl import matplotlib.pyplot as plt import matplotlib.image as image import", "= document.image_path self.img = plt.imread(self.image_path) self.img_opencv = cv2.imread(self.image_path) dpi =", "plt.title(plot_title) plt.scatter(x_list, y_list, c=colors, s=18, alpha=1.0, edgecolors='black', linewidth=1.0, zorder=3) plt.tick_params(axis='both',", "enumerate(cluster_ids)} # Converts from list of labels to list of", "selected from distance matrix & accumulator distances_matrix[:, random_index] = 0", "lambda e1, e2: not (e1.right < e2.left or e1.left >", "= pil_image return word_indices_to_crops @staticmethod def _space_out_crops(indices_to_crops, words, x_list, y_list,", "+ height, y_list[point_index] + dist_from_pt overlap = True while overlap:", "as plt import matplotlib.image as image import matplotlib.patches as patches", "= min(max_y - min_y, max_x - min_x) * dist_from_pt for", "cluster_id == -1: # Ignore non-clustered words continue cluster_idx =", "to extens describing position and dimensions of each crop. Crops", "image and returning it rgb_color = rgb_hex_to_tuple(face_color) cv2.rectangle(output_img, (int(x), int(y)),", "words, x_list, y_list, dist_from_pt=0.02, height=0.04) # Plot crop images for", "embeddings_2d, k=crops_per_cluster) indices_to_crops = PlotsProducer._extract_crops_per_cluster_solution(document, selected_word_crops_per_cluster) indices_to_extents = PlotsProducer._space_out_crops(indices_to_crops, words,", "colors_palette @staticmethod def animate_pca_embedding_space_for_clusters(document, output_path, embeddings_history, colors_palette=None): \"\"\" Plot 2d", "the plot as an image rray fig.tight_layout() fig.canvas.draw() # draw", "overlay each other. This method assumes a small number of", "are shifted so they don't cover each other, \"\"\" indices_to_extents", "+ width bottom, top = y_list[point_index] + dist_from_pt + height,", "colors_list = VisHandler.generate_colors_list(amount=len(entity_sets)) face_colors = colors_list edge_colors = VisHandler.generate_darker_palette(colors_list) for", "spaceout_margin = dist_from_pt / 2 if is_extent_intersect(extent, other_crop_extent): overlap =", "= [] for word in words: unprojected_embedding = torch.cat(word.unprojected_embedding['embeddings'], dim=1)", "= [cluster.words for cluster in self.document.get_clusters()] # list of list", "linear comparison for each crop. :param indices_to_crops: dict of word", "word in k-furthest neighbours solution :param document: :param solution_per_cluster: Solution", "left='off', labelleft='off') ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) fig.tight_layout() fig.savefig(os.path.join(output_path, document.basename + '_' +", "output_img @staticmethod def _draw_entity_bounding_boxes(fig, ax, bg_img, title, entity_sets, colors_list=None): ax.set_title(title)", "plot_title = unprojected_caption plt.title(plot_title) plt.scatter(x_list, y_list, c=colors, s=18, alpha=1.0, edgecolors='black',", "= None for embedding_property in embedding_properties: if embedding_property == 'unprojected_embedding':", "for _ in self.document.get_words()] self._draw_entity_bounding_boxes(fig=fig, ax=ax, bg_img=self.img, title='', entity_sets=set_of_words, colors_list=monochrome_colors_list)", "None: colors_list = VisHandler.generate_colors_list(amount=len(entity_sets)) face_colors = colors_list edge_colors = VisHandler.generate_darker_palette(colors_list)", "save_clustering_labels(self, clustering_labels, colors_list=None): cluster_ids = np.unique(np.array(clustering_labels)) cluster_id_to_cluster_idx = {cluster_id: idx", "= self._draw_entity_bounding_boxes_opencv(bg_img=self.img_opencv, entity_sets=set_of_clusters, colors_list=colors_list) cv2.imwrite(os.path.join(self.output_path, self.document.basename + '_clustering.png'), output_img) @staticmethod", "img_height rect = patches.Rectangle((x, y), width, height, linewidth=2, edgecolor=edge_color, facecolor=face_color,", "word_indices_to_crops[word_index] = pil_image return word_indices_to_crops @staticmethod def _space_out_crops(indices_to_crops, words, x_list,", "= VisHandler.generate_colors_list(amount=len(clusters)) word_to_color = {word: colors_palette[cluster_idx] for cluster_idx, cluster in", "point_index, crop in indices_to_crops.items(): extent = indices_to_extents[point_index] rect = patches.Rectangle((extent.left,", "== 0 or \\ all([getattr(words[0], embedding_property) is None for embedding_property", "clusters: # Generate cluster pairwise distances matrix all_cluster_embeddings_indices = [word_to_embedding_2d_idx[word]", "range(embeddings_2d.shape[0])] fig, ax = plt.subplots(1) if crops_per_cluster > 0: if", "min_y -= (max_y - min_y) * padding_factor max_y += (max_y", "= max(max(scatter_data, key=lambda entry: max(entry[1]))[1]) min_y = min(min(scatter_data, key=lambda entry:", "import matplotlib.image as image import matplotlib.patches as patches from multimodal_affinities.visualization.vis_handler", "normalized_embeddings_dict = embeddings_state['normalized'] unnormalized_embeddings_dict = embeddings_state['unnormalized'] if len(normalized_embeddings_dict) > 0:", "title plt.title(plot_title) plt.scatter(x_list, y_list, c=colors, s=1, alpha=0.8) fig.tight_layout() fig.savefig(os.path.join(output_path, document.basename", "height else: # shift above bottom = other_top - spaceout_margin", "plot :param height: Height of the crop, in figure axes", "{cluster_id: idx for idx, cluster_id in enumerate(cluster_ids)} # Converts from", "unprojected_caption plt.title(plot_title) plt.scatter(x_list, y_list, c=colors, s=18, alpha=1.0, edgecolors='black', linewidth=1.0, zorder=3)", "min_x = min(min(scatter_data, key=lambda entry: min(entry[1]))[1]) max_x = max(max(scatter_data, key=lambda", "bottom='off', top='off', labelbottom='off', right='off', left='off', labelleft='off') ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) # Used", "spaceout_margin top = bottom - height continue indices_to_extents[point_index] = extent", "== 0: return if colors_palette is None: colors_palette = VisHandler.generate_colors_list(amount=len(clusters))", "continue cluster_idx = cluster_id_to_cluster_idx[cluster_id] set_of_clusters[cluster_idx].append(word) self._save_set_of_clusters(set_of_clusters, colors_list) def _save_set_of_clusters(self, set_of_clusters,", "1) :return: indices_to_extents: dict of word index to extens describing", "- min_y) * height dist_from_pt = min(max_y - min_y, max_x", "- min_y, max_x - min_x) * dist_from_pt for point_index, crop", "= [] for state_idx, embeddings_state in enumerate(embeddings_history): epoch = state_idx", "num_pca_comp = 2 embeddings_2d = PCA(n_components=num_pca_comp).fit_transform(embeddings_array) x_list = [embeddings_2d[i, 0]", "= VisHandler.generate_colors_list(amount=len(entity_sets)) face_colors = colors_list edge_colors = VisHandler.generate_darker_palette(colors_list) output_img =", "= min(k - 1, len(words) - 1) for _ in", "for point in selected_points] selected_word_indices = [word_to_embedding_2d_idx[word] for word in", "= PlotsProducer._extract_crops_per_cluster_solution(document, selected_word_crops_per_cluster) indices_to_extents = PlotsProducer._space_out_crops(indices_to_crops, words, x_list, y_list, dist_from_pt=0.02,", "word_aspect_ratio = words[point_index].geometry.width / words[point_index].geometry.height axis_ratio = (max_x-min_x) / (max_y-min_y)", "* img_width height = entity.geometry.height * img_height # writing the", "i in range(embeddings_2d.shape[0])] fig, ax = plt.subplots(1) plot_title = embedding_property", "= [word_to_color[word] for word in words] embeddings_array = np.array(embeddings).squeeze() num_pca_comp", "crop images for point_index, crop in indices_to_crops.items(): extent = indices_to_extents[point_index]", "= edge_colors[set_idx] for entity in entities_set: x = entity.geometry.left *", "word_to_color = {word: colors_palette[cluster_idx] for cluster_idx, cluster in enumerate(clusters) for", "= words[point_index].geometry.width / words[point_index].geometry.height axis_ratio = (max_x-min_x) / (max_y-min_y) /", "colors. :param document: Document with clustering results :param embedding_property: Embedding", "y = entity.geometry.top * img_height width = entity.geometry.width * img_width", "should be placed from the plot :param height: Height of", "= other_bottom + spaceout_margin bottom = top + height else:", "Makes sure crops don't overlay each other. This method assumes", "return the plot as an image rray fig.tight_layout() fig.canvas.draw() #", "plot_title = embedding_property if plot_title != '': plot_title += ':", "for set_idx, entities_set in enumerate(entity_sets): face_color = face_colors[set_idx] edge_color =", "set_of_phrases = [[phrase] for phrase in self.document.get_phrases()] # list of", "of each crop. Crops are shifted so they don't cover", "embeddings, pre training (PCA)' else: if unprojected_caption is None: plot_title", "solution_per_cluster: Solution of k-furthest neighbours :return: \"\"\" word_indices_to_crops = {}", "other_left, other_right, other_bottom, other_top = other_crop_extent spaceout_margin = dist_from_pt /", "indices_to_extents.values(): other_left, other_right, other_bottom, other_top = other_crop_extent spaceout_margin = dist_from_pt", "PCA visualization of the embedding space according to cluster colors.", "= False extent = MatplotExtent(left, right, bottom, top) for other_crop_extent", "image self.image_path = document.image_path self.img = plt.imread(self.image_path) self.img_opencv = cv2.imread(self.image_path)", "= MatplotExtent(left, right, bottom, top) for other_crop_extent in indices_to_extents.values(): other_left,", "= plt.subplots(1) if crops_per_cluster > 0: if selected_word_crops_per_cluster is None", "other_top: top = other_bottom + spaceout_margin bottom = top +", "= clustering_labels[word_idx] if cluster_id == -1: # Ignore non-clustered words", "for all figures selected_word_crops_per_cluster = None indices_to_crops = None for", "'_pca.png')) plt.close(fig) @staticmethod def _find_k_furthest_words_per_cluster(document, embeddings_2d, k=3): \"\"\" Greedy approximation", "0: unnormalized_embeddings = [unnormalized_embeddings_dict[word].detach().cpu().numpy() for word in words] chosen_embedding =", "word index (by order in doc) to PIL crop :param", "results :param embedding_property: Embedding property of words - normally 'embedding'", "selected_word_crops_per_cluster is None and indices_to_crops is None: # Calculate per", "-1: # Ignore non-clustered words continue cluster_idx = cluster_id_to_cluster_idx[cluster_id] set_of_clusters[cluster_idx].append(word)", "+ '_word_boxes.png')) plt.close(fig) def save_phrase_detection_results(self): set_of_phrases = [[phrase] for phrase", "[] for state_idx, embeddings_state in enumerate(embeddings_history): epoch = state_idx +", "-= (max_x - min_x) * padding_factor max_x += (max_x -", "padding_factor = 0.1 min_x -= (max_x - min_x) * padding_factor", "else: if unprojected_caption is None: plot_title = 'Projected embeddings, post", "self._save_set_of_clusters(set_of_clusters, colors_list) def _save_set_of_clusters(self, set_of_clusters, with_title=True, colors_list=None): \"\"\" :param document:", "axis_ratio left, right = x_list[point_index] + dist_from_pt, x_list[point_index] + dist_from_pt", "+ dist_from_pt, x_list[point_index] + dist_from_pt + width bottom, top =", "# How many points we need to add points_to_calc_count =", "for point_index, crop in indices_to_crops.items(): word_aspect_ratio = words[point_index].geometry.width / words[point_index].geometry.height", "crop should be placed from the plot :param height: Height", "import matplotlib.patches as patches from multimodal_affinities.visualization.vis_handler import VisHandler from multimodal_affinities.visualization.image_utils", "title=''): \"\"\" Plot 2d PCA visualization of the embedding space", "[getattr(word, embedding_property).detach().cpu().numpy() for word in words] embeddings_array = np.array(embeddings).squeeze() num_pca_comp", "(by order in doc) to PIL crop :param words: List", "don't overlay each other. This method assumes a small number", "enumerate(entity_sets): face_color = face_colors[set_idx] edge_color = edge_colors[set_idx] for entity in", "facecolor=face_color, alpha=0.4) ax.add_patch(rect) @staticmethod def plot_pca_embedding_space_for_clusters(document, output_path, embedding_property='embedding', title=''): \"\"\"", "be relatively small (< 100) \"\"\" words = document.get_words() word_to_embedding_2d_idx", "# Fig size in inches self.document = document self.output_path =", "ax.imshow(crop, aspect='auto', alpha=0.65, extent=extent, zorder=4) ax.add_patch(rect) # Plot points if", "import matplotlib.pyplot as plt import matplotlib.image as image import matplotlib.patches", "clustering results :param embedding_property: Embedding property of words - normally", "of words (clusters) set_of_clusters = [[] for _ in range(len(cluster_ids))]", "set_of_clusters = [[] for _ in range(len(cluster_ids))] for word_idx, word", "visualization of the embedding space according to cluster colors. :param", "height = self.img.shape[0] width = self.img.shape[1] self.figsize = width /", "* img_height # writing the text onto the image and", "@staticmethod def _space_out_crops(indices_to_crops, words, x_list, y_list, dist_from_pt=0.01, height=0.02): \"\"\" Calculates", "= 0.1 min_x -= (max_x - min_x) * padding_factor max_x", "# shift below if other_bottom <= top <= other_top: top", "= 'Projected embeddings, post training (PCA)' else: plot_title = unprojected_caption", "< e2.left or e1.left > e2.right) is_extent_y_intersect = lambda e1,", "all([getattr(words[0], embedding_property) is None for embedding_property in embedding_properties]): return colors_palette", "import namedtuple import imageio from PIL import Image from random", "# BGR to RGB pil_image = pil_image.convert('RGB') word_indices_to_crops[word_index] = pil_image", "face_colors = colors_list edge_colors = VisHandler.generate_darker_palette(colors_list) output_img = bg_img.copy() alpha", "unprojected_embedding = unprojected_embedding.detach().cpu().numpy() embeddings.append(unprojected_embedding) else: embeddings = [getattr(word, embedding_property).detach().cpu().numpy() for", "+ '_pca.png')) plt.close(fig) # Finally plot clusters on original image", "labelleft='off') plt.imshow(bg_img) img_height = bg_img.shape[0] img_width = bg_img.shape[1] if colors_list", "set_of_clusters: list of list of words (clusters) :return: \"\"\" output_img", "colors_list=monochrome_colors_list) fig.savefig(os.path.join(self.output_path, self.document.basename + '_word_boxes.png')) plt.close(fig) def save_phrase_detection_results(self): set_of_phrases =", "= rgb_hex_to_tuple(face_color) cv2.rectangle(output_img, (int(x), int(y)), (int(x + width), int(y +", "first point random_index = randrange(len(cluster.words)) # Indices of selected points", "k=3): \"\"\" Greedy approximation algorithm for finding k furthest neighbour", ":param indices_to_crops: dict of word index (by order in doc)", "cluster_id = clustering_labels[word_idx] if cluster_id == -1: # Ignore non-clustered", "entity.geometry.left * img_width y = entity.geometry.top * img_height width =", ":param set_of_clusters: list of list of words (clusters) :return: \"\"\"", "point distances_accumulator += distances_matrix[last_point_selected] # Eliminate last point selected from", "self._save_set_of_clusters(set_of_clusters, with_title, colors_list) def save_clustering_labels(self, clustering_labels, colors_list=None): cluster_ids = np.unique(np.array(clustering_labels))", "[embeddings_2d[i, 0] for i in range(embeddings_2d.shape[0])] y_list = [embeddings_2d[i, 1]", "== 0 or embeddings_history is None or len(embeddings_history) == 0:", "self._draw_entity_bounding_boxes(fig=fig, ax=ax, bg_img=self.img, title='Phrase Detection', entity_sets=set_of_phrases) fig.savefig(os.path.join(self.output_path, self.document.basename + '_phrase_detection.png'))", "plt.subplots(1) plot_title = embedding_property if plot_title != '': plot_title +=", "output_path, embeddings_history, colors_palette=None): \"\"\" Plot 2d PCA visualization of the", "= np.array(chosen_embedding).squeeze() num_pca_comp = 2 embeddings_2d = PCA(n_components=num_pca_comp).fit_transform(embeddings_array) x_list =", "clusters = document.get_clusters() solution_per_cluster = {} ClusterSolution = namedtuple('ClusterSolution', ['word_indices',", "small (< 100) \"\"\" words = document.get_words() word_to_embedding_2d_idx = {word:", "cluster_idx, cluster in enumerate(clusters) for word in cluster.words} colors =", "for word in words] scatter_data = [] for state_idx, embeddings_state", "[unnormalized_embeddings_dict[word].detach().cpu().numpy() for word in words] chosen_embedding = unnormalized_embeddings else: return", "crop. :param indices_to_crops: dict of word index (by order in", "figsize=self.figsize) self._draw_entity_bounding_boxes(fig=fig, ax=ax, bg_img=self.img, title='Phrase Detection', entity_sets=set_of_phrases) fig.savefig(os.path.join(self.output_path, self.document.basename +", "self.document.get_words()] # list of singleton word lists fig, ax =", "matplotlib.patches as patches from multimodal_affinities.visualization.vis_handler import VisHandler from multimodal_affinities.visualization.image_utils import", "word in enumerate(words)} clusters = document.get_clusters() solution_per_cluster = {} ClusterSolution", "for each selected word in k-furthest neighbours solution :param document:", "clusters = document.get_clusters() if len(words) == 0 or embeddings_history is", "list of words (clusters) set_of_clusters = [[] for _ in", "x positions :param y_list: List of corresponding pt y positions", "= [word_to_embedding_2d_idx[word] for word in cluster.words] all_cluster_embeddings = np.take(embeddings_2d, all_cluster_embeddings_indices,", "top='off', labelbottom='off', right='off', left='off', labelleft='off') plt.imshow(bg_img) img_height = bg_img.shape[0] img_width", "neighbours solution :param document: :param solution_per_cluster: Solution of k-furthest neighbours", "with distance collected from last point distances_accumulator += distances_matrix[last_point_selected] #", "= plt.subplots(1) ax.set_xlim(min_x, max_x) ax.set_ylim(min_y, max_y) plot_title = 'Projected embeddings", "'unprojected_embedding': embeddings = [] for word in words: unprojected_embedding =", "0.1 min_x -= (max_x - min_x) * padding_factor max_x +=", "is None or len(embeddings_history) == 0: return if colors_palette is", "on original image self.save_clustering_results(with_title=False, colors_list=colors_palette) return colors_palette @staticmethod def animate_pca_embedding_space_for_clusters(document,", "is None: colors_list = VisHandler.generate_colors_list(amount=len(entity_sets)) face_colors = colors_list edge_colors =", "= lambda e1, e2: is_extent_x_intersect(e1, e2) and is_extent_y_intersect(e1, e2) min_x,", "animations import matplotlib as mpl import matplotlib.pyplot as plt import", "handle tuples, concat them embeddings = [] for word in", "size in inches self.document = document self.output_path = output_path if", "0 distances_matrix[random_index, :] = 0 furthrest_point_from_set = np.argmax(distances_accumulator, axis=0) selected_points.append(furthrest_point_from_set)", "if not os.path.exists(output_path): os.makedirs(output_path) words = document.get_words() clusters = document.get_clusters()", "Indices of selected points selected_points = [random_index] # How many", "words per cluster. k is expected to be relatively small", "dpi = 120 mpl.rcParams['figure.dpi'] = dpi height = self.img.shape[0] width", "import matplotlib matplotlib.use('Agg') # Required for gif animations import matplotlib", "# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.", "numpy as np from sklearn.decomposition import PCA from scipy.spatial.distance import", "Plot 2d PCA visualization of the embedding space according to", "= [normalized_embeddings_dict[word].detach().cpu().numpy() for word in words] chosen_embedding = normalized_embeddings elif", "return solution_per_cluster @staticmethod def _extract_crops_per_cluster_solution(document, solution_per_cluster): \"\"\" Extracts crops for", "right = x_list[point_index] + dist_from_pt, x_list[point_index] + dist_from_pt + width", "entry: max(entry[1]))[1]) min_y = min(min(scatter_data, key=lambda entry: min(entry[2]))[2]) max_y =", "max_y = max(max(scatter_data, key=lambda entry: max(entry[2]))[2]) padding_factor = 0.1 min_x", "top <= other_top: top = other_bottom + spaceout_margin bottom =", "embedding_property in embedding_properties]): return colors_palette = VisHandler.generate_colors_list(amount=len(clusters)) word_to_color = {word:", "and is_extent_y_intersect(e1, e2) min_x, max_x = min(x_list), max(x_list) min_y, max_y", "other_top = other_crop_extent spaceout_margin = dist_from_pt / 2 if is_extent_intersect(extent,", "max_y = min(y_list), max(y_list) height = (max_y - min_y) *", "point in selected_points] selected_word_indices = [word_to_embedding_2d_idx[word] for word in selected_words]", "None indices_to_crops = None for embedding_property in embedding_properties: if embedding_property", "(int(x), int(y)), (int(x + width), int(y + height)), (rgb_color[2], rgb_color[1],", "+= distances_matrix[last_point_selected] # Eliminate last point selected from distance matrix", "word in cluster.words] all_cluster_embeddings = np.take(embeddings_2d, all_cluster_embeddings_indices, axis=0) pairwise_distances =", "document.get_words() clusters = document.get_clusters() if len(words) == 0 or embeddings_history", "cluster colors. :param document: Document with clustering results :param embedding_property:", "embeddings_2d, k=3): \"\"\" Greedy approximation algorithm for finding k furthest", "- normally 'embedding' or 'unprojected_embedding' :return: \"\"\" if not os.path.exists(output_path):", "= [getattr(word, embedding_property).detach().cpu().numpy() for word in words] colors_palette = VisHandler.generate_colors_list(amount=len(clusters))", "while overlap: overlap = False extent = MatplotExtent(left, right, bottom,", "document: Document with clustering results :param embedding_property: Embedding property of", "[cluster.words[point] for point in selected_points] selected_word_indices = [word_to_embedding_2d_idx[word] for word", "indices_to_crops: dict of word index (by order in doc) to", "in clusters: # Generate cluster pairwise distances matrix all_cluster_embeddings_indices =", "on the embedding space plot. Makes sure crops don't overlay", "fig.savefig(os.path.join(self.output_path, self.document.basename + '_phrase_detection.png')) plt.close(fig) def save_clustering_results(self, with_title=True, colors_list=None): set_of_clusters", "of singleton word lists fig, ax = plt.subplots(1, figsize=self.figsize) monochrome_colors_list", "chosen_embedding = unnormalized_embeddings else: return embeddings_array = np.array(chosen_embedding).squeeze() num_pca_comp =", "= dist_from_pt / 2 if is_extent_intersect(extent, other_crop_extent): overlap = True", "bg_img=self.img, title='Phrase Detection', entity_sets=set_of_phrases) fig.savefig(os.path.join(self.output_path, self.document.basename + '_phrase_detection.png')) plt.close(fig) def", "(e1.right < e2.left or e1.left > e2.right) is_extent_y_intersect = lambda", "x_max = int(round((bbox[0] + bbox[2]) * document.width)) image_of_crop = document.image[max(0,", "cv2.imread(self.image_path) dpi = 120 mpl.rcParams['figure.dpi'] = dpi height = self.img.shape[0]", "solution_per_cluster.items(): for word_index, word in zip(cluster_solution.word_indices, cluster_solution.words): bbox = word.get_bbox()", "from multimodal_affinities.visualization.image_utils import resize_image from multimodal_affinities.visualization.colors_util import rgb_hex_to_tuple class PlotsProducer:", "= entity.geometry.width * img_width height = entity.geometry.height * img_height #", "patches from multimodal_affinities.visualization.vis_handler import VisHandler from multimodal_affinities.visualization.image_utils import resize_image from", "word in selected_words] solution_per_cluster[cluster] = ClusterSolution(word_indices=selected_word_indices, words=selected_words) return solution_per_cluster @staticmethod", "_ in range(points_to_calc_count): last_point_selected = selected_points[-1] # Update accumulator with", "import randrange import numpy as np from sklearn.decomposition import PCA", "x_list: List of corresponding pt x positions :param y_list: List", "will set those for all figures selected_word_crops_per_cluster = None indices_to_crops", "distances_matrix[random_index, :] = 0 furthrest_point_from_set = np.argmax(distances_accumulator, axis=0) selected_points.append(furthrest_point_from_set) selected_words", "if len(words) == 0 or embeddings_history is None or len(embeddings_history)", "= bottom - height continue indices_to_extents[point_index] = extent return indices_to_extents", "# Update accumulator with distance collected from last point distances_accumulator", "frames = [] for epoch, x_list, y_list, push_pull_ratio in scatter_data:", "distance matrix & accumulator distances_matrix[:, random_index] = 0 distances_matrix[random_index, :]", "for cluster, cluster_solution in solution_per_cluster.items(): for word_index, word in zip(cluster_solution.word_indices,", "scipy.spatial.distance import pdist, squareform import torch import matplotlib matplotlib.use('Agg') #", "word_to_embedding_2d_idx = {word: idx for idx, word in enumerate(words)} clusters", "= unprojected_embedding.detach().cpu().numpy() embeddings.append(unprojected_embedding) else: embeddings = [getattr(word, embedding_property).detach().cpu().numpy() for word", "is expected to be relatively small (< 100) \"\"\" words", "from sklearn.decomposition import PCA from scipy.spatial.distance import pdist, squareform import", "Image from random import randrange import numpy as np from", "Detection', entity_sets=set_of_phrases) fig.savefig(os.path.join(self.output_path, self.document.basename + '_phrase_detection.png')) plt.close(fig) def save_clustering_results(self, with_title=True,", "top = other_bottom + spaceout_margin bottom = top + height", "/ words[point_index].geometry.height axis_ratio = (max_x-min_x) / (max_y-min_y) / 2 width", "output_frame.reshape(fig.canvas.get_width_height()[::-1] + (3,)) frames.append(output_frame) imageio.mimsave(os.path.join(output_path, document.basename + '_embeddings_history.gif'), frames, fps=2)", "import numpy as np from sklearn.decomposition import PCA from scipy.spatial.distance", "in self.document.get_phrases()] # list of singleton phrase lists fig, ax", "Greedy approximation algorithm for finding k furthest neighbour words per", "# Used to return the plot as an image rray", "training (PCA)' else: plot_title = unprojected_caption plt.title(plot_title) plt.scatter(x_list, y_list, c=colors,", "singleton word lists fig, ax = plt.subplots(1, figsize=self.figsize) monochrome_colors_list =", "range(embeddings_2d.shape[0])] fig, ax = plt.subplots(1) plot_title = embedding_property if plot_title", "words] colors_palette = VisHandler.generate_colors_list(amount=len(clusters)) word_to_color = {word: colors_palette[cluster_idx] for cluster_idx,", "doc) to PIL crop :param words: List of words :param", "min_x) * padding_factor max_x += (max_x - min_x) * padding_factor", "max(entry[1]))[1]) min_y = min(min(scatter_data, key=lambda entry: min(entry[2]))[2]) max_y = max(max(scatter_data,", "in self.document.get_words()] self._draw_entity_bounding_boxes(fig=fig, ax=ax, bg_img=self.img, title='', entity_sets=set_of_words, colors_list=monochrome_colors_list) fig.savefig(os.path.join(self.output_path, self.document.basename", "right, bottom, top) for other_crop_extent in indices_to_extents.values(): other_left, other_right, other_bottom,", "self._draw_entity_bounding_boxes(fig=fig, ax=ax, bg_img=self.img, title='', entity_sets=set_of_words, colors_list=monochrome_colors_list) fig.savefig(os.path.join(self.output_path, self.document.basename + '_word_boxes.png'))", "plt.close(fig) def save_clustering_results(self, with_title=True, colors_list=None): set_of_clusters = [cluster.words for cluster", "import Image from random import randrange import numpy as np", "- 1, len(words) - 1) for _ in range(points_to_calc_count): last_point_selected", "for word in cluster.words} colors = [word_to_color[word] for word in", "first embedding property we process will set those for all", "* img_height width = entity.geometry.width * img_width height = entity.geometry.height", "idx for idx, cluster_id in enumerate(cluster_ids)} # Converts from list", "(int(x + width), int(y + height)), (rgb_color[2], rgb_color[1], rgb_color[0]), cv2.FILLED)", "= other_top - spaceout_margin top = bottom - height continue", "embedding_property + '_pca.png')) plt.close(fig) # Finally plot clusters on original", "colors_list=None): cluster_ids = np.unique(np.array(clustering_labels)) cluster_id_to_cluster_idx = {cluster_id: idx for idx,", "matplotlib.pyplot as plt import matplotlib.image as image import matplotlib.patches as", "height / float(dpi) # Fig size in inches self.document =", "pairwise_distances = pdist(all_cluster_embeddings, metric='euclidean') distances_matrix = squareform(pairwise_distances) # Total distance", "= document.image[max(0, y_min):min(y_max, document.height), max(0, x_min):min(x_max, document.width), :] pil_image =", "* padding_factor max_y += (max_y - min_y) * padding_factor frames", "'words']) for cluster in clusters: # Generate cluster pairwise distances", "order in doc) to PIL crop :param words: List of", "of word index (by order in doc) to PIL crop", "[word_to_color[word] for word in words] # Initially empty, the first", "document: :param set_of_clusters: list of list of words (clusters) :return:", "min_y) * height dist_from_pt = min(max_y - min_y, max_x -", "y positions :param dist_from_pt: How far in (x-y) coords the", "Update accumulator with distance collected from last point distances_accumulator +=", "push_pull_ratio = embeddings_state['push_pull_ratio'] scatter_data.append((epoch, x_list, y_list, push_pull_ratio)) min_x = min(min(scatter_data,", "distances_matrix[:, random_index] = 0 distances_matrix[random_index, :] = 0 furthrest_point_from_set =", "'top']) is_extent_x_intersect = lambda e1, e2: not (e1.right < e2.left", "cache the renderer output_frame = np.frombuffer(fig.canvas.tostring_rgb(), dtype='uint8') output_frame = output_frame.reshape(fig.canvas.get_width_height()[::-1]", "+ '_clustering.png'), output_img) @staticmethod def _draw_entity_bounding_boxes_opencv(bg_img, entity_sets, colors_list=None): img_height =", "= [embeddings_2d[i, 1] for i in range(embeddings_2d.shape[0])] push_pull_ratio = embeddings_state['push_pull_ratio']", "positions :param y_list: List of corresponding pt y positions :param", "embeddings, post training (PCA)' else: plot_title = unprojected_caption plt.title(plot_title) plt.scatter(x_list,", "_find_k_furthest_words_per_cluster(document, embeddings_2d, k=3): \"\"\" Greedy approximation algorithm for finding k", "in cluster.words} colors = [word_to_color[word] for word in words] scatter_data", "indices_to_extents[point_index] = extent return indices_to_extents def plot_clusters_and_embedding_space_with_crops(self, document, output_path, crops_per_cluster=3,", "(PCA)' else: if unprojected_caption is None: plot_title = 'Projected embeddings,", "Plot crop images for point_index, crop in indices_to_crops.items(): extent =", "in indices_to_crops.items(): word_aspect_ratio = words[point_index].geometry.width / words[point_index].geometry.height axis_ratio = (max_x-min_x)", "(x-y) coords the crop should be placed from the plot", "min(entry[1]))[1]) max_x = max(max(scatter_data, key=lambda entry: max(entry[1]))[1]) min_y = min(min(scatter_data,", "y_list, push_pull_ratio)) min_x = min(min(scatter_data, key=lambda entry: min(entry[1]))[1]) max_x =", "= unnormalized_embeddings else: return embeddings_array = np.array(chosen_embedding).squeeze() num_pca_comp = 2", "edgecolor=edge_color, facecolor=face_color, alpha=0.4) ax.add_patch(rect) @staticmethod def plot_pca_embedding_space_for_clusters(document, output_path, embedding_property='embedding', title=''):", "chosen_embedding = normalized_embeddings elif len(unnormalized_embeddings_dict) > 0: unnormalized_embeddings = [unnormalized_embeddings_dict[word].detach().cpu().numpy()", "- min_x) * padding_factor min_y -= (max_y - min_y) *", "+= (max_y - min_y) * padding_factor frames = [] for", "[random_index] # How many points we need to add points_to_calc_count", "selected_points] selected_word_indices = [word_to_embedding_2d_idx[word] for word in selected_words] solution_per_cluster[cluster] =", "from distance matrix & accumulator distances_matrix[:, random_index] = 0 distances_matrix[random_index,", "= bg_img.copy() alpha = 0.8 for set_idx, entities_set in enumerate(entity_sets):", "as image import matplotlib.patches as patches from multimodal_affinities.visualization.vis_handler import VisHandler", "y_max = int(round((bbox[1] + bbox[3]) * document.height)) x_min = int(round(bbox[0]", "def plot_clusters_and_embedding_space_with_crops(self, document, output_path, crops_per_cluster=3, embedding_properties=['embedding', 'unprojected_embedding'], unprojected_caption=None): \"\"\" Plot", "# Plot crop images for point_index, crop in indices_to_crops.items(): extent", "\"\"\" Calculates the positions and dimensions of crop images on", "idx, cluster_id in enumerate(cluster_ids)} # Converts from list of labels", "from list of labels to list of list of words", "words[point_index].geometry.height axis_ratio = (max_x-min_x) / (max_y-min_y) / 2 width =", "in enumerate(entity_sets): face_color = face_colors[set_idx] edge_color = edge_colors[set_idx] for entity", "index (by order in doc) to PIL crop :param words:", "(e1.top > e2.bottom or e1.bottom < e2.top) is_extent_intersect = lambda", "patches.Rectangle((extent.left, extent.top), extent.right-extent.left, extent.bottom-extent.top, linewidth=0.5, edgecolor=\"black\", facecolor=\"none\", zorder=5) ax.imshow(crop, aspect='auto',", "PlotsProducer: def __init__(self, document, output_path): # Load background image self.image_path", "- alpha, 0) return output_img @staticmethod def _draw_entity_bounding_boxes(fig, ax, bg_img,", "\"\"\" Extracts crops for each selected word in k-furthest neighbours", "self.document.get_phrases()] # list of singleton phrase lists fig, ax =", "method assumes a small number of crops (< 1000) and", "document.width), :] pil_image = Image.fromarray(image_of_crop[...,::-1]) # BGR to RGB pil_image", "plot_word_boxes_on_image(self): set_of_words = [[word] for word in self.document.get_words()] # list", "'Initial unprojected embeddings, pre training (PCA)' else: if unprojected_caption is", "writing the text onto the image and returning it rgb_color", "dict of word index (by order in doc) to PIL", "dist_from_pt + width bottom, top = y_list[point_index] + dist_from_pt +", "rgb_hex_to_tuple(face_color) cv2.rectangle(output_img, (int(x), int(y)), (int(x + width), int(y + height)),", "set those for all figures selected_word_crops_per_cluster = None indices_to_crops =", "pdist(all_cluster_embeddings, metric='euclidean') distances_matrix = squareform(pairwise_distances) # Total distance from selected", "'Projected embeddings at epoch #' + str(epoch) + ' (PCA)'", "max_x) ax.set_ylim(min_y, max_y) plot_title = 'Projected embeddings at epoch #'", "'_' + embedding_property + '_pca.png')) plt.close(fig) # Finally plot clusters", "crop, in figure axes dimensions (note: for normalized pca space:", "other_bottom <= top <= other_top: top = other_bottom + spaceout_margin", "embedding_property).detach().cpu().numpy() for word in words] colors_palette = VisHandler.generate_colors_list(amount=len(clusters)) word_to_color =", "alpha = 0.8 for set_idx, entities_set in enumerate(entity_sets): face_color =", "min_y, max_y = min(y_list), max(y_list) height = (max_y - min_y)", "key=lambda entry: min(entry[1]))[1]) max_x = max(max(scatter_data, key=lambda entry: max(entry[1]))[1]) min_y", "import PCA from scipy.spatial.distance import pdist, squareform import torch import", "draw the canvas, cache the renderer output_frame = np.frombuffer(fig.canvas.tostring_rgb(), dtype='uint8')", "e2) and is_extent_y_intersect(e1, e2) min_x, max_x = min(x_list), max(x_list) min_y,", "os.makedirs(output_path) words = document.get_words() clusters = document.get_clusters() if len(words) ==", "width = self.img.shape[1] self.figsize = width / float(dpi), height /", "the crop should be placed from the plot :param height:", "= document.get_clusters() if len(words) == 0 or getattr(words[0], embedding_property) is", "is None: colors_palette = VisHandler.generate_colors_list(amount=len(clusters)) word_to_color = {word: colors_palette[cluster_idx] for", "[word_to_color[word] for word in words] embeddings_array = np.array(embeddings).squeeze() num_pca_comp =", "edge_colors = VisHandler.generate_darker_palette(colors_list) for set_idx, entities_set in enumerate(entity_sets): face_color =", "colors_list) def _save_set_of_clusters(self, set_of_clusters, with_title=True, colors_list=None): \"\"\" :param document: :param", "of word index to extens describing position and dimensions of", "0 furthrest_point_from_set = np.argmax(distances_accumulator, axis=0) selected_points.append(furthrest_point_from_set) selected_words = [cluster.words[point] for", "bg_img.shape[0] img_width = bg_img.shape[1] if colors_list is None: colors_list =", "which='both', bottom='off', top='off', labelbottom='off', right='off', left='off', labelleft='off') ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) fig.tight_layout()", "Solution of k-furthest neighbours :return: \"\"\" word_indices_to_crops = {} for", "top='off', labelbottom='off', right='off', left='off', labelleft='off') ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) # Used to", "RGB pil_image = pil_image.convert('RGB') word_indices_to_crops[word_index] = pil_image return word_indices_to_crops @staticmethod", ":param height: Height of the crop, in figure axes dimensions", "VisHandler.generate_darker_palette(colors_list) for set_idx, entities_set in enumerate(entity_sets): face_color = face_colors[set_idx] edge_color", "crop in indices_to_crops.items(): word_aspect_ratio = words[point_index].geometry.width / words[point_index].geometry.height axis_ratio =", "fig, ax = plt.subplots(1, figsize=self.figsize) self._draw_entity_bounding_boxes(fig=fig, ax=ax, bg_img=self.img, title='Phrase Detection',", "clustering_labels, colors_list=None): cluster_ids = np.unique(np.array(clustering_labels)) cluster_id_to_cluster_idx = {cluster_id: idx for", "= {} for cluster, cluster_solution in solution_per_cluster.items(): for word_index, word", "+ '_phrase_detection.png')) plt.close(fig) def save_clustering_results(self, with_title=True, colors_list=None): set_of_clusters = [cluster.words", "for point_index, crop in indices_to_crops.items(): extent = indices_to_extents[point_index] rect =", "title='Phrase Detection', entity_sets=set_of_phrases) fig.savefig(os.path.join(self.output_path, self.document.basename + '_phrase_detection.png')) plt.close(fig) def save_clustering_results(self,", "+= (max_x - min_x) * padding_factor min_y -= (max_y -", "as np from sklearn.decomposition import PCA from scipy.spatial.distance import pdist,", "ax.add_patch(rect) @staticmethod def plot_pca_embedding_space_for_clusters(document, output_path, embedding_property='embedding', title=''): \"\"\" Plot 2d", "continue indices_to_extents[point_index] = extent return indices_to_extents def plot_clusters_and_embedding_space_with_crops(self, document, output_path,", "bottom = top + height else: # shift above bottom", "* axis_ratio left, right = x_list[point_index] + dist_from_pt, x_list[point_index] +", "of list of words (clusters) :return: \"\"\" output_img = self._draw_entity_bounding_boxes_opencv(bg_img=self.img_opencv,", "ax = plt.subplots(1) if crops_per_cluster > 0: if selected_word_crops_per_cluster is", "= entity.geometry.width * img_width height = entity.geometry.height * img_height rect", "list of singleton phrase lists fig, ax = plt.subplots(1, figsize=self.figsize)", "range(embeddings_2d.shape[0])] push_pull_ratio = embeddings_state['push_pull_ratio'] scatter_data.append((epoch, x_list, y_list, push_pull_ratio)) min_x =", "self.document.get_clusters()] # list of list of words (clusters) self._save_set_of_clusters(set_of_clusters, with_title,", "at epoch #' + str(epoch) + ' (PCA)' plt.title(plot_title) plt.scatter(x_list,", "distance collected from last point distances_accumulator += distances_matrix[last_point_selected] # Eliminate", "import pdist, squareform import torch import matplotlib matplotlib.use('Agg') # Required", "entity.geometry.height * img_height rect = patches.Rectangle((x, y), width, height, linewidth=2,", "rray fig.tight_layout() fig.canvas.draw() # draw the canvas, cache the renderer", "= True while overlap: overlap = False extent = MatplotExtent(left,", "collections import namedtuple import imageio from PIL import Image from", "embeddings = [] for word in words: unprojected_embedding = torch.cat(word.unprojected_embedding['embeddings'],", "in embedding_properties]): return colors_palette = VisHandler.generate_colors_list(amount=len(clusters)) word_to_color = {word: colors_palette[cluster_idx]", "fig.savefig(os.path.join(self.output_path, self.document.basename + '_word_boxes.png')) plt.close(fig) def save_phrase_detection_results(self): set_of_phrases = [[phrase]", "Initially empty, the first embedding property we process will set", "img_height # writing the text onto the image and returning", "c=colors, s=1, alpha=0.8) fig.tight_layout() fig.savefig(os.path.join(output_path, document.basename + '_' + embedding_property", "fig, ax = plt.subplots(1, figsize=self.figsize) monochrome_colors_list = ['#5a5d8f' for _", "to PIL crop :param words: List of words :param x_list:", "= entity.geometry.top * img_height width = entity.geometry.width * img_width height", "y_min):min(y_max, document.height), max(0, x_min):min(x_max, document.width), :] pil_image = Image.fromarray(image_of_crop[...,::-1]) #", "plt.tick_params(axis='both', which='both', bottom='off', top='off', labelbottom='off', right='off', left='off', labelleft='off') ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False)", "points selected_points = [random_index] # How many points we need", "= ['#5a5d8f' for _ in self.document.get_words()] self._draw_entity_bounding_boxes(fig=fig, ax=ax, bg_img=self.img, title='',", "elif len(unnormalized_embeddings_dict) > 0: unnormalized_embeddings = [unnormalized_embeddings_dict[word].detach().cpu().numpy() for word in", "affiliates. All Rights Reserved. # SPDX-License-Identifier: CC-BY-4.0 import os import", "list of list of words (clusters) :return: \"\"\" output_img =", "pre training (PCA)' else: if unprojected_caption is None: plot_title =", "= face_colors[set_idx] edge_color = edge_colors[set_idx] for entity in entities_set: x", "Finally plot clusters on original image self.save_clustering_results(with_title=False, colors_list=colors_palette) return colors_palette", "bg_img, title, entity_sets, colors_list=None): ax.set_title(title) plt.tick_params(axis='both', which='both', bottom='off', top='off', labelbottom='off',", "_extract_crops_per_cluster_solution(document, solution_per_cluster): \"\"\" Extracts crops for each selected word in", "= VisHandler.generate_darker_palette(colors_list) output_img = bg_img.copy() alpha = 0.8 for set_idx,", "in figure axes dimensions (note: for normalized pca space: -1", "labelbottom='off', right='off', left='off', labelleft='off') ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) fig.tight_layout() fig.savefig(os.path.join(output_path, document.basename +", "= [[] for _ in range(len(cluster_ids))] for word_idx, word in", "'_word_boxes.png')) plt.close(fig) def save_phrase_detection_results(self): set_of_phrases = [[phrase] for phrase in", "== 'unprojected_embedding': embeddings = [] for word in words: unprojected_embedding", "width / float(dpi), height / float(dpi) # Fig size in", "/ 2 width = height * word_aspect_ratio * axis_ratio left,", "document.width)) x_max = int(round((bbox[0] + bbox[2]) * document.width)) image_of_crop =", "True while overlap: overlap = False extent = MatplotExtent(left, right,", "width, height y_min = int(round(bbox[1] * document.height)) y_max = int(round((bbox[1]", "plt.title(plot_title) plt.scatter(x_list, y_list, c=colors, s=1, alpha=0.8) fig.tight_layout() fig.savefig(os.path.join(output_path, document.basename +", "\\ all([getattr(words[0], embedding_property) is None for embedding_property in embedding_properties]): return", "np.argmax(distances_accumulator, axis=0) selected_points.append(furthrest_point_from_set) selected_words = [cluster.words[point] for point in selected_points]", "document.image_path self.img = plt.imread(self.image_path) self.img_opencv = cv2.imread(self.image_path) dpi = 120", "k-furthest neighbours solution :param document: :param solution_per_cluster: Solution of k-furthest", "cluster.words} colors = [word_to_color[word] for word in words] # Initially", "# Generate cluster pairwise distances matrix all_cluster_embeddings_indices = [word_to_embedding_2d_idx[word] for", "according to cluster colors. :param document: Document with clustering results", "colors_list=None): ax.set_title(title) plt.tick_params(axis='both', which='both', bottom='off', top='off', labelbottom='off', right='off', left='off', labelleft='off')", "bottom - height continue indices_to_extents[point_index] = extent return indices_to_extents def", "* padding_factor frames = [] for epoch, x_list, y_list, push_pull_ratio", "y_list = [embeddings_2d[i, 1] for i in range(embeddings_2d.shape[0])] push_pull_ratio =", "def __init__(self, document, output_path): # Load background image self.image_path =", "plot as an image rray fig.tight_layout() fig.canvas.draw() # draw the", "the plot :param height: Height of the crop, in figure", "all figures selected_word_crops_per_cluster = None indices_to_crops = None for embedding_property", "unnormalized_embeddings else: return embeddings_array = np.array(chosen_embedding).squeeze() num_pca_comp = 2 embeddings_2d", "y_list, dist_from_pt=0.02, height=0.04) # Plot crop images for point_index, crop", "of words (clusters) :return: \"\"\" output_img = self._draw_entity_bounding_boxes_opencv(bg_img=self.img_opencv, entity_sets=set_of_clusters, colors_list=colors_list)", "== 'unprojected_embedding': # Can't handle tuples, concat them embeddings =", "x_list = [embeddings_2d[i, 0] for i in range(embeddings_2d.shape[0])] y_list =", "concat them embeddings = [] for word in words: unprojected_embedding", "1] for i in range(embeddings_2d.shape[0])] fig, ax = plt.subplots(1) plot_title", "ClusterSolution(word_indices=selected_word_indices, words=selected_words) return solution_per_cluster @staticmethod def _extract_crops_per_cluster_solution(document, solution_per_cluster): \"\"\" Extracts", "placed from the plot :param height: Height of the crop,", "document.height)) y_max = int(round((bbox[1] + bbox[3]) * document.height)) x_min =", "selected_points = [random_index] # How many points we need to", "(max_x-min_x) / (max_y-min_y) / 2 width = height * word_aspect_ratio", "e1, e2: not (e1.right < e2.left or e1.left > e2.right)", "embedding_property) is None for embedding_property in embedding_properties]): return colors_palette =", "for gif animations import matplotlib as mpl import matplotlib.pyplot as", "lambda e1, e2: is_extent_x_intersect(e1, e2) and is_extent_y_intersect(e1, e2) min_x, max_x", "in inches self.document = document self.output_path = output_path if not", "is_extent_y_intersect(e1, e2) min_x, max_x = min(x_list), max(x_list) min_y, max_y =", "x_min):min(x_max, document.width), :] pil_image = Image.fromarray(image_of_crop[...,::-1]) # BGR to RGB", "= True # shift below if other_bottom <= top <=", "colors_list is None: colors_list = VisHandler.generate_colors_list(amount=len(entity_sets)) face_colors = colors_list edge_colors", "of list of words (clusters) set_of_clusters = [[] for _", "bg_img, 1 - alpha, 0) return output_img @staticmethod def _draw_entity_bounding_boxes(fig,", "plt import matplotlib.image as image import matplotlib.patches as patches from", "idx, word in enumerate(words)} clusters = document.get_clusters() solution_per_cluster = {}", "[embeddings_2d[i, 1] for i in range(embeddings_2d.shape[0])] push_pull_ratio = embeddings_state['push_pull_ratio'] scatter_data.append((epoch,", "word lists fig, ax = plt.subplots(1, figsize=self.figsize) monochrome_colors_list = ['#5a5d8f'", "def _draw_entity_bounding_boxes(fig, ax, bg_img, title, entity_sets, colors_list=None): ax.set_title(title) plt.tick_params(axis='both', which='both',", "return if colors_palette is None: colors_palette = VisHandler.generate_colors_list(amount=len(clusters)) word_to_color =", "y_list, c=colors, s=1, alpha=0.8) fig.tight_layout() fig.savefig(os.path.join(output_path, document.basename + '_' +", ":param solution_per_cluster: Solution of k-furthest neighbours :return: \"\"\" word_indices_to_crops =", "normally 'embedding' or 'unprojected_embedding' :return: \"\"\" if not os.path.exists(output_path): os.makedirs(output_path)", "in embedding_properties: if embedding_property == 'unprojected_embedding': # Can't handle tuples,", "dist_from_pt: How far in (x-y) coords the crop should be", "extent.top), extent.right-extent.left, extent.bottom-extent.top, linewidth=0.5, edgecolor=\"black\", facecolor=\"none\", zorder=5) ax.imshow(crop, aspect='auto', alpha=0.65,", "Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: CC-BY-4.0", "neighbour words per cluster. k is expected to be relatively", "x_min = int(round(bbox[0] * document.width)) x_max = int(round((bbox[0] + bbox[2])", "fig.tight_layout() fig.canvas.draw() # draw the canvas, cache the renderer output_frame", "of singleton phrase lists fig, ax = plt.subplots(1, figsize=self.figsize) self._draw_entity_bounding_boxes(fig=fig,", "extent = indices_to_extents[point_index] rect = patches.Rectangle((extent.left, extent.top), extent.right-extent.left, extent.bottom-extent.top, linewidth=0.5,", "# Converts from list of labels to list of list", "e1.bottom < e2.top) is_extent_intersect = lambda e1, e2: is_extent_x_intersect(e1, e2)", "= max(max(scatter_data, key=lambda entry: max(entry[2]))[2]) padding_factor = 0.1 min_x -=", "finding k furthest neighbour words per cluster. k is expected", "we process will set those for all figures selected_word_crops_per_cluster =", "\"\"\" words = document.get_words() word_to_embedding_2d_idx = {word: idx for idx,", "word in words] scatter_data = [] for state_idx, embeddings_state in", "in words] scatter_data = [] for state_idx, embeddings_state in enumerate(embeddings_history):", "self.document.basename + '_word_boxes.png')) plt.close(fig) def save_phrase_detection_results(self): set_of_phrases = [[phrase] for", ":param document: :param set_of_clusters: list of list of words (clusters)", "selected_word_crops_per_cluster = PlotsProducer._find_k_furthest_words_per_cluster(document, embeddings_2d, k=crops_per_cluster) indices_to_crops = PlotsProducer._extract_crops_per_cluster_solution(document, selected_word_crops_per_cluster) indices_to_extents", "max(max(scatter_data, key=lambda entry: max(entry[2]))[2]) padding_factor = 0.1 min_x -= (max_x", "from the plot :param height: Height of the crop, in", "if embedding_property == 'unprojected_embedding': plot_title = 'Initial unprojected embeddings, pre", "left='off', labelleft='off') plt.imshow(bg_img) img_height = bg_img.shape[0] img_width = bg_img.shape[1] if", "else: # shift above bottom = other_top - spaceout_margin top", "width, height, linewidth=2, edgecolor=edge_color, facecolor=face_color, alpha=0.4) ax.add_patch(rect) @staticmethod def plot_pca_embedding_space_for_clusters(document,", "dpi height = self.img.shape[0] width = self.img.shape[1] self.figsize = width", "word in words] # Initially empty, the first embedding property", "colors_list=None): set_of_clusters = [cluster.words for cluster in self.document.get_clusters()] # list", "img_width = bg_img.shape[1] if colors_list is None: colors_list = VisHandler.generate_colors_list(amount=len(entity_sets))", "zorder=3) plt.tick_params(axis='both', which='both', bottom='off', top='off', labelbottom='off', right='off', left='off', labelleft='off') ax.get_xaxis().set_visible(False)", "bottom = other_top - spaceout_margin top = bottom - height", "indices_to_extents = PlotsProducer._space_out_crops(indices_to_crops, words, x_list, y_list, dist_from_pt=0.02, height=0.04) # Plot", "set_of_clusters[cluster_idx].append(word) self._save_set_of_clusters(set_of_clusters, colors_list) def _save_set_of_clusters(self, set_of_clusters, with_title=True, colors_list=None): \"\"\" :param", "points_to_calc_count = min(k - 1, len(words) - 1) for _", "right='off', left='off', labelleft='off') ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) fig.tight_layout() fig.savefig(os.path.join(output_path, document.basename + '_'", "other. This method assumes a small number of crops (<", "multimodal_affinities.visualization.colors_util import rgb_hex_to_tuple class PlotsProducer: def __init__(self, document, output_path): #", "* img_width y = entity.geometry.top * img_height width = entity.geometry.width", "* img_width height = entity.geometry.height * img_height rect = patches.Rectangle((x,", "in range(embeddings_2d.shape[0])] push_pull_ratio = embeddings_state['push_pull_ratio'] scatter_data.append((epoch, x_list, y_list, push_pull_ratio)) min_x", "= VisHandler.generate_colors_list(amount=len(entity_sets)) face_colors = colors_list edge_colors = VisHandler.generate_darker_palette(colors_list) for set_idx,", "edgecolor=\"black\", facecolor=\"none\", zorder=5) ax.imshow(crop, aspect='auto', alpha=0.65, extent=extent, zorder=4) ax.add_patch(rect) #", "= np.frombuffer(fig.canvas.tostring_rgb(), dtype='uint8') output_frame = output_frame.reshape(fig.canvas.get_width_height()[::-1] + (3,)) frames.append(output_frame) imageio.mimsave(os.path.join(output_path,", "len(words) - 1) for _ in range(points_to_calc_count): last_point_selected = selected_points[-1]", "!= '': plot_title += ': ' + title plt.title(plot_title) plt.scatter(x_list,", "entity_sets, colors_list=None): img_height = bg_img.shape[0] img_width = bg_img.shape[1] if colors_list", "multimodal_affinities.visualization.image_utils import resize_image from multimodal_affinities.visualization.colors_util import rgb_hex_to_tuple class PlotsProducer: def", "max(0, x_min):min(x_max, document.width), :] pil_image = Image.fromarray(image_of_crop[...,::-1]) # BGR to", "top + height else: # shift above bottom = other_top", "padding_factor min_y -= (max_y - min_y) * padding_factor max_y +=", "canvas, cache the renderer output_frame = np.frombuffer(fig.canvas.tostring_rgb(), dtype='uint8') output_frame =", "in enumerate(cluster_ids)} # Converts from list of labels to list", "per first attribute selected_word_crops_per_cluster = PlotsProducer._find_k_furthest_words_per_cluster(document, embeddings_2d, k=crops_per_cluster) indices_to_crops =", "entry: max(entry[2]))[2]) padding_factor = 0.1 min_x -= (max_x - min_x)", "e2.left or e1.left > e2.right) is_extent_y_intersect = lambda e1, e2:", "height * word_aspect_ratio * axis_ratio left, right = x_list[point_index] +", "document.get_clusters() if len(words) == 0 or getattr(words[0], embedding_property) is None:", "e2: not (e1.right < e2.left or e1.left > e2.right) is_extent_y_intersect", "(< 1000) and performs a naive linear comparison for each", "lambda e1, e2: not (e1.top > e2.bottom or e1.bottom <", "ax.add_patch(rect) # Plot points if embedding_property == 'unprojected_embedding': plot_title =", "cluster_ids = np.unique(np.array(clustering_labels)) cluster_id_to_cluster_idx = {cluster_id: idx for idx, cluster_id", "in indices_to_extents.values(): other_left, other_right, other_bottom, other_top = other_crop_extent spaceout_margin =", "title, entity_sets, colors_list=None): ax.set_title(title) plt.tick_params(axis='both', which='both', bottom='off', top='off', labelbottom='off', right='off',", "* height dist_from_pt = min(max_y - min_y, max_x - min_x)", "from last point distances_accumulator += distances_matrix[last_point_selected] # Eliminate last point", "the first embedding property we process will set those for", "* document.width)) image_of_crop = document.image[max(0, y_min):min(y_max, document.height), max(0, x_min):min(x_max, document.width),", "= [word_to_embedding_2d_idx[word] for word in selected_words] solution_per_cluster[cluster] = ClusterSolution(word_indices=selected_word_indices, words=selected_words)", "if plot_title != '': plot_title += ': ' + title", "background image self.image_path = document.image_path self.img = plt.imread(self.image_path) self.img_opencv =", "the text onto the image and returning it rgb_color =", "furthest neighbour words per cluster. k is expected to be", "plot. Makes sure crops don't overlay each other. This method", "cluster, cluster_solution in solution_per_cluster.items(): for word_index, word in zip(cluster_solution.word_indices, cluster_solution.words):", "corresponding pt x positions :param y_list: List of corresponding pt", "_draw_entity_bounding_boxes_opencv(bg_img, entity_sets, colors_list=None): img_height = bg_img.shape[0] img_width = bg_img.shape[1] if", "for word_idx, word in enumerate(self.document.get_words()): cluster_id = clustering_labels[word_idx] if cluster_id", "collected from last point distances_accumulator += distances_matrix[last_point_selected] # Eliminate last", "document self.output_path = output_path if not os.path.exists(output_path): os.makedirs(output_path) def plot_word_boxes_on_image(self):", "MatplotExtent = namedtuple('matplot_extent', ['left', 'right', 'bottom', 'top']) is_extent_x_intersect = lambda", "inches self.document = document self.output_path = output_path if not os.path.exists(output_path):", "'unprojected_embedding': # Can't handle tuples, concat them embeddings = []", "'_pca.png')) plt.close(fig) # Finally plot clusters on original image self.save_clustering_results(with_title=False,", "random_index] = 0 distances_matrix[random_index, :] = 0 furthrest_point_from_set = np.argmax(distances_accumulator,", "SPDX-License-Identifier: CC-BY-4.0 import os import cv2 from collections import namedtuple", "document.get_words() clusters = document.get_clusters() if len(words) == 0 or \\", "self.save_clustering_results(with_title=False, colors_list=colors_palette) return colors_palette @staticmethod def animate_pca_embedding_space_for_clusters(document, output_path, embeddings_history, colors_palette=None):", "zorder=5) ax.imshow(crop, aspect='auto', alpha=0.65, extent=extent, zorder=4) ax.add_patch(rect) # Plot points", "= 'Initial unprojected embeddings, pre training (PCA)' else: if unprojected_caption", "need to add points_to_calc_count = min(k - 1, len(words) -", "* padding_factor max_x += (max_x - min_x) * padding_factor min_y", "output_img = cv2.addWeighted(output_img, alpha, bg_img, 1 - alpha, 0) return", "+ '_' + embedding_property + '_pca.png')) plt.close(fig) @staticmethod def _find_k_furthest_words_per_cluster(document,", "fig.canvas.draw() # draw the canvas, cache the renderer output_frame =", "small number of crops (< 1000) and performs a naive", "img_width y = entity.geometry.top * img_height width = entity.geometry.width *", "output_img) @staticmethod def _draw_entity_bounding_boxes_opencv(bg_img, entity_sets, colors_list=None): img_height = bg_img.shape[0] img_width", "plt.scatter(x_list, y_list, c=colors, s=1, alpha=0.8) fig.tight_layout() fig.savefig(os.path.join(output_path, document.basename + '_'", "in words] chosen_embedding = unnormalized_embeddings else: return embeddings_array = np.array(chosen_embedding).squeeze()", "[cluster.words for cluster in self.document.get_clusters()] # list of list of", "normalized_embeddings elif len(unnormalized_embeddings_dict) > 0: unnormalized_embeddings = [unnormalized_embeddings_dict[word].detach().cpu().numpy() for word", "fig.tight_layout() fig.savefig(os.path.join(output_path, document.basename + '_' + embedding_property + '_pca.png')) plt.close(fig)", "for word_index, word in zip(cluster_solution.word_indices, cluster_solution.words): bbox = word.get_bbox() #", "Generate cluster pairwise distances matrix all_cluster_embeddings_indices = [word_to_embedding_2d_idx[word] for word", "def save_phrase_detection_results(self): set_of_phrases = [[phrase] for phrase in self.document.get_phrases()] #", "embedding_properties: if embedding_property == 'unprojected_embedding': # Can't handle tuples, concat", ":return: \"\"\" word_indices_to_crops = {} for cluster, cluster_solution in solution_per_cluster.items():", "alpha, bg_img, 1 - alpha, 0) return output_img @staticmethod def", "space: -1 to 1) :return: indices_to_extents: dict of word index", "embedding_property).detach().cpu().numpy() for word in words] embeddings_array = np.array(embeddings).squeeze() num_pca_comp =", "ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) # Used to return the plot as an", "entity_sets=set_of_clusters, colors_list=colors_list) cv2.imwrite(os.path.join(self.output_path, self.document.basename + '_clustering.png'), output_img) @staticmethod def _draw_entity_bounding_boxes_opencv(bg_img,", "for word in words] # Initially empty, the first embedding", "plt.tick_params(axis='both', which='both', bottom='off', top='off', labelbottom='off', right='off', left='off', labelleft='off') plt.imshow(bg_img) img_height", "with_title=True, colors_list=None): set_of_clusters = [cluster.words for cluster in self.document.get_clusters()] #", "each other. This method assumes a small number of crops", "= self.img.shape[1] self.figsize = width / float(dpi), height / float(dpi)", "embeddings_state['push_pull_ratio'] scatter_data.append((epoch, x_list, y_list, push_pull_ratio)) min_x = min(min(scatter_data, key=lambda entry:", "cv2.addWeighted(output_img, alpha, bg_img, 1 - alpha, 0) return output_img @staticmethod", "distance from selected set so far distances_accumulator = np.zeros(len(cluster.words)) #", "- min_x) * dist_from_pt for point_index, crop in indices_to_crops.items(): word_aspect_ratio", "' (PCA)' plt.title(plot_title) plt.scatter(x_list, y_list, c=colors, s=18, alpha=1.0, edgecolors='black', linewidth=1.0,", "from multimodal_affinities.visualization.vis_handler import VisHandler from multimodal_affinities.visualization.image_utils import resize_image from multimodal_affinities.visualization.colors_util", "BGR to RGB pil_image = pil_image.convert('RGB') word_indices_to_crops[word_index] = pil_image return", "words continue cluster_idx = cluster_id_to_cluster_idx[cluster_id] set_of_clusters[cluster_idx].append(word) self._save_set_of_clusters(set_of_clusters, colors_list) def _save_set_of_clusters(self,", "* document.height)) x_min = int(round(bbox[0] * document.width)) x_max = int(round((bbox[0]", "output_img = self._draw_entity_bounding_boxes_opencv(bg_img=self.img_opencv, entity_sets=set_of_clusters, colors_list=colors_list) cv2.imwrite(os.path.join(self.output_path, self.document.basename + '_clustering.png'), output_img)", "# Calculate per first attribute selected_word_crops_per_cluster = PlotsProducer._find_k_furthest_words_per_cluster(document, embeddings_2d, k=crops_per_cluster)", "= None indices_to_crops = None for embedding_property in embedding_properties: if", "for normalized pca space: -1 to 1) :return: indices_to_extents: dict", "ax.set_ylim(min_y, max_y) plot_title = 'Projected embeddings at epoch #' +", "each other, \"\"\" indices_to_extents = {} MatplotExtent = namedtuple('matplot_extent', ['left',", "ax = plt.subplots(1, figsize=self.figsize) monochrome_colors_list = ['#5a5d8f' for _ in", "random import randrange import numpy as np from sklearn.decomposition import", "'_' + embedding_property + '_pca.png')) plt.close(fig) @staticmethod def _find_k_furthest_words_per_cluster(document, embeddings_2d,", "Crops are shifted so they don't cover each other, \"\"\"", "clusters = document.get_clusters() if len(words) == 0 or \\ all([getattr(words[0],", "> 0: normalized_embeddings = [normalized_embeddings_dict[word].detach().cpu().numpy() for word in words] chosen_embedding", "of labels to list of list of words (clusters) set_of_clusters", "range(len(cluster_ids))] for word_idx, word in enumerate(self.document.get_words()): cluster_id = clustering_labels[word_idx] if", "max_x - min_x) * dist_from_pt for point_index, crop in indices_to_crops.items():", "labelleft='off') ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) # Used to return the plot as", "img_width height = entity.geometry.height * img_height # writing the text", "cluster in enumerate(clusters) for word in cluster.words} colors = [word_to_color[word]", "Required for gif animations import matplotlib as mpl import matplotlib.pyplot", "dist_from_pt / 2 if is_extent_intersect(extent, other_crop_extent): overlap = True #", "y_list[point_index] + dist_from_pt + height, y_list[point_index] + dist_from_pt overlap =", "from scipy.spatial.distance import pdist, squareform import torch import matplotlib matplotlib.use('Agg')", "document.basename + '_' + embedding_property + '_pca.png')) plt.close(fig) @staticmethod def", "Image.fromarray(image_of_crop[...,::-1]) # BGR to RGB pil_image = pil_image.convert('RGB') word_indices_to_crops[word_index] =", "word_indices_to_crops @staticmethod def _space_out_crops(indices_to_crops, words, x_list, y_list, dist_from_pt=0.01, height=0.02): \"\"\"", "its affiliates. All Rights Reserved. # SPDX-License-Identifier: CC-BY-4.0 import os", "= entity.geometry.height * img_height # writing the text onto the", "or 'unprojected_embedding' :return: \"\"\" if not os.path.exists(output_path): os.makedirs(output_path) words =", "bg_img.copy() alpha = 0.8 for set_idx, entities_set in enumerate(entity_sets): face_color", "cluster. k is expected to be relatively small (< 100)", "matrix & accumulator distances_matrix[:, random_index] = 0 distances_matrix[random_index, :] =", "in words] # Initially empty, the first embedding property we", "from multimodal_affinities.visualization.colors_util import rgb_hex_to_tuple class PlotsProducer: def __init__(self, document, output_path):", "= VisHandler.generate_darker_palette(colors_list) for set_idx, entities_set in enumerate(entity_sets): face_color = face_colors[set_idx]", "for other_crop_extent in indices_to_extents.values(): other_left, other_right, other_bottom, other_top = other_crop_extent", "== -1: # Ignore non-clustered words continue cluster_idx = cluster_id_to_cluster_idx[cluster_id]", "words: unprojected_embedding = torch.cat(word.unprojected_embedding['embeddings'], dim=1) unprojected_embedding = unprojected_embedding.detach().cpu().numpy() embeddings.append(unprojected_embedding) else:", "= [embeddings_2d[i, 0] for i in range(embeddings_2d.shape[0])] y_list = [embeddings_2d[i,", "ax = plt.subplots(1, figsize=self.figsize) self._draw_entity_bounding_boxes(fig=fig, ax=ax, bg_img=self.img, title='Phrase Detection', entity_sets=set_of_phrases)", "embeddings_2d = PCA(n_components=num_pca_comp).fit_transform(embeddings_array) x_list = [embeddings_2d[i, 0] for i in", "namedtuple('ClusterSolution', ['word_indices', 'words']) for cluster in clusters: # Generate cluster", "as mpl import matplotlib.pyplot as plt import matplotlib.image as image", "scatter_data.append((epoch, x_list, y_list, push_pull_ratio)) min_x = min(min(scatter_data, key=lambda entry: min(entry[1]))[1])", "document.width)) image_of_crop = document.image[max(0, y_min):min(y_max, document.height), max(0, x_min):min(x_max, document.width), :]", "face_colors[set_idx] edge_color = edge_colors[set_idx] for entity in entities_set: x =", "dtype='uint8') output_frame = output_frame.reshape(fig.canvas.get_width_height()[::-1] + (3,)) frames.append(output_frame) imageio.mimsave(os.path.join(output_path, document.basename +", "in range(len(cluster_ids))] for word_idx, word in enumerate(self.document.get_words()): cluster_id = clustering_labels[word_idx]", "dist_from_pt, x_list[point_index] + dist_from_pt + width bottom, top = y_list[point_index]", "int(y)), (int(x + width), int(y + height)), (rgb_color[2], rgb_color[1], rgb_color[0]),", "height)), (rgb_color[2], rgb_color[1], rgb_color[0]), cv2.FILLED) output_img = cv2.addWeighted(output_img, alpha, bg_img,", "neighbours :return: \"\"\" word_indices_to_crops = {} for cluster, cluster_solution in", "== 0 or getattr(words[0], embedding_property) is None: return if embedding_property", "min(max_y - min_y, max_x - min_x) * dist_from_pt for point_index,", "selected word in k-furthest neighbours solution :param document: :param solution_per_cluster:", "overlap = True # shift below if other_bottom <= top", "face_color = face_colors[set_idx] edge_color = edge_colors[set_idx] for entity in entities_set:", "extent return indices_to_extents def plot_clusters_and_embedding_space_with_crops(self, document, output_path, crops_per_cluster=3, embedding_properties=['embedding', 'unprojected_embedding'],", "1) for _ in range(points_to_calc_count): last_point_selected = selected_points[-1] # Update", "in entities_set: x = entity.geometry.left * img_width y = entity.geometry.top", "indices_to_crops.items(): word_aspect_ratio = words[point_index].geometry.width / words[point_index].geometry.height axis_ratio = (max_x-min_x) /", "epoch, x_list, y_list, push_pull_ratio in scatter_data: fig, ax = plt.subplots(1)", "= document.get_words() word_to_embedding_2d_idx = {word: idx for idx, word in", "pil_image = Image.fromarray(image_of_crop[...,::-1]) # BGR to RGB pil_image = pil_image.convert('RGB')", "= int(round(bbox[0] * document.width)) x_max = int(round((bbox[0] + bbox[2]) *", "height, linewidth=2, edgecolor=edge_color, facecolor=face_color, alpha=0.4) ax.add_patch(rect) @staticmethod def plot_pca_embedding_space_for_clusters(document, output_path,", "embeddings_state['normalized'] unnormalized_embeddings_dict = embeddings_state['unnormalized'] if len(normalized_embeddings_dict) > 0: normalized_embeddings =", "selected_points.append(furthrest_point_from_set) selected_words = [cluster.words[point] for point in selected_points] selected_word_indices =", "edgecolors='black', linewidth=1.0, zorder=3) plt.tick_params(axis='both', which='both', bottom='off', top='off', labelbottom='off', right='off', left='off',", "enumerate(words)} clusters = document.get_clusters() solution_per_cluster = {} ClusterSolution = namedtuple('ClusterSolution',", "of corresponding pt x positions :param y_list: List of corresponding", "output_frame = output_frame.reshape(fig.canvas.get_width_height()[::-1] + (3,)) frames.append(output_frame) imageio.mimsave(os.path.join(output_path, document.basename + '_embeddings_history.gif'),", "not os.path.exists(output_path): os.makedirs(output_path) words = document.get_words() clusters = document.get_clusters() if", "number of crops (< 1000) and performs a naive linear", "selected points selected_points = [random_index] # How many points we", "embeddings_history is None or len(embeddings_history) == 0: return if colors_palette", "spaceout_margin bottom = top + height else: # shift above", "for i in range(embeddings_2d.shape[0])] push_pull_ratio = embeddings_state['push_pull_ratio'] scatter_data.append((epoch, x_list, y_list,", "self.img.shape[1] self.figsize = width / float(dpi), height / float(dpi) #", "of k-furthest neighbours :return: \"\"\" word_indices_to_crops = {} for cluster,", "embedding space plot. Makes sure crops don't overlay each other.", "in range(points_to_calc_count): last_point_selected = selected_points[-1] # Update accumulator with distance", "+= ': ' + title plt.title(plot_title) plt.scatter(x_list, y_list, c=colors, s=1,", "dist_from_pt + height, y_list[point_index] + dist_from_pt overlap = True while", "(max_y - min_y) * padding_factor max_y += (max_y - min_y)", "words (clusters) set_of_clusters = [[] for _ in range(len(cluster_ids))] for", "property of words - normally 'embedding' or 'unprojected_embedding' :return: \"\"\"", "\"\"\" if not os.path.exists(output_path): os.makedirs(output_path) words = document.get_words() clusters =", "entry: min(entry[2]))[2]) max_y = max(max(scatter_data, key=lambda entry: max(entry[2]))[2]) padding_factor =", "max_x = max(max(scatter_data, key=lambda entry: max(entry[1]))[1]) min_y = min(min(scatter_data, key=lambda", "e1, e2: is_extent_x_intersect(e1, e2) and is_extent_y_intersect(e1, e2) min_x, max_x =", "extens describing position and dimensions of each crop. Crops are", "points if embedding_property == 'unprojected_embedding': plot_title = 'Initial unprojected embeddings,", "to be relatively small (< 100) \"\"\" words = document.get_words()", "plt.close(fig) # Finally plot clusters on original image self.save_clustering_results(with_title=False, colors_list=colors_palette)", "max(entry[2]))[2]) padding_factor = 0.1 min_x -= (max_x - min_x) *", "= colors_list edge_colors = VisHandler.generate_darker_palette(colors_list) output_img = bg_img.copy() alpha =", "left='off', labelleft='off') ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) # Used to return the plot", "clustering_labels[word_idx] if cluster_id == -1: # Ignore non-clustered words continue", "height y_min = int(round(bbox[1] * document.height)) y_max = int(round((bbox[1] +", "np.frombuffer(fig.canvas.tostring_rgb(), dtype='uint8') output_frame = output_frame.reshape(fig.canvas.get_width_height()[::-1] + (3,)) frames.append(output_frame) imageio.mimsave(os.path.join(output_path, document.basename", "return word_indices_to_crops @staticmethod def _space_out_crops(indices_to_crops, words, x_list, y_list, dist_from_pt=0.01, height=0.02):", "torch.cat(word.unprojected_embedding['embeddings'], dim=1) unprojected_embedding = unprojected_embedding.detach().cpu().numpy() embeddings.append(unprojected_embedding) else: embeddings = [getattr(word,", "= document self.output_path = output_path if not os.path.exists(output_path): os.makedirs(output_path) def", "plt.close(fig) @staticmethod def _find_k_furthest_words_per_cluster(document, embeddings_2d, k=3): \"\"\" Greedy approximation algorithm", "for epoch, x_list, y_list, push_pull_ratio in scatter_data: fig, ax =", "matplotlib.use('Agg') # Required for gif animations import matplotlib as mpl", "self.document = document self.output_path = output_path if not os.path.exists(output_path): os.makedirs(output_path)", ":param words: List of words :param x_list: List of corresponding", "'_clustering.png'), output_img) @staticmethod def _draw_entity_bounding_boxes_opencv(bg_img, entity_sets, colors_list=None): img_height = bg_img.shape[0]", "embeddings_history, colors_palette=None): \"\"\" Plot 2d PCA visualization of the embedding", "_space_out_crops(indices_to_crops, words, x_list, y_list, dist_from_pt=0.01, height=0.02): \"\"\" Calculates the positions", "min(min(scatter_data, key=lambda entry: min(entry[1]))[1]) max_x = max(max(scatter_data, key=lambda entry: max(entry[1]))[1])", "img_width height = entity.geometry.height * img_height rect = patches.Rectangle((x, y),", "shift above bottom = other_top - spaceout_margin top = bottom", ":] pil_image = Image.fromarray(image_of_crop[...,::-1]) # BGR to RGB pil_image =", "e1, e2: not (e1.top > e2.bottom or e1.bottom < e2.top)", "rect = patches.Rectangle((extent.left, extent.top), extent.right-extent.left, extent.bottom-extent.top, linewidth=0.5, edgecolor=\"black\", facecolor=\"none\", zorder=5)", "for cluster_idx, cluster in enumerate(clusters) for word in cluster.words} colors", "points we need to add points_to_calc_count = min(k - 1,", "= min(y_list), max(y_list) height = (max_y - min_y) * height", "+ str(epoch) + ' (PCA)' plt.title(plot_title) plt.scatter(x_list, y_list, c=colors, s=18,", "width bottom, top = y_list[point_index] + dist_from_pt + height, y_list[point_index]", "fig, ax = plt.subplots(1) ax.set_xlim(min_x, max_x) ax.set_ylim(min_y, max_y) plot_title =", "original image self.save_clustering_results(with_title=False, colors_list=colors_palette) return colors_palette @staticmethod def animate_pca_embedding_space_for_clusters(document, output_path,", "unnormalized_embeddings_dict = embeddings_state['unnormalized'] if len(normalized_embeddings_dict) > 0: normalized_embeddings = [normalized_embeddings_dict[word].detach().cpu().numpy()", "top) for other_crop_extent in indices_to_extents.values(): other_left, other_right, other_bottom, other_top =", "not (e1.top > e2.bottom or e1.bottom < e2.top) is_extent_intersect =", "word.get_bbox() # left, top, width, height y_min = int(round(bbox[1] *", "in cluster.words} colors = [word_to_color[word] for word in words] #", "word in cluster.words} colors = [word_to_color[word] for word in words]", "axis_ratio = (max_x-min_x) / (max_y-min_y) / 2 width = height", "= embeddings_state['push_pull_ratio'] scatter_data.append((epoch, x_list, y_list, push_pull_ratio)) min_x = min(min(scatter_data, key=lambda", "min(x_list), max(x_list) min_y, max_y = min(y_list), max(y_list) height = (max_y", "is_extent_x_intersect = lambda e1, e2: not (e1.right < e2.left or", "* dist_from_pt for point_index, crop in indices_to_crops.items(): word_aspect_ratio = words[point_index].geometry.width", "namedtuple import imageio from PIL import Image from random import", "s=1, alpha=0.8) fig.tight_layout() fig.savefig(os.path.join(output_path, document.basename + '_' + embedding_property +", "alpha, 0) return output_img @staticmethod def _draw_entity_bounding_boxes(fig, ax, bg_img, title,", "self.output_path = output_path if not os.path.exists(output_path): os.makedirs(output_path) def plot_word_boxes_on_image(self): set_of_words", "np.array(embeddings).squeeze() num_pca_comp = 2 embeddings_2d = PCA(n_components=num_pca_comp).fit_transform(embeddings_array) x_list = [embeddings_2d[i,", "linewidth=0.5, edgecolor=\"black\", facecolor=\"none\", zorder=5) ax.imshow(crop, aspect='auto', alpha=0.65, extent=extent, zorder=4) ax.add_patch(rect)", "algorithm for finding k furthest neighbour words per cluster. k", "= {} ClusterSolution = namedtuple('ClusterSolution', ['word_indices', 'words']) for cluster in", "zorder=4) ax.add_patch(rect) # Plot points if embedding_property == 'unprojected_embedding': plot_title", "as patches from multimodal_affinities.visualization.vis_handler import VisHandler from multimodal_affinities.visualization.image_utils import resize_image", "crops don't overlay each other. This method assumes a small", "= [cluster.words[point] for point in selected_points] selected_word_indices = [word_to_embedding_2d_idx[word] for", "tuples, concat them embeddings = [] for word in words:", "= 0 distances_matrix[random_index, :] = 0 furthrest_point_from_set = np.argmax(distances_accumulator, axis=0)", "(< 100) \"\"\" words = document.get_words() word_to_embedding_2d_idx = {word: idx", "all_cluster_embeddings_indices, axis=0) pairwise_distances = pdist(all_cluster_embeddings, metric='euclidean') distances_matrix = squareform(pairwise_distances) #", "to return the plot as an image rray fig.tight_layout() fig.canvas.draw()", "all_cluster_embeddings_indices = [word_to_embedding_2d_idx[word] for word in cluster.words] all_cluster_embeddings = np.take(embeddings_2d,", "_draw_entity_bounding_boxes(fig, ax, bg_img, title, entity_sets, colors_list=None): ax.set_title(title) plt.tick_params(axis='both', which='both', bottom='off',", "> 0: if selected_word_crops_per_cluster is None and indices_to_crops is None:", "120 mpl.rcParams['figure.dpi'] = dpi height = self.img.shape[0] width = self.img.shape[1]", "pdist, squareform import torch import matplotlib matplotlib.use('Agg') # Required for", "or embeddings_history is None or len(embeddings_history) == 0: return if", "min_y) * padding_factor max_y += (max_y - min_y) * padding_factor", "None: return if embedding_property == 'unprojected_embedding': embeddings = [] for", "face_colors = colors_list edge_colors = VisHandler.generate_darker_palette(colors_list) for set_idx, entities_set in", "imageio from PIL import Image from random import randrange import", "= [random_index] # How many points we need to add", "+ 1 normalized_embeddings_dict = embeddings_state['normalized'] unnormalized_embeddings_dict = embeddings_state['unnormalized'] if len(normalized_embeddings_dict)", "= x_list[point_index] + dist_from_pt, x_list[point_index] + dist_from_pt + width bottom,", "> e2.right) is_extent_y_intersect = lambda e1, e2: not (e1.top >", "len(embeddings_history) == 0: return if colors_palette is None: colors_palette =", "plt.close(fig) def save_phrase_detection_results(self): set_of_phrases = [[phrase] for phrase in self.document.get_phrases()]", "2 if is_extent_intersect(extent, other_crop_extent): overlap = True # shift below", "@staticmethod def _extract_crops_per_cluster_solution(document, solution_per_cluster): \"\"\" Extracts crops for each selected", "animate_pca_embedding_space_for_clusters(document, output_path, embeddings_history, colors_palette=None): \"\"\" Plot 2d PCA visualization of", "bbox[3]) * document.height)) x_min = int(round(bbox[0] * document.width)) x_max =", "selected_words = [cluster.words[point] for point in selected_points] selected_word_indices = [word_to_embedding_2d_idx[word]", "' + title plt.title(plot_title) plt.scatter(x_list, y_list, c=colors, s=1, alpha=0.8) fig.tight_layout()", "from selected set so far distances_accumulator = np.zeros(len(cluster.words)) # Sample", "top = y_list[point_index] + dist_from_pt + height, y_list[point_index] + dist_from_pt", "[getattr(word, embedding_property).detach().cpu().numpy() for word in words] colors_palette = VisHandler.generate_colors_list(amount=len(clusters)) word_to_color", "dist_from_pt = min(max_y - min_y, max_x - min_x) * dist_from_pt", "c=colors, s=18, alpha=1.0, edgecolors='black', linewidth=1.0, zorder=3) plt.tick_params(axis='both', which='both', bottom='off', top='off',", "MatplotExtent(left, right, bottom, top) for other_crop_extent in indices_to_extents.values(): other_left, other_right,", "+ dist_from_pt overlap = True while overlap: overlap = False", "onto the image and returning it rgb_color = rgb_hex_to_tuple(face_color) cv2.rectangle(output_img,", "in enumerate(clusters) for word in cluster.words} colors = [word_to_color[word] for", "word in self.document.get_words()] # list of singleton word lists fig,", "selected_word_indices = [word_to_embedding_2d_idx[word] for word in selected_words] solution_per_cluster[cluster] = ClusterSolution(word_indices=selected_word_indices,", "figures selected_word_crops_per_cluster = None indices_to_crops = None for embedding_property in", "ax.get_yaxis().set_visible(False) # Used to return the plot as an image", "in selected_points] selected_word_indices = [word_to_embedding_2d_idx[word] for word in selected_words] solution_per_cluster[cluster]", "space according to cluster colors. :param document: Document with clustering", "Reserved. # SPDX-License-Identifier: CC-BY-4.0 import os import cv2 from collections", "extent.right-extent.left, extent.bottom-extent.top, linewidth=0.5, edgecolor=\"black\", facecolor=\"none\", zorder=5) ax.imshow(crop, aspect='auto', alpha=0.65, extent=extent,", "k furthest neighbour words per cluster. k is expected to", "= namedtuple('matplot_extent', ['left', 'right', 'bottom', 'top']) is_extent_x_intersect = lambda e1,", "document.get_clusters() if len(words) == 0 or embeddings_history is None or", "[word_to_embedding_2d_idx[word] for word in cluster.words] all_cluster_embeddings = np.take(embeddings_2d, all_cluster_embeddings_indices, axis=0)", "All Rights Reserved. # SPDX-License-Identifier: CC-BY-4.0 import os import cv2", "{} MatplotExtent = namedtuple('matplot_extent', ['left', 'right', 'bottom', 'top']) is_extent_x_intersect =", "= plt.subplots(1) plot_title = embedding_property if plot_title != '': plot_title", "rgb_color[0]), cv2.FILLED) output_img = cv2.addWeighted(output_img, alpha, bg_img, 1 - alpha,", "in words] chosen_embedding = normalized_embeddings elif len(unnormalized_embeddings_dict) > 0: unnormalized_embeddings", "range(embeddings_2d.shape[0])] y_list = [embeddings_2d[i, 1] for i in range(embeddings_2d.shape[0])] fig,", "1] for i in range(embeddings_2d.shape[0])] fig, ax = plt.subplots(1) if", "sure crops don't overlay each other. This method assumes a", "crop :param words: List of words :param x_list: List of", "document, output_path): # Load background image self.image_path = document.image_path self.img", "accumulator distances_matrix[:, random_index] = 0 distances_matrix[random_index, :] = 0 furthrest_point_from_set", "embeddings_array = np.array(embeddings).squeeze() num_pca_comp = 2 embeddings_2d = PCA(n_components=num_pca_comp).fit_transform(embeddings_array) x_list", "crop. Crops are shifted so they don't cover each other,", "entities_set: x = entity.geometry.left * img_width y = entity.geometry.top *", "\"\"\" Plot 2d PCA visualization of the embedding space according", "embedding_property == 'unprojected_embedding': embeddings = [] for word in words:", "cluster in self.document.get_clusters()] # list of list of words (clusters)", "be placed from the plot :param height: Height of the", "= cluster_id_to_cluster_idx[cluster_id] set_of_clusters[cluster_idx].append(word) self._save_set_of_clusters(set_of_clusters, colors_list) def _save_set_of_clusters(self, set_of_clusters, with_title=True, colors_list=None):", "= min(min(scatter_data, key=lambda entry: min(entry[1]))[1]) max_x = max(max(scatter_data, key=lambda entry:", "float(dpi) # Fig size in inches self.document = document self.output_path", "= self.img.shape[0] width = self.img.shape[1] self.figsize = width / float(dpi),", "else: return embeddings_array = np.array(chosen_embedding).squeeze() num_pca_comp = 2 embeddings_2d =", "fig, ax = plt.subplots(1) if crops_per_cluster > 0: if selected_word_crops_per_cluster", "os import cv2 from collections import namedtuple import imageio from", "(max_y - min_y) * padding_factor frames = [] for epoch,", ":] = 0 furthrest_point_from_set = np.argmax(distances_accumulator, axis=0) selected_points.append(furthrest_point_from_set) selected_words =", "#' + str(epoch) + ' (PCA)' plt.title(plot_title) plt.scatter(x_list, y_list, c=colors,", "document, output_path, crops_per_cluster=3, embedding_properties=['embedding', 'unprojected_embedding'], unprojected_caption=None): \"\"\" Plot 2d PCA", "which='both', bottom='off', top='off', labelbottom='off', right='off', left='off', labelleft='off') ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) #", "Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. #", "(rgb_color[2], rgb_color[1], rgb_color[0]), cv2.FILLED) output_img = cv2.addWeighted(output_img, alpha, bg_img, 1", "= [] for epoch, x_list, y_list, push_pull_ratio in scatter_data: fig,", "clusters = document.get_clusters() if len(words) == 0 or getattr(words[0], embedding_property)", "VisHandler from multimodal_affinities.visualization.image_utils import resize_image from multimodal_affinities.visualization.colors_util import rgb_hex_to_tuple class", "colors_palette = VisHandler.generate_colors_list(amount=len(clusters)) word_to_color = {word: colors_palette[cluster_idx] for cluster_idx, cluster", "we need to add points_to_calc_count = min(k - 1, len(words)", "position and dimensions of each crop. Crops are shifted so", "output_img = bg_img.copy() alpha = 0.8 for set_idx, entities_set in", "= {} MatplotExtent = namedtuple('matplot_extent', ['left', 'right', 'bottom', 'top']) is_extent_x_intersect", "image_of_crop = document.image[max(0, y_min):min(y_max, document.height), max(0, x_min):min(x_max, document.width), :] pil_image", "for finding k furthest neighbour words per cluster. k is", "other_crop_extent): overlap = True # shift below if other_bottom <=", "= int(round(bbox[1] * document.height)) y_max = int(round((bbox[1] + bbox[3]) *", "np.take(embeddings_2d, all_cluster_embeddings_indices, axis=0) pairwise_distances = pdist(all_cluster_embeddings, metric='euclidean') distances_matrix = squareform(pairwise_distances)", "None for embedding_property in embedding_properties]): return colors_palette = VisHandler.generate_colors_list(amount=len(clusters)) word_to_color", "monochrome_colors_list = ['#5a5d8f' for _ in self.document.get_words()] self._draw_entity_bounding_boxes(fig=fig, ax=ax, bg_img=self.img,", "in zip(cluster_solution.word_indices, cluster_solution.words): bbox = word.get_bbox() # left, top, width,", "y), width, height, linewidth=2, edgecolor=edge_color, facecolor=face_color, alpha=0.4) ax.add_patch(rect) @staticmethod def", "axis=0) selected_points.append(furthrest_point_from_set) selected_words = [cluster.words[point] for point in selected_points] selected_word_indices", "for word in words] colors_palette = VisHandler.generate_colors_list(amount=len(clusters)) word_to_color = {word:", "right='off', left='off', labelleft='off') ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) # Used to return the", "dim=1) unprojected_embedding = unprojected_embedding.detach().cpu().numpy() embeddings.append(unprojected_embedding) else: embeddings = [getattr(word, embedding_property).detach().cpu().numpy()", "embedding_property == 'unprojected_embedding': # Can't handle tuples, concat them embeddings", "matrix all_cluster_embeddings_indices = [word_to_embedding_2d_idx[word] for word in cluster.words] all_cluster_embeddings =", "them embeddings = [] for word in words: unprojected_embedding =", "plot_clusters_and_embedding_space_with_crops(self, document, output_path, crops_per_cluster=3, embedding_properties=['embedding', 'unprojected_embedding'], unprojected_caption=None): \"\"\" Plot 2d", "i in range(embeddings_2d.shape[0])] fig, ax = plt.subplots(1) if crops_per_cluster >", "# Finally plot clusters on original image self.save_clustering_results(with_title=False, colors_list=colors_palette) return", "+ bbox[2]) * document.width)) image_of_crop = document.image[max(0, y_min):min(y_max, document.height), max(0,", "in words: unprojected_embedding = torch.cat(word.unprojected_embedding['embeddings'], dim=1) unprojected_embedding = unprojected_embedding.detach().cpu().numpy() embeddings.append(unprojected_embedding)", "plt.scatter(x_list, y_list, c=colors, s=18, alpha=1.0, edgecolors='black', linewidth=1.0, zorder=3) plt.tick_params(axis='both', which='both',", "output_frame = np.frombuffer(fig.canvas.tostring_rgb(), dtype='uint8') output_frame = output_frame.reshape(fig.canvas.get_width_height()[::-1] + (3,)) frames.append(output_frame)", "approximation algorithm for finding k furthest neighbour words per cluster.", "padding_factor frames = [] for epoch, x_list, y_list, push_pull_ratio in", "cluster pairwise distances matrix all_cluster_embeddings_indices = [word_to_embedding_2d_idx[word] for word in", "crops_per_cluster=3, embedding_properties=['embedding', 'unprojected_embedding'], unprojected_caption=None): \"\"\" Plot 2d PCA visualization of", "of list of words (clusters) self._save_set_of_clusters(set_of_clusters, with_title, colors_list) def save_clustering_labels(self,", "None: colors_palette = VisHandler.generate_colors_list(amount=len(clusters)) word_to_color = {word: colors_palette[cluster_idx] for cluster_idx,", "len(words) == 0 or \\ all([getattr(words[0], embedding_property) is None for", "other_crop_extent in indices_to_extents.values(): other_left, other_right, other_bottom, other_top = other_crop_extent spaceout_margin", "epoch #' + str(epoch) + ' (PCA)' plt.title(plot_title) plt.scatter(x_list, y_list,", "in k-furthest neighbours solution :param document: :param solution_per_cluster: Solution of", "plt.imread(self.image_path) self.img_opencv = cv2.imread(self.image_path) dpi = 120 mpl.rcParams['figure.dpi'] = dpi", "import VisHandler from multimodal_affinities.visualization.image_utils import resize_image from multimodal_affinities.visualization.colors_util import rgb_hex_to_tuple", "List of corresponding pt x positions :param y_list: List of", ":return: \"\"\" if not os.path.exists(output_path): os.makedirs(output_path) words = document.get_words() clusters", "labelbottom='off', right='off', left='off', labelleft='off') plt.imshow(bg_img) img_height = bg_img.shape[0] img_width =", "other, \"\"\" indices_to_extents = {} MatplotExtent = namedtuple('matplot_extent', ['left', 'right',", "embeddings at epoch #' + str(epoch) + ' (PCA)' plt.title(plot_title)", "plt.subplots(1, figsize=self.figsize) self._draw_entity_bounding_boxes(fig=fig, ax=ax, bg_img=self.img, title='Phrase Detection', entity_sets=set_of_phrases) fig.savefig(os.path.join(self.output_path, self.document.basename", "comparison for each crop. :param indices_to_crops: dict of word index", "returning it rgb_color = rgb_hex_to_tuple(face_color) cv2.rectangle(output_img, (int(x), int(y)), (int(x +", "describing position and dimensions of each crop. Crops are shifted", "cluster_solution in solution_per_cluster.items(): for word_index, word in zip(cluster_solution.word_indices, cluster_solution.words): bbox", "= (max_x-min_x) / (max_y-min_y) / 2 width = height *", "of the crop, in figure axes dimensions (note: for normalized", "words[point_index].geometry.width / words[point_index].geometry.height axis_ratio = (max_x-min_x) / (max_y-min_y) / 2", "'embedding' or 'unprojected_embedding' :return: \"\"\" if not os.path.exists(output_path): os.makedirs(output_path) words", "scatter_data = [] for state_idx, embeddings_state in enumerate(embeddings_history): epoch =", "class PlotsProducer: def __init__(self, document, output_path): # Load background image", "other_right, other_bottom, other_top = other_crop_extent spaceout_margin = dist_from_pt / 2", "np from sklearn.decomposition import PCA from scipy.spatial.distance import pdist, squareform", "= namedtuple('ClusterSolution', ['word_indices', 'words']) for cluster in clusters: # Generate", "\"\"\" indices_to_extents = {} MatplotExtent = namedtuple('matplot_extent', ['left', 'right', 'bottom',", "to list of list of words (clusters) set_of_clusters = [[]", "in selected_words] solution_per_cluster[cluster] = ClusterSolution(word_indices=selected_word_indices, words=selected_words) return solution_per_cluster @staticmethod def", "= PlotsProducer._space_out_crops(indices_to_crops, words, x_list, y_list, dist_from_pt=0.02, height=0.04) # Plot crop", "[embeddings_2d[i, 1] for i in range(embeddings_2d.shape[0])] fig, ax = plt.subplots(1)", "+ spaceout_margin bottom = top + height else: # shift", "# Load background image self.image_path = document.image_path self.img = plt.imread(self.image_path)", "height=0.04) # Plot crop images for point_index, crop in indices_to_crops.items():", "document.image[max(0, y_min):min(y_max, document.height), max(0, x_min):min(x_max, document.width), :] pil_image = Image.fromarray(image_of_crop[...,::-1])", "# Sample first point random_index = randrange(len(cluster.words)) # Indices of", "solution_per_cluster @staticmethod def _extract_crops_per_cluster_solution(document, solution_per_cluster): \"\"\" Extracts crops for each", "y_min = int(round(bbox[1] * document.height)) y_max = int(round((bbox[1] + bbox[3])", "attribute selected_word_crops_per_cluster = PlotsProducer._find_k_furthest_words_per_cluster(document, embeddings_2d, k=crops_per_cluster) indices_to_crops = PlotsProducer._extract_crops_per_cluster_solution(document, selected_word_crops_per_cluster)", "randrange import numpy as np from sklearn.decomposition import PCA from", "key=lambda entry: min(entry[2]))[2]) max_y = max(max(scatter_data, key=lambda entry: max(entry[2]))[2]) padding_factor", "normalized pca space: -1 to 1) :return: indices_to_extents: dict of", "embedding_property + '_pca.png')) plt.close(fig) @staticmethod def _find_k_furthest_words_per_cluster(document, embeddings_2d, k=3): \"\"\"", "empty, the first embedding property we process will set those", "img_height width = entity.geometry.width * img_width height = entity.geometry.height *", "sklearn.decomposition import PCA from scipy.spatial.distance import pdist, squareform import torch", "= pdist(all_cluster_embeddings, metric='euclidean') distances_matrix = squareform(pairwise_distances) # Total distance from", "2 width = height * word_aspect_ratio * axis_ratio left, right", "def _find_k_furthest_words_per_cluster(document, embeddings_2d, k=3): \"\"\" Greedy approximation algorithm for finding", "ax.set_xlim(min_x, max_x) ax.set_ylim(min_y, max_y) plot_title = 'Projected embeddings at epoch", "state_idx + 1 normalized_embeddings_dict = embeddings_state['normalized'] unnormalized_embeddings_dict = embeddings_state['unnormalized'] if", "of words :param x_list: List of corresponding pt x positions", "embedding_property) is None: return if embedding_property == 'unprojected_embedding': embeddings =", "int(round((bbox[0] + bbox[2]) * document.width)) image_of_crop = document.image[max(0, y_min):min(y_max, document.height),", "is_extent_x_intersect(e1, e2) and is_extent_y_intersect(e1, e2) min_x, max_x = min(x_list), max(x_list)", "i in range(embeddings_2d.shape[0])] push_pull_ratio = embeddings_state['push_pull_ratio'] scatter_data.append((epoch, x_list, y_list, push_pull_ratio))", "height, y_list[point_index] + dist_from_pt overlap = True while overlap: overlap", "min_y = min(min(scatter_data, key=lambda entry: min(entry[2]))[2]) max_y = max(max(scatter_data, key=lambda", "words] embeddings_array = np.array(embeddings).squeeze() num_pca_comp = 2 embeddings_2d = PCA(n_components=num_pca_comp).fit_transform(embeddings_array)", "embeddings.append(unprojected_embedding) else: embeddings = [getattr(word, embedding_property).detach().cpu().numpy() for word in words]", "else: embeddings = [getattr(word, embedding_property).detach().cpu().numpy() for word in words] colors_palette", "for word in self.document.get_words()] # list of singleton word lists", "in indices_to_crops.items(): extent = indices_to_extents[point_index] rect = patches.Rectangle((extent.left, extent.top), extent.right-extent.left,", "x_list, y_list, dist_from_pt=0.01, height=0.02): \"\"\" Calculates the positions and dimensions", "'unprojected_embedding': plot_title = 'Initial unprojected embeddings, pre training (PCA)' else:", "# Plot points if embedding_property == 'unprojected_embedding': plot_title = 'Initial", "for state_idx, embeddings_state in enumerate(embeddings_history): epoch = state_idx + 1", "embeddings_state in enumerate(embeddings_history): epoch = state_idx + 1 normalized_embeddings_dict =", "max(max(scatter_data, key=lambda entry: max(entry[1]))[1]) min_y = min(min(scatter_data, key=lambda entry: min(entry[2]))[2])", "patches.Rectangle((x, y), width, height, linewidth=2, edgecolor=edge_color, facecolor=face_color, alpha=0.4) ax.add_patch(rect) @staticmethod", "selected set so far distances_accumulator = np.zeros(len(cluster.words)) # Sample first", "furthrest_point_from_set = np.argmax(distances_accumulator, axis=0) selected_points.append(furthrest_point_from_set) selected_words = [cluster.words[point] for point", "if len(words) == 0 or getattr(words[0], embedding_property) is None: return", "aspect='auto', alpha=0.65, extent=extent, zorder=4) ax.add_patch(rect) # Plot points if embedding_property", "squareform(pairwise_distances) # Total distance from selected set so far distances_accumulator", "crop in indices_to_crops.items(): extent = indices_to_extents[point_index] rect = patches.Rectangle((extent.left, extent.top),", "int(round((bbox[1] + bbox[3]) * document.height)) x_min = int(round(bbox[0] * document.width))", "Load background image self.image_path = document.image_path self.img = plt.imread(self.image_path) self.img_opencv", "{} for cluster, cluster_solution in solution_per_cluster.items(): for word_index, word in", "in words] colors_palette = VisHandler.generate_colors_list(amount=len(clusters)) word_to_color = {word: colors_palette[cluster_idx] for", "for word in words] chosen_embedding = unnormalized_embeddings else: return embeddings_array", "= embeddings_state['normalized'] unnormalized_embeddings_dict = embeddings_state['unnormalized'] if len(normalized_embeddings_dict) > 0: normalized_embeddings", "PlotsProducer._extract_crops_per_cluster_solution(document, selected_word_crops_per_cluster) indices_to_extents = PlotsProducer._space_out_crops(indices_to_crops, words, x_list, y_list, dist_from_pt=0.02, height=0.04)", "and performs a naive linear comparison for each crop. :param", "# Eliminate last point selected from distance matrix & accumulator", "None for embedding_property in embedding_properties: if embedding_property == 'unprojected_embedding': #", "max_y += (max_y - min_y) * padding_factor frames = []", ":param x_list: List of corresponding pt x positions :param y_list:", "Converts from list of labels to list of list of", "figsize=self.figsize) monochrome_colors_list = ['#5a5d8f' for _ in self.document.get_words()] self._draw_entity_bounding_boxes(fig=fig, ax=ax,", "bbox = word.get_bbox() # left, top, width, height y_min =", "Ignore non-clustered words continue cluster_idx = cluster_id_to_cluster_idx[cluster_id] set_of_clusters[cluster_idx].append(word) self._save_set_of_clusters(set_of_clusters, colors_list)", "min_x) * dist_from_pt for point_index, crop in indices_to_crops.items(): word_aspect_ratio =", "\"\"\" Greedy approximation algorithm for finding k furthest neighbour words", "in words] embeddings_array = np.array(embeddings).squeeze() num_pca_comp = 2 embeddings_2d =", "plot clusters on original image self.save_clustering_results(with_title=False, colors_list=colors_palette) return colors_palette @staticmethod", "enumerate(embeddings_history): epoch = state_idx + 1 normalized_embeddings_dict = embeddings_state['normalized'] unnormalized_embeddings_dict", "max(x_list) min_y, max_y = min(y_list), max(y_list) height = (max_y -", "e2.right) is_extent_y_intersect = lambda e1, e2: not (e1.top > e2.bottom", "@staticmethod def animate_pca_embedding_space_for_clusters(document, output_path, embeddings_history, colors_palette=None): \"\"\" Plot 2d PCA", "each crop. :param indices_to_crops: dict of word index (by order", "linewidth=2, edgecolor=edge_color, facecolor=face_color, alpha=0.4) ax.add_patch(rect) @staticmethod def plot_pca_embedding_space_for_clusters(document, output_path, embedding_property='embedding',", "ax.set_title(title) plt.tick_params(axis='both', which='both', bottom='off', top='off', labelbottom='off', right='off', left='off', labelleft='off') plt.imshow(bg_img)", "self.document.get_words()] self._draw_entity_bounding_boxes(fig=fig, ax=ax, bg_img=self.img, title='', entity_sets=set_of_words, colors_list=monochrome_colors_list) fig.savefig(os.path.join(self.output_path, self.document.basename +", "= [embeddings_2d[i, 1] for i in range(embeddings_2d.shape[0])] fig, ax =", "return colors_palette @staticmethod def animate_pca_embedding_space_for_clusters(document, output_path, embeddings_history, colors_palette=None): \"\"\" Plot", "embeddings_state['unnormalized'] if len(normalized_embeddings_dict) > 0: normalized_embeddings = [normalized_embeddings_dict[word].detach().cpu().numpy() for word", "[[phrase] for phrase in self.document.get_phrases()] # list of singleton phrase", "e1.left > e2.right) is_extent_y_intersect = lambda e1, e2: not (e1.top", "= y_list[point_index] + dist_from_pt + height, y_list[point_index] + dist_from_pt overlap", "dimensions of crop images on the embedding space plot. Makes", "the crop, in figure axes dimensions (note: for normalized pca", "dimensions (note: for normalized pca space: -1 to 1) :return:", "self.document.basename + '_clustering.png'), output_img) @staticmethod def _draw_entity_bounding_boxes_opencv(bg_img, entity_sets, colors_list=None): img_height", "self.img = plt.imread(self.image_path) self.img_opencv = cv2.imread(self.image_path) dpi = 120 mpl.rcParams['figure.dpi']", "True # shift below if other_bottom <= top <= other_top:", "'unprojected_embedding' :return: \"\"\" if not os.path.exists(output_path): os.makedirs(output_path) words = document.get_words()", "y_list[point_index] + dist_from_pt overlap = True while overlap: overlap =", "figure axes dimensions (note: for normalized pca space: -1 to", "entity.geometry.top * img_height width = entity.geometry.width * img_width height =", "= ClusterSolution(word_indices=selected_word_indices, words=selected_words) return solution_per_cluster @staticmethod def _extract_crops_per_cluster_solution(document, solution_per_cluster): \"\"\"", "return output_img @staticmethod def _draw_entity_bounding_boxes(fig, ax, bg_img, title, entity_sets, colors_list=None):", "How many points we need to add points_to_calc_count = min(k", "entity_sets=set_of_phrases) fig.savefig(os.path.join(self.output_path, self.document.basename + '_phrase_detection.png')) plt.close(fig) def save_clustering_results(self, with_title=True, colors_list=None):", "def _draw_entity_bounding_boxes_opencv(bg_img, entity_sets, colors_list=None): img_height = bg_img.shape[0] img_width = bg_img.shape[1]", "(PCA)' else: plot_title = unprojected_caption plt.title(plot_title) plt.scatter(x_list, y_list, c=colors, s=18,", "in solution_per_cluster.items(): for word_index, word in zip(cluster_solution.word_indices, cluster_solution.words): bbox =", "self._draw_entity_bounding_boxes_opencv(bg_img=self.img_opencv, entity_sets=set_of_clusters, colors_list=colors_list) cv2.imwrite(os.path.join(self.output_path, self.document.basename + '_clustering.png'), output_img) @staticmethod def", "words] scatter_data = [] for state_idx, embeddings_state in enumerate(embeddings_history): epoch", "self.image_path = document.image_path self.img = plt.imread(self.image_path) self.img_opencv = cv2.imread(self.image_path) dpi", "extent=extent, zorder=4) ax.add_patch(rect) # Plot points if embedding_property == 'unprojected_embedding':", "min_x -= (max_x - min_x) * padding_factor max_x += (max_x", "= plt.subplots(1, figsize=self.figsize) monochrome_colors_list = ['#5a5d8f' for _ in self.document.get_words()]", "for word in cluster.words] all_cluster_embeddings = np.take(embeddings_2d, all_cluster_embeddings_indices, axis=0) pairwise_distances", "VisHandler.generate_colors_list(amount=len(clusters)) word_to_color = {word: colors_palette[cluster_idx] for cluster_idx, cluster in enumerate(clusters)", "= min(x_list), max(x_list) min_y, max_y = min(y_list), max(y_list) height =", "height dist_from_pt = min(max_y - min_y, max_x - min_x) *", "other_bottom, other_top = other_crop_extent spaceout_margin = dist_from_pt / 2 if", "height continue indices_to_extents[point_index] = extent return indices_to_extents def plot_clusters_and_embedding_space_with_crops(self, document,", "# draw the canvas, cache the renderer output_frame = np.frombuffer(fig.canvas.tostring_rgb(),", "/ (max_y-min_y) / 2 width = height * word_aspect_ratio *", "0.8 for set_idx, entities_set in enumerate(entity_sets): face_color = face_colors[set_idx] edge_color", "np.unique(np.array(clustering_labels)) cluster_id_to_cluster_idx = {cluster_id: idx for idx, cluster_id in enumerate(cluster_ids)}", "pt y positions :param dist_from_pt: How far in (x-y) coords", "plot_pca_embedding_space_for_clusters(document, output_path, embedding_property='embedding', title=''): \"\"\" Plot 2d PCA visualization of", "'right', 'bottom', 'top']) is_extent_x_intersect = lambda e1, e2: not (e1.right", "colors_palette[cluster_idx] for cluster_idx, cluster in enumerate(clusters) for word in cluster.words}", "list of labels to list of list of words (clusters)", "other_bottom + spaceout_margin bottom = top + height else: #", "indices_to_extents def plot_clusters_and_embedding_space_with_crops(self, document, output_path, crops_per_cluster=3, embedding_properties=['embedding', 'unprojected_embedding'], unprojected_caption=None): \"\"\"", "= entity.geometry.left * img_width y = entity.geometry.top * img_height width", "Used to return the plot as an image rray fig.tight_layout()", "top='off', labelbottom='off', right='off', left='off', labelleft='off') ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) fig.tight_layout() fig.savefig(os.path.join(output_path, document.basename", "entities_set in enumerate(entity_sets): face_color = face_colors[set_idx] edge_color = edge_colors[set_idx] for", "'bottom', 'top']) is_extent_x_intersect = lambda e1, e2: not (e1.right <", "return indices_to_extents def plot_clusters_and_embedding_space_with_crops(self, document, output_path, crops_per_cluster=3, embedding_properties=['embedding', 'unprojected_embedding'], unprojected_caption=None):", ":param y_list: List of corresponding pt y positions :param dist_from_pt:", "colors_list edge_colors = VisHandler.generate_darker_palette(colors_list) output_img = bg_img.copy() alpha = 0.8", "plt.subplots(1, figsize=self.figsize) monochrome_colors_list = ['#5a5d8f' for _ in self.document.get_words()] self._draw_entity_bounding_boxes(fig=fig,", ":param document: Document with clustering results :param embedding_property: Embedding property", "or e1.bottom < e2.top) is_extent_intersect = lambda e1, e2: is_extent_x_intersect(e1,", "How far in (x-y) coords the crop should be placed", "padding_factor max_x += (max_x - min_x) * padding_factor min_y -=", "is_extent_intersect = lambda e1, e2: is_extent_x_intersect(e1, e2) and is_extent_y_intersect(e1, e2)", "in self.document.get_words()] # list of singleton word lists fig, ax", "/ float(dpi) # Fig size in inches self.document = document", "unprojected_caption=None): \"\"\" Plot 2d PCA visualization of the embedding space", "in range(embeddings_2d.shape[0])] fig, ax = plt.subplots(1) if crops_per_cluster > 0:", "last point selected from distance matrix & accumulator distances_matrix[:, random_index]", "[[] for _ in range(len(cluster_ids))] for word_idx, word in enumerate(self.document.get_words()):", "ax, bg_img, title, entity_sets, colors_list=None): ax.set_title(title) plt.tick_params(axis='both', which='both', bottom='off', top='off',", "# Ignore non-clustered words continue cluster_idx = cluster_id_to_cluster_idx[cluster_id] set_of_clusters[cluster_idx].append(word) self._save_set_of_clusters(set_of_clusters,", "+ bbox[3]) * document.height)) x_min = int(round(bbox[0] * document.width)) x_max", "len(words) == 0 or getattr(words[0], embedding_property) is None: return if", "colors_list=colors_list) cv2.imwrite(os.path.join(self.output_path, self.document.basename + '_clustering.png'), output_img) @staticmethod def _draw_entity_bounding_boxes_opencv(bg_img, entity_sets,", "def save_clustering_results(self, with_title=True, colors_list=None): set_of_clusters = [cluster.words for cluster in", "[[word] for word in self.document.get_words()] # list of singleton word", "lists fig, ax = plt.subplots(1, figsize=self.figsize) monochrome_colors_list = ['#5a5d8f' for", "and dimensions of crop images on the embedding space plot.", "= np.array(embeddings).squeeze() num_pca_comp = 2 embeddings_2d = PCA(n_components=num_pca_comp).fit_transform(embeddings_array) x_list =", "(PCA)' plt.title(plot_title) plt.scatter(x_list, y_list, c=colors, s=18, alpha=1.0, edgecolors='black', linewidth=1.0, zorder=3)", "edge_colors = VisHandler.generate_darker_palette(colors_list) output_img = bg_img.copy() alpha = 0.8 for", "y_list = [embeddings_2d[i, 1] for i in range(embeddings_2d.shape[0])] fig, ax", "word in zip(cluster_solution.word_indices, cluster_solution.words): bbox = word.get_bbox() # left, top,", ":return: \"\"\" output_img = self._draw_entity_bounding_boxes_opencv(bg_img=self.img_opencv, entity_sets=set_of_clusters, colors_list=colors_list) cv2.imwrite(os.path.join(self.output_path, self.document.basename +", "the embedding space according to cluster colors. :param document: Document", "cluster_id_to_cluster_idx[cluster_id] set_of_clusters[cluster_idx].append(word) self._save_set_of_clusters(set_of_clusters, colors_list) def _save_set_of_clusters(self, set_of_clusters, with_title=True, colors_list=None): \"\"\"", "dist_from_pt=0.01, height=0.02): \"\"\" Calculates the positions and dimensions of crop", "= lambda e1, e2: not (e1.right < e2.left or e1.left", "= 'Projected embeddings at epoch #' + str(epoch) + '", "point random_index = randrange(len(cluster.words)) # Indices of selected points selected_points", "set_of_words = [[word] for word in self.document.get_words()] # list of", "for cluster in self.document.get_clusters()] # list of list of words", "embedding_properties]): return colors_palette = VisHandler.generate_colors_list(amount=len(clusters)) word_to_color = {word: colors_palette[cluster_idx] for", "None: # Calculate per first attribute selected_word_crops_per_cluster = PlotsProducer._find_k_furthest_words_per_cluster(document, embeddings_2d,", "+ '_' + embedding_property + '_pca.png')) plt.close(fig) # Finally plot", "PlotsProducer._space_out_crops(indices_to_crops, words, x_list, y_list, dist_from_pt=0.02, height=0.04) # Plot crop images", "accumulator with distance collected from last point distances_accumulator += distances_matrix[last_point_selected]", "as an image rray fig.tight_layout() fig.canvas.draw() # draw the canvas,", "# Required for gif animations import matplotlib as mpl import", "to cluster colors. :param document: Document with clustering results :param", "Sample first point random_index = randrange(len(cluster.words)) # Indices of selected", "words, x_list, y_list, dist_from_pt=0.01, height=0.02): \"\"\" Calculates the positions and", "document.get_clusters() if len(words) == 0 or \\ all([getattr(words[0], embedding_property) is", "/ 2 if is_extent_intersect(extent, other_crop_extent): overlap = True # shift", "plot_title = 'Projected embeddings, post training (PCA)' else: plot_title =", "np.zeros(len(cluster.words)) # Sample first point random_index = randrange(len(cluster.words)) # Indices", "@staticmethod def plot_pca_embedding_space_for_clusters(document, output_path, embedding_property='embedding', title=''): \"\"\" Plot 2d PCA", "the embedding space plot. Makes sure crops don't overlay each", "the canvas, cache the renderer output_frame = np.frombuffer(fig.canvas.tostring_rgb(), dtype='uint8') output_frame", "of crop images on the embedding space plot. Makes sure", "min(entry[2]))[2]) max_y = max(max(scatter_data, key=lambda entry: max(entry[2]))[2]) padding_factor = 0.1", "in cluster.words} colors = [word_to_color[word] for word in words] embeddings_array", "min(y_list), max(y_list) height = (max_y - min_y) * height dist_from_pt", "for word in selected_words] solution_per_cluster[cluster] = ClusterSolution(word_indices=selected_word_indices, words=selected_words) return solution_per_cluster", "word in words: unprojected_embedding = torch.cat(word.unprojected_embedding['embeddings'], dim=1) unprojected_embedding = unprojected_embedding.detach().cpu().numpy()", "['#5a5d8f' for _ in self.document.get_words()] self._draw_entity_bounding_boxes(fig=fig, ax=ax, bg_img=self.img, title='', entity_sets=set_of_words,", "scatter_data: fig, ax = plt.subplots(1) ax.set_xlim(min_x, max_x) ax.set_ylim(min_y, max_y) plot_title", "bottom='off', top='off', labelbottom='off', right='off', left='off', labelleft='off') ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) fig.tight_layout() fig.savefig(os.path.join(output_path,", "many points we need to add points_to_calc_count = min(k -", "+ dist_from_pt + height, y_list[point_index] + dist_from_pt overlap = True", "add points_to_calc_count = min(k - 1, len(words) - 1) for", "to RGB pil_image = pil_image.convert('RGB') word_indices_to_crops[word_index] = pil_image return word_indices_to_crops", "def _save_set_of_clusters(self, set_of_clusters, with_title=True, colors_list=None): \"\"\" :param document: :param set_of_clusters:", "edge_color = edge_colors[set_idx] for entity in entities_set: x = entity.geometry.left", "= dpi height = self.img.shape[0] width = self.img.shape[1] self.figsize =", "selected_words] solution_per_cluster[cluster] = ClusterSolution(word_indices=selected_word_indices, words=selected_words) return solution_per_cluster @staticmethod def _extract_crops_per_cluster_solution(document,", "= PCA(n_components=num_pca_comp).fit_transform(embeddings_array) x_list = [embeddings_2d[i, 0] for i in range(embeddings_2d.shape[0])]", "word index to extens describing position and dimensions of each", "property we process will set those for all figures selected_word_crops_per_cluster", "dict of word index to extens describing position and dimensions", "point_index, crop in indices_to_crops.items(): word_aspect_ratio = words[point_index].geometry.width / words[point_index].geometry.height axis_ratio", "plot_title = 'Projected embeddings at epoch #' + str(epoch) +", "state_idx, embeddings_state in enumerate(embeddings_history): epoch = state_idx + 1 normalized_embeddings_dict", "for embedding_property in embedding_properties: if embedding_property == 'unprojected_embedding': # Can't", "PCA from scipy.spatial.distance import pdist, squareform import torch import matplotlib", "from collections import namedtuple import imageio from PIL import Image", "title='', entity_sets=set_of_words, colors_list=monochrome_colors_list) fig.savefig(os.path.join(self.output_path, self.document.basename + '_word_boxes.png')) plt.close(fig) def save_phrase_detection_results(self):", "False extent = MatplotExtent(left, right, bottom, top) for other_crop_extent in", "shift below if other_bottom <= top <= other_top: top =", "= colors_list edge_colors = VisHandler.generate_darker_palette(colors_list) for set_idx, entities_set in enumerate(entity_sets):", "indices_to_crops is None: # Calculate per first attribute selected_word_crops_per_cluster =", "width = entity.geometry.width * img_width height = entity.geometry.height * img_height", "width = height * word_aspect_ratio * axis_ratio left, right =", "singleton phrase lists fig, ax = plt.subplots(1, figsize=self.figsize) self._draw_entity_bounding_boxes(fig=fig, ax=ax,", "word_aspect_ratio * axis_ratio left, right = x_list[point_index] + dist_from_pt, x_list[point_index]", "= plt.subplots(1, figsize=self.figsize) self._draw_entity_bounding_boxes(fig=fig, ax=ax, bg_img=self.img, title='Phrase Detection', entity_sets=set_of_phrases) fig.savefig(os.path.join(self.output_path,", "[] for word in words: unprojected_embedding = torch.cat(word.unprojected_embedding['embeddings'], dim=1) unprojected_embedding", "0: normalized_embeddings = [normalized_embeddings_dict[word].detach().cpu().numpy() for word in words] chosen_embedding =", "height = entity.geometry.height * img_height # writing the text onto", "= pil_image.convert('RGB') word_indices_to_crops[word_index] = pil_image return word_indices_to_crops @staticmethod def _space_out_crops(indices_to_crops,", "0 or getattr(words[0], embedding_property) is None: return if embedding_property ==", "each crop. Crops are shifted so they don't cover each", "* word_aspect_ratio * axis_ratio left, right = x_list[point_index] + dist_from_pt,", "or its affiliates. All Rights Reserved. # SPDX-License-Identifier: CC-BY-4.0 import", "extent.bottom-extent.top, linewidth=0.5, edgecolor=\"black\", facecolor=\"none\", zorder=5) ax.imshow(crop, aspect='auto', alpha=0.65, extent=extent, zorder=4)", "colors_list) def save_clustering_labels(self, clustering_labels, colors_list=None): cluster_ids = np.unique(np.array(clustering_labels)) cluster_id_to_cluster_idx =", "ax=ax, bg_img=self.img, title='', entity_sets=set_of_words, colors_list=monochrome_colors_list) fig.savefig(os.path.join(self.output_path, self.document.basename + '_word_boxes.png')) plt.close(fig)", "_ in self.document.get_words()] self._draw_entity_bounding_boxes(fig=fig, ax=ax, bg_img=self.img, title='', entity_sets=set_of_words, colors_list=monochrome_colors_list) fig.savefig(os.path.join(self.output_path,", "= torch.cat(word.unprojected_embedding['embeddings'], dim=1) unprojected_embedding = unprojected_embedding.detach().cpu().numpy() embeddings.append(unprojected_embedding) else: embeddings =", "of corresponding pt y positions :param dist_from_pt: How far in", "os.makedirs(output_path) def plot_word_boxes_on_image(self): set_of_words = [[word] for word in self.document.get_words()]", "def save_clustering_labels(self, clustering_labels, colors_list=None): cluster_ids = np.unique(np.array(clustering_labels)) cluster_id_to_cluster_idx = {cluster_id:", "range(points_to_calc_count): last_point_selected = selected_points[-1] # Update accumulator with distance collected", "crop images on the embedding space plot. Makes sure crops", "+ height)), (rgb_color[2], rgb_color[1], rgb_color[0]), cv2.FILLED) output_img = cv2.addWeighted(output_img, alpha,", "dimensions of each crop. Crops are shifted so they don't", "if not os.path.exists(output_path): os.makedirs(output_path) def plot_word_boxes_on_image(self): set_of_words = [[word] for", "-1 to 1) :return: indices_to_extents: dict of word index to", "document.get_words() word_to_embedding_2d_idx = {word: idx for idx, word in enumerate(words)}", "plot_title = 'Initial unprojected embeddings, pre training (PCA)' else: if", "\"\"\" :param document: :param set_of_clusters: list of list of words", "= Image.fromarray(image_of_crop[...,::-1]) # BGR to RGB pil_image = pil_image.convert('RGB') word_indices_to_crops[word_index]", "'_phrase_detection.png')) plt.close(fig) def save_clustering_results(self, with_title=True, colors_list=None): set_of_clusters = [cluster.words for", "axes dimensions (note: for normalized pca space: -1 to 1)", "so they don't cover each other, \"\"\" indices_to_extents = {}", "cover each other, \"\"\" indices_to_extents = {} MatplotExtent = namedtuple('matplot_extent',", "= np.unique(np.array(clustering_labels)) cluster_id_to_cluster_idx = {cluster_id: idx for idx, cluster_id in", "for i in range(embeddings_2d.shape[0])] y_list = [embeddings_2d[i, 1] for i", "= [word_to_color[word] for word in words] scatter_data = [] for", "output_path if not os.path.exists(output_path): os.makedirs(output_path) def plot_word_boxes_on_image(self): set_of_words = [[word]", "distances_matrix = squareform(pairwise_distances) # Total distance from selected set so", "- min_x) * padding_factor max_x += (max_x - min_x) *", "don't cover each other, \"\"\" indices_to_extents = {} MatplotExtent =", "colors = [word_to_color[word] for word in words] scatter_data = []", "- min_y) * padding_factor max_y += (max_y - min_y) *", "PlotsProducer._find_k_furthest_words_per_cluster(document, embeddings_2d, k=crops_per_cluster) indices_to_crops = PlotsProducer._extract_crops_per_cluster_solution(document, selected_word_crops_per_cluster) indices_to_extents = PlotsProducer._space_out_crops(indices_to_crops,", "in scatter_data: fig, ax = plt.subplots(1) ax.set_xlim(min_x, max_x) ax.set_ylim(min_y, max_y)", "ax = plt.subplots(1) plot_title = embedding_property if plot_title != '':", "colors = [word_to_color[word] for word in words] # Initially empty,", "embeddings = [getattr(word, embedding_property).detach().cpu().numpy() for word in words] colors_palette =", "self.img.shape[0] width = self.img.shape[1] self.figsize = width / float(dpi), height", "embeddings = [getattr(word, embedding_property).detach().cpu().numpy() for word in words] embeddings_array =", "float(dpi), height / float(dpi) # Fig size in inches self.document", "len(unnormalized_embeddings_dict) > 0: unnormalized_embeddings = [unnormalized_embeddings_dict[word].detach().cpu().numpy() for word in words]", "torch import matplotlib matplotlib.use('Agg') # Required for gif animations import", "cluster_id in enumerate(cluster_ids)} # Converts from list of labels to", "for phrase in self.document.get_phrases()] # list of singleton phrase lists", "plot_title != '': plot_title += ': ' + title plt.title(plot_title)", "if embedding_property == 'unprojected_embedding': # Can't handle tuples, concat them", "is_extent_intersect(extent, other_crop_extent): overlap = True # shift below if other_bottom", "below if other_bottom <= top <= other_top: top = other_bottom", "= normalized_embeddings elif len(unnormalized_embeddings_dict) > 0: unnormalized_embeddings = [unnormalized_embeddings_dict[word].detach().cpu().numpy() for", "from PIL import Image from random import randrange import numpy", "embedding_property if plot_title != '': plot_title += ': ' +", ":param document: :param solution_per_cluster: Solution of k-furthest neighbours :return: \"\"\"", "which='both', bottom='off', top='off', labelbottom='off', right='off', left='off', labelleft='off') plt.imshow(bg_img) img_height =", "<= other_top: top = other_bottom + spaceout_margin bottom = top", "in enumerate(embeddings_history): epoch = state_idx + 1 normalized_embeddings_dict = embeddings_state['normalized']", "expected to be relatively small (< 100) \"\"\" words =", "max_x += (max_x - min_x) * padding_factor min_y -= (max_y", "def plot_pca_embedding_space_for_clusters(document, output_path, embedding_property='embedding', title=''): \"\"\" Plot 2d PCA visualization", "if colors_palette is None: colors_palette = VisHandler.generate_colors_list(amount=len(clusters)) word_to_color = {word:", "Total distance from selected set so far distances_accumulator = np.zeros(len(cluster.words))", "of crops (< 1000) and performs a naive linear comparison", "crops_per_cluster > 0: if selected_word_crops_per_cluster is None and indices_to_crops is", "= bg_img.shape[1] if colors_list is None: colors_list = VisHandler.generate_colors_list(amount=len(entity_sets)) face_colors", "or len(embeddings_history) == 0: return if colors_palette is None: colors_palette", "Document with clustering results :param embedding_property: Embedding property of words", "if other_bottom <= top <= other_top: top = other_bottom +", "the positions and dimensions of crop images on the embedding", "set_of_clusters, with_title=True, colors_list=None): \"\"\" :param document: :param set_of_clusters: list of", "embeddings_array = np.array(chosen_embedding).squeeze() num_pca_comp = 2 embeddings_2d = PCA(n_components=num_pca_comp).fit_transform(embeddings_array) x_list", "ax.get_yaxis().set_visible(False) fig.tight_layout() fig.savefig(os.path.join(output_path, document.basename + '_' + embedding_property + '_pca.png'))", "labelleft='off') ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) fig.tight_layout() fig.savefig(os.path.join(output_path, document.basename + '_' + embedding_property", "max_y) plot_title = 'Projected embeddings at epoch #' + str(epoch)", "set_of_clusters = [cluster.words for cluster in self.document.get_clusters()] # list of", "(clusters) set_of_clusters = [[] for _ in range(len(cluster_ids))] for word_idx,", "+ ' (PCA)' plt.title(plot_title) plt.scatter(x_list, y_list, c=colors, s=18, alpha=1.0, edgecolors='black',", "for entity in entities_set: x = entity.geometry.left * img_width y", "1, len(words) - 1) for _ in range(points_to_calc_count): last_point_selected =", "mpl.rcParams['figure.dpi'] = dpi height = self.img.shape[0] width = self.img.shape[1] self.figsize", "Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier:", "= unprojected_caption plt.title(plot_title) plt.scatter(x_list, y_list, c=colors, s=18, alpha=1.0, edgecolors='black', linewidth=1.0,", "epoch = state_idx + 1 normalized_embeddings_dict = embeddings_state['normalized'] unnormalized_embeddings_dict =", "= embeddings_state['unnormalized'] if len(normalized_embeddings_dict) > 0: normalized_embeddings = [normalized_embeddings_dict[word].detach().cpu().numpy() for", "s=18, alpha=1.0, edgecolors='black', linewidth=1.0, zorder=3) plt.tick_params(axis='both', which='both', bottom='off', top='off', labelbottom='off',", "in range(embeddings_2d.shape[0])] y_list = [embeddings_2d[i, 1] for i in range(embeddings_2d.shape[0])]", "height = (max_y - min_y) * height dist_from_pt = min(max_y", "for cluster in clusters: # Generate cluster pairwise distances matrix", "(note: for normalized pca space: -1 to 1) :return: indices_to_extents:", "ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) fig.tight_layout() fig.savefig(os.path.join(output_path, document.basename + '_' + embedding_property +", "post training (PCA)' else: plot_title = unprojected_caption plt.title(plot_title) plt.scatter(x_list, y_list,", "= (max_y - min_y) * height dist_from_pt = min(max_y -", "np.array(chosen_embedding).squeeze() num_pca_comp = 2 embeddings_2d = PCA(n_components=num_pca_comp).fit_transform(embeddings_array) x_list = [embeddings_2d[i,", "os.path.exists(output_path): os.makedirs(output_path) words = document.get_words() clusters = document.get_clusters() if len(words)", "Calculates the positions and dimensions of crop images on the", "words (clusters) self._save_set_of_clusters(set_of_clusters, with_title, colors_list) def save_clustering_labels(self, clustering_labels, colors_list=None): cluster_ids", "phrase lists fig, ax = plt.subplots(1, figsize=self.figsize) self._draw_entity_bounding_boxes(fig=fig, ax=ax, bg_img=self.img,", "indices_to_extents = {} MatplotExtent = namedtuple('matplot_extent', ['left', 'right', 'bottom', 'top'])", "axis=0) pairwise_distances = pdist(all_cluster_embeddings, metric='euclidean') distances_matrix = squareform(pairwise_distances) # Total", "of selected points selected_points = [random_index] # How many points", "str(epoch) + ' (PCA)' plt.title(plot_title) plt.scatter(x_list, y_list, c=colors, s=18, alpha=1.0,", "positions and dimensions of crop images on the embedding space", "words - normally 'embedding' or 'unprojected_embedding' :return: \"\"\" if not", "list of list of words (clusters) self._save_set_of_clusters(set_of_clusters, with_title, colors_list) def", "(clusters) self._save_set_of_clusters(set_of_clusters, with_title, colors_list) def save_clustering_labels(self, clustering_labels, colors_list=None): cluster_ids =", "index to extens describing position and dimensions of each crop.", "[normalized_embeddings_dict[word].detach().cpu().numpy() for word in words] chosen_embedding = normalized_embeddings elif len(unnormalized_embeddings_dict)", "2d PCA visualization of the embedding space according to cluster", "words = document.get_words() word_to_embedding_2d_idx = {word: idx for idx, word", "bottom, top) for other_crop_extent in indices_to_extents.values(): other_left, other_right, other_bottom, other_top", "other_top - spaceout_margin top = bottom - height continue indices_to_extents[point_index]", "matplotlib as mpl import matplotlib.pyplot as plt import matplotlib.image as", "those for all figures selected_word_crops_per_cluster = None indices_to_crops = None", "= embedding_property if plot_title != '': plot_title += ': '", "0 or embeddings_history is None or len(embeddings_history) == 0: return", "pairwise distances matrix all_cluster_embeddings_indices = [word_to_embedding_2d_idx[word] for word in cluster.words]", "This method assumes a small number of crops (< 1000)", "colors_list = VisHandler.generate_colors_list(amount=len(entity_sets)) face_colors = colors_list edge_colors = VisHandler.generate_darker_palette(colors_list) output_img", "* document.width)) x_max = int(round((bbox[0] + bbox[2]) * document.width)) image_of_crop", "min_x) * padding_factor min_y -= (max_y - min_y) * padding_factor", "solution_per_cluster[cluster] = ClusterSolution(word_indices=selected_word_indices, words=selected_words) return solution_per_cluster @staticmethod def _extract_crops_per_cluster_solution(document, solution_per_cluster):", "min(k - 1, len(words) - 1) for _ in range(points_to_calc_count):", "assumes a small number of crops (< 1000) and performs", "bottom, top = y_list[point_index] + dist_from_pt + height, y_list[point_index] +", "document.height), max(0, x_min):min(x_max, document.width), :] pil_image = Image.fromarray(image_of_crop[...,::-1]) # BGR", "is None: # Calculate per first attribute selected_word_crops_per_cluster = PlotsProducer._find_k_furthest_words_per_cluster(document,", "with clustering results :param embedding_property: Embedding property of words -", "naive linear comparison for each crop. :param indices_to_crops: dict of", "selected_word_crops_per_cluster) indices_to_extents = PlotsProducer._space_out_crops(indices_to_crops, words, x_list, y_list, dist_from_pt=0.02, height=0.04) #", "right='off', left='off', labelleft='off') plt.imshow(bg_img) img_height = bg_img.shape[0] img_width = bg_img.shape[1]", "labelbottom='off', right='off', left='off', labelleft='off') ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) # Used to return", "# list of singleton word lists fig, ax = plt.subplots(1,", "or e1.left > e2.right) is_extent_y_intersect = lambda e1, e2: not", "entry: min(entry[1]))[1]) max_x = max(max(scatter_data, key=lambda entry: max(entry[1]))[1]) min_y =", "CC-BY-4.0 import os import cv2 from collections import namedtuple import", "_ in range(len(cluster_ids))] for word_idx, word in enumerate(self.document.get_words()): cluster_id =", "document.get_clusters() solution_per_cluster = {} ClusterSolution = namedtuple('ClusterSolution', ['word_indices', 'words']) for", "# shift above bottom = other_top - spaceout_margin top =", "is None: return if embedding_property == 'unprojected_embedding': embeddings = []", "distances_accumulator += distances_matrix[last_point_selected] # Eliminate last point selected from distance", "= np.take(embeddings_2d, all_cluster_embeddings_indices, axis=0) pairwise_distances = pdist(all_cluster_embeddings, metric='euclidean') distances_matrix =", "max_x = min(x_list), max(x_list) min_y, max_y = min(y_list), max(y_list) height", "= PlotsProducer._find_k_furthest_words_per_cluster(document, embeddings_2d, k=crops_per_cluster) indices_to_crops = PlotsProducer._extract_crops_per_cluster_solution(document, selected_word_crops_per_cluster) indices_to_extents =", "word_indices_to_crops = {} for cluster, cluster_solution in solution_per_cluster.items(): for word_index,", "coords the crop should be placed from the plot :param", "cv2.rectangle(output_img, (int(x), int(y)), (int(x + width), int(y + height)), (rgb_color[2],", "- 1) for _ in range(points_to_calc_count): last_point_selected = selected_points[-1] #", "= extent return indices_to_extents def plot_clusters_and_embedding_space_with_crops(self, document, output_path, crops_per_cluster=3, embedding_properties=['embedding',", "multimodal_affinities.visualization.vis_handler import VisHandler from multimodal_affinities.visualization.image_utils import resize_image from multimodal_affinities.visualization.colors_util import", "= 2 embeddings_2d = PCA(n_components=num_pca_comp).fit_transform(embeddings_array) x_list = [embeddings_2d[i, 0] for", "min_x, max_x = min(x_list), max(x_list) min_y, max_y = min(y_list), max(y_list)", "shifted so they don't cover each other, \"\"\" indices_to_extents =", "word in words] colors_palette = VisHandler.generate_colors_list(amount=len(clusters)) word_to_color = {word: colors_palette[cluster_idx]", "is None and indices_to_crops is None: # Calculate per first", "(max_y-min_y) / 2 width = height * word_aspect_ratio * axis_ratio", "cv2.FILLED) output_img = cv2.addWeighted(output_img, alpha, bg_img, 1 - alpha, 0)", "alpha=0.65, extent=extent, zorder=4) ax.add_patch(rect) # Plot points if embedding_property ==", "= other_crop_extent spaceout_margin = dist_from_pt / 2 if is_extent_intersect(extent, other_crop_extent):", "cluster_idx = cluster_id_to_cluster_idx[cluster_id] set_of_clusters[cluster_idx].append(word) self._save_set_of_clusters(set_of_clusters, colors_list) def _save_set_of_clusters(self, set_of_clusters, with_title=True,", "min_y, max_x - min_x) * dist_from_pt for point_index, crop in", "x_list, y_list, push_pull_ratio)) min_x = min(min(scatter_data, key=lambda entry: min(entry[1]))[1]) max_x", "PIL import Image from random import randrange import numpy as", "other_crop_extent spaceout_margin = dist_from_pt / 2 if is_extent_intersect(extent, other_crop_extent): overlap", "pca space: -1 to 1) :return: indices_to_extents: dict of word", "unprojected_embedding.detach().cpu().numpy() embeddings.append(unprojected_embedding) else: embeddings = [getattr(word, embedding_property).detach().cpu().numpy() for word in", "1 normalized_embeddings_dict = embeddings_state['normalized'] unnormalized_embeddings_dict = embeddings_state['unnormalized'] if len(normalized_embeddings_dict) >", "ax=ax, bg_img=self.img, title='Phrase Detection', entity_sets=set_of_phrases) fig.savefig(os.path.join(self.output_path, self.document.basename + '_phrase_detection.png')) plt.close(fig)", "they don't cover each other, \"\"\" indices_to_extents = {} MatplotExtent", "push_pull_ratio in scatter_data: fig, ax = plt.subplots(1) ax.set_xlim(min_x, max_x) ax.set_ylim(min_y,", ":param dist_from_pt: How far in (x-y) coords the crop should", "'Projected embeddings, post training (PCA)' else: plot_title = unprojected_caption plt.title(plot_title)", "corresponding pt y positions :param dist_from_pt: How far in (x-y)", "idx for idx, word in enumerate(words)} clusters = document.get_clusters() solution_per_cluster", "os.path.exists(output_path): os.makedirs(output_path) def plot_word_boxes_on_image(self): set_of_words = [[word] for word in", "for word in words: unprojected_embedding = torch.cat(word.unprojected_embedding['embeddings'], dim=1) unprojected_embedding =", "bg_img=self.img, title='', entity_sets=set_of_words, colors_list=monochrome_colors_list) fig.savefig(os.path.join(self.output_path, self.document.basename + '_word_boxes.png')) plt.close(fig) def", "= {word: idx for idx, word in enumerate(words)} clusters =", "colors = [word_to_color[word] for word in words] embeddings_array = np.array(embeddings).squeeze()", "@staticmethod def _find_k_furthest_words_per_cluster(document, embeddings_2d, k=3): \"\"\" Greedy approximation algorithm for", "= entity.geometry.height * img_height rect = patches.Rectangle((x, y), width, height,", "x_list[point_index] + dist_from_pt, x_list[point_index] + dist_from_pt + width bottom, top", "relatively small (< 100) \"\"\" words = document.get_words() word_to_embedding_2d_idx =", "alpha=1.0, edgecolors='black', linewidth=1.0, zorder=3) plt.tick_params(axis='both', which='both', bottom='off', top='off', labelbottom='off', right='off',", "Fig size in inches self.document = document self.output_path = output_path", "unnormalized_embeddings = [unnormalized_embeddings_dict[word].detach().cpu().numpy() for word in words] chosen_embedding = unnormalized_embeddings", "it rgb_color = rgb_hex_to_tuple(face_color) cv2.rectangle(output_img, (int(x), int(y)), (int(x + width),", "not os.path.exists(output_path): os.makedirs(output_path) def plot_word_boxes_on_image(self): set_of_words = [[word] for word", "embedding_property == 'unprojected_embedding': plot_title = 'Initial unprojected embeddings, pre training", "def _extract_crops_per_cluster_solution(document, solution_per_cluster): \"\"\" Extracts crops for each selected word", "word in words] chosen_embedding = normalized_embeddings elif len(unnormalized_embeddings_dict) > 0:", "len(normalized_embeddings_dict) > 0: normalized_embeddings = [normalized_embeddings_dict[word].detach().cpu().numpy() for word in words]", "point selected from distance matrix & accumulator distances_matrix[:, random_index] =", "* img_height rect = patches.Rectangle((x, y), width, height, linewidth=2, edgecolor=edge_color,", "plt.imshow(bg_img) img_height = bg_img.shape[0] img_width = bg_img.shape[1] if colors_list is", "['left', 'right', 'bottom', 'top']) is_extent_x_intersect = lambda e1, e2: not", "if colors_list is None: colors_list = VisHandler.generate_colors_list(amount=len(entity_sets)) face_colors = colors_list", "overlap: overlap = False extent = MatplotExtent(left, right, bottom, top)", "indices_to_crops = None for embedding_property in embedding_properties: if embedding_property ==", "import rgb_hex_to_tuple class PlotsProducer: def __init__(self, document, output_path): # Load", "save_phrase_detection_results(self): set_of_phrases = [[phrase] for phrase in self.document.get_phrases()] # list", "word in words] embeddings_array = np.array(embeddings).squeeze() num_pca_comp = 2 embeddings_2d", "for idx, word in enumerate(words)} clusters = document.get_clusters() solution_per_cluster =", "in self.document.get_clusters()] # list of list of words (clusters) self._save_set_of_clusters(set_of_clusters,", "# Indices of selected points selected_points = [random_index] # How", "Can't handle tuples, concat them embeddings = [] for word", "left, top, width, height y_min = int(round(bbox[1] * document.height)) y_max", "e2: not (e1.top > e2.bottom or e1.bottom < e2.top) is_extent_intersect", "None or len(embeddings_history) == 0: return if colors_palette is None:", "* padding_factor min_y -= (max_y - min_y) * padding_factor max_y", "cluster_id_to_cluster_idx = {cluster_id: idx for idx, cluster_id in enumerate(cluster_ids)} #", "for _ in range(points_to_calc_count): last_point_selected = selected_points[-1] # Update accumulator", "image self.save_clustering_results(with_title=False, colors_list=colors_palette) return colors_palette @staticmethod def animate_pca_embedding_space_for_clusters(document, output_path, embeddings_history,", "document.basename + '_' + embedding_property + '_pca.png')) plt.close(fig) # Finally", "int(round(bbox[0] * document.width)) x_max = int(round((bbox[0] + bbox[2]) * document.width))", "Eliminate last point selected from distance matrix & accumulator distances_matrix[:,", "= output_frame.reshape(fig.canvas.get_width_height()[::-1] + (3,)) frames.append(output_frame) imageio.mimsave(os.path.join(output_path, document.basename + '_embeddings_history.gif'), frames,", "= 0 furthrest_point_from_set = np.argmax(distances_accumulator, axis=0) selected_points.append(furthrest_point_from_set) selected_words = [cluster.words[point]", "first attribute selected_word_crops_per_cluster = PlotsProducer._find_k_furthest_words_per_cluster(document, embeddings_2d, k=crops_per_cluster) indices_to_crops = PlotsProducer._extract_crops_per_cluster_solution(document,", "images on the embedding space plot. Makes sure crops don't", "list of singleton word lists fig, ax = plt.subplots(1, figsize=self.figsize)", "= min(min(scatter_data, key=lambda entry: min(entry[2]))[2]) max_y = max(max(scatter_data, key=lambda entry:", "selected_points[-1] # Update accumulator with distance collected from last point", "lists fig, ax = plt.subplots(1, figsize=self.figsize) self._draw_entity_bounding_boxes(fig=fig, ax=ax, bg_img=self.img, title='Phrase", "= [[word] for word in self.document.get_words()] # list of singleton", "y_list: List of corresponding pt y positions :param dist_from_pt: How", "rgb_color[1], rgb_color[0]), cv2.FILLED) output_img = cv2.addWeighted(output_img, alpha, bg_img, 1 -", "an image rray fig.tight_layout() fig.canvas.draw() # draw the canvas, cache", "(max_x - min_x) * padding_factor min_y -= (max_y - min_y)", "in (x-y) coords the crop should be placed from the", "- height continue indices_to_extents[point_index] = extent return indices_to_extents def plot_clusters_and_embedding_space_with_crops(self,", "+ width), int(y + height)), (rgb_color[2], rgb_color[1], rgb_color[0]), cv2.FILLED) output_img", "alpha=0.4) ax.add_patch(rect) @staticmethod def plot_pca_embedding_space_for_clusters(document, output_path, embedding_property='embedding', title=''): \"\"\" Plot", "dist_from_pt overlap = True while overlap: overlap = False extent", "-= (max_y - min_y) * padding_factor max_y += (max_y -", "[word_to_embedding_2d_idx[word] for word in selected_words] solution_per_cluster[cluster] = ClusterSolution(word_indices=selected_word_indices, words=selected_words) return", "= indices_to_extents[point_index] rect = patches.Rectangle((extent.left, extent.top), extent.right-extent.left, extent.bottom-extent.top, linewidth=0.5, edgecolor=\"black\",", "= squareform(pairwise_distances) # Total distance from selected set so far", "enumerate(self.document.get_words()): cluster_id = clustering_labels[word_idx] if cluster_id == -1: # Ignore", "entity in entities_set: x = entity.geometry.left * img_width y =", "fig.savefig(os.path.join(output_path, document.basename + '_' + embedding_property + '_pca.png')) plt.close(fig) #", "import os import cv2 from collections import namedtuple import imageio", "= cv2.addWeighted(output_img, alpha, bg_img, 1 - alpha, 0) return output_img", "namedtuple('matplot_extent', ['left', 'right', 'bottom', 'top']) is_extent_x_intersect = lambda e1, e2:", "so far distances_accumulator = np.zeros(len(cluster.words)) # Sample first point random_index", "plt.subplots(1) if crops_per_cluster > 0: if selected_word_crops_per_cluster is None and", "'unprojected_embedding'], unprojected_caption=None): \"\"\" Plot 2d PCA visualization of the embedding", "# Initially empty, the first embedding property we process will", "ClusterSolution = namedtuple('ClusterSolution', ['word_indices', 'words']) for cluster in clusters: #", "VisHandler.generate_darker_palette(colors_list) output_img = bg_img.copy() alpha = 0.8 for set_idx, entities_set", "= width / float(dpi), height / float(dpi) # Fig size", "for each crop. :param indices_to_crops: dict of word index (by", "colors_list=None): \"\"\" :param document: :param set_of_clusters: list of list of", "# Can't handle tuples, concat them embeddings = [] for", "# Total distance from selected set so far distances_accumulator =", "# list of list of words (clusters) self._save_set_of_clusters(set_of_clusters, with_title, colors_list)", "def _space_out_crops(indices_to_crops, words, x_list, y_list, dist_from_pt=0.01, height=0.02): \"\"\" Calculates the", "to 1) :return: indices_to_extents: dict of word index to extens", "1] for i in range(embeddings_2d.shape[0])] push_pull_ratio = embeddings_state['push_pull_ratio'] scatter_data.append((epoch, x_list,", "random_index = randrange(len(cluster.words)) # Indices of selected points selected_points =", "document: :param solution_per_cluster: Solution of k-furthest neighbours :return: \"\"\" word_indices_to_crops", "__init__(self, document, output_path): # Load background image self.image_path = document.image_path", "last_point_selected = selected_points[-1] # Update accumulator with distance collected from", "list of words (clusters) :return: \"\"\" output_img = self._draw_entity_bounding_boxes_opencv(bg_img=self.img_opencv, entity_sets=set_of_clusters,", "plot_title += ': ' + title plt.title(plot_title) plt.scatter(x_list, y_list, c=colors,", "max(y_list) height = (max_y - min_y) * height dist_from_pt =", "return if embedding_property == 'unprojected_embedding': embeddings = [] for word", "_save_set_of_clusters(self, set_of_clusters, with_title=True, colors_list=None): \"\"\" :param document: :param set_of_clusters: list", "crops (< 1000) and performs a naive linear comparison for", "x_list[point_index] + dist_from_pt + width bottom, top = y_list[point_index] +", "int(round(bbox[1] * document.height)) y_max = int(round((bbox[1] + bbox[3]) * document.height))", "= output_path if not os.path.exists(output_path): os.makedirs(output_path) def plot_word_boxes_on_image(self): set_of_words =", "alpha=0.8) fig.tight_layout() fig.savefig(os.path.join(output_path, document.basename + '_' + embedding_property + '_pca.png'))", "and dimensions of each crop. Crops are shifted so they", "ax = plt.subplots(1) ax.set_xlim(min_x, max_x) ax.set_ylim(min_y, max_y) plot_title = 'Projected", "to add points_to_calc_count = min(k - 1, len(words) - 1)", "(max_y - min_y) * height dist_from_pt = min(max_y - min_y,", "'': plot_title += ': ' + title plt.title(plot_title) plt.scatter(x_list, y_list,", "facecolor=\"none\", zorder=5) ax.imshow(crop, aspect='auto', alpha=0.65, extent=extent, zorder=4) ax.add_patch(rect) # Plot", "PIL crop :param words: List of words :param x_list: List", "\"\"\" word_indices_to_crops = {} for cluster, cluster_solution in solution_per_cluster.items(): for", "for idx, cluster_id in enumerate(cluster_ids)} # Converts from list of", "randrange(len(cluster.words)) # Indices of selected points selected_points = [random_index] #", "= np.zeros(len(cluster.words)) # Sample first point random_index = randrange(len(cluster.words)) #", "matplotlib matplotlib.use('Agg') # Required for gif animations import matplotlib as", "entity.geometry.width * img_width height = entity.geometry.height * img_height rect =", "entity_sets=set_of_words, colors_list=monochrome_colors_list) fig.savefig(os.path.join(self.output_path, self.document.basename + '_word_boxes.png')) plt.close(fig) def save_phrase_detection_results(self): set_of_phrases", "colors_palette=None): \"\"\" Plot 2d PCA visualization of the embedding space", "clusters on original image self.save_clustering_results(with_title=False, colors_list=colors_palette) return colors_palette @staticmethod def", "zip(cluster_solution.word_indices, cluster_solution.words): bbox = word.get_bbox() # left, top, width, height", "pil_image = pil_image.convert('RGB') word_indices_to_crops[word_index] = pil_image return word_indices_to_crops @staticmethod def", "colors_palette is None: colors_palette = VisHandler.generate_colors_list(amount=len(clusters)) word_to_color = {word: colors_palette[cluster_idx]", "Height of the crop, in figure axes dimensions (note: for", "solution_per_cluster): \"\"\" Extracts crops for each selected word in k-furthest", "overlap = True while overlap: overlap = False extent =", "the renderer output_frame = np.frombuffer(fig.canvas.tostring_rgb(), dtype='uint8') output_frame = output_frame.reshape(fig.canvas.get_width_height()[::-1] +", "y_list, dist_from_pt=0.01, height=0.02): \"\"\" Calculates the positions and dimensions of", "else: plot_title = unprojected_caption plt.title(plot_title) plt.scatter(x_list, y_list, c=colors, s=18, alpha=1.0,", "of words (clusters) self._save_set_of_clusters(set_of_clusters, with_title, colors_list) def save_clustering_labels(self, clustering_labels, colors_list=None):", "len(words) == 0 or embeddings_history is None or len(embeddings_history) ==", "if len(words) == 0 or \\ all([getattr(words[0], embedding_property) is None", "': ' + title plt.title(plot_title) plt.scatter(x_list, y_list, c=colors, s=1, alpha=0.8)", "and indices_to_crops is None: # Calculate per first attribute selected_word_crops_per_cluster", "= selected_points[-1] # Update accumulator with distance collected from last", "document.get_words() clusters = document.get_clusters() if len(words) == 0 or getattr(words[0],", "text onto the image and returning it rgb_color = rgb_hex_to_tuple(face_color)", "is None for embedding_property in embedding_properties]): return colors_palette = VisHandler.generate_colors_list(amount=len(clusters))", "\"\"\" output_img = self._draw_entity_bounding_boxes_opencv(bg_img=self.img_opencv, entity_sets=set_of_clusters, colors_list=colors_list) cv2.imwrite(os.path.join(self.output_path, self.document.basename + '_clustering.png'),", "image rray fig.tight_layout() fig.canvas.draw() # draw the canvas, cache the", "Embedding property of words - normally 'embedding' or 'unprojected_embedding' :return:", "above bottom = other_top - spaceout_margin top = bottom -", "else: embeddings = [getattr(word, embedding_property).detach().cpu().numpy() for word in words] embeddings_array", "list of list of words (clusters) set_of_clusters = [[] for", "last point distances_accumulator += distances_matrix[last_point_selected] # Eliminate last point selected", "= word.get_bbox() # left, top, width, height y_min = int(round(bbox[1]", "= randrange(len(cluster.words)) # Indices of selected points selected_points = [random_index]", "- min_y) * padding_factor frames = [] for epoch, x_list,", "int(y + height)), (rgb_color[2], rgb_color[1], rgb_color[0]), cv2.FILLED) output_img = cv2.addWeighted(output_img,", "cluster.words} colors = [word_to_color[word] for word in words] embeddings_array =", "k=crops_per_cluster) indices_to_crops = PlotsProducer._extract_crops_per_cluster_solution(document, selected_word_crops_per_cluster) indices_to_extents = PlotsProducer._space_out_crops(indices_to_crops, words, x_list,", "resize_image from multimodal_affinities.visualization.colors_util import rgb_hex_to_tuple class PlotsProducer: def __init__(self, document,", "self.figsize = width / float(dpi), height / float(dpi) # Fig", "images for point_index, crop in indices_to_crops.items(): extent = indices_to_extents[point_index] rect", "min(min(scatter_data, key=lambda entry: min(entry[2]))[2]) max_y = max(max(scatter_data, key=lambda entry: max(entry[2]))[2])", "a naive linear comparison for each crop. :param indices_to_crops: dict", "extent = MatplotExtent(left, right, bottom, top) for other_crop_extent in indices_to_extents.values():", "entity.geometry.height * img_height # writing the text onto the image", "words (clusters) :return: \"\"\" output_img = self._draw_entity_bounding_boxes_opencv(bg_img=self.img_opencv, entity_sets=set_of_clusters, colors_list=colors_list) cv2.imwrite(os.path.join(self.output_path,", "key=lambda entry: max(entry[1]))[1]) min_y = min(min(scatter_data, key=lambda entry: min(entry[2]))[2]) max_y", "= np.argmax(distances_accumulator, axis=0) selected_points.append(furthrest_point_from_set) selected_words = [cluster.words[point] for point in", "rgb_color = rgb_hex_to_tuple(face_color) cv2.rectangle(output_img, (int(x), int(y)), (int(x + width), int(y", "output_path): # Load background image self.image_path = document.image_path self.img =", "# left, top, width, height y_min = int(round(bbox[1] * document.height))", "output_path, crops_per_cluster=3, embedding_properties=['embedding', 'unprojected_embedding'], unprojected_caption=None): \"\"\" Plot 2d PCA visualization", "in enumerate(words)} clusters = document.get_clusters() solution_per_cluster = {} ClusterSolution =", "self.img_opencv = cv2.imread(self.image_path) dpi = 120 mpl.rcParams['figure.dpi'] = dpi height", "* document.height)) y_max = int(round((bbox[1] + bbox[3]) * document.height)) x_min", "range(embeddings_2d.shape[0])] y_list = [embeddings_2d[i, 1] for i in range(embeddings_2d.shape[0])] push_pull_ratio", "push_pull_ratio)) min_x = min(min(scatter_data, key=lambda entry: min(entry[1]))[1]) max_x = max(max(scatter_data,", "renderer output_frame = np.frombuffer(fig.canvas.tostring_rgb(), dtype='uint8') output_frame = output_frame.reshape(fig.canvas.get_width_height()[::-1] + (3,))", "fig.savefig(os.path.join(output_path, document.basename + '_' + embedding_property + '_pca.png')) plt.close(fig) @staticmethod", "bbox[2]) * document.width)) image_of_crop = document.image[max(0, y_min):min(y_max, document.height), max(0, x_min):min(x_max,", "training (PCA)' else: if unprojected_caption is None: plot_title = 'Projected", "gif animations import matplotlib as mpl import matplotlib.pyplot as plt", "= {word: colors_palette[cluster_idx] for cluster_idx, cluster in enumerate(clusters) for word", "entity_sets, colors_list=None): ax.set_title(title) plt.tick_params(axis='both', which='both', bottom='off', top='off', labelbottom='off', right='off', left='off',", "words :param x_list: List of corresponding pt x positions :param", "cluster.words} colors = [word_to_color[word] for word in words] scatter_data =", "words = document.get_words() clusters = document.get_clusters() if len(words) == 0", "# list of singleton phrase lists fig, ax = plt.subplots(1,", "+ height else: # shift above bottom = other_top -", "rect = patches.Rectangle((x, y), width, height, linewidth=2, edgecolor=edge_color, facecolor=face_color, alpha=0.4)", "if is_extent_intersect(extent, other_crop_extent): overlap = True # shift below if", "/ float(dpi), height / float(dpi) # Fig size in inches", "0 or \\ all([getattr(words[0], embedding_property) is None for embedding_property in", "for _ in range(len(cluster_ids))] for word_idx, word in enumerate(self.document.get_words()): cluster_id", "if cluster_id == -1: # Ignore non-clustered words continue cluster_idx", "image import matplotlib.patches as patches from multimodal_affinities.visualization.vis_handler import VisHandler from", "phrase in self.document.get_phrases()] # list of singleton phrase lists fig,", "= document.get_clusters() if len(words) == 0 or \\ all([getattr(words[0], embedding_property)", "> 0: unnormalized_embeddings = [unnormalized_embeddings_dict[word].detach().cpu().numpy() for word in words] chosen_embedding", "metric='euclidean') distances_matrix = squareform(pairwise_distances) # Total distance from selected set", "= int(round((bbox[1] + bbox[3]) * document.height)) x_min = int(round(bbox[0] *", "word_idx, word in enumerate(self.document.get_words()): cluster_id = clustering_labels[word_idx] if cluster_id ==", "+ embedding_property + '_pca.png')) plt.close(fig) # Finally plot clusters on", "cluster.words] all_cluster_embeddings = np.take(embeddings_2d, all_cluster_embeddings_indices, axis=0) pairwise_distances = pdist(all_cluster_embeddings, metric='euclidean')", "= cv2.imread(self.image_path) dpi = 120 mpl.rcParams['figure.dpi'] = dpi height =", "embedding_property='embedding', title=''): \"\"\" Plot 2d PCA visualization of the embedding", "import cv2 from collections import namedtuple import imageio from PIL", "entity.geometry.width * img_width height = entity.geometry.height * img_height # writing", "words] chosen_embedding = unnormalized_embeddings else: return embeddings_array = np.array(chosen_embedding).squeeze() num_pca_comp", "Extracts crops for each selected word in k-furthest neighbours solution", "pt x positions :param y_list: List of corresponding pt y", "[word_to_color[word] for word in words] scatter_data = [] for state_idx,", "per cluster. k is expected to be relatively small (<", "if selected_word_crops_per_cluster is None and indices_to_crops is None: # Calculate", "in range(embeddings_2d.shape[0])] fig, ax = plt.subplots(1) plot_title = embedding_property if", "0] for i in range(embeddings_2d.shape[0])] y_list = [embeddings_2d[i, 1] for", "words] # Initially empty, the first embedding property we process", "= bg_img.shape[0] img_width = bg_img.shape[1] if colors_list is None: colors_list", "space plot. Makes sure crops don't overlay each other. This", "solution_per_cluster = {} ClusterSolution = namedtuple('ClusterSolution', ['word_indices', 'words']) for cluster", "[] for epoch, x_list, y_list, push_pull_ratio in scatter_data: fig, ax", "with_title, colors_list) def save_clustering_labels(self, clustering_labels, colors_list=None): cluster_ids = np.unique(np.array(clustering_labels)) cluster_id_to_cluster_idx", "words=selected_words) return solution_per_cluster @staticmethod def _extract_crops_per_cluster_solution(document, solution_per_cluster): \"\"\" Extracts crops", "or getattr(words[0], embedding_property) is None: return if embedding_property == 'unprojected_embedding':" ]
[ "address=None) dist_office = dict(name=\"Outside Office\", type=\"capitol\", phone=None,fax=None, email=dist_email, address=None) #this", "+= '&TableRow=1.5.5' frame_doc = self.lxmlize(url) actual_url = frame_doc.xpath(\"//frame[@name='right']/@src\")[0] doc =", "phone return office def clean_phone(self,phone): if not phone.strip(): return if", "url += '&TableRow=1.5.5' frame_doc = self.lxmlize(url) actual_url = frame_doc.xpath(\"//frame[@name='right']/@src\")[0] doc", "for o in [leg_office,dist_office] if o[\"address\"]] assert len(offices) > 0,", "but kindly in actual html trs = doc.xpath('//tr') base_url =", "phones: if \"phone\" in line: phone = self.clean_phone(line) if phone:", "content = office.xpath(\"./td\")[title_td+1].text_content() except IndexError: continue leg_office = self.add_contact(\"legislative\", title_text,content,leg_office)", "= 1 try: title_text = office.xpath(\"./td\")[title_td].text_content().lower() content = office.xpath(\"./td\")[title_td+1].text_content() except", "without having to do another request url += '&TableRow=1.5.5' frame_doc", "html is hard-coded in js. table_js = doc.xpath('.//script')[-1].text_content() table =", "\"{} office\".format(office_type) in title_text: office[\"address\"] = content.strip() if \"{} phone\".format(office_type)", "= doc.xpath('.//script')[-1].text_content() table = None for line in table_js.split(\"\\n\"): if", "leg_email = None dist_email = None try: emails = email.split(\";\")", "0, \"No offices with addresses found \"\\ \"make sure we're", "self.clean_phone(line) if phone: office[\"phone\"] = phone elif \"fax\" in line:", "= name_and_url.text_content() if name.strip() == \".\" or name.strip() == \"\":", "these party = doc.xpath('//div[@id=\"page_header\"]')[0].text.strip()[-3:] if '(D)' in party: party =", "the house, but kindly in actual html trs = doc.xpath('//tr')", "continue re_spaces=re.compile(r'\\s{1,5}') name = ' '.join(re_spaces.split(name)) district = tr.xpath('.//td')[2].text_content() district", "actual html trs = doc.xpath('//tr') base_url = \"http://legis.delaware.gov\" for tr", "type is the name of the office #either \"legislative\" or", "'http://legis.delaware.gov/legislature.nsf/sen?openview', 'lower': 'http://legis.delaware.gov/Legislature.nsf/Reps?openview', }[chamber] doc = self.lxmlize(url) if chamber ==", "None dist_email = None try: emails = email.split(\";\") except AttributeError:", "not losing any data.\" return {\"offices\":offices} def add_contact(self,office_type, title_text,content,office): #office", "be found\" table = lxml.html.fromstring(table) table.make_links_absolute(url) trs = table.xpath('//tr') else:", "is the name of the office #either \"legislative\" or \"outside\"", "return leg def scrape_contact_info(self, doc): # Email email = doc.xpath(\".//a[contains(@href,'mailto')]\")", "#for the senate, it's the same table #but the html", "= phone elif \"fax\" in line: phone = self.clean_phone(line) if", "offices with addresses found \"\\ \"make sure we're not losing", "the committee section without having to do another request url", "> 0, \"No offices with addresses found \"\\ \"make sure", "request url += '&TableRow=1.5.5' frame_doc = self.lxmlize(url) actual_url = frame_doc.xpath(\"//frame[@name='right']/@src\")[0]", "\"legislative\" or \"outside\" if \"{} office\".format(office_type) in title_text: office[\"address\"] =", "if e: if \"state.de.us\" in e: leg_email = e else:", "if name.strip().lower().startswith(\"vacant\"): continue re_spaces=re.compile(r'\\s{1,5}') name = ' '.join(re_spaces.split(name)) district =", "= bio_url.replace('\"','') name = name_and_url.text_content() if name.strip() == \".\" or", "could not be found\" table = lxml.html.fromstring(table) table.make_links_absolute(url) trs =", "is not None, \"Senate table could not be found\" table", "self.save_legislator(leg) def scrape_bio(self, term, chamber, district, name, url): # this", "DE. office_list = doc.xpath(\"//tr\") for office in office_list: title_td =", "'Republican' else: raise AssertionError(\"No party found for {name}\".format(name=name)) leg =", "content.strip() if \"{} phone\".format(office_type) in title_text: phones = content.lower().split(\"\\n\") if", "== \".\" or name.strip() == \"\": continue if name.strip().lower().startswith(\"vacant\"): continue", "import LXMLMixin from billy.scrape.legislators import LegislatorScraper, Legislator class DELegislatorScraper(LegislatorScraper,LXMLMixin): jurisdiction", "office_list: title_td = 0 #in some trs the photo is", "sure we're not losing any data.\" return {\"offices\":offices} def add_contact(self,office_type,", "in title_text: phones = content.lower().split(\"\\n\") if len(phones) == 1: phone", "else: raise AssertionError(\"No party found for {name}\".format(name=name)) leg = Legislator(term,", "e: leg_email = e else: dist_email = e # Offices", "raise AssertionError(\"No party found for {name}\".format(name=name)) leg = Legislator(term, chamber,", "IndexError: continue leg_office = self.add_contact(\"legislative\", title_text,content,leg_office) dist_office = self.add_contact(\"outside\", title_text,content,dist_office)", "import LegislatorScraper, Legislator class DELegislatorScraper(LegislatorScraper,LXMLMixin): jurisdiction = 'de' def scrape(self,", "= email[0].text_content().strip() leg_email = None dist_email = None try: emails", "email[0].text_content().strip() leg_email = None dist_email = None try: emails =", "do another request url += '&TableRow=1.5.5' frame_doc = self.lxmlize(url) actual_url", "#either \"legislative\" or \"outside\" if \"{} office\".format(office_type) in title_text: office[\"address\"]", "office[\"address\"] = content.strip() if \"{} phone\".format(office_type) in title_text: phones =", "== \"upper\": #for the senate, it's the same table #but", "dist_email = e # Offices leg_office = dict(name=\"Capitol Office\", type=\"capitol\",", "url): # this opens the committee section without having to", "title_text: phones = content.lower().split(\"\\n\") if len(phones) == 1: phone =", "dict(name=\"Capitol Office\", type=\"capitol\", phone=None, fax=None, email=leg_email, address=None) dist_office = dict(name=\"Outside", "table.xpath('//tr') else: #same table for the house, but kindly in", "if phone: office[\"fax\"] = phone return office def clean_phone(self,phone): if", "in line: table = line.replace(\"var\",\"\") table = table.replace('sen=\"<','<') table =", "if phone: office[\"phone\"] = phone else: for line in phones:", "scrape_bio(self, term, chamber, district, name, url): # this opens the", "table could not be found\" table = lxml.html.fromstring(table) table.make_links_absolute(url) trs", "#in some trs the photo is the first td if", "line: table = line.replace(\"var\",\"\") table = table.replace('sen=\"<','<') table = table.replace('>\";','>')", "line.replace(\"var\",\"\") table = table.replace('sen=\"<','<') table = table.replace('>\";','>') break assert table", "#same table for the house, but kindly in actual html", "assert len(offices) > 0, \"No offices with addresses found \"\\", "= doc.xpath('//div[@id=\"page_header\"]')[0].text.strip()[-3:] if '(D)' in party: party = 'Democratic' elif", "district, name, url): # this opens the committee section without", "dist_office = self.add_contact(\"outside\", title_text,content,dist_office) offices = [o for o in", "= e # Offices leg_office = dict(name=\"Capitol Office\", type=\"capitol\", phone=None,", "self.lxmlize(actual_url) # party is in one of these party =", "def scrape_bio(self, term, chamber, district, name, url): # this opens", "in party: party = 'Republican' else: raise AssertionError(\"No party found", "e: if \"state.de.us\" in e: leg_email = e else: dist_email", "\"upper\": #for the senate, it's the same table #but the", "one of these party = doc.xpath('//div[@id=\"page_header\"]')[0].text.strip()[-3:] if '(D)' in party:", "\"outside\" if \"{} office\".format(office_type) in title_text: office[\"address\"] = content.strip() if", "if len(phones) == 1: phone = self.clean_phone(phones[0]) if phone: office[\"phone\"]", "any data.\" return {\"offices\":offices} def add_contact(self,office_type, title_text,content,office): #office type is", "else: for e in emails: e = e.strip() if e:", "table #but the html is hard-coded in js. table_js =", "the same table #but the html is hard-coded in js.", "Legislator class DELegislatorScraper(LegislatorScraper,LXMLMixin): jurisdiction = 'de' def scrape(self, chamber, term):", "= 0 #in some trs the photo is the first", "#but the html is hard-coded in js. table_js = doc.xpath('.//script')[-1].text_content()", "'lower': 'http://legis.delaware.gov/Legislature.nsf/Reps?openview', }[chamber] doc = self.lxmlize(url) if chamber == \"upper\":", "office #either \"legislative\" or \"outside\" if \"{} office\".format(office_type) in title_text:", "Email email = doc.xpath(\".//a[contains(@href,'mailto')]\") email = email[0].text_content().strip() leg_email = None", "' '.join(re_spaces.split(name)) district = tr.xpath('.//td')[2].text_content() district = district.replace(\"District:\",\"\").strip() leg =", "phone.strip(): return if not re.search(\"\\d\",phone): return if not \":\" in", "None for line in table_js.split(\"\\n\"): if line.strip().startswith(\"var\") and \"sen=\" in", "office.xpath(\"./td\")[title_td+1].text_content() except IndexError: continue leg_office = self.add_contact(\"legislative\", title_text,content,leg_office) dist_office =", "table = line.replace(\"var\",\"\") table = table.replace('sen=\"<','<') table = table.replace('>\";','>') break", "0 #in some trs the photo is the first td", "painful, DE. office_list = doc.xpath(\"//tr\") for office in office_list: title_td", "office[\"phone\"] = phone else: for line in phones: if \"phone\"", "= table.replace('sen=\"<','<') table = table.replace('>\";','>') break assert table is not", "doc): # Email email = doc.xpath(\".//a[contains(@href,'mailto')]\") email = email[0].text_content().strip() leg_email", "import lxml.html from openstates.utils import LXMLMixin from billy.scrape.legislators import LegislatorScraper,", "if '(D)' in party: party = 'Democratic' elif '(R)' in", "self.scrape_bio(term, chamber, district, name, bio_url) leg.add_source(bio_url, page=\"legislator detail page\") leg.add_source(url,", "Office\", type=\"capitol\", phone=None, fax=None, email=leg_email, address=None) dist_office = dict(name=\"Outside Office\",", "party=party) photo_url = doc.xpath('//img[contains(@src, \"jpg\")]/@src') if photo_url: leg['photo_url'] = photo_url[0]", "= None for line in table_js.split(\"\\n\"): if line.strip().startswith(\"var\") and \"sen=\"", "party = doc.xpath('//div[@id=\"page_header\"]')[0].text.strip()[-3:] if '(D)' in party: party = 'Democratic'", "= table.replace('>\";','>') break assert table is not None, \"Senate table", "len(offices) > 0, \"No offices with addresses found \"\\ \"make", "= name_and_url.attrib[\"href\"] bio_url = bio_url.replace(\"JavaScript:window.top.location.href=\",\"\") bio_url = bio_url.replace('\"','') name =", "leg def scrape_contact_info(self, doc): # Email email = doc.xpath(\".//a[contains(@href,'mailto')]\") email", "self.clean_phone(line) if phone: office[\"fax\"] = phone return office def clean_phone(self,phone):", "leg = Legislator(term, chamber, district, name, party=party) photo_url = doc.xpath('//img[contains(@src,", "1: phone = self.clean_phone(phones[0]) if phone: office[\"phone\"] = phone else:", "opens the committee section without having to do another request", "#office type is the name of the office #either \"legislative\"", "\"Senate table could not be found\" table = lxml.html.fromstring(table) table.make_links_absolute(url)", "e # Offices leg_office = dict(name=\"Capitol Office\", type=\"capitol\", phone=None, fax=None,", "phones = content.lower().split(\"\\n\") if len(phones) == 1: phone = self.clean_phone(phones[0])", "= e else: dist_email = e # Offices leg_office =", "addresses found \"\\ \"make sure we're not losing any data.\"", "openstates.utils import LXMLMixin from billy.scrape.legislators import LegislatorScraper, Legislator class DELegislatorScraper(LegislatorScraper,LXMLMixin):", "= self.lxmlize(url) actual_url = frame_doc.xpath(\"//frame[@name='right']/@src\")[0] doc = self.lxmlize(actual_url) # party", "if \"{} phone\".format(office_type) in title_text: phones = content.lower().split(\"\\n\") if len(phones)", "= self.add_contact(\"legislative\", title_text,content,leg_office) dist_office = self.add_contact(\"outside\", title_text,content,dist_office) offices = [o", "title_td = 0 #in some trs the photo is the", "re import lxml.html from openstates.utils import LXMLMixin from billy.scrape.legislators import", "we're not losing any data.\" return {\"offices\":offices} def add_contact(self,office_type, title_text,content,office):", "Office\", type=\"capitol\", phone=None,fax=None, email=dist_email, address=None) #this is enormously painful, DE.", "return office def clean_phone(self,phone): if not phone.strip(): return if not", "re.search(\"\\d\",phone): return if not \":\" in phone: return phone return", "in line: phone = self.clean_phone(line) if phone: office[\"phone\"] = phone", "bio_url) leg.add_source(bio_url, page=\"legislator detail page\") leg.add_source(url, page=\"legislator list page\") self.save_legislator(leg)", "self.lxmlize(url) actual_url = frame_doc.xpath(\"//frame[@name='right']/@src\")[0] doc = self.lxmlize(actual_url) # party is", "\"phone\" in line: phone = self.clean_phone(line) if phone: office[\"phone\"] =", "self.add_contact(\"outside\", title_text,content,dist_office) offices = [o for o in [leg_office,dist_office] if", "clean_phone(self,phone): if not phone.strip(): return if not re.search(\"\\d\",phone): return if", "# Offices leg_office = dict(name=\"Capitol Office\", type=\"capitol\", phone=None, fax=None, email=leg_email,", "name_and_url = tr.xpath('.//a')[0] bio_url = name_and_url.attrib[\"href\"] bio_url = bio_url.replace(\"JavaScript:window.top.location.href=\",\"\") bio_url", "phone else: for line in phones: if \"phone\" in line:", "if chamber == \"upper\": #for the senate, it's the same", "email=dist_email, address=None) #this is enormously painful, DE. office_list = doc.xpath(\"//tr\")", "phone elif \"fax\" in line: phone = self.clean_phone(line) if phone:", "leg.update(contact_info) return leg def scrape_contact_info(self, doc): # Email email =", "= [o for o in [leg_office,dist_office] if o[\"address\"]] assert len(offices)", "table.replace('sen=\"<','<') table = table.replace('>\";','>') break assert table is not None,", "phone = self.clean_phone(line) if phone: office[\"phone\"] = phone elif \"fax\"", "AssertionError(\"No party found for {name}\".format(name=name)) leg = Legislator(term, chamber, district,", "party: party = 'Republican' else: raise AssertionError(\"No party found for", "page\") self.save_legislator(leg) def scrape_bio(self, term, chamber, district, name, url): #", "continue leg_office = self.add_contact(\"legislative\", title_text,content,leg_office) dist_office = self.add_contact(\"outside\", title_text,content,dist_office) offices", "bio_url.replace('\"','') name = name_and_url.text_content() if name.strip() == \".\" or name.strip()", "'(R)' in party: party = 'Republican' else: raise AssertionError(\"No party", "in phones: if \"phone\" in line: phone = self.clean_phone(line) if", "'Democratic' elif '(R)' in party: party = 'Republican' else: raise", "import re import lxml.html from openstates.utils import LXMLMixin from billy.scrape.legislators", "trs = table.xpath('//tr') else: #same table for the house, but", "= 'de' def scrape(self, chamber, term): url = { 'upper':", "o in [leg_office,dist_office] if o[\"address\"]] assert len(offices) > 0, \"No", "if len(office.xpath(\"./td/img\")) > 0: title_td = 1 try: title_text =", "leg_office = dict(name=\"Capitol Office\", type=\"capitol\", phone=None, fax=None, email=leg_email, address=None) dist_office", "office.xpath(\"./td\")[title_td].text_content().lower() content = office.xpath(\"./td\")[title_td+1].text_content() except IndexError: continue leg_office = self.add_contact(\"legislative\",", "table_js = doc.xpath('.//script')[-1].text_content() table = None for line in table_js.split(\"\\n\"):", "if not re.search(\"\\d\",phone): return if not \":\" in phone: return", "phone=None, fax=None, email=leg_email, address=None) dist_office = dict(name=\"Outside Office\", type=\"capitol\", phone=None,fax=None,", "found\" table = lxml.html.fromstring(table) table.make_links_absolute(url) trs = table.xpath('//tr') else: #same", "'&TableRow=1.5.5' frame_doc = self.lxmlize(url) actual_url = frame_doc.xpath(\"//frame[@name='right']/@src\")[0] doc = self.lxmlize(actual_url)", "> 0: title_td = 1 try: title_text = office.xpath(\"./td\")[title_td].text_content().lower() content", "found \"\\ \"make sure we're not losing any data.\" return", "else: dist_email = e # Offices leg_office = dict(name=\"Capitol Office\",", "hard-coded in js. table_js = doc.xpath('.//script')[-1].text_content() table = None for", "table for the house, but kindly in actual html trs", "of these party = doc.xpath('//div[@id=\"page_header\"]')[0].text.strip()[-3:] if '(D)' in party: party", "# this opens the committee section without having to do", "= Legislator(term, chamber, district, name, party=party) photo_url = doc.xpath('//img[contains(@src, \"jpg\")]/@src')", "office in office_list: title_td = 0 #in some trs the", "name, party=party) photo_url = doc.xpath('//img[contains(@src, \"jpg\")]/@src') if photo_url: leg['photo_url'] =", "def scrape(self, chamber, term): url = { 'upper': 'http://legis.delaware.gov/legislature.nsf/sen?openview', 'lower':", "else: #same table for the house, but kindly in actual", "[o for o in [leg_office,dist_office] if o[\"address\"]] assert len(offices) >", "table = table.replace('sen=\"<','<') table = table.replace('>\";','>') break assert table is", "doc.xpath('//div[@id=\"page_header\"]')[0].text.strip()[-3:] if '(D)' in party: party = 'Democratic' elif '(R)'", "leg['photo_url'] = photo_url[0] contact_info = self.scrape_contact_info(doc) leg.update(contact_info) return leg def", "'de' def scrape(self, chamber, term): url = { 'upper': 'http://legis.delaware.gov/legislature.nsf/sen?openview',", "phone = self.clean_phone(phones[0]) if phone: office[\"phone\"] = phone else: for", "table = lxml.html.fromstring(table) table.make_links_absolute(url) trs = table.xpath('//tr') else: #same table", "in emails: e = e.strip() if e: if \"state.de.us\" in", "= phone else: for line in phones: if \"phone\" in", "phone\".format(office_type) in title_text: phones = content.lower().split(\"\\n\") if len(phones) == 1:", "page\") leg.add_source(url, page=\"legislator list page\") self.save_legislator(leg) def scrape_bio(self, term, chamber,", "and \"sen=\" in line: table = line.replace(\"var\",\"\") table = table.replace('sen=\"<','<')", "if photo_url: leg['photo_url'] = photo_url[0] contact_info = self.scrape_contact_info(doc) leg.update(contact_info) return", "is the first td if len(office.xpath(\"./td/img\")) > 0: title_td =", "table.replace('>\";','>') break assert table is not None, \"Senate table could", "name.strip().lower().startswith(\"vacant\"): continue re_spaces=re.compile(r'\\s{1,5}') name = ' '.join(re_spaces.split(name)) district = tr.xpath('.//td')[2].text_content()", "re_spaces=re.compile(r'\\s{1,5}') name = ' '.join(re_spaces.split(name)) district = tr.xpath('.//td')[2].text_content() district =", "= content.strip() if \"{} phone\".format(office_type) in title_text: phones = content.lower().split(\"\\n\")", "except IndexError: continue leg_office = self.add_contact(\"legislative\", title_text,content,leg_office) dist_office = self.add_contact(\"outside\",", "= ' '.join(re_spaces.split(name)) district = tr.xpath('.//td')[2].text_content() district = district.replace(\"District:\",\"\").strip() leg", "for line in table_js.split(\"\\n\"): if line.strip().startswith(\"var\") and \"sen=\" in line:", "doc = self.lxmlize(url) if chamber == \"upper\": #for the senate,", "chamber == \"upper\": #for the senate, it's the same table", "it's the same table #but the html is hard-coded in", "section without having to do another request url += '&TableRow=1.5.5'", "\"fax\" in line: phone = self.clean_phone(line) if phone: office[\"fax\"] =", "= dict(name=\"Outside Office\", type=\"capitol\", phone=None,fax=None, email=dist_email, address=None) #this is enormously", "line.strip().startswith(\"var\") and \"sen=\" in line: table = line.replace(\"var\",\"\") table =", "else: for line in phones: if \"phone\" in line: phone", "photo_url: leg['photo_url'] = photo_url[0] contact_info = self.scrape_contact_info(doc) leg.update(contact_info) return leg", "office[\"phone\"] = phone elif \"fax\" in line: phone = self.clean_phone(line)", "party = 'Republican' else: raise AssertionError(\"No party found for {name}\".format(name=name))", "= tr.xpath('.//td')[2].text_content() district = district.replace(\"District:\",\"\").strip() leg = self.scrape_bio(term, chamber, district,", "= frame_doc.xpath(\"//frame[@name='right']/@src\")[0] doc = self.lxmlize(actual_url) # party is in one", "table_js.split(\"\\n\"): if line.strip().startswith(\"var\") and \"sen=\" in line: table = line.replace(\"var\",\"\")", "emails: e = e.strip() if e: if \"state.de.us\" in e:", "if o[\"address\"]] assert len(offices) > 0, \"No offices with addresses", "district = district.replace(\"District:\",\"\").strip() leg = self.scrape_bio(term, chamber, district, name, bio_url)", "in e: leg_email = e else: dist_email = e #", "\".\" or name.strip() == \"\": continue if name.strip().lower().startswith(\"vacant\"): continue re_spaces=re.compile(r'\\s{1,5}')", "in party: party = 'Democratic' elif '(R)' in party: party", "bio_url = name_and_url.attrib[\"href\"] bio_url = bio_url.replace(\"JavaScript:window.top.location.href=\",\"\") bio_url = bio_url.replace('\"','') name", "same table #but the html is hard-coded in js. table_js", "another request url += '&TableRow=1.5.5' frame_doc = self.lxmlize(url) actual_url =", "= self.clean_phone(line) if phone: office[\"fax\"] = phone return office def", "leg_email = e else: dist_email = e # Offices leg_office", "table is not None, \"Senate table could not be found\"", "if line.strip().startswith(\"var\") and \"sen=\" in line: table = line.replace(\"var\",\"\") table", "= doc.xpath('//tr') base_url = \"http://legis.delaware.gov\" for tr in trs: name_and_url", "with addresses found \"\\ \"make sure we're not losing any", "LegislatorScraper, Legislator class DELegislatorScraper(LegislatorScraper,LXMLMixin): jurisdiction = 'de' def scrape(self, chamber,", "leg = self.scrape_bio(term, chamber, district, name, bio_url) leg.add_source(bio_url, page=\"legislator detail", "chamber, district, name, bio_url) leg.add_source(bio_url, page=\"legislator detail page\") leg.add_source(url, page=\"legislator", "the senate, it's the same table #but the html is", "= doc.xpath('//img[contains(@src, \"jpg\")]/@src') if photo_url: leg['photo_url'] = photo_url[0] contact_info =", "bio_url.replace(\"JavaScript:window.top.location.href=\",\"\") bio_url = bio_url.replace('\"','') name = name_and_url.text_content() if name.strip() ==", "None try: emails = email.split(\";\") except AttributeError: pass else: for", "contact_info = self.scrape_contact_info(doc) leg.update(contact_info) return leg def scrape_contact_info(self, doc): #", "not phone.strip(): return if not re.search(\"\\d\",phone): return if not \":\"", "= { 'upper': 'http://legis.delaware.gov/legislature.nsf/sen?openview', 'lower': 'http://legis.delaware.gov/Legislature.nsf/Reps?openview', }[chamber] doc = self.lxmlize(url)", "= 'Republican' else: raise AssertionError(\"No party found for {name}\".format(name=name)) leg", "dist_email = None try: emails = email.split(\";\") except AttributeError: pass", "if not phone.strip(): return if not re.search(\"\\d\",phone): return if not", "class DELegislatorScraper(LegislatorScraper,LXMLMixin): jurisdiction = 'de' def scrape(self, chamber, term): url", "title_text = office.xpath(\"./td\")[title_td].text_content().lower() content = office.xpath(\"./td\")[title_td+1].text_content() except IndexError: continue leg_office", "return if not \":\" in phone: return phone return phone.split(\":\")[1].strip()", "having to do another request url += '&TableRow=1.5.5' frame_doc =", "return if not re.search(\"\\d\",phone): return if not \":\" in phone:", "in actual html trs = doc.xpath('//tr') base_url = \"http://legis.delaware.gov\" for", "from openstates.utils import LXMLMixin from billy.scrape.legislators import LegislatorScraper, Legislator class", "doc.xpath(\".//a[contains(@href,'mailto')]\") email = email[0].text_content().strip() leg_email = None dist_email = None", "emails = email.split(\";\") except AttributeError: pass else: for e in", "doc.xpath(\"//tr\") for office in office_list: title_td = 0 #in some", "frame_doc.xpath(\"//frame[@name='right']/@src\")[0] doc = self.lxmlize(actual_url) # party is in one of", "in title_text: office[\"address\"] = content.strip() if \"{} phone\".format(office_type) in title_text:", "= photo_url[0] contact_info = self.scrape_contact_info(doc) leg.update(contact_info) return leg def scrape_contact_info(self,", "{\"offices\":offices} def add_contact(self,office_type, title_text,content,office): #office type is the name of", "for office in office_list: title_td = 0 #in some trs", "if name.strip() == \".\" or name.strip() == \"\": continue if", "line: phone = self.clean_phone(line) if phone: office[\"fax\"] = phone return", "line: phone = self.clean_phone(line) if phone: office[\"phone\"] = phone elif", "phone = self.clean_phone(line) if phone: office[\"fax\"] = phone return office", "the first td if len(office.xpath(\"./td/img\")) > 0: title_td = 1", "tr.xpath('.//td')[2].text_content() district = district.replace(\"District:\",\"\").strip() leg = self.scrape_bio(term, chamber, district, name,", "email = email[0].text_content().strip() leg_email = None dist_email = None try:", "= office.xpath(\"./td\")[title_td].text_content().lower() content = office.xpath(\"./td\")[title_td+1].text_content() except IndexError: continue leg_office =", "phone: office[\"phone\"] = phone elif \"fax\" in line: phone =", "# party is in one of these party = doc.xpath('//div[@id=\"page_header\"]')[0].text.strip()[-3:]", "type=\"capitol\", phone=None,fax=None, email=dist_email, address=None) #this is enormously painful, DE. office_list", "lxml.html from openstates.utils import LXMLMixin from billy.scrape.legislators import LegislatorScraper, Legislator", "len(office.xpath(\"./td/img\")) > 0: title_td = 1 try: title_text = office.xpath(\"./td\")[title_td].text_content().lower()", "term): url = { 'upper': 'http://legis.delaware.gov/legislature.nsf/sen?openview', 'lower': 'http://legis.delaware.gov/Legislature.nsf/Reps?openview', }[chamber] doc", "name = name_and_url.text_content() if name.strip() == \".\" or name.strip() ==", "= self.add_contact(\"outside\", title_text,content,dist_office) offices = [o for o in [leg_office,dist_office]", "}[chamber] doc = self.lxmlize(url) if chamber == \"upper\": #for the", "email = doc.xpath(\".//a[contains(@href,'mailto')]\") email = email[0].text_content().strip() leg_email = None dist_email", "\"jpg\")]/@src') if photo_url: leg['photo_url'] = photo_url[0] contact_info = self.scrape_contact_info(doc) leg.update(contact_info)", "title_text,content,dist_office) offices = [o for o in [leg_office,dist_office] if o[\"address\"]]", "detail page\") leg.add_source(url, page=\"legislator list page\") self.save_legislator(leg) def scrape_bio(self, term,", "the html is hard-coded in js. table_js = doc.xpath('.//script')[-1].text_content() table", "= None dist_email = None try: emails = email.split(\";\") except", "\"http://legis.delaware.gov\" for tr in trs: name_and_url = tr.xpath('.//a')[0] bio_url =", "doc.xpath('.//script')[-1].text_content() table = None for line in table_js.split(\"\\n\"): if line.strip().startswith(\"var\")", "self.clean_phone(phones[0]) if phone: office[\"phone\"] = phone else: for line in", "= None try: emails = email.split(\";\") except AttributeError: pass else:", "{ 'upper': 'http://legis.delaware.gov/legislature.nsf/sen?openview', 'lower': 'http://legis.delaware.gov/Legislature.nsf/Reps?openview', }[chamber] doc = self.lxmlize(url) if", "trs the photo is the first td if len(office.xpath(\"./td/img\")) >", "url = { 'upper': 'http://legis.delaware.gov/legislature.nsf/sen?openview', 'lower': 'http://legis.delaware.gov/Legislature.nsf/Reps?openview', }[chamber] doc =", "\"state.de.us\" in e: leg_email = e else: dist_email = e", "trs: name_and_url = tr.xpath('.//a')[0] bio_url = name_and_url.attrib[\"href\"] bio_url = bio_url.replace(\"JavaScript:window.top.location.href=\",\"\")", "Legislator(term, chamber, district, name, party=party) photo_url = doc.xpath('//img[contains(@src, \"jpg\")]/@src') if", "not None, \"Senate table could not be found\" table =", "type=\"capitol\", phone=None, fax=None, email=leg_email, address=None) dist_office = dict(name=\"Outside Office\", type=\"capitol\",", "#this is enormously painful, DE. office_list = doc.xpath(\"//tr\") for office", "== \"\": continue if name.strip().lower().startswith(\"vacant\"): continue re_spaces=re.compile(r'\\s{1,5}') name = '", "fax=None, email=leg_email, address=None) dist_office = dict(name=\"Outside Office\", type=\"capitol\", phone=None,fax=None, email=dist_email,", "name.strip() == \".\" or name.strip() == \"\": continue if name.strip().lower().startswith(\"vacant\"):", "= self.scrape_contact_info(doc) leg.update(contact_info) return leg def scrape_contact_info(self, doc): # Email", "data.\" return {\"offices\":offices} def add_contact(self,office_type, title_text,content,office): #office type is the", "for the house, but kindly in actual html trs =", "= doc.xpath(\"//tr\") for office in office_list: title_td = 0 #in", "not be found\" table = lxml.html.fromstring(table) table.make_links_absolute(url) trs = table.xpath('//tr')", "in office_list: title_td = 0 #in some trs the photo", "phone=None,fax=None, email=dist_email, address=None) #this is enormously painful, DE. office_list =", "chamber, district, name, party=party) photo_url = doc.xpath('//img[contains(@src, \"jpg\")]/@src') if photo_url:", "return {\"offices\":offices} def add_contact(self,office_type, title_text,content,office): #office type is the name", "o[\"address\"]] assert len(offices) > 0, \"No offices with addresses found", "billy.scrape.legislators import LegislatorScraper, Legislator class DELegislatorScraper(LegislatorScraper,LXMLMixin): jurisdiction = 'de' def", "district, name, bio_url) leg.add_source(bio_url, page=\"legislator detail page\") leg.add_source(url, page=\"legislator list", "district = tr.xpath('.//td')[2].text_content() district = district.replace(\"District:\",\"\").strip() leg = self.scrape_bio(term, chamber,", "self.scrape_contact_info(doc) leg.update(contact_info) return leg def scrape_contact_info(self, doc): # Email email", "continue if name.strip().lower().startswith(\"vacant\"): continue re_spaces=re.compile(r'\\s{1,5}') name = ' '.join(re_spaces.split(name)) district", "phone: office[\"fax\"] = phone return office def clean_phone(self,phone): if not", "in table_js.split(\"\\n\"): if line.strip().startswith(\"var\") and \"sen=\" in line: table =", "name_and_url.text_content() if name.strip() == \".\" or name.strip() == \"\": continue", "bio_url = bio_url.replace(\"JavaScript:window.top.location.href=\",\"\") bio_url = bio_url.replace('\"','') name = name_and_url.text_content() if", "senate, it's the same table #but the html is hard-coded", "party = 'Democratic' elif '(R)' in party: party = 'Republican'", "def scrape_contact_info(self, doc): # Email email = doc.xpath(\".//a[contains(@href,'mailto')]\") email =", "dict(name=\"Outside Office\", type=\"capitol\", phone=None,fax=None, email=dist_email, address=None) #this is enormously painful,", "LXMLMixin from billy.scrape.legislators import LegislatorScraper, Legislator class DELegislatorScraper(LegislatorScraper,LXMLMixin): jurisdiction =", "if phone: office[\"phone\"] = phone elif \"fax\" in line: phone", "some trs the photo is the first td if len(office.xpath(\"./td/img\"))", "doc = self.lxmlize(actual_url) # party is in one of these", "the photo is the first td if len(office.xpath(\"./td/img\")) > 0:", "frame_doc = self.lxmlize(url) actual_url = frame_doc.xpath(\"//frame[@name='right']/@src\")[0] doc = self.lxmlize(actual_url) #", "or name.strip() == \"\": continue if name.strip().lower().startswith(\"vacant\"): continue re_spaces=re.compile(r'\\s{1,5}') name", "term, chamber, district, name, url): # this opens the committee", "title_text: office[\"address\"] = content.strip() if \"{} phone\".format(office_type) in title_text: phones", "= line.replace(\"var\",\"\") table = table.replace('sen=\"<','<') table = table.replace('>\";','>') break assert", "tr in trs: name_and_url = tr.xpath('.//a')[0] bio_url = name_and_url.attrib[\"href\"] bio_url", "in [leg_office,dist_office] if o[\"address\"]] assert len(offices) > 0, \"No offices", "= e.strip() if e: if \"state.de.us\" in e: leg_email =", "for tr in trs: name_and_url = tr.xpath('.//a')[0] bio_url = name_and_url.attrib[\"href\"]", "= office.xpath(\"./td\")[title_td+1].text_content() except IndexError: continue leg_office = self.add_contact(\"legislative\", title_text,content,leg_office) dist_office", "try: emails = email.split(\";\") except AttributeError: pass else: for e", "table = None for line in table_js.split(\"\\n\"): if line.strip().startswith(\"var\") and", "\"{} phone\".format(office_type) in title_text: phones = content.lower().split(\"\\n\") if len(phones) ==", "the office #either \"legislative\" or \"outside\" if \"{} office\".format(office_type) in", "photo is the first td if len(office.xpath(\"./td/img\")) > 0: title_td", "in one of these party = doc.xpath('//div[@id=\"page_header\"]')[0].text.strip()[-3:] if '(D)' in", "elif \"fax\" in line: phone = self.clean_phone(line) if phone: office[\"fax\"]", "trs = doc.xpath('//tr') base_url = \"http://legis.delaware.gov\" for tr in trs:", "= doc.xpath(\".//a[contains(@href,'mailto')]\") email = email[0].text_content().strip() leg_email = None dist_email =", "= email.split(\";\") except AttributeError: pass else: for e in emails:", "e in emails: e = e.strip() if e: if \"state.de.us\"", "add_contact(self,office_type, title_text,content,office): #office type is the name of the office", "email=leg_email, address=None) dist_office = dict(name=\"Outside Office\", type=\"capitol\", phone=None,fax=None, email=dist_email, address=None)", "= 'Democratic' elif '(R)' in party: party = 'Republican' else:", "e else: dist_email = e # Offices leg_office = dict(name=\"Capitol", "title_text,content,office): #office type is the name of the office #either", "the name of the office #either \"legislative\" or \"outside\" if", "party: party = 'Democratic' elif '(R)' in party: party =", "in js. table_js = doc.xpath('.//script')[-1].text_content() table = None for line", "house, but kindly in actual html trs = doc.xpath('//tr') base_url", "leg_office = self.add_contact(\"legislative\", title_text,content,leg_office) dist_office = self.add_contact(\"outside\", title_text,content,dist_office) offices =", "not re.search(\"\\d\",phone): return if not \":\" in phone: return phone", "= self.lxmlize(url) if chamber == \"upper\": #for the senate, it's", "name_and_url.attrib[\"href\"] bio_url = bio_url.replace(\"JavaScript:window.top.location.href=\",\"\") bio_url = bio_url.replace('\"','') name = name_and_url.text_content()", "chamber, term): url = { 'upper': 'http://legis.delaware.gov/legislature.nsf/sen?openview', 'lower': 'http://legis.delaware.gov/Legislature.nsf/Reps?openview', }[chamber]", "found for {name}\".format(name=name)) leg = Legislator(term, chamber, district, name, party=party)", "committee section without having to do another request url +=", "if \"{} office\".format(office_type) in title_text: office[\"address\"] = content.strip() if \"{}", "= bio_url.replace(\"JavaScript:window.top.location.href=\",\"\") bio_url = bio_url.replace('\"','') name = name_and_url.text_content() if name.strip()", "if \"phone\" in line: phone = self.clean_phone(line) if phone: office[\"phone\"]", "= district.replace(\"District:\",\"\").strip() leg = self.scrape_bio(term, chamber, district, name, bio_url) leg.add_source(bio_url,", "dist_office = dict(name=\"Outside Office\", type=\"capitol\", phone=None,fax=None, email=dist_email, address=None) #this is", "def add_contact(self,office_type, title_text,content,office): #office type is the name of the", "phone: office[\"phone\"] = phone else: for line in phones: if", "list page\") self.save_legislator(leg) def scrape_bio(self, term, chamber, district, name, url):", "party is in one of these party = doc.xpath('//div[@id=\"page_header\"]')[0].text.strip()[-3:] if", "'http://legis.delaware.gov/Legislature.nsf/Reps?openview', }[chamber] doc = self.lxmlize(url) if chamber == \"upper\": #for", "enormously painful, DE. office_list = doc.xpath(\"//tr\") for office in office_list:", "== 1: phone = self.clean_phone(phones[0]) if phone: office[\"phone\"] = phone", "lxml.html.fromstring(table) table.make_links_absolute(url) trs = table.xpath('//tr') else: #same table for the", "table = table.replace('>\";','>') break assert table is not None, \"Senate", "= table.xpath('//tr') else: #same table for the house, but kindly", "name of the office #either \"legislative\" or \"outside\" if \"{}", "office def clean_phone(self,phone): if not phone.strip(): return if not re.search(\"\\d\",phone):", "def clean_phone(self,phone): if not phone.strip(): return if not re.search(\"\\d\",phone): return", "scrape_contact_info(self, doc): # Email email = doc.xpath(\".//a[contains(@href,'mailto')]\") email = email[0].text_content().strip()", "page=\"legislator list page\") self.save_legislator(leg) def scrape_bio(self, term, chamber, district, name,", "break assert table is not None, \"Senate table could not", "name = ' '.join(re_spaces.split(name)) district = tr.xpath('.//td')[2].text_content() district = district.replace(\"District:\",\"\").strip()", "name, bio_url) leg.add_source(bio_url, page=\"legislator detail page\") leg.add_source(url, page=\"legislator list page\")", "name, url): # this opens the committee section without having", "self.add_contact(\"legislative\", title_text,content,leg_office) dist_office = self.add_contact(\"outside\", title_text,content,dist_office) offices = [o for", "= content.lower().split(\"\\n\") if len(phones) == 1: phone = self.clean_phone(phones[0]) if", "line in table_js.split(\"\\n\"): if line.strip().startswith(\"var\") and \"sen=\" in line: table", "actual_url = frame_doc.xpath(\"//frame[@name='right']/@src\")[0] doc = self.lxmlize(actual_url) # party is in", "None, \"Senate table could not be found\" table = lxml.html.fromstring(table)", "table.make_links_absolute(url) trs = table.xpath('//tr') else: #same table for the house,", "office_list = doc.xpath(\"//tr\") for office in office_list: title_td = 0", "e.strip() if e: if \"state.de.us\" in e: leg_email = e", "= tr.xpath('.//a')[0] bio_url = name_and_url.attrib[\"href\"] bio_url = bio_url.replace(\"JavaScript:window.top.location.href=\",\"\") bio_url =", "td if len(office.xpath(\"./td/img\")) > 0: title_td = 1 try: title_text", "this opens the committee section without having to do another", "\"\\ \"make sure we're not losing any data.\" return {\"offices\":offices}", "= \"http://legis.delaware.gov\" for tr in trs: name_and_url = tr.xpath('.//a')[0] bio_url", "first td if len(office.xpath(\"./td/img\")) > 0: title_td = 1 try:", "title_text,content,leg_office) dist_office = self.add_contact(\"outside\", title_text,content,dist_office) offices = [o for o", "1 try: title_text = office.xpath(\"./td\")[title_td].text_content().lower() content = office.xpath(\"./td\")[title_td+1].text_content() except IndexError:", "if \"state.de.us\" in e: leg_email = e else: dist_email =", "assert table is not None, \"Senate table could not be", "elif '(R)' in party: party = 'Republican' else: raise AssertionError(\"No", "DELegislatorScraper(LegislatorScraper,LXMLMixin): jurisdiction = 'de' def scrape(self, chamber, term): url =", "doc.xpath('//tr') base_url = \"http://legis.delaware.gov\" for tr in trs: name_and_url =", "leg.add_source(url, page=\"legislator list page\") self.save_legislator(leg) def scrape_bio(self, term, chamber, district,", "e = e.strip() if e: if \"state.de.us\" in e: leg_email", "= self.clean_phone(phones[0]) if phone: office[\"phone\"] = phone else: for line", "line in phones: if \"phone\" in line: phone = self.clean_phone(line)", "\"\": continue if name.strip().lower().startswith(\"vacant\"): continue re_spaces=re.compile(r'\\s{1,5}') name = ' '.join(re_spaces.split(name))", "office\".format(office_type) in title_text: office[\"address\"] = content.strip() if \"{} phone\".format(office_type) in", "AttributeError: pass else: for e in emails: e = e.strip()", "of the office #either \"legislative\" or \"outside\" if \"{} office\".format(office_type)", "chamber, district, name, url): # this opens the committee section", "name.strip() == \"\": continue if name.strip().lower().startswith(\"vacant\"): continue re_spaces=re.compile(r'\\s{1,5}') name =", "or \"outside\" if \"{} office\".format(office_type) in title_text: office[\"address\"] = content.strip()", "'upper': 'http://legis.delaware.gov/legislature.nsf/sen?openview', 'lower': 'http://legis.delaware.gov/Legislature.nsf/Reps?openview', }[chamber] doc = self.lxmlize(url) if chamber", "pass else: for e in emails: e = e.strip() if", "\"make sure we're not losing any data.\" return {\"offices\":offices} def", "js. table_js = doc.xpath('.//script')[-1].text_content() table = None for line in", "\"sen=\" in line: table = line.replace(\"var\",\"\") table = table.replace('sen=\"<','<') table", "html trs = doc.xpath('//tr') base_url = \"http://legis.delaware.gov\" for tr in", "photo_url = doc.xpath('//img[contains(@src, \"jpg\")]/@src') if photo_url: leg['photo_url'] = photo_url[0] contact_info", "except AttributeError: pass else: for e in emails: e =", "scrape(self, chamber, term): url = { 'upper': 'http://legis.delaware.gov/legislature.nsf/sen?openview', 'lower': 'http://legis.delaware.gov/Legislature.nsf/Reps?openview',", "jurisdiction = 'de' def scrape(self, chamber, term): url = {", "'(D)' in party: party = 'Democratic' elif '(R)' in party:", "{name}\".format(name=name)) leg = Legislator(term, chamber, district, name, party=party) photo_url =", "[leg_office,dist_office] if o[\"address\"]] assert len(offices) > 0, \"No offices with", "address=None) #this is enormously painful, DE. office_list = doc.xpath(\"//tr\") for", "kindly in actual html trs = doc.xpath('//tr') base_url = \"http://legis.delaware.gov\"", "= self.lxmlize(actual_url) # party is in one of these party", "email.split(\";\") except AttributeError: pass else: for e in emails: e", "is in one of these party = doc.xpath('//div[@id=\"page_header\"]')[0].text.strip()[-3:] if '(D)'", "losing any data.\" return {\"offices\":offices} def add_contact(self,office_type, title_text,content,office): #office type", "# Email email = doc.xpath(\".//a[contains(@href,'mailto')]\") email = email[0].text_content().strip() leg_email =", "to do another request url += '&TableRow=1.5.5' frame_doc = self.lxmlize(url)", "content.lower().split(\"\\n\") if len(phones) == 1: phone = self.clean_phone(phones[0]) if phone:", "from billy.scrape.legislators import LegislatorScraper, Legislator class DELegislatorScraper(LegislatorScraper,LXMLMixin): jurisdiction = 'de'", "page=\"legislator detail page\") leg.add_source(url, page=\"legislator list page\") self.save_legislator(leg) def scrape_bio(self,", "leg.add_source(bio_url, page=\"legislator detail page\") leg.add_source(url, page=\"legislator list page\") self.save_legislator(leg) def", "0: title_td = 1 try: title_text = office.xpath(\"./td\")[title_td].text_content().lower() content =", "for line in phones: if \"phone\" in line: phone =", "in line: phone = self.clean_phone(line) if phone: office[\"fax\"] = phone", "self.lxmlize(url) if chamber == \"upper\": #for the senate, it's the", "bio_url = bio_url.replace('\"','') name = name_and_url.text_content() if name.strip() == \".\"", "Offices leg_office = dict(name=\"Capitol Office\", type=\"capitol\", phone=None, fax=None, email=leg_email, address=None)", "\"No offices with addresses found \"\\ \"make sure we're not", "is hard-coded in js. table_js = doc.xpath('.//script')[-1].text_content() table = None", "district, name, party=party) photo_url = doc.xpath('//img[contains(@src, \"jpg\")]/@src') if photo_url: leg['photo_url']", "tr.xpath('.//a')[0] bio_url = name_and_url.attrib[\"href\"] bio_url = bio_url.replace(\"JavaScript:window.top.location.href=\",\"\") bio_url = bio_url.replace('\"','')", "'.join(re_spaces.split(name)) district = tr.xpath('.//td')[2].text_content() district = district.replace(\"District:\",\"\").strip() leg = self.scrape_bio(term,", "office[\"fax\"] = phone return office def clean_phone(self,phone): if not phone.strip():", "= lxml.html.fromstring(table) table.make_links_absolute(url) trs = table.xpath('//tr') else: #same table for", "for {name}\".format(name=name)) leg = Legislator(term, chamber, district, name, party=party) photo_url", "= dict(name=\"Capitol Office\", type=\"capitol\", phone=None, fax=None, email=leg_email, address=None) dist_office =", "is enormously painful, DE. office_list = doc.xpath(\"//tr\") for office in", "offices = [o for o in [leg_office,dist_office] if o[\"address\"]] assert", "doc.xpath('//img[contains(@src, \"jpg\")]/@src') if photo_url: leg['photo_url'] = photo_url[0] contact_info = self.scrape_contact_info(doc)", "len(phones) == 1: phone = self.clean_phone(phones[0]) if phone: office[\"phone\"] =", "= self.clean_phone(line) if phone: office[\"phone\"] = phone elif \"fax\" in", "photo_url[0] contact_info = self.scrape_contact_info(doc) leg.update(contact_info) return leg def scrape_contact_info(self, doc):", "title_td = 1 try: title_text = office.xpath(\"./td\")[title_td].text_content().lower() content = office.xpath(\"./td\")[title_td+1].text_content()", "party found for {name}\".format(name=name)) leg = Legislator(term, chamber, district, name,", "base_url = \"http://legis.delaware.gov\" for tr in trs: name_and_url = tr.xpath('.//a')[0]", "for e in emails: e = e.strip() if e: if", "in trs: name_and_url = tr.xpath('.//a')[0] bio_url = name_and_url.attrib[\"href\"] bio_url =", "try: title_text = office.xpath(\"./td\")[title_td].text_content().lower() content = office.xpath(\"./td\")[title_td+1].text_content() except IndexError: continue", "= phone return office def clean_phone(self,phone): if not phone.strip(): return", "district.replace(\"District:\",\"\").strip() leg = self.scrape_bio(term, chamber, district, name, bio_url) leg.add_source(bio_url, page=\"legislator", "= self.scrape_bio(term, chamber, district, name, bio_url) leg.add_source(bio_url, page=\"legislator detail page\")" ]
[ "ids[-(self.args['max_len']-2):] # ignore [CLS] and [SEP] position_w = position_w[-(self.args['max_len']-2):] rids_", "= [], [] for _, utterances in batch: item =", "rids = [] for label, utterances in batch: item =", "= [torch.LongTensor(i) for i in bundle['rids']] return ids, rids, bundle['label'],", "= self.vocab.batch_encode_plus(utterances, add_special_tokens=False)['input_ids'] cids = [] for u in item[:-1]:", "(len(cids) + 2) + [1] * (len(rids) + 1) ids.append(ids_)", "self.special_tokens: position_w.append(w) else: position_w.append(self.args['w_sp_token']) w += self.args['w_delta'] ids.pop() position_w.pop() ids", "from .util_func import * '''Only for Testing''' class FineGrainedTestDataset(Dataset): def", "rids_ = item[:-1], item[-1] ids = [] position_w, w =", "context, 'responses': responses, 'owner': fix, }) def __len__(self): return len(self.data)", "= torch.LongTensor(bundle['ids']) rids = [torch.LongTensor(i) for i in bundle['rids']] return", "return { 'ids': ids, 'rids': rids, 'rids_mask': rids_mask, 'pos_w': pos_w,", "responses, bundle['owner'] def save(self): data = torch.save(self.data, self.pp_path) print(f'[!] save", "== 1 ids, rids, label, text, owner = batch[0] rids", "rids_mask, label = to_cuda(ids, rids, pos_w, rids_mask, label) return {", "'ids': ids, 'rids': rids, 'rids_mask': rids_mask, 'pos_w': pos_w, 'label': label,", "rids_mask = generate_mask(rids) label = torch.LongTensor(label) ids, rids, rids_mask, label", "= [torch.LongTensor(i) for i in bundle['ids']] tids = [torch.LongTensor(i) for", "7)): batch = data[i:i+7] rids = [] for label, utterances", "item[-1] truncate_pair(cids, rids, self.args['max_len']) ids_ = [self.cls] + cids +", "item[-1] ids = [] for u in cids: ids.extend(u +", "+ 1) ids.append(ids_) tids.append(tids_) responses.append(utterances[-1]) context = ' [SEP] '.join(utterances[:-1])", "'owner': owner, } class FineGrainedTestPositionWeightDataset(Dataset): def __init__(self, vocab, path, **args):", "**args): self.args = args self.vocab = vocab self.vocab.add_tokens(['[EOS]']) self.pad =", "batch[0] ids = pad_sequence(ids, batch_first=True, padding_value=self.pad) tids = pad_sequence(tids, batch_first=True,", "tids, 'context': context, 'responses': responses, 'owner': fix, }) def __len__(self):", "cids: ids.extend(u + [self.sep]) ids.pop() ids = ids[-(self.args['max_len']-2):] # ignore", "to_cuda(ids, rids, rids_mask, label) return { 'ids': ids, 'rids': rids,", "bundle['tids']] context, responses = bundle['context'], bundle['responses'] return ids, tids, bundle['label'],", "def __init__(self, vocab, path, **args): self.args = args self.vocab =", "generate_mask(ids) ids, tids, mask, label = to_cuda(ids, tids, mask, label)", "torch.save(self.data, self.pp_path) print(f'[!] save preprocessed dataset into {self.pp_path}') def collate(self,", "= f'{os.path.splitext(path)[0]}_fg_interaction_test_{suffix}.pt' if os.path.exists(self.pp_path): self.data = torch.load(self.pp_path) print(f'[!] load preprocessed", "tqdm(range(0, len(data), 7)): batch = data[i:i+7] rids = [] ids,", "label = to_cuda(ids, rids, pos_w, rids_mask, label) return { 'ids':", "return { 'ids': ids, 'rids': rids, 'rids_mask': rids_mask, 'label': label,", "torch.LongTensor(label) ids, rids, pos_w, rids_mask, label = to_cuda(ids, rids, pos_w,", "[SEP] '.join(utterances[:-1]) self.data.append({ 'label': [b[0] for b in batch], 'ids':", "= args['tokenizer'].replace('/', '_') self.pp_path = f'{os.path.splitext(path)[0]}_fg_test_pw_{suffix}.pt' if os.path.exists(self.pp_path): self.data =", "len(self.data) def __getitem__(self, i): bundle = self.data[i] ids = [torch.LongTensor(i)", "in bundle['rids']] return ids, rids, bundle['label'], bundle['text'], bundle['owner'] def save(self):", "[self.eos]) cids.pop() rids = item[-1] truncate_pair(cids, rids, self.args['max_len']) ids_ =", "= [torch.LongTensor(i) for i in bundle['rids']] position_w = torch.tensor(bundle['position_w']) return", "pos_w, 'label': label, 'text': text, 'owner': owner, } class FineGrainedTestInteractionDataset(Dataset):", "rids = [torch.LongTensor(i) for i in bundle['rids']] position_w = torch.tensor(bundle['position_w'])", "+= self.args['w_delta'] ids.pop() position_w.pop() ids = ids[-(self.args['max_len']-2):] # ignore [CLS]", "= [], [] context, responses = [], [] for _,", "mask, label = to_cuda(ids, tids, mask, label) return { 'ids':", "ignore [CLS] and [SEP] rids_ = rids_[:(self.args['res_max_len']-2)] ids = [self.cls]", "position_w = [w-self.args['w_delta']] + position_w + [self.args['w_sp_token']] rids_ = [self.cls]", "rids_mask, label) return { 'ids': ids, 'rids': rids, 'rids_mask': rids_mask,", "= [], self.args['min_w'] for u in cids: ids.extend(u + [self.sep])", "'owner': owner, } class FineGrainedTestInteractionDataset(Dataset): def __init__(self, vocab, path, **args):", "rids_ = [self.cls] + rids_ + [self.sep] rids.append(rids_) self.data.append({ 'label':", "__getitem__(self, i): bundle = self.data[i] ids = [torch.LongTensor(i) for i", "u in cids: ids.extend(u + [self.sep]) for token in u", "} class FineGrainedTestInteractionDataset(Dataset): def __init__(self, vocab, path, **args): self.args =", "len(self.data) def __getitem__(self, i): bundle = self.data[i] ids = torch.LongTensor(bundle['ids'])", "= args self.vocab = vocab self.vocab.add_tokens(['[EOS]']) self.pad = self.vocab.convert_tokens_to_ids('[PAD]') self.sep", "<gh_stars>10-100 from header import * from .utils import * from", "= pad_sequence(rids, batch_first=True, padding_value=self.pad) rids_mask = generate_mask(rids) label = torch.LongTensor(label)", "len(batch) == 1 ids, rids, pos_w, label, text, owner =", "ids = pad_sequence(ids, batch_first=True, padding_value=self.pad) tids = pad_sequence(tids, batch_first=True, padding_value=self.pad)", "collate(self, batch): assert len(batch) == 1 ids, rids, pos_w, label,", "[CLS] and [SEP] position_w = position_w[-(self.args['max_len']-2):] rids_ = rids_[:(self.args['res_max_len']-2)] ids", "i in bundle['ids']] tids = [torch.LongTensor(i) for i in bundle['tids']]", "[torch.LongTensor(i) for i in bundle['rids']] return ids, rids, bundle['label'], bundle['text'],", "= generate_mask(rids) label = torch.LongTensor(label) ids, rids, pos_w, rids_mask, label", "padding_value=self.pad) rids_mask = generate_mask(rids) label = torch.LongTensor(label) ids, rids, pos_w,", "suffix = args['tokenizer'].replace('/', '_') self.pp_path = f'{os.path.splitext(path)[0]}_fg_test_{suffix}.pt' if os.path.exists(self.pp_path): self.data", "self.cls = self.vocab.convert_tokens_to_ids('[CLS]') suffix = args['tokenizer'].replace('/', '_') self.pp_path = f'{os.path.splitext(path)[0]}_fg_test_{suffix}.pt'", "args['tokenizer'].replace('/', '_') self.pp_path = f'{os.path.splitext(path)[0]}_fg_test_pw_{suffix}.pt' if os.path.exists(self.pp_path): self.data = torch.load(self.pp_path)", "in batch: item = self.vocab.batch_encode_plus(utterances, add_special_tokens=False)['input_ids'] cids, rids_ = item[:-1],", "bundle['ids']] tids = [torch.LongTensor(i) for i in bundle['tids']] context, responses", "+ [self.sep] + rids + [self.sep] tids_ = [0] *", "self.eos = self.vocab.convert_tokens_to_ids('[EOS]') self.cls = self.vocab.convert_tokens_to_ids('[CLS]') suffix = args['tokenizer'].replace('/', '_')", "rids_mask = generate_mask(rids) label = torch.LongTensor(label) ids, rids, pos_w, rids_mask,", "rids, rids_mask, label) return { 'ids': ids, 'rids': rids, 'rids_mask':", "header import * from .utils import * from .util_func import", "ids, rids, label, text, owner = batch[0] rids = pad_sequence(rids,", "'ids': ids, 'tids': tids, 'context': context, 'responses': responses, 'owner': fix,", "data[i:i+7] rids = [] for label, utterances in batch: item", "'rids_mask': rids_mask, 'label': label, 'text': text, 'owner': owner, } class", "rids, self.args['max_len']) ids_ = [self.cls] + cids + [self.sep] +", "position_w.append(w) else: position_w.append(self.args['w_sp_token']) w += self.args['w_delta'] ids.pop() position_w.pop() ids =", "text, 'owner': owner, } class FineGrainedTestInteractionDataset(Dataset): def __init__(self, vocab, path,", "ids = [self.cls] + ids + [self.sep] rids_ = [self.cls]", "[] for u in item[:-1]: cids.extend(u + [self.eos]) cids.pop() rids", "= pad_sequence(ids, batch_first=True, padding_value=self.pad) tids = pad_sequence(tids, batch_first=True, padding_value=self.pad) label", "pad_sequence(rids, batch_first=True, padding_value=self.pad) rids_mask = generate_mask(rids) label = torch.LongTensor(label) ids,", "7)): batch = data[i:i+7] rids = [] ids, tids =", "save(self): data = torch.save(self.data, self.pp_path) print(f'[!] save preprocessed dataset into", "= self.vocab.convert_tokens_to_ids('[CLS]') self.unk = self.vocab.convert_tokens_to_ids('[UNK]') self.special_tokens = set([self.unk, self.cls, self.sep])", "+ position_w + [self.args['w_sp_token']] rids_ = [self.cls] + rids_ +", "u + [self.sep]: if token not in self.special_tokens: position_w.append(w) else:", "'label': label, 'text': text, 'owner': owner, } class FineGrainedTestInteractionDataset(Dataset): def", "= to_cuda(ids, rids, rids_mask, label) return { 'ids': ids, 'rids':", "ids = ids[-(self.args['max_len']-2):] # ignore [CLS] and [SEP] position_w =", "torch.LongTensor(bundle['ids']) rids = [torch.LongTensor(i) for i in bundle['rids']] return ids,", "[self.cls] + ids + [self.sep] position_w = [w-self.args['w_delta']] + position_w", "'ids': ids, 'tids': tids, 'mask': mask, 'label': label, 'owner': owner,", "self.data[i] ids = torch.LongTensor(bundle['ids']) rids = [torch.LongTensor(i) for i in", "in self.special_tokens: position_w.append(w) else: position_w.append(self.args['w_sp_token']) w += self.args['w_delta'] ids.pop() position_w.pop()", "__init__(self, vocab, path, **args): self.args = args self.vocab = vocab", "cids + [self.sep] + rids + [self.sep] tids_ = [0]", "batch], 'position_w': position_w, 'owner': fix, }) def __len__(self): return len(self.data)", "in bundle['rids']] position_w = torch.tensor(bundle['position_w']) return ids, rids, position_w, bundle['label'],", "batch[0] rids = pad_sequence(rids, batch_first=True, padding_value=self.pad) rids_mask = generate_mask(rids) label", "torch.load(self.pp_path) print(f'[!] load preprocessed file from {self.pp_path}') return None self.data", "args self.vocab = vocab self.vocab.add_tokens(['[EOS]']) self.pad = self.vocab.convert_tokens_to_ids('[PAD]') self.sep =", "context, responses, bundle['owner'] def save(self): data = torch.save(self.data, self.pp_path) print(f'[!]", "[], self.args['min_w'] for u in cids: ids.extend(u + [self.sep]) for", "rids, pos_w, label, text, owner = batch[0] rids = pad_sequence(rids,", "[SEP] position_w = position_w[-(self.args['max_len']-2):] rids_ = rids_[:(self.args['res_max_len']-2)] ids = [self.cls]", "batch): assert len(batch) == 1 ids, tids, label, context, responses,", "label, 'text': text, 'owner': owner, } class FineGrainedTestPositionWeightDataset(Dataset): def __init__(self,", "args['tokenizer'].replace('/', '_') self.pp_path = f'{os.path.splitext(path)[0]}_fg_test_{suffix}.pt' if os.path.exists(self.pp_path): self.data = torch.load(self.pp_path)", "= self.data[i] ids = torch.LongTensor(bundle['ids']) rids = [torch.LongTensor(i) for i", "rids_[:(self.args['res_max_len']-2)] ids = [self.cls] + ids + [self.sep] rids_ =", "label) return { 'ids': ids, 'rids': rids, 'rids_mask': rids_mask, 'label':", "= item[:-1], item[-1] ids = [] position_w, w = [],", "position_w, w = [], self.args['min_w'] for u in cids: ids.extend(u", "in bundle['ids']] tids = [torch.LongTensor(i) for i in bundle['tids']] context,", "{self.pp_path}') def collate(self, batch): assert len(batch) == 1 ids, rids,", "'text': ['\\t'.join(b[1]) for b in batch], 'position_w': position_w, 'owner': fix,", "= [] for u in item[:-1]: cids.extend(u + [self.eos]) cids.pop()", "self.special_tokens = set([self.unk, self.cls, self.sep]) suffix = args['tokenizer'].replace('/', '_') self.pp_path", "= read_text_data_utterances(path, lang=self.args['lang']) for i in tqdm(range(0, len(data), 7)): batch", "[self.cls] + cids + [self.sep] + rids + [self.sep] tids_", "rids, 'rids_mask': rids_mask, 'label': label, 'text': text, 'owner': owner, }", "rids, position_w, bundle['label'], bundle['text'], bundle['owner'] def save(self): data = torch.save(self.data,", "= [self.cls] + ids + [self.sep] rids_ = [self.cls] +", "args['tokenizer'].replace('/', '_') self.pp_path = f'{os.path.splitext(path)[0]}_fg_interaction_test_{suffix}.pt' if os.path.exists(self.pp_path): self.data = torch.load(self.pp_path)", "rids_[:(self.args['res_max_len']-2)] ids = [self.cls] + ids + [self.sep] position_w =", "= rids_[:(self.args['res_max_len']-2)] ids = [self.cls] + ids + [self.sep] rids_", "ids[-(self.args['max_len']-2):] # ignore [CLS] and [SEP] rids_ = rids_[:(self.args['res_max_len']-2)] ids", "utterances in batch: item = self.vocab.batch_encode_plus(utterances, add_special_tokens=False)['input_ids'] cids, rids_ =", "rids = item[-1] truncate_pair(cids, rids, self.args['max_len']) ids_ = [self.cls] +", "def collate(self, batch): assert len(batch) == 1 ids, rids, label,", "self.vocab.convert_tokens_to_ids('[EOS]') self.cls = self.vocab.convert_tokens_to_ids('[CLS]') suffix = args['tokenizer'].replace('/', '_') self.pp_path =", "= self.vocab.convert_tokens_to_ids('[EOS]') self.cls = self.vocab.convert_tokens_to_ids('[CLS]') self.unk = self.vocab.convert_tokens_to_ids('[UNK]') self.special_tokens =", "assert len(batch) == 1 ids, rids, label, text, owner =", "len(batch) == 1 ids, tids, label, context, responses, owner =", "position_w = position_w[-(self.args['max_len']-2):] rids_ = rids_[:(self.args['res_max_len']-2)] ids = [self.cls] +", "batch], 'ids': ids, 'rids': rids, 'text': ['\\t'.join(b[1]) for b in", "save preprocessed dataset into {self.pp_path}') def collate(self, batch): assert len(batch)", "label, 'text': text, 'owner': owner, } class FineGrainedTestInteractionDataset(Dataset): def __init__(self,", "= item[-1] truncate_pair(cids, rids, self.args['max_len']) ids_ = [self.cls] + cids", "for Testing''' class FineGrainedTestDataset(Dataset): def __init__(self, vocab, path, **args): self.args", "fix in ['brandenwang', 'lt', 'lt2']: path = f'{args[\"root_dir\"]}/data/{args[\"dataset\"]}/fg-{fix}-test.txt' data =", "FineGrainedTestPositionWeightDataset(Dataset): def __init__(self, vocab, path, **args): self.args = args self.vocab", "in u + [self.sep]: if token not in self.special_tokens: position_w.append(w)", "= torch.LongTensor(label) mask = generate_mask(ids) ids, tids, mask, label =", "* from .utils import * from .util_func import * '''Only", "for i in tqdm(range(0, len(data), 7)): batch = data[i:i+7] rids", "tids = [torch.LongTensor(i) for i in bundle['tids']] context, responses =", "= [w-self.args['w_delta']] + position_w + [self.args['w_sp_token']] rids_ = [self.cls] +", "+ [self.sep]) for token in u + [self.sep]: if token", "self.args['max_len']) ids_ = [self.cls] + cids + [self.sep] + rids", "self.vocab.convert_tokens_to_ids('[CLS]') suffix = args['tokenizer'].replace('/', '_') self.pp_path = f'{os.path.splitext(path)[0]}_fg_test_{suffix}.pt' if os.path.exists(self.pp_path):", "self.unk = self.vocab.convert_tokens_to_ids('[UNK]') self.special_tokens = set([self.unk, self.cls, self.sep]) suffix =", "return len(self.data) def __getitem__(self, i): bundle = self.data[i] ids =", "'owner': fix, }) def __len__(self): return len(self.data) def __getitem__(self, i):", "label = torch.LongTensor(label) ids, rids, rids_mask, label = to_cuda(ids, rids,", "path = f'{args[\"root_dir\"]}/data/{args[\"dataset\"]}/fg-{fix}-test.txt' data = read_text_data_utterances(path, lang=self.args['lang']) for i in", "'text': ['\\t'.join(b[1]) for b in batch], 'owner': fix, }) def", "set([self.unk, self.cls, self.sep]) suffix = args['tokenizer'].replace('/', '_') self.pp_path = f'{os.path.splitext(path)[0]}_fg_test_pw_{suffix}.pt'", "from .utils import * from .util_func import * '''Only for", "in cids: ids.extend(u + [self.sep]) ids.pop() ids = ids[-(self.args['max_len']-2):] #", "'_') self.pp_path = f'{os.path.splitext(path)[0]}_fg_test_{suffix}.pt' if os.path.exists(self.pp_path): self.data = torch.load(self.pp_path) print(f'[!]", "[self.cls] + rids_ + [self.sep] rids.append(rids_) self.data.append({ 'label': [b[0] for", "if os.path.exists(self.pp_path): self.data = torch.load(self.pp_path) print(f'[!] load preprocessed file from", "bundle['label'], context, responses, bundle['owner'] def save(self): data = torch.save(self.data, self.pp_path)", "position_w, bundle['label'], bundle['text'], bundle['owner'] def save(self): data = torch.save(self.data, self.pp_path)", "suffix = args['tokenizer'].replace('/', '_') self.pp_path = f'{os.path.splitext(path)[0]}_fg_test_pw_{suffix}.pt' if os.path.exists(self.pp_path): self.data", "text, owner = batch[0] rids = pad_sequence(rids, batch_first=True, padding_value=self.pad) rids_mask", "len(data), 7)): batch = data[i:i+7] rids = [] ids, tids", "[self.sep] rids.append(rids_) self.data.append({ 'label': [b[0] for b in batch], 'ids':", "w = [], self.args['min_w'] for u in cids: ids.extend(u +", "[] for label, utterances in batch: item = self.vocab.batch_encode_plus(utterances, add_special_tokens=False)['input_ids']", "tqdm(range(0, len(data), 7)): batch = data[i:i+7] rids = [] for", "= self.vocab.convert_tokens_to_ids('[SEP]') self.eos = self.vocab.convert_tokens_to_ids('[EOS]') self.cls = self.vocab.convert_tokens_to_ids('[CLS]') self.unk =", "rids = [] ids, tids = [], [] context, responses", "'rids': rids, 'text': ['\\t'.join(b[1]) for b in batch], 'position_w': position_w,", "ids, 'tids': tids, 'mask': mask, 'label': label, 'owner': owner, }", "Testing''' class FineGrainedTestDataset(Dataset): def __init__(self, vocab, path, **args): self.args =", "'ids': ids, 'rids': rids, 'text': ['\\t'.join(b[1]) for b in batch],", "rids, label, text, owner = batch[0] rids = pad_sequence(rids, batch_first=True,", "rids + [self.sep] tids_ = [0] * (len(cids) + 2)", "+ [self.eos]) cids.pop() rids = item[-1] truncate_pair(cids, rids, self.args['max_len']) ids_", "for u in item[:-1]: cids.extend(u + [self.eos]) cids.pop() rids =", "path, **args): self.args = args self.vocab = vocab self.vocab.add_tokens(['[EOS]']) self.pad", "[b[0] for b in batch], 'ids': ids, 'rids': rids, 'text':", "= f'{os.path.splitext(path)[0]}_fg_test_pw_{suffix}.pt' if os.path.exists(self.pp_path): self.data = torch.load(self.pp_path) print(f'[!] load preprocessed", "__getitem__(self, i): bundle = self.data[i] ids = torch.LongTensor(bundle['ids']) rids =", "[w-self.args['w_delta']] + position_w + [self.args['w_sp_token']] rids_ = [self.cls] + rids_", "in batch], 'ids': ids, 'rids': rids, 'text': ['\\t'.join(b[1]) for b", "torch.LongTensor(label) mask = generate_mask(ids) ids, tids, mask, label = to_cuda(ids,", "torch.LongTensor(bundle['ids']) rids = [torch.LongTensor(i) for i in bundle['rids']] position_w =", "2) + [1] * (len(rids) + 1) ids.append(ids_) tids.append(tids_) responses.append(utterances[-1])", "[torch.LongTensor(i) for i in bundle['ids']] tids = [torch.LongTensor(i) for i", "i in tqdm(range(0, len(data), 7)): batch = data[i:i+7] rids =", "= torch.LongTensor(bundle['ids']) rids = [torch.LongTensor(i) for i in bundle['rids']] position_w", "= f'{args[\"root_dir\"]}/data/{args[\"dataset\"]}/fg-{fix}-test.txt' data = read_text_data_utterances(path, lang=self.args['lang']) for i in tqdm(range(0,", "u in item[:-1]: cids.extend(u + [self.eos]) cids.pop() rids = item[-1]", "preprocessed file from {self.pp_path}') return None self.data = [] for", "= ids[-(self.args['max_len']-2):] # ignore [CLS] and [SEP] position_w = position_w[-(self.args['max_len']-2):]", "self.vocab.convert_tokens_to_ids('[PAD]') self.sep = self.vocab.convert_tokens_to_ids('[SEP]') self.eos = self.vocab.convert_tokens_to_ids('[EOS]') self.cls = self.vocab.convert_tokens_to_ids('[CLS]')", "position_w = torch.tensor(bundle['position_w']) return ids, rids, position_w, bundle['label'], bundle['text'], bundle['owner']", "def collate(self, batch): assert len(batch) == 1 ids, rids, pos_w,", "= pad_sequence(tids, batch_first=True, padding_value=self.pad) label = torch.LongTensor(label) mask = generate_mask(ids)", "+ [self.sep] position_w = [w-self.args['w_delta']] + position_w + [self.args['w_sp_token']] rids_", "[CLS] and [SEP] rids_ = rids_[:(self.args['res_max_len']-2)] ids = [self.cls] +", "self.args['w_delta'] ids.pop() position_w.pop() ids = ids[-(self.args['max_len']-2):] # ignore [CLS] and", "for i in bundle['tids']] context, responses = bundle['context'], bundle['responses'] return", "self.data.append({ 'label': [b[0] for b in batch], 'ids': ids, 'rids':", "print(f'[!] load preprocessed file from {self.pp_path}') return None self.data =", "batch = data[i:i+7] rids = [] ids, tids = [],", "= to_cuda(ids, rids, pos_w, rids_mask, label) return { 'ids': ids,", "+ [1] * (len(rids) + 1) ids.append(ids_) tids.append(tids_) responses.append(utterances[-1]) context", "# ignore [CLS] and [SEP] rids_ = rids_[:(self.args['res_max_len']-2)] ids =", "add_special_tokens=False)['input_ids'] cids, rids_ = item[:-1], item[-1] ids = [] for", "b in batch], 'position_w': position_w, 'owner': fix, }) def __len__(self):", "batch = data[i:i+7] rids = [] for label, utterances in", "def __getitem__(self, i): bundle = self.data[i] ids = [torch.LongTensor(i) for", "ids, 'tids': tids, 'context': context, 'responses': responses, 'owner': fix, })", "1 ids, rids, pos_w, label, text, owner = batch[0] rids", "lang=self.args['lang']) for i in tqdm(range(0, len(data), 7)): batch = data[i:i+7]", "read_text_data_utterances(path, lang=self.args['lang']) for i in tqdm(range(0, len(data), 7)): batch =", "'position_w': position_w, 'owner': fix, }) def __len__(self): return len(self.data) def", "'context': context, 'responses': responses, 'owner': fix, }) def __len__(self): return", "bundle['context'], bundle['responses'] return ids, tids, bundle['label'], context, responses, bundle['owner'] def", "[0] * (len(cids) + 2) + [1] * (len(rids) +", "= [self.cls] + rids_ + [self.sep] rids.append(rids_) self.data.append({ 'label': [b[0]", "cids.extend(u + [self.eos]) cids.pop() rids = item[-1] truncate_pair(cids, rids, self.args['max_len'])", "label = to_cuda(ids, rids, rids_mask, label) return { 'ids': ids,", "* (len(cids) + 2) + [1] * (len(rids) + 1)", "[torch.LongTensor(i) for i in bundle['tids']] context, responses = bundle['context'], bundle['responses']", "for i in bundle['rids']] return ids, rids, bundle['label'], bundle['text'], bundle['owner']", "= position_w[-(self.args['max_len']-2):] rids_ = rids_[:(self.args['res_max_len']-2)] ids = [self.cls] + ids", "bundle['rids']] position_w = torch.tensor(bundle['position_w']) return ids, rids, position_w, bundle['label'], bundle['text'],", "f'{os.path.splitext(path)[0]}_fg_test_pw_{suffix}.pt' if os.path.exists(self.pp_path): self.data = torch.load(self.pp_path) print(f'[!] load preprocessed file", "w += self.args['w_delta'] ids.pop() position_w.pop() ids = ids[-(self.args['max_len']-2):] # ignore", "tids, mask, label) return { 'ids': ids, 'tids': tids, 'mask':", "batch): assert len(batch) == 1 ids, rids, pos_w, label, text,", "tids = [], [] context, responses = [], [] for", "ids + [self.sep] rids_ = [self.cls] + rids_ + [self.sep]", "truncate_pair(cids, rids, self.args['max_len']) ids_ = [self.cls] + cids + [self.sep]", "pad_sequence(tids, batch_first=True, padding_value=self.pad) label = torch.LongTensor(label) mask = generate_mask(ids) ids,", "position_w.append(self.args['w_sp_token']) w += self.args['w_delta'] ids.pop() position_w.pop() ids = ids[-(self.args['max_len']-2):] #", "class FineGrainedTestDataset(Dataset): def __init__(self, vocab, path, **args): self.args = args", "self.sep = self.vocab.convert_tokens_to_ids('[SEP]') self.eos = self.vocab.convert_tokens_to_ids('[EOS]') self.cls = self.vocab.convert_tokens_to_ids('[CLS]') suffix", "return { 'ids': ids, 'tids': tids, 'mask': mask, 'label': label,", "'label': [b[0] for b in batch], 'ids': ids, 'tids': tids,", "owner, } class FineGrainedTestInteractionDataset(Dataset): def __init__(self, vocab, path, **args): self.args", "label = to_cuda(ids, tids, mask, label) return { 'ids': ids,", "context, responses, owner = batch[0] ids = pad_sequence(ids, batch_first=True, padding_value=self.pad)", "+ cids + [self.sep] + rids + [self.sep] tids_ =", "def __len__(self): return len(self.data) def __getitem__(self, i): bundle = self.data[i]", "+ rids + [self.sep] tids_ = [0] * (len(cids) +", "= ' [SEP] '.join(utterances[:-1]) self.data.append({ 'label': [b[0] for b in", "import * '''Only for Testing''' class FineGrainedTestDataset(Dataset): def __init__(self, vocab,", "batch): assert len(batch) == 1 ids, rids, label, text, owner", "padding_value=self.pad) rids_mask = generate_mask(rids) label = torch.LongTensor(label) ids, rids, rids_mask,", "self.vocab = vocab self.vocab.add_tokens(['[EOS]']) self.pad = self.vocab.convert_tokens_to_ids('[PAD]') self.sep = self.vocab.convert_tokens_to_ids('[SEP]')", "self.cls, self.sep]) suffix = args['tokenizer'].replace('/', '_') self.pp_path = f'{os.path.splitext(path)[0]}_fg_test_pw_{suffix}.pt' if", "ids.append(ids_) tids.append(tids_) responses.append(utterances[-1]) context = ' [SEP] '.join(utterances[:-1]) self.data.append({ 'label':", "cids, rids_ = item[:-1], item[-1] ids = [] position_w, w", "item[:-1], item[-1] ids = [] for u in cids: ids.extend(u", "position_w + [self.args['w_sp_token']] rids_ = [self.cls] + rids_ + [self.sep]", "= [] for fix in ['brandenwang', 'lt', 'lt2']: path =", "for fix in ['brandenwang', 'lt', 'lt2']: path = f'{args[\"root_dir\"]}/data/{args[\"dataset\"]}/fg-{fix}-test.txt' data", "pos_w, rids_mask, label) return { 'ids': ids, 'rids': rids, 'rids_mask':", "for b in batch], 'owner': fix, }) def __len__(self): return", "self.vocab.convert_tokens_to_ids('[EOS]') self.cls = self.vocab.convert_tokens_to_ids('[CLS]') self.unk = self.vocab.convert_tokens_to_ids('[UNK]') self.special_tokens = set([self.unk,", "self.pp_path = f'{os.path.splitext(path)[0]}_fg_interaction_test_{suffix}.pt' if os.path.exists(self.pp_path): self.data = torch.load(self.pp_path) print(f'[!] load", "self.cls = self.vocab.convert_tokens_to_ids('[CLS]') self.unk = self.vocab.convert_tokens_to_ids('[UNK]') self.special_tokens = set([self.unk, self.cls,", "+ 2) + [1] * (len(rids) + 1) ids.append(ids_) tids.append(tids_)", "dataset into {self.pp_path}') def collate(self, batch): assert len(batch) == 1", "= vocab self.vocab.add_tokens(['[EOS]']) self.pad = self.vocab.convert_tokens_to_ids('[PAD]') self.sep = self.vocab.convert_tokens_to_ids('[SEP]') self.eos", "= [torch.LongTensor(i) for i in bundle['tids']] context, responses = bundle['context'],", "bundle['label'], bundle['text'], bundle['owner'] def save(self): data = torch.save(self.data, self.pp_path) print(f'[!]", "in cids: ids.extend(u + [self.sep]) for token in u +", "self.sep]) suffix = args['tokenizer'].replace('/', '_') self.pp_path = f'{os.path.splitext(path)[0]}_fg_test_pw_{suffix}.pt' if os.path.exists(self.pp_path):", "[] context, responses = [], [] for _, utterances in", "* from .util_func import * '''Only for Testing''' class FineGrainedTestDataset(Dataset):", "= self.vocab.convert_tokens_to_ids('[CLS]') suffix = args['tokenizer'].replace('/', '_') self.pp_path = f'{os.path.splitext(path)[0]}_fg_interaction_test_{suffix}.pt' if", "rids, pos_w, rids_mask, label = to_cuda(ids, rids, pos_w, rids_mask, label)", "= torch.LongTensor(label) ids, rids, pos_w, rids_mask, label = to_cuda(ids, rids,", "suffix = args['tokenizer'].replace('/', '_') self.pp_path = f'{os.path.splitext(path)[0]}_fg_interaction_test_{suffix}.pt' if os.path.exists(self.pp_path): self.data", "in batch], 'position_w': position_w, 'owner': fix, }) def __len__(self): return", "in batch], 'owner': fix, }) def __len__(self): return len(self.data) def", "rids = [torch.LongTensor(i) for i in bundle['rids']] return ids, rids,", "for label, utterances in batch: item = self.vocab.batch_encode_plus(utterances, add_special_tokens=False)['input_ids'] cids,", "self.data.append({ 'label': [b[0] for b in batch], 'ids': ids, 'tids':", "self.data = torch.load(self.pp_path) print(f'[!] load preprocessed file from {self.pp_path}') return", "i in bundle['tids']] context, responses = bundle['context'], bundle['responses'] return ids,", "bundle = self.data[i] ids = torch.LongTensor(bundle['ids']) rids = [torch.LongTensor(i) for", "= torch.LongTensor(label) ids, rids, rids_mask, label = to_cuda(ids, rids, rids_mask,", "[SEP] rids_ = rids_[:(self.args['res_max_len']-2)] ids = [self.cls] + ids +", "self.vocab.convert_tokens_to_ids('[SEP]') self.eos = self.vocab.convert_tokens_to_ids('[EOS]') self.cls = self.vocab.convert_tokens_to_ids('[CLS]') self.unk = self.vocab.convert_tokens_to_ids('[UNK]')", "'ids': ids, 'rids': rids, 'rids_mask': rids_mask, 'label': label, 'text': text,", "# ignore [CLS] and [SEP] position_w = position_w[-(self.args['max_len']-2):] rids_ =", "__len__(self): return len(self.data) def __getitem__(self, i): bundle = self.data[i] ids", "vocab self.vocab.add_tokens(['[EOS]']) self.pad = self.vocab.convert_tokens_to_ids('[PAD]') self.sep = self.vocab.convert_tokens_to_ids('[SEP]') self.eos =", "['brandenwang', 'lt', 'lt2']: path = f'{args[\"root_dir\"]}/data/{args[\"dataset\"]}/fg-{fix}-test.txt' data = read_text_data_utterances(path, lang=self.args['lang'])", "label, text, owner = batch[0] rids = pad_sequence(rids, batch_first=True, padding_value=self.pad)", "item = self.vocab.batch_encode_plus(utterances, add_special_tokens=False)['input_ids'] cids, rids_ = item[:-1], item[-1] ids", "token not in self.special_tokens: position_w.append(w) else: position_w.append(self.args['w_sp_token']) w += self.args['w_delta']", "ids, tids, mask, label = to_cuda(ids, tids, mask, label) return", "= self.vocab.convert_tokens_to_ids('[SEP]') self.eos = self.vocab.convert_tokens_to_ids('[EOS]') self.cls = self.vocab.convert_tokens_to_ids('[CLS]') suffix =", "ids, 'rids': rids, 'rids_mask': rids_mask, 'label': label, 'text': text, 'owner':", "self.vocab.convert_tokens_to_ids('[SEP]') self.eos = self.vocab.convert_tokens_to_ids('[EOS]') self.cls = self.vocab.convert_tokens_to_ids('[CLS]') suffix = args['tokenizer'].replace('/',", "padding_value=self.pad) tids = pad_sequence(tids, batch_first=True, padding_value=self.pad) label = torch.LongTensor(label) mask", "= args['tokenizer'].replace('/', '_') self.pp_path = f'{os.path.splitext(path)[0]}_fg_test_{suffix}.pt' if os.path.exists(self.pp_path): self.data =", "owner, } class FineGrainedTestPositionWeightDataset(Dataset): def __init__(self, vocab, path, **args): self.args", "= set([self.unk, self.cls, self.sep]) suffix = args['tokenizer'].replace('/', '_') self.pp_path =", "collate(self, batch): assert len(batch) == 1 ids, tids, label, context,", "'text': text, 'owner': owner, } class FineGrainedTestPositionWeightDataset(Dataset): def __init__(self, vocab,", "data = torch.save(self.data, self.pp_path) print(f'[!] save preprocessed dataset into {self.pp_path}')", "batch: item = self.vocab.batch_encode_plus(utterances, add_special_tokens=False)['input_ids'] cids, rids_ = item[:-1], item[-1]", "b in batch], 'ids': ids, 'rids': rids, 'text': ['\\t'.join(b[1]) for", "torch.LongTensor(label) ids, rids, rids_mask, label = to_cuda(ids, rids, rids_mask, label)", "label, utterances in batch: item = self.vocab.batch_encode_plus(utterances, add_special_tokens=False)['input_ids'] cids, rids_", "self.data = [] for fix in ['brandenwang', 'lt', 'lt2']: path", "rids_ = rids_[:(self.args['res_max_len']-2)] ids = [self.cls] + ids + [self.sep]", "vocab, path, **args): self.args = args self.vocab = vocab self.vocab.add_tokens(['[EOS]'])", "= batch[0] rids = pad_sequence(rids, batch_first=True, padding_value=self.pad) rids_mask = generate_mask(rids)", "ids.pop() position_w.pop() ids = ids[-(self.args['max_len']-2):] # ignore [CLS] and [SEP]", "[self.sep] tids_ = [0] * (len(cids) + 2) + [1]", ".util_func import * '''Only for Testing''' class FineGrainedTestDataset(Dataset): def __init__(self,", "token in u + [self.sep]: if token not in self.special_tokens:", "class FineGrainedTestInteractionDataset(Dataset): def __init__(self, vocab, path, **args): self.args = args", "'lt2']: path = f'{args[\"root_dir\"]}/data/{args[\"dataset\"]}/fg-{fix}-test.txt' data = read_text_data_utterances(path, lang=self.args['lang']) for i", "utterances in batch: item = self.vocab.batch_encode_plus(utterances, add_special_tokens=False)['input_ids'] cids = []", "return ids, tids, bundle['label'], context, responses, bundle['owner'] def save(self): data", "for _, utterances in batch: item = self.vocab.batch_encode_plus(utterances, add_special_tokens=False)['input_ids'] cids", "cids, rids_ = item[:-1], item[-1] ids = [] for u", "self.vocab.convert_tokens_to_ids('[CLS]') suffix = args['tokenizer'].replace('/', '_') self.pp_path = f'{os.path.splitext(path)[0]}_fg_interaction_test_{suffix}.pt' if os.path.exists(self.pp_path):", "label) return { 'ids': ids, 'tids': tids, 'mask': mask, 'label':", "self.args = args self.vocab = vocab self.vocab.add_tokens(['[EOS]']) self.pad = self.vocab.convert_tokens_to_ids('[PAD]')", "'tids': tids, 'context': context, 'responses': responses, 'owner': fix, }) def", "= bundle['context'], bundle['responses'] return ids, tids, bundle['label'], context, responses, bundle['owner']", "[] for fix in ['brandenwang', 'lt', 'lt2']: path = f'{args[\"root_dir\"]}/data/{args[\"dataset\"]}/fg-{fix}-test.txt'", "batch: item = self.vocab.batch_encode_plus(utterances, add_special_tokens=False)['input_ids'] cids = [] for u", "self.data[i] ids = [torch.LongTensor(i) for i in bundle['ids']] tids =", "ids_ = [self.cls] + cids + [self.sep] + rids +", "{self.pp_path}') return None self.data = [] for fix in ['brandenwang',", "} class FineGrainedTestPositionWeightDataset(Dataset): def __init__(self, vocab, path, **args): self.args =", "rids, rids_mask, label = to_cuda(ids, rids, rids_mask, label) return {", "= rids_[:(self.args['res_max_len']-2)] ids = [self.cls] + ids + [self.sep] position_w", "['\\t'.join(b[1]) for b in batch], 'position_w': position_w, 'owner': fix, })", "ids.pop() ids = ids[-(self.args['max_len']-2):] # ignore [CLS] and [SEP] rids_", "from {self.pp_path}') return None self.data = [] for fix in", "batch], 'owner': fix, }) def __len__(self): return len(self.data) def __getitem__(self,", "generate_mask(rids) label = torch.LongTensor(label) ids, rids, rids_mask, label = to_cuda(ids,", "[self.cls] + ids + [self.sep] rids_ = [self.cls] + rids_", "owner = batch[0] rids = pad_sequence(rids, batch_first=True, padding_value=self.pad) rids_mask =", "'rids': rids, 'rids_mask': rids_mask, 'pos_w': pos_w, 'label': label, 'text': text,", "'pos_w': pos_w, 'label': label, 'text': text, 'owner': owner, } class", "assert len(batch) == 1 ids, tids, label, context, responses, owner", "rids_mask, 'label': label, 'text': text, 'owner': owner, } class FineGrainedTestPositionWeightDataset(Dataset):", "context = ' [SEP] '.join(utterances[:-1]) self.data.append({ 'label': [b[0] for b", "'rids': rids, 'rids_mask': rids_mask, 'label': label, 'text': text, 'owner': owner,", "[self.sep]: if token not in self.special_tokens: position_w.append(w) else: position_w.append(self.args['w_sp_token']) w", "self.vocab.batch_encode_plus(utterances, add_special_tokens=False)['input_ids'] cids, rids_ = item[:-1], item[-1] ids = []", "ids = [torch.LongTensor(i) for i in bundle['ids']] tids = [torch.LongTensor(i)", "def __getitem__(self, i): bundle = self.data[i] ids = torch.LongTensor(bundle['ids']) rids", "ignore [CLS] and [SEP] position_w = position_w[-(self.args['max_len']-2):] rids_ = rids_[:(self.args['res_max_len']-2)]", "= generate_mask(rids) label = torch.LongTensor(label) ids, rids, rids_mask, label =", "responses.append(utterances[-1]) context = ' [SEP] '.join(utterances[:-1]) self.data.append({ 'label': [b[0] for", "self.sep = self.vocab.convert_tokens_to_ids('[SEP]') self.eos = self.vocab.convert_tokens_to_ids('[EOS]') self.cls = self.vocab.convert_tokens_to_ids('[CLS]') self.unk", "= [] ids, tids = [], [] context, responses =", "self.cls = self.vocab.convert_tokens_to_ids('[CLS]') suffix = args['tokenizer'].replace('/', '_') self.pp_path = f'{os.path.splitext(path)[0]}_fg_interaction_test_{suffix}.pt'", "import * from .utils import * from .util_func import *", "self.vocab.convert_tokens_to_ids('[UNK]') self.special_tokens = set([self.unk, self.cls, self.sep]) suffix = args['tokenizer'].replace('/', '_')", "= torch.save(self.data, self.pp_path) print(f'[!] save preprocessed dataset into {self.pp_path}') def", "ids = [self.cls] + ids + [self.sep] position_w = [w-self.args['w_delta']]", "}) def __len__(self): return len(self.data) def __getitem__(self, i): bundle =", "[self.sep] rids_ = [self.cls] + rids_ + [self.sep] rids.append(rids_) self.data.append({", "else: position_w.append(self.args['w_sp_token']) w += self.args['w_delta'] ids.pop() position_w.pop() ids = ids[-(self.args['max_len']-2):]", "return ids, rids, position_w, bundle['label'], bundle['text'], bundle['owner'] def save(self): data", "b in batch], 'owner': fix, }) def __len__(self): return len(self.data)", "pos_w, label, text, owner = batch[0] rids = pad_sequence(rids, batch_first=True,", "ids = torch.LongTensor(bundle['ids']) rids = [torch.LongTensor(i) for i in bundle['rids']]", "rids, 'text': ['\\t'.join(b[1]) for b in batch], 'position_w': position_w, 'owner':", "[], [] context, responses = [], [] for _, utterances", "= [0] * (len(cids) + 2) + [1] * (len(rids)", "item[:-1]: cids.extend(u + [self.eos]) cids.pop() rids = item[-1] truncate_pair(cids, rids,", "rids, pos_w, rids_mask, label) return { 'ids': ids, 'rids': rids,", "f'{args[\"root_dir\"]}/data/{args[\"dataset\"]}/fg-{fix}-test.txt' data = read_text_data_utterances(path, lang=self.args['lang']) for i in tqdm(range(0, len(data),", "[] position_w, w = [], self.args['min_w'] for u in cids:", "cids: ids.extend(u + [self.sep]) for token in u + [self.sep]:", "rids_ + [self.sep] rids.append(rids_) self.data.append({ 'label': [b[0] for b in", "[1] * (len(rids) + 1) ids.append(ids_) tids.append(tids_) responses.append(utterances[-1]) context =", "pad_sequence(ids, batch_first=True, padding_value=self.pad) tids = pad_sequence(tids, batch_first=True, padding_value=self.pad) label =", "+ rids_ + [self.sep] rids.append(rids_) self.data.append({ 'label': [b[0] for b", "collate(self, batch): assert len(batch) == 1 ids, rids, label, text,", "+ [self.sep]) ids.pop() ids = ids[-(self.args['max_len']-2):] # ignore [CLS] and", "label) return { 'ids': ids, 'rids': rids, 'rids_mask': rids_mask, 'pos_w':", "self.args['min_w'] for u in cids: ids.extend(u + [self.sep]) for token", "= [] position_w, w = [], self.args['min_w'] for u in", "'rids_mask': rids_mask, 'pos_w': pos_w, 'label': label, 'text': text, 'owner': owner,", "ids, rids, pos_w, rids_mask, label = to_cuda(ids, rids, pos_w, rids_mask,", "rids, 'rids_mask': rids_mask, 'pos_w': pos_w, 'label': label, 'text': text, 'owner':", "[self.sep] + rids + [self.sep] tids_ = [0] * (len(cids)", "ids.extend(u + [self.sep]) ids.pop() ids = ids[-(self.args['max_len']-2):] # ignore [CLS]", "for b in batch], 'ids': ids, 'tids': tids, 'context': context,", "self.pp_path = f'{os.path.splitext(path)[0]}_fg_test_{suffix}.pt' if os.path.exists(self.pp_path): self.data = torch.load(self.pp_path) print(f'[!] load", "position_w.pop() ids = ids[-(self.args['max_len']-2):] # ignore [CLS] and [SEP] position_w", "i in bundle['rids']] position_w = torch.tensor(bundle['position_w']) return ids, rids, position_w,", "ids, rids, pos_w, label, text, owner = batch[0] rids =", "context, responses = [], [] for _, utterances in batch:", "= args['tokenizer'].replace('/', '_') self.pp_path = f'{os.path.splitext(path)[0]}_fg_interaction_test_{suffix}.pt' if os.path.exists(self.pp_path): self.data =", "= item[:-1], item[-1] ids = [] for u in cids:", "'rids': rids, 'text': ['\\t'.join(b[1]) for b in batch], 'owner': fix,", "pos_w, rids_mask, label = to_cuda(ids, rids, pos_w, rids_mask, label) return", "tids, label, context, responses, owner = batch[0] ids = pad_sequence(ids,", "ids, tids = [], [] context, responses = [], []", "mask = generate_mask(ids) ids, tids, mask, label = to_cuda(ids, tids,", "owner = batch[0] ids = pad_sequence(ids, batch_first=True, padding_value=self.pad) tids =", "print(f'[!] save preprocessed dataset into {self.pp_path}') def collate(self, batch): assert", "bundle['responses'] return ids, tids, bundle['label'], context, responses, bundle['owner'] def save(self):", "class FineGrainedTestPositionWeightDataset(Dataset): def __init__(self, vocab, path, **args): self.args = args", "torch.tensor(bundle['position_w']) return ids, rids, position_w, bundle['label'], bundle['text'], bundle['owner'] def save(self):", "[] for _, utterances in batch: item = self.vocab.batch_encode_plus(utterances, add_special_tokens=False)['input_ids']", "FineGrainedTestInteractionDataset(Dataset): def __init__(self, vocab, path, **args): self.args = args self.vocab", "== 1 ids, tids, label, context, responses, owner = batch[0]", "+ [self.args['w_sp_token']] rids_ = [self.cls] + rids_ + [self.sep] rids.append(rids_)", "label = torch.LongTensor(label) ids, rids, pos_w, rids_mask, label = to_cuda(ids,", "[torch.LongTensor(i) for i in bundle['rids']] position_w = torch.tensor(bundle['position_w']) return ids,", "from header import * from .utils import * from .util_func", "'lt', 'lt2']: path = f'{args[\"root_dir\"]}/data/{args[\"dataset\"]}/fg-{fix}-test.txt' data = read_text_data_utterances(path, lang=self.args['lang']) for", "for token in u + [self.sep]: if token not in", "1) ids.append(ids_) tids.append(tids_) responses.append(utterances[-1]) context = ' [SEP] '.join(utterances[:-1]) self.data.append({", "+ [self.sep] tids_ = [0] * (len(cids) + 2) +", "[], [] for _, utterances in batch: item = self.vocab.batch_encode_plus(utterances,", "position_w, 'owner': fix, }) def __len__(self): return len(self.data) def __getitem__(self,", "batch_first=True, padding_value=self.pad) rids_mask = generate_mask(rids) label = torch.LongTensor(label) ids, rids,", "responses = [], [] for _, utterances in batch: item", "= self.data[i] ids = [torch.LongTensor(i) for i in bundle['ids']] tids", "self.pad = self.vocab.convert_tokens_to_ids('[PAD]') self.sep = self.vocab.convert_tokens_to_ids('[SEP]') self.eos = self.vocab.convert_tokens_to_ids('[EOS]') self.cls", "= data[i:i+7] rids = [] for label, utterances in batch:", "data[i:i+7] rids = [] ids, tids = [], [] context,", "= [] for label, utterances in batch: item = self.vocab.batch_encode_plus(utterances,", "bundle = self.data[i] ids = [torch.LongTensor(i) for i in bundle['ids']]", "ids, tids, bundle['label'], context, responses, bundle['owner'] def save(self): data =", "rids = pad_sequence(rids, batch_first=True, padding_value=self.pad) rids_mask = generate_mask(rids) label =", "ids, tids, label, context, responses, owner = batch[0] ids =", "= [] for u in cids: ids.extend(u + [self.sep]) ids.pop()", "load preprocessed file from {self.pp_path}') return None self.data = []", "add_special_tokens=False)['input_ids'] cids, rids_ = item[:-1], item[-1] ids = [] position_w,", "_, utterances in batch: item = self.vocab.batch_encode_plus(utterances, add_special_tokens=False)['input_ids'] cids =", "= self.vocab.convert_tokens_to_ids('[UNK]') self.special_tokens = set([self.unk, self.cls, self.sep]) suffix = args['tokenizer'].replace('/',", "['\\t'.join(b[1]) for b in batch], 'owner': fix, }) def __len__(self):", "rids_ = item[:-1], item[-1] ids = [] for u in", "self.vocab.add_tokens(['[EOS]']) self.pad = self.vocab.convert_tokens_to_ids('[PAD]') self.sep = self.vocab.convert_tokens_to_ids('[SEP]') self.eos = self.vocab.convert_tokens_to_ids('[EOS]')", "for u in cids: ids.extend(u + [self.sep]) ids.pop() ids =", "None self.data = [] for fix in ['brandenwang', 'lt', 'lt2']:", "rids, bundle['label'], bundle['text'], bundle['owner'] def save(self): data = torch.save(self.data, self.pp_path)", "f'{os.path.splitext(path)[0]}_fg_interaction_test_{suffix}.pt' if os.path.exists(self.pp_path): self.data = torch.load(self.pp_path) print(f'[!] load preprocessed file", "tids = pad_sequence(tids, batch_first=True, padding_value=self.pad) label = torch.LongTensor(label) mask =", "position_w[-(self.args['max_len']-2):] rids_ = rids_[:(self.args['res_max_len']-2)] ids = [self.cls] + ids +", "ids + [self.sep] position_w = [w-self.args['w_delta']] + position_w + [self.args['w_sp_token']]", "i): bundle = self.data[i] ids = [torch.LongTensor(i) for i in", "'responses': responses, 'owner': fix, }) def __len__(self): return len(self.data) def", "data = read_text_data_utterances(path, lang=self.args['lang']) for i in tqdm(range(0, len(data), 7)):", "cids.pop() rids = item[-1] truncate_pair(cids, rids, self.args['max_len']) ids_ = [self.cls]", "= self.vocab.convert_tokens_to_ids('[CLS]') suffix = args['tokenizer'].replace('/', '_') self.pp_path = f'{os.path.splitext(path)[0]}_fg_test_{suffix}.pt' if", "'label': [b[0] for b in batch], 'ids': ids, 'rids': rids,", "= self.vocab.convert_tokens_to_ids('[PAD]') self.sep = self.vocab.convert_tokens_to_ids('[SEP]') self.eos = self.vocab.convert_tokens_to_ids('[EOS]') self.cls =", "[self.args['w_sp_token']] rids_ = [self.cls] + rids_ + [self.sep] rids.append(rids_) self.data.append({", "'label': label, 'text': text, 'owner': owner, } class FineGrainedTestPositionWeightDataset(Dataset): def", "rids, 'text': ['\\t'.join(b[1]) for b in batch], 'owner': fix, })", "def collate(self, batch): assert len(batch) == 1 ids, tids, label,", "batch_first=True, padding_value=self.pad) tids = pad_sequence(tids, batch_first=True, padding_value=self.pad) label = torch.LongTensor(label)", "== 1 ids, rids, pos_w, label, text, owner = batch[0]", "'.join(utterances[:-1]) self.data.append({ 'label': [b[0] for b in batch], 'ids': ids,", "import * from .util_func import * '''Only for Testing''' class", "to_cuda(ids, rids, pos_w, rids_mask, label) return { 'ids': ids, 'rids':", "ids, rids, position_w, bundle['label'], bundle['text'], bundle['owner'] def save(self): data =", "cids = [] for u in item[:-1]: cids.extend(u + [self.eos])", "return None self.data = [] for fix in ['brandenwang', 'lt',", "if token not in self.special_tokens: position_w.append(w) else: position_w.append(self.args['w_sp_token']) w +=", "label = torch.LongTensor(label) mask = generate_mask(ids) ids, tids, mask, label", "rids_mask, label = to_cuda(ids, rids, rids_mask, label) return { 'ids':", "[] for u in cids: ids.extend(u + [self.sep]) ids.pop() ids", "+ ids + [self.sep] position_w = [w-self.args['w_delta']] + position_w +", "not in self.special_tokens: position_w.append(w) else: position_w.append(self.args['w_sp_token']) w += self.args['w_delta'] ids.pop()", "text, 'owner': owner, } class FineGrainedTestPositionWeightDataset(Dataset): def __init__(self, vocab, path,", "in batch: item = self.vocab.batch_encode_plus(utterances, add_special_tokens=False)['input_ids'] cids = [] for", "= batch[0] ids = pad_sequence(ids, batch_first=True, padding_value=self.pad) tids = pad_sequence(tids,", "1 ids, rids, label, text, owner = batch[0] rids =", "[] ids, tids = [], [] context, responses = [],", "+ ids + [self.sep] rids_ = [self.cls] + rids_ +", "to_cuda(ids, tids, mask, label) return { 'ids': ids, 'tids': tids,", "tids_ = [0] * (len(cids) + 2) + [1] *", "rids_mask, 'pos_w': pos_w, 'label': label, 'text': text, 'owner': owner, }", "len(batch) == 1 ids, rids, label, text, owner = batch[0]", "= [self.cls] + ids + [self.sep] position_w = [w-self.args['w_delta']] +", "u in cids: ids.extend(u + [self.sep]) ids.pop() ids = ids[-(self.args['max_len']-2):]", "= [self.cls] + cids + [self.sep] + rids + [self.sep]", "'text': text, 'owner': owner, } class FineGrainedTestInteractionDataset(Dataset): def __init__(self, vocab,", "ids = ids[-(self.args['max_len']-2):] # ignore [CLS] and [SEP] rids_ =", "item[:-1], item[-1] ids = [] position_w, w = [], self.args['min_w']", "generate_mask(rids) label = torch.LongTensor(label) ids, rids, pos_w, rids_mask, label =", "tids, mask, label = to_cuda(ids, tids, mask, label) return {", ".utils import * from .util_func import * '''Only for Testing'''", "def save(self): data = torch.save(self.data, self.pp_path) print(f'[!] save preprocessed dataset", "len(data), 7)): batch = data[i:i+7] rids = [] for label,", "ids, rids, bundle['label'], bundle['text'], bundle['owner'] def save(self): data = torch.save(self.data,", "self.eos = self.vocab.convert_tokens_to_ids('[EOS]') self.cls = self.vocab.convert_tokens_to_ids('[CLS]') self.unk = self.vocab.convert_tokens_to_ids('[UNK]') self.special_tokens", "bundle['owner'] def save(self): data = torch.save(self.data, self.pp_path) print(f'[!] save preprocessed", "= generate_mask(ids) ids, tids, mask, label = to_cuda(ids, tids, mask,", "preprocessed dataset into {self.pp_path}') def collate(self, batch): assert len(batch) ==", "ids.extend(u + [self.sep]) for token in u + [self.sep]: if", "in tqdm(range(0, len(data), 7)): batch = data[i:i+7] rids = []", "add_special_tokens=False)['input_ids'] cids = [] for u in item[:-1]: cids.extend(u +", "context, responses = bundle['context'], bundle['responses'] return ids, tids, bundle['label'], context,", "i): bundle = self.data[i] ids = torch.LongTensor(bundle['ids']) rids = [torch.LongTensor(i)", "in batch], 'ids': ids, 'tids': tids, 'context': context, 'responses': responses,", "[b[0] for b in batch], 'ids': ids, 'tids': tids, 'context':", "and [SEP] rids_ = rids_[:(self.args['res_max_len']-2)] ids = [self.cls] + ids", "+ [self.sep]: if token not in self.special_tokens: position_w.append(w) else: position_w.append(self.args['w_sp_token'])", "ids, rids, rids_mask, label = to_cuda(ids, rids, rids_mask, label) return", "self.pp_path = f'{os.path.splitext(path)[0]}_fg_test_pw_{suffix}.pt' if os.path.exists(self.pp_path): self.data = torch.load(self.pp_path) print(f'[!] load", "= to_cuda(ids, tids, mask, label) return { 'ids': ids, 'tids':", "os.path.exists(self.pp_path): self.data = torch.load(self.pp_path) print(f'[!] load preprocessed file from {self.pp_path}')", "{self.pp_path}') def collate(self, batch): assert len(batch) == 1 ids, tids,", "label, context, responses, owner = batch[0] ids = pad_sequence(ids, batch_first=True,", "= data[i:i+7] rids = [] ids, tids = [], []", "batch], 'ids': ids, 'tids': tids, 'context': context, 'responses': responses, 'owner':", "for b in batch], 'ids': ids, 'rids': rids, 'text': ['\\t'.join(b[1])", "self.pp_path) print(f'[!] save preprocessed dataset into {self.pp_path}') def collate(self, batch):", "= self.vocab.convert_tokens_to_ids('[EOS]') self.cls = self.vocab.convert_tokens_to_ids('[CLS]') suffix = args['tokenizer'].replace('/', '_') self.pp_path", "into {self.pp_path}') def collate(self, batch): assert len(batch) == 1 ids,", "for i in bundle['ids']] tids = [torch.LongTensor(i) for i in", "ids = [] for u in cids: ids.extend(u + [self.sep])", "'_') self.pp_path = f'{os.path.splitext(path)[0]}_fg_interaction_test_{suffix}.pt' if os.path.exists(self.pp_path): self.data = torch.load(self.pp_path) print(f'[!]", "item[-1] ids = [] position_w, w = [], self.args['min_w'] for", "[self.sep]) ids.pop() ids = ids[-(self.args['max_len']-2):] # ignore [CLS] and [SEP]", "return ids, rids, bundle['label'], bundle['text'], bundle['owner'] def save(self): data =", "tids.append(tids_) responses.append(utterances[-1]) context = ' [SEP] '.join(utterances[:-1]) self.data.append({ 'label': [b[0]", "batch_first=True, padding_value=self.pad) label = torch.LongTensor(label) mask = generate_mask(ids) ids, tids,", "* '''Only for Testing''' class FineGrainedTestDataset(Dataset): def __init__(self, vocab, path,", "assert len(batch) == 1 ids, rids, pos_w, label, text, owner", "self.vocab.convert_tokens_to_ids('[CLS]') self.unk = self.vocab.convert_tokens_to_ids('[UNK]') self.special_tokens = set([self.unk, self.cls, self.sep]) suffix", "[self.sep] position_w = [w-self.args['w_delta']] + position_w + [self.args['w_sp_token']] rids_ =", "{ 'ids': ids, 'rids': rids, 'rids_mask': rids_mask, 'pos_w': pos_w, 'label':", "padding_value=self.pad) label = torch.LongTensor(label) mask = generate_mask(ids) ids, tids, mask,", "{ 'ids': ids, 'tids': tids, 'mask': mask, 'label': label, 'owner':", "[self.sep]) for token in u + [self.sep]: if token not", "= ids[-(self.args['max_len']-2):] # ignore [CLS] and [SEP] rids_ = rids_[:(self.args['res_max_len']-2)]", "bundle['rids']] return ids, rids, bundle['label'], bundle['text'], bundle['owner'] def save(self): data", "'_') self.pp_path = f'{os.path.splitext(path)[0]}_fg_test_pw_{suffix}.pt' if os.path.exists(self.pp_path): self.data = torch.load(self.pp_path) print(f'[!]", "= torch.tensor(bundle['position_w']) return ids, rids, position_w, bundle['label'], bundle['text'], bundle['owner'] def", "and [SEP] position_w = position_w[-(self.args['max_len']-2):] rids_ = rids_[:(self.args['res_max_len']-2)] ids =", "item = self.vocab.batch_encode_plus(utterances, add_special_tokens=False)['input_ids'] cids = [] for u in", "tids, bundle['label'], context, responses, bundle['owner'] def save(self): data = torch.save(self.data,", "' [SEP] '.join(utterances[:-1]) self.data.append({ 'label': [b[0] for b in batch],", "1 ids, tids, label, context, responses, owner = batch[0] ids", "* (len(rids) + 1) ids.append(ids_) tids.append(tids_) responses.append(utterances[-1]) context = '", "i in bundle['rids']] return ids, rids, bundle['label'], bundle['text'], bundle['owner'] def", "responses = bundle['context'], bundle['responses'] return ids, tids, bundle['label'], context, responses,", "ids, 'rids': rids, 'rids_mask': rids_mask, 'pos_w': pos_w, 'label': label, 'text':", "FineGrainedTestDataset(Dataset): def __init__(self, vocab, path, **args): self.args = args self.vocab", "+ [self.sep] rids_ = [self.cls] + rids_ + [self.sep] rids.append(rids_)", "ids = [] position_w, w = [], self.args['min_w'] for u", "bundle['text'], bundle['owner'] def save(self): data = torch.save(self.data, self.pp_path) print(f'[!] save", "responses, 'owner': fix, }) def __len__(self): return len(self.data) def __getitem__(self,", "responses, owner = batch[0] ids = pad_sequence(ids, batch_first=True, padding_value=self.pad) tids", "for b in batch], 'position_w': position_w, 'owner': fix, }) def", "in ['brandenwang', 'lt', 'lt2']: path = f'{args[\"root_dir\"]}/data/{args[\"dataset\"]}/fg-{fix}-test.txt' data = read_text_data_utterances(path,", "for i in bundle['rids']] position_w = torch.tensor(bundle['position_w']) return ids, rids,", "self.vocab.batch_encode_plus(utterances, add_special_tokens=False)['input_ids'] cids = [] for u in item[:-1]: cids.extend(u", "'''Only for Testing''' class FineGrainedTestDataset(Dataset): def __init__(self, vocab, path, **args):", "(len(rids) + 1) ids.append(ids_) tids.append(tids_) responses.append(utterances[-1]) context = ' [SEP]", "in item[:-1]: cids.extend(u + [self.eos]) cids.pop() rids = item[-1] truncate_pair(cids,", "in bundle['tids']] context, responses = bundle['context'], bundle['responses'] return ids, tids,", "= self.vocab.batch_encode_plus(utterances, add_special_tokens=False)['input_ids'] cids, rids_ = item[:-1], item[-1] ids =", "rids.append(rids_) self.data.append({ 'label': [b[0] for b in batch], 'ids': ids,", "ids, 'rids': rids, 'text': ['\\t'.join(b[1]) for b in batch], 'position_w':", "= f'{os.path.splitext(path)[0]}_fg_test_{suffix}.pt' if os.path.exists(self.pp_path): self.data = torch.load(self.pp_path) print(f'[!] load preprocessed", "{ 'ids': ids, 'rids': rids, 'rids_mask': rids_mask, 'label': label, 'text':", "ids, 'rids': rids, 'text': ['\\t'.join(b[1]) for b in batch], 'owner':", "= torch.load(self.pp_path) print(f'[!] load preprocessed file from {self.pp_path}') return None", "fix, }) def __len__(self): return len(self.data) def __getitem__(self, i): bundle", "+ [self.sep] rids.append(rids_) self.data.append({ 'label': [b[0] for b in batch],", "for u in cids: ids.extend(u + [self.sep]) for token in", "b in batch], 'ids': ids, 'tids': tids, 'context': context, 'responses':", "mask, label) return { 'ids': ids, 'tids': tids, 'mask': mask,", "file from {self.pp_path}') return None self.data = [] for fix", "f'{os.path.splitext(path)[0]}_fg_test_{suffix}.pt' if os.path.exists(self.pp_path): self.data = torch.load(self.pp_path) print(f'[!] load preprocessed file" ]
[ "= MibScalar((1, 3, 6, 1, 4, 1, 55532, 4, 2,", "MibScalar((1, 3, 6, 1, 4, 1, 55532, 2, 1), Integer32()).setMaxAccess(\"readwrite\")", "1, 55532, 4, 2, 1), OctetString()).setMaxAccess(\"accessiblefornotify\") if mibBuilder.loadTexts: genericPayload.setStatus('current') malfunctionTrap", "Tue Mar 22 12:53:47 2022 # On host ? platform", "version 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 22:45:29) [MSC v.1916 32", "agentStatus = MibScalar((1, 3, 6, 1, 4, 1, 55532, 2,", "= mibBuilder.importSymbols(\"SNMPv2-TC\", \"DisplayString\", \"TextualConvention\") dabing = ModuleIdentity((1, 3, 6, 1,", "malfunctionTrap.setStatus('current') testTrap = NotificationType((1, 3, 6, 1, 4, 1, 55532,", "if mibBuilder.loadTexts: testTrap.setStatus('current') mibBuilder.exportSymbols(\"DABING-MIB\", Notifications=Notifications, channel=channel, PYSNMP_MODULE_ID=dabing, testTrap=testTrap, malfunctionTrap=malfunctionTrap, Parameters=Parameters,", "mibBuilder.importSymbols(\"SNMPv2-TC\", \"DisplayString\", \"TextualConvention\") dabing = ModuleIdentity((1, 3, 6, 1, 4,", "2, 2), OctetString()).setMaxAccess(\"readwrite\") if mibBuilder.loadTexts: agentLabel.setStatus('current') agentStatus = MibScalar((1, 3,", "1, 55532, 4)) NotificationPrefix = MibIdentifier((1, 3, 6, 1, 4,", "1, 4, 1, 55532, 3, 1), OctetString()).setMaxAccess(\"readonly\") if mibBuilder.loadTexts: managerHostname.setStatus('current')", "mibBuilder.loadTexts: agentIdentifier.setStatus('current') agentLabel = MibScalar((1, 3, 6, 1, 4, 1,", "\"DisplayString\", \"TextualConvention\") dabing = ModuleIdentity((1, 3, 6, 1, 4, 1,", "agentStatus.setStatus('current') managerHostname = MibScalar((1, 3, 6, 1, 4, 1, 55532,", "6, 1, 4, 1, 55532)) dabing.setRevisions(('2022-03-17 00:00',)) if mibBuilder.loadTexts: dabing.setLastUpdated('202203170000Z')", "mibBuilder.loadTexts: testTrap.setStatus('current') mibBuilder.exportSymbols(\"DABING-MIB\", Notifications=Notifications, channel=channel, PYSNMP_MODULE_ID=dabing, testTrap=testTrap, malfunctionTrap=malfunctionTrap, Parameters=Parameters, agentLabel=agentLabel,", "\"ValueSizeConstraint\") NotificationGroup, ModuleCompliance = mibBuilder.importSymbols(\"SNMPv2-CONF\", \"NotificationGroup\", \"ModuleCompliance\") MibScalar, MibTable, MibTableRow,", "MibScalar((1, 3, 6, 1, 4, 1, 55532, 2, 3), Integer32()).setMaxAccess(\"readonly\")", "mibBuilder.importSymbols(\"ASN1-ENUMERATION\", \"NamedValues\") ConstraintsIntersection, ConstraintsUnion, ValueRangeConstraint, SingleValueConstraint, ValueSizeConstraint = mibBuilder.importSymbols(\"ASN1-REFINEMENT\", \"ConstraintsIntersection\",", "\"SingleValueConstraint\", \"ValueSizeConstraint\") NotificationGroup, ModuleCompliance = mibBuilder.importSymbols(\"SNMPv2-CONF\", \"NotificationGroup\", \"ModuleCompliance\") MibScalar, MibTable,", "IpAddress, ObjectIdentity, iso, Counter32, Unsigned32, Bits, NotificationType, TimeTicks, Counter64, enterprises,", "= MibScalar((1, 3, 6, 1, 4, 1, 55532, 1, 1),", "55532, 1, 1), OctetString().clone('12C')).setMaxAccess(\"readonly\") if mibBuilder.loadTexts: channel.setStatus('current') interval = MibScalar((1,", "mibBuilder.exportSymbols(\"DABING-MIB\", Notifications=Notifications, channel=channel, PYSNMP_MODULE_ID=dabing, testTrap=testTrap, malfunctionTrap=malfunctionTrap, Parameters=Parameters, agentLabel=agentLabel, managerPort=managerPort, trapEnabled=trapEnabled,", "\"MibTableColumn\", \"Gauge32\", \"ModuleIdentity\", \"IpAddress\", \"ObjectIdentity\", \"iso\", \"Counter32\", \"Unsigned32\", \"Bits\", \"NotificationType\",", "NotificationType, TimeTicks, Counter64, enterprises, MibIdentifier, Integer32 = mibBuilder.importSymbols(\"SNMPv2-SMI\", \"MibScalar\", \"MibTable\",", "mibBuilder.loadTexts: dabing.setOrganization('www.stuba.sk') Parameters = MibIdentifier((1, 3, 6, 1, 4, 1,", "Unsigned32, Bits, NotificationType, TimeTicks, Counter64, enterprises, MibIdentifier, Integer32 = mibBuilder.importSymbols(\"SNMPv2-SMI\",", "3, 6, 1, 4, 1, 55532, 2, 1), Integer32()).setMaxAccess(\"readwrite\") if", "1, 4, 1, 55532, 2, 1), Integer32()).setMaxAccess(\"readwrite\") if mibBuilder.loadTexts: agentIdentifier.setStatus('current')", "file://..\\DABING-MIB.mib # Produced by pysmi-0.3.4 at Tue Mar 22 12:53:47", "6, 1, 4, 1, 55532, 1, 2), Integer32().clone(960)).setMaxAccess(\"readonly\") if mibBuilder.loadTexts:", "6, 1, 4, 1, 55532, 3)) Notifications = MibIdentifier((1, 3,", "1, 55532, 3, 1), OctetString()).setMaxAccess(\"readonly\") if mibBuilder.loadTexts: managerHostname.setStatus('current') managerPort =", "= NotificationType((1, 3, 6, 1, 4, 1, 55532, 4, 1,", "MibIdentifier((1, 3, 6, 1, 4, 1, 55532, 4, 2)) channel", "3, 6, 1, 4, 1, 55532, 2, 2), OctetString()).setMaxAccess(\"readwrite\") if", "55532, 3, 1), OctetString()).setMaxAccess(\"readonly\") if mibBuilder.loadTexts: managerHostname.setStatus('current') managerPort = MibScalar((1,", "1, 4, 1, 55532, 1)) Agent = MibIdentifier((1, 3, 6,", "= mibBuilder.importSymbols(\"SNMPv2-SMI\", \"MibScalar\", \"MibTable\", \"MibTableRow\", \"MibTableColumn\", \"Gauge32\", \"ModuleIdentity\", \"IpAddress\", \"ObjectIdentity\",", "25 2020, 22:45:29) [MSC v.1916 32 bit (Intel)] # OctetString,", "Integer32().clone(162)).setMaxAccess(\"readonly\") if mibBuilder.loadTexts: managerPort.setStatus('current') genericPayload = MibScalar((1, 3, 6, 1,", "Integer = mibBuilder.importSymbols(\"ASN1\", \"OctetString\", \"ObjectIdentifier\", \"Integer\") NamedValues, = mibBuilder.importSymbols(\"ASN1-ENUMERATION\", \"NamedValues\")", "mibBuilder.loadTexts: genericPayload.setStatus('current') malfunctionTrap = NotificationType((1, 3, 6, 1, 4, 1,", "1, 2), Integer32().clone(960)).setMaxAccess(\"readonly\") if mibBuilder.loadTexts: interval.setStatus('current') trapEnabled = MibScalar((1, 3,", "1, 55532, 4, 1, 1)).setObjects((\"DABING-MIB\", \"genericPayload\")) if mibBuilder.loadTexts: malfunctionTrap.setStatus('current') testTrap", "4)) NotificationPrefix = MibIdentifier((1, 3, 6, 1, 4, 1, 55532,", "1, 55532, 4, 1, 2)).setObjects((\"DABING-MIB\", \"genericPayload\")) if mibBuilder.loadTexts: testTrap.setStatus('current') mibBuilder.exportSymbols(\"DABING-MIB\",", "(http://snmplabs.com/pysmi) # ASN.1 source file://..\\DABING-MIB.mib # Produced by pysmi-0.3.4 at", "4, 2)) channel = MibScalar((1, 3, 6, 1, 4, 1,", "MIB module DABING-MIB (http://snmplabs.com/pysmi) # ASN.1 source file://..\\DABING-MIB.mib # Produced", "1), OctetString()).setMaxAccess(\"readonly\") if mibBuilder.loadTexts: managerHostname.setStatus('current') managerPort = MibScalar((1, 3, 6,", "? version ? by user ? # Using Python version", "1, 4, 1, 55532, 2, 3), Integer32()).setMaxAccess(\"readonly\") if mibBuilder.loadTexts: agentStatus.setStatus('current')", "dabing = ModuleIdentity((1, 3, 6, 1, 4, 1, 55532)) dabing.setRevisions(('2022-03-17", "MibTableColumn, Gauge32, ModuleIdentity, IpAddress, ObjectIdentity, iso, Counter32, Unsigned32, Bits, NotificationType,", "if mibBuilder.loadTexts: channel.setStatus('current') interval = MibScalar((1, 3, 6, 1, 4,", "4, 1, 55532, 4, 2)) channel = MibScalar((1, 3, 6,", "interval = MibScalar((1, 3, 6, 1, 4, 1, 55532, 1,", "user ? # Using Python version 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25", "# OctetString, ObjectIdentifier, Integer = mibBuilder.importSymbols(\"ASN1\", \"OctetString\", \"ObjectIdentifier\", \"Integer\") NamedValues,", "if mibBuilder.loadTexts: dabing.setLastUpdated('202203170000Z') if mibBuilder.loadTexts: dabing.setOrganization('www.stuba.sk') Parameters = MibIdentifier((1, 3,", "6, 1, 4, 1, 55532, 2)) Manager = MibIdentifier((1, 3,", "Integer32 = mibBuilder.importSymbols(\"SNMPv2-SMI\", \"MibScalar\", \"MibTable\", \"MibTableRow\", \"MibTableColumn\", \"Gauge32\", \"ModuleIdentity\", \"IpAddress\",", "# PySNMP MIB module DABING-MIB (http://snmplabs.com/pysmi) # ASN.1 source file://..\\DABING-MIB.mib", "2)) Manager = MibIdentifier((1, 3, 6, 1, 4, 1, 55532,", "dabing.setLastUpdated('202203170000Z') if mibBuilder.loadTexts: dabing.setOrganization('www.stuba.sk') Parameters = MibIdentifier((1, 3, 6, 1,", "2020, 22:45:29) [MSC v.1916 32 bit (Intel)] # OctetString, ObjectIdentifier,", "\"iso\", \"Counter32\", \"Unsigned32\", \"Bits\", \"NotificationType\", \"TimeTicks\", \"Counter64\", \"enterprises\", \"MibIdentifier\", \"Integer32\")", "\"ConstraintsUnion\", \"ValueRangeConstraint\", \"SingleValueConstraint\", \"ValueSizeConstraint\") NotificationGroup, ModuleCompliance = mibBuilder.importSymbols(\"SNMPv2-CONF\", \"NotificationGroup\", \"ModuleCompliance\")", "55532, 3, 2), Integer32().clone(162)).setMaxAccess(\"readonly\") if mibBuilder.loadTexts: managerPort.setStatus('current') genericPayload = MibScalar((1,", "managerPort.setStatus('current') genericPayload = MibScalar((1, 3, 6, 1, 4, 1, 55532,", "1, 4, 1, 55532, 4)) NotificationPrefix = MibIdentifier((1, 3, 6,", "= MibScalar((1, 3, 6, 1, 4, 1, 55532, 2, 2),", "\"genericPayload\")) if mibBuilder.loadTexts: testTrap.setStatus('current') mibBuilder.exportSymbols(\"DABING-MIB\", Notifications=Notifications, channel=channel, PYSNMP_MODULE_ID=dabing, testTrap=testTrap, malfunctionTrap=malfunctionTrap,", "4, 1, 55532, 4, 1)) NotificationObjects = MibIdentifier((1, 3, 6,", "Parameters = MibIdentifier((1, 3, 6, 1, 4, 1, 55532, 1))", "4, 1, 2)).setObjects((\"DABING-MIB\", \"genericPayload\")) if mibBuilder.loadTexts: testTrap.setStatus('current') mibBuilder.exportSymbols(\"DABING-MIB\", Notifications=Notifications, channel=channel,", "agentLabel=agentLabel, managerPort=managerPort, trapEnabled=trapEnabled, managerHostname=managerHostname, Manager=Manager, NotificationPrefix=NotificationPrefix, Agent=Agent, genericPayload=genericPayload, NotificationObjects=NotificationObjects, agentIdentifier=agentIdentifier,", "MibTableRow, MibTableColumn, Gauge32, ModuleIdentity, IpAddress, ObjectIdentity, iso, Counter32, Unsigned32, Bits,", "= MibScalar((1, 3, 6, 1, 4, 1, 55532, 2, 3),", "1, 4, 1, 55532, 4, 1, 2)).setObjects((\"DABING-MIB\", \"genericPayload\")) if mibBuilder.loadTexts:", "\"MibTableRow\", \"MibTableColumn\", \"Gauge32\", \"ModuleIdentity\", \"IpAddress\", \"ObjectIdentity\", \"iso\", \"Counter32\", \"Unsigned32\", \"Bits\",", "trapEnabled=trapEnabled, managerHostname=managerHostname, Manager=Manager, NotificationPrefix=NotificationPrefix, Agent=Agent, genericPayload=genericPayload, NotificationObjects=NotificationObjects, agentIdentifier=agentIdentifier, dabing=dabing, agentStatus=agentStatus,", "1, 4, 1, 55532, 4, 2, 1), OctetString()).setMaxAccess(\"accessiblefornotify\") if mibBuilder.loadTexts:", "OctetString().clone('12C')).setMaxAccess(\"readonly\") if mibBuilder.loadTexts: channel.setStatus('current') interval = MibScalar((1, 3, 6, 1,", "NotificationPrefix = MibIdentifier((1, 3, 6, 1, 4, 1, 55532, 4,", "if mibBuilder.loadTexts: dabing.setOrganization('www.stuba.sk') Parameters = MibIdentifier((1, 3, 6, 1, 4,", "1, 55532, 3, 2), Integer32().clone(162)).setMaxAccess(\"readonly\") if mibBuilder.loadTexts: managerPort.setStatus('current') genericPayload =", "2)).setObjects((\"DABING-MIB\", \"genericPayload\")) if mibBuilder.loadTexts: testTrap.setStatus('current') mibBuilder.exportSymbols(\"DABING-MIB\", Notifications=Notifications, channel=channel, PYSNMP_MODULE_ID=dabing, testTrap=testTrap,", "\"Gauge32\", \"ModuleIdentity\", \"IpAddress\", \"ObjectIdentity\", \"iso\", \"Counter32\", \"Unsigned32\", \"Bits\", \"NotificationType\", \"TimeTicks\",", "4, 1, 55532, 1, 2), Integer32().clone(960)).setMaxAccess(\"readonly\") if mibBuilder.loadTexts: interval.setStatus('current') trapEnabled", "3, 6, 1, 4, 1, 55532, 3)) Notifications = MibIdentifier((1,", "4, 1, 55532, 3, 2), Integer32().clone(162)).setMaxAccess(\"readonly\") if mibBuilder.loadTexts: managerPort.setStatus('current') genericPayload", "NotificationType((1, 3, 6, 1, 4, 1, 55532, 4, 1, 1)).setObjects((\"DABING-MIB\",", "3)) Notifications = MibIdentifier((1, 3, 6, 1, 4, 1, 55532,", "55532, 4, 1)) NotificationObjects = MibIdentifier((1, 3, 6, 1, 4,", "1, 4, 1, 55532, 1, 3), Integer32()).setMaxAccess(\"readonly\") if mibBuilder.loadTexts: trapEnabled.setStatus('current')", "4, 1, 55532, 4, 1, 1)).setObjects((\"DABING-MIB\", \"genericPayload\")) if mibBuilder.loadTexts: malfunctionTrap.setStatus('current')", "by user ? # Using Python version 3.8.2 (tags/v3.8.2:7b3ab59, Feb", "managerHostname.setStatus('current') managerPort = MibScalar((1, 3, 6, 1, 4, 1, 55532,", "testTrap.setStatus('current') mibBuilder.exportSymbols(\"DABING-MIB\", Notifications=Notifications, channel=channel, PYSNMP_MODULE_ID=dabing, testTrap=testTrap, malfunctionTrap=malfunctionTrap, Parameters=Parameters, agentLabel=agentLabel, managerPort=managerPort,", "\"ObjectIdentifier\", \"Integer\") NamedValues, = mibBuilder.importSymbols(\"ASN1-ENUMERATION\", \"NamedValues\") ConstraintsIntersection, ConstraintsUnion, ValueRangeConstraint, SingleValueConstraint,", "SingleValueConstraint, ValueSizeConstraint = mibBuilder.importSymbols(\"ASN1-REFINEMENT\", \"ConstraintsIntersection\", \"ConstraintsUnion\", \"ValueRangeConstraint\", \"SingleValueConstraint\", \"ValueSizeConstraint\") NotificationGroup,", "3, 6, 1, 4, 1, 55532, 4, 2, 1), OctetString()).setMaxAccess(\"accessiblefornotify\")", "4, 1, 55532, 4)) NotificationPrefix = MibIdentifier((1, 3, 6, 1,", "Bits, NotificationType, TimeTicks, Counter64, enterprises, MibIdentifier, Integer32 = mibBuilder.importSymbols(\"SNMPv2-SMI\", \"MibScalar\",", "channel=channel, PYSNMP_MODULE_ID=dabing, testTrap=testTrap, malfunctionTrap=malfunctionTrap, Parameters=Parameters, agentLabel=agentLabel, managerPort=managerPort, trapEnabled=trapEnabled, managerHostname=managerHostname, Manager=Manager,", "2022 # On host ? platform ? version ? by", "mibBuilder.loadTexts: malfunctionTrap.setStatus('current') testTrap = NotificationType((1, 3, 6, 1, 4, 1,", "3, 6, 1, 4, 1, 55532, 1, 2), Integer32().clone(960)).setMaxAccess(\"readonly\") if", "= MibScalar((1, 3, 6, 1, 4, 1, 55532, 3, 2),", "NotificationGroup, ModuleCompliance = mibBuilder.importSymbols(\"SNMPv2-CONF\", \"NotificationGroup\", \"ModuleCompliance\") MibScalar, MibTable, MibTableRow, MibTableColumn,", "if mibBuilder.loadTexts: managerPort.setStatus('current') genericPayload = MibScalar((1, 3, 6, 1, 4,", "ObjectIdentity, iso, Counter32, Unsigned32, Bits, NotificationType, TimeTicks, Counter64, enterprises, MibIdentifier,", "4, 1, 55532, 2, 2), OctetString()).setMaxAccess(\"readwrite\") if mibBuilder.loadTexts: agentLabel.setStatus('current') agentStatus", "1, 55532, 3)) Notifications = MibIdentifier((1, 3, 6, 1, 4,", "MibIdentifier((1, 3, 6, 1, 4, 1, 55532, 4, 1)) NotificationObjects", "= MibScalar((1, 3, 6, 1, 4, 1, 55532, 1, 3),", "at Tue Mar 22 12:53:47 2022 # On host ?", "\"Integer\") NamedValues, = mibBuilder.importSymbols(\"ASN1-ENUMERATION\", \"NamedValues\") ConstraintsIntersection, ConstraintsUnion, ValueRangeConstraint, SingleValueConstraint, ValueSizeConstraint", "\"ModuleIdentity\", \"IpAddress\", \"ObjectIdentity\", \"iso\", \"Counter32\", \"Unsigned32\", \"Bits\", \"NotificationType\", \"TimeTicks\", \"Counter64\",", "Mar 22 12:53:47 2022 # On host ? platform ?", "= mibBuilder.importSymbols(\"ASN1\", \"OctetString\", \"ObjectIdentifier\", \"Integer\") NamedValues, = mibBuilder.importSymbols(\"ASN1-ENUMERATION\", \"NamedValues\") ConstraintsIntersection,", "3, 1), OctetString()).setMaxAccess(\"readonly\") if mibBuilder.loadTexts: managerHostname.setStatus('current') managerPort = MibScalar((1, 3,", "1, 55532, 1, 2), Integer32().clone(960)).setMaxAccess(\"readonly\") if mibBuilder.loadTexts: interval.setStatus('current') trapEnabled =", "agentIdentifier = MibScalar((1, 3, 6, 1, 4, 1, 55532, 2,", "ConstraintsUnion, ValueRangeConstraint, SingleValueConstraint, ValueSizeConstraint = mibBuilder.importSymbols(\"ASN1-REFINEMENT\", \"ConstraintsIntersection\", \"ConstraintsUnion\", \"ValueRangeConstraint\", \"SingleValueConstraint\",", "22 12:53:47 2022 # On host ? platform ? version", "channel = MibScalar((1, 3, 6, 1, 4, 1, 55532, 1,", "= MibScalar((1, 3, 6, 1, 4, 1, 55532, 1, 2),", "# # PySNMP MIB module DABING-MIB (http://snmplabs.com/pysmi) # ASN.1 source", "55532, 1, 2), Integer32().clone(960)).setMaxAccess(\"readonly\") if mibBuilder.loadTexts: interval.setStatus('current') trapEnabled = MibScalar((1,", "55532, 2, 3), Integer32()).setMaxAccess(\"readonly\") if mibBuilder.loadTexts: agentStatus.setStatus('current') managerHostname = MibScalar((1,", "2), Integer32().clone(162)).setMaxAccess(\"readonly\") if mibBuilder.loadTexts: managerPort.setStatus('current') genericPayload = MibScalar((1, 3, 6,", "4, 2, 1), OctetString()).setMaxAccess(\"accessiblefornotify\") if mibBuilder.loadTexts: genericPayload.setStatus('current') malfunctionTrap = NotificationType((1,", "3, 6, 1, 4, 1, 55532, 4, 1)) NotificationObjects =", "NotificationObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 55532, 4,", "MibScalar((1, 3, 6, 1, 4, 1, 55532, 2, 2), OctetString()).setMaxAccess(\"readwrite\")", "1, 55532, 1, 3), Integer32()).setMaxAccess(\"readonly\") if mibBuilder.loadTexts: trapEnabled.setStatus('current') agentIdentifier =", "mibBuilder.loadTexts: agentLabel.setStatus('current') agentStatus = MibScalar((1, 3, 6, 1, 4, 1,", "Python version 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 22:45:29) [MSC v.1916", "ValueRangeConstraint, SingleValueConstraint, ValueSizeConstraint = mibBuilder.importSymbols(\"ASN1-REFINEMENT\", \"ConstraintsIntersection\", \"ConstraintsUnion\", \"ValueRangeConstraint\", \"SingleValueConstraint\", \"ValueSizeConstraint\")", "1, 4, 1, 55532)) dabing.setRevisions(('2022-03-17 00:00',)) if mibBuilder.loadTexts: dabing.setLastUpdated('202203170000Z') if", "(Intel)] # OctetString, ObjectIdentifier, Integer = mibBuilder.importSymbols(\"ASN1\", \"OctetString\", \"ObjectIdentifier\", \"Integer\")", "platform ? version ? by user ? # Using Python", "testTrap=testTrap, malfunctionTrap=malfunctionTrap, Parameters=Parameters, agentLabel=agentLabel, managerPort=managerPort, trapEnabled=trapEnabled, managerHostname=managerHostname, Manager=Manager, NotificationPrefix=NotificationPrefix, Agent=Agent,", "Integer32()).setMaxAccess(\"readwrite\") if mibBuilder.loadTexts: agentIdentifier.setStatus('current') agentLabel = MibScalar((1, 3, 6, 1,", "6, 1, 4, 1, 55532, 4)) NotificationPrefix = MibIdentifier((1, 3,", "Integer32()).setMaxAccess(\"readonly\") if mibBuilder.loadTexts: agentStatus.setStatus('current') managerHostname = MibScalar((1, 3, 6, 1,", "3, 6, 1, 4, 1, 55532)) dabing.setRevisions(('2022-03-17 00:00',)) if mibBuilder.loadTexts:", "2)) channel = MibScalar((1, 3, 6, 1, 4, 1, 55532,", "managerHostname=managerHostname, Manager=Manager, NotificationPrefix=NotificationPrefix, Agent=Agent, genericPayload=genericPayload, NotificationObjects=NotificationObjects, agentIdentifier=agentIdentifier, dabing=dabing, agentStatus=agentStatus, interval=interval)", "MibScalar((1, 3, 6, 1, 4, 1, 55532, 1, 1), OctetString().clone('12C')).setMaxAccess(\"readonly\")", "1, 55532)) dabing.setRevisions(('2022-03-17 00:00',)) if mibBuilder.loadTexts: dabing.setLastUpdated('202203170000Z') if mibBuilder.loadTexts: dabing.setOrganization('www.stuba.sk')", "= ModuleIdentity((1, 3, 6, 1, 4, 1, 55532)) dabing.setRevisions(('2022-03-17 00:00',))", "\"ObjectIdentity\", \"iso\", \"Counter32\", \"Unsigned32\", \"Bits\", \"NotificationType\", \"TimeTicks\", \"Counter64\", \"enterprises\", \"MibIdentifier\",", "4, 1, 55532, 2)) Manager = MibIdentifier((1, 3, 6, 1,", "Integer32()).setMaxAccess(\"readonly\") if mibBuilder.loadTexts: trapEnabled.setStatus('current') agentIdentifier = MibScalar((1, 3, 6, 1,", "1, 4, 1, 55532, 3)) Notifications = MibIdentifier((1, 3, 6,", "2), Integer32().clone(960)).setMaxAccess(\"readonly\") if mibBuilder.loadTexts: interval.setStatus('current') trapEnabled = MibScalar((1, 3, 6,", "bit (Intel)] # OctetString, ObjectIdentifier, Integer = mibBuilder.importSymbols(\"ASN1\", \"OctetString\", \"ObjectIdentifier\",", "55532, 2, 2), OctetString()).setMaxAccess(\"readwrite\") if mibBuilder.loadTexts: agentLabel.setStatus('current') agentStatus = MibScalar((1,", "MibScalar((1, 3, 6, 1, 4, 1, 55532, 1, 2), Integer32().clone(960)).setMaxAccess(\"readonly\")", "if mibBuilder.loadTexts: trapEnabled.setStatus('current') agentIdentifier = MibScalar((1, 3, 6, 1, 4,", "? by user ? # Using Python version 3.8.2 (tags/v3.8.2:7b3ab59,", "mibBuilder.importSymbols(\"ASN1\", \"OctetString\", \"ObjectIdentifier\", \"Integer\") NamedValues, = mibBuilder.importSymbols(\"ASN1-ENUMERATION\", \"NamedValues\") ConstraintsIntersection, ConstraintsUnion,", "1, 4, 1, 55532, 2, 2), OctetString()).setMaxAccess(\"readwrite\") if mibBuilder.loadTexts: agentLabel.setStatus('current')", "mibBuilder.loadTexts: trapEnabled.setStatus('current') agentIdentifier = MibScalar((1, 3, 6, 1, 4, 1,", "NotificationType((1, 3, 6, 1, 4, 1, 55532, 4, 1, 2)).setObjects((\"DABING-MIB\",", "by pysmi-0.3.4 at Tue Mar 22 12:53:47 2022 # On", "v.1916 32 bit (Intel)] # OctetString, ObjectIdentifier, Integer = mibBuilder.importSymbols(\"ASN1\",", "iso, Counter32, Unsigned32, Bits, NotificationType, TimeTicks, Counter64, enterprises, MibIdentifier, Integer32", "6, 1, 4, 1, 55532, 4, 2, 1), OctetString()).setMaxAccess(\"accessiblefornotify\") if", "ConstraintsIntersection, ConstraintsUnion, ValueRangeConstraint, SingleValueConstraint, ValueSizeConstraint = mibBuilder.importSymbols(\"ASN1-REFINEMENT\", \"ConstraintsIntersection\", \"ConstraintsUnion\", \"ValueRangeConstraint\",", "MibIdentifier((1, 3, 6, 1, 4, 1, 55532, 1)) Agent =", "mibBuilder.importSymbols(\"SNMPv2-CONF\", \"NotificationGroup\", \"ModuleCompliance\") MibScalar, MibTable, MibTableRow, MibTableColumn, Gauge32, ModuleIdentity, IpAddress,", "managerPort = MibScalar((1, 3, 6, 1, 4, 1, 55532, 3,", "mibBuilder.importSymbols(\"SNMPv2-SMI\", \"MibScalar\", \"MibTable\", \"MibTableRow\", \"MibTableColumn\", \"Gauge32\", \"ModuleIdentity\", \"IpAddress\", \"ObjectIdentity\", \"iso\",", "\"Unsigned32\", \"Bits\", \"NotificationType\", \"TimeTicks\", \"Counter64\", \"enterprises\", \"MibIdentifier\", \"Integer32\") DisplayString, TextualConvention", "32 bit (Intel)] # OctetString, ObjectIdentifier, Integer = mibBuilder.importSymbols(\"ASN1\", \"OctetString\",", "MibIdentifier((1, 3, 6, 1, 4, 1, 55532, 3)) Notifications =", "1), OctetString()).setMaxAccess(\"accessiblefornotify\") if mibBuilder.loadTexts: genericPayload.setStatus('current') malfunctionTrap = NotificationType((1, 3, 6,", "malfunctionTrap = NotificationType((1, 3, 6, 1, 4, 1, 55532, 4,", "= MibIdentifier((1, 3, 6, 1, 4, 1, 55532, 3)) Notifications", "1), OctetString().clone('12C')).setMaxAccess(\"readonly\") if mibBuilder.loadTexts: channel.setStatus('current') interval = MibScalar((1, 3, 6,", "55532, 4, 2)) channel = MibScalar((1, 3, 6, 1, 4,", "\"MibScalar\", \"MibTable\", \"MibTableRow\", \"MibTableColumn\", \"Gauge32\", \"ModuleIdentity\", \"IpAddress\", \"ObjectIdentity\", \"iso\", \"Counter32\",", "= MibScalar((1, 3, 6, 1, 4, 1, 55532, 3, 1),", "1, 4, 1, 55532, 1, 1), OctetString().clone('12C')).setMaxAccess(\"readonly\") if mibBuilder.loadTexts: channel.setStatus('current')", "1, 1), OctetString().clone('12C')).setMaxAccess(\"readonly\") if mibBuilder.loadTexts: channel.setStatus('current') interval = MibScalar((1, 3,", "[MSC v.1916 32 bit (Intel)] # OctetString, ObjectIdentifier, Integer =", "\"OctetString\", \"ObjectIdentifier\", \"Integer\") NamedValues, = mibBuilder.importSymbols(\"ASN1-ENUMERATION\", \"NamedValues\") ConstraintsIntersection, ConstraintsUnion, ValueRangeConstraint,", "4, 1, 55532)) dabing.setRevisions(('2022-03-17 00:00',)) if mibBuilder.loadTexts: dabing.setLastUpdated('202203170000Z') if mibBuilder.loadTexts:", "00:00',)) if mibBuilder.loadTexts: dabing.setLastUpdated('202203170000Z') if mibBuilder.loadTexts: dabing.setOrganization('www.stuba.sk') Parameters = MibIdentifier((1,", "1, 55532, 2, 1), Integer32()).setMaxAccess(\"readwrite\") if mibBuilder.loadTexts: agentIdentifier.setStatus('current') agentLabel =", "On host ? platform ? version ? by user ?", "OctetString()).setMaxAccess(\"accessiblefornotify\") if mibBuilder.loadTexts: genericPayload.setStatus('current') malfunctionTrap = NotificationType((1, 3, 6, 1,", "DABING-MIB (http://snmplabs.com/pysmi) # ASN.1 source file://..\\DABING-MIB.mib # Produced by pysmi-0.3.4", "= MibIdentifier((1, 3, 6, 1, 4, 1, 55532, 2)) Manager", "ValueSizeConstraint = mibBuilder.importSymbols(\"ASN1-REFINEMENT\", \"ConstraintsIntersection\", \"ConstraintsUnion\", \"ValueRangeConstraint\", \"SingleValueConstraint\", \"ValueSizeConstraint\") NotificationGroup, ModuleCompliance", "1, 4, 1, 55532, 2)) Manager = MibIdentifier((1, 3, 6,", "1), Integer32()).setMaxAccess(\"readwrite\") if mibBuilder.loadTexts: agentIdentifier.setStatus('current') agentLabel = MibScalar((1, 3, 6,", "= MibIdentifier((1, 3, 6, 1, 4, 1, 55532, 1)) Agent", "1, 55532, 4, 1)) NotificationObjects = MibIdentifier((1, 3, 6, 1,", "Using Python version 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 22:45:29) [MSC", "\"Counter64\", \"enterprises\", \"MibIdentifier\", \"Integer32\") DisplayString, TextualConvention = mibBuilder.importSymbols(\"SNMPv2-TC\", \"DisplayString\", \"TextualConvention\")", "3, 6, 1, 4, 1, 55532, 3, 2), Integer32().clone(162)).setMaxAccess(\"readonly\") if", "# ASN.1 source file://..\\DABING-MIB.mib # Produced by pysmi-0.3.4 at Tue", "1, 4, 1, 55532, 4, 1, 1)).setObjects((\"DABING-MIB\", \"genericPayload\")) if mibBuilder.loadTexts:", "dabing.setOrganization('www.stuba.sk') Parameters = MibIdentifier((1, 3, 6, 1, 4, 1, 55532,", "testTrap = NotificationType((1, 3, 6, 1, 4, 1, 55532, 4,", "\"TimeTicks\", \"Counter64\", \"enterprises\", \"MibIdentifier\", \"Integer32\") DisplayString, TextualConvention = mibBuilder.importSymbols(\"SNMPv2-TC\", \"DisplayString\",", "4, 1, 55532, 3, 1), OctetString()).setMaxAccess(\"readonly\") if mibBuilder.loadTexts: managerHostname.setStatus('current') managerPort", "4, 1, 55532, 4, 2, 1), OctetString()).setMaxAccess(\"accessiblefornotify\") if mibBuilder.loadTexts: genericPayload.setStatus('current')", "MibScalar((1, 3, 6, 1, 4, 1, 55532, 3, 1), OctetString()).setMaxAccess(\"readonly\")", "MibIdentifier, Integer32 = mibBuilder.importSymbols(\"SNMPv2-SMI\", \"MibScalar\", \"MibTable\", \"MibTableRow\", \"MibTableColumn\", \"Gauge32\", \"ModuleIdentity\",", "22:45:29) [MSC v.1916 32 bit (Intel)] # OctetString, ObjectIdentifier, Integer", "= mibBuilder.importSymbols(\"ASN1-REFINEMENT\", \"ConstraintsIntersection\", \"ConstraintsUnion\", \"ValueRangeConstraint\", \"SingleValueConstraint\", \"ValueSizeConstraint\") NotificationGroup, ModuleCompliance =", "4, 1, 55532, 4, 1, 2)).setObjects((\"DABING-MIB\", \"genericPayload\")) if mibBuilder.loadTexts: testTrap.setStatus('current')", "OctetString()).setMaxAccess(\"readwrite\") if mibBuilder.loadTexts: agentLabel.setStatus('current') agentStatus = MibScalar((1, 3, 6, 1,", "channel.setStatus('current') interval = MibScalar((1, 3, 6, 1, 4, 1, 55532,", "6, 1, 4, 1, 55532, 4, 2)) channel = MibScalar((1,", "4, 1, 55532, 2, 3), Integer32()).setMaxAccess(\"readonly\") if mibBuilder.loadTexts: agentStatus.setStatus('current') managerHostname", "55532, 2)) Manager = MibIdentifier((1, 3, 6, 1, 4, 1,", "\"NamedValues\") ConstraintsIntersection, ConstraintsUnion, ValueRangeConstraint, SingleValueConstraint, ValueSizeConstraint = mibBuilder.importSymbols(\"ASN1-REFINEMENT\", \"ConstraintsIntersection\", \"ConstraintsUnion\",", "(tags/v3.8.2:7b3ab59, Feb 25 2020, 22:45:29) [MSC v.1916 32 bit (Intel)]", "mibBuilder.loadTexts: dabing.setLastUpdated('202203170000Z') if mibBuilder.loadTexts: dabing.setOrganization('www.stuba.sk') Parameters = MibIdentifier((1, 3, 6,", "ObjectIdentifier, Integer = mibBuilder.importSymbols(\"ASN1\", \"OctetString\", \"ObjectIdentifier\", \"Integer\") NamedValues, = mibBuilder.importSymbols(\"ASN1-ENUMERATION\",", "enterprises, MibIdentifier, Integer32 = mibBuilder.importSymbols(\"SNMPv2-SMI\", \"MibScalar\", \"MibTable\", \"MibTableRow\", \"MibTableColumn\", \"Gauge32\",", "1, 2)).setObjects((\"DABING-MIB\", \"genericPayload\")) if mibBuilder.loadTexts: testTrap.setStatus('current') mibBuilder.exportSymbols(\"DABING-MIB\", Notifications=Notifications, channel=channel, PYSNMP_MODULE_ID=dabing,", "managerHostname = MibScalar((1, 3, 6, 1, 4, 1, 55532, 3,", "1, 55532, 2, 3), Integer32()).setMaxAccess(\"readonly\") if mibBuilder.loadTexts: agentStatus.setStatus('current') managerHostname =", "genericPayload = MibScalar((1, 3, 6, 1, 4, 1, 55532, 4,", "3), Integer32()).setMaxAccess(\"readonly\") if mibBuilder.loadTexts: agentStatus.setStatus('current') managerHostname = MibScalar((1, 3, 6,", "= mibBuilder.importSymbols(\"SNMPv2-CONF\", \"NotificationGroup\", \"ModuleCompliance\") MibScalar, MibTable, MibTableRow, MibTableColumn, Gauge32, ModuleIdentity,", "3, 6, 1, 4, 1, 55532, 1, 3), Integer32()).setMaxAccess(\"readonly\") if", "1)) NotificationObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 55532,", "2, 3), Integer32()).setMaxAccess(\"readonly\") if mibBuilder.loadTexts: agentStatus.setStatus('current') managerHostname = MibScalar((1, 3,", "55532, 4)) NotificationPrefix = MibIdentifier((1, 3, 6, 1, 4, 1,", "\"NotificationGroup\", \"ModuleCompliance\") MibScalar, MibTable, MibTableRow, MibTableColumn, Gauge32, ModuleIdentity, IpAddress, ObjectIdentity,", "<filename>dabing/DABING-MIB.py # # PySNMP MIB module DABING-MIB (http://snmplabs.com/pysmi) # ASN.1", "55532, 4, 1, 1)).setObjects((\"DABING-MIB\", \"genericPayload\")) if mibBuilder.loadTexts: malfunctionTrap.setStatus('current') testTrap =", "MibTable, MibTableRow, MibTableColumn, Gauge32, ModuleIdentity, IpAddress, ObjectIdentity, iso, Counter32, Unsigned32,", "OctetString, ObjectIdentifier, Integer = mibBuilder.importSymbols(\"ASN1\", \"OctetString\", \"ObjectIdentifier\", \"Integer\") NamedValues, =", "mibBuilder.loadTexts: agentStatus.setStatus('current') managerHostname = MibScalar((1, 3, 6, 1, 4, 1,", "55532, 4, 1, 2)).setObjects((\"DABING-MIB\", \"genericPayload\")) if mibBuilder.loadTexts: testTrap.setStatus('current') mibBuilder.exportSymbols(\"DABING-MIB\", Notifications=Notifications,", "managerPort=managerPort, trapEnabled=trapEnabled, managerHostname=managerHostname, Manager=Manager, NotificationPrefix=NotificationPrefix, Agent=Agent, genericPayload=genericPayload, NotificationObjects=NotificationObjects, agentIdentifier=agentIdentifier, dabing=dabing,", "version ? by user ? # Using Python version 3.8.2", "malfunctionTrap=malfunctionTrap, Parameters=Parameters, agentLabel=agentLabel, managerPort=managerPort, trapEnabled=trapEnabled, managerHostname=managerHostname, Manager=Manager, NotificationPrefix=NotificationPrefix, Agent=Agent, genericPayload=genericPayload,", "ModuleCompliance = mibBuilder.importSymbols(\"SNMPv2-CONF\", \"NotificationGroup\", \"ModuleCompliance\") MibScalar, MibTable, MibTableRow, MibTableColumn, Gauge32,", "6, 1, 4, 1, 55532, 4, 1, 2)).setObjects((\"DABING-MIB\", \"genericPayload\")) if", "? platform ? version ? by user ? # Using", "DisplayString, TextualConvention = mibBuilder.importSymbols(\"SNMPv2-TC\", \"DisplayString\", \"TextualConvention\") dabing = ModuleIdentity((1, 3,", "agentLabel.setStatus('current') agentStatus = MibScalar((1, 3, 6, 1, 4, 1, 55532,", "\"genericPayload\")) if mibBuilder.loadTexts: malfunctionTrap.setStatus('current') testTrap = NotificationType((1, 3, 6, 1,", "Gauge32, ModuleIdentity, IpAddress, ObjectIdentity, iso, Counter32, Unsigned32, Bits, NotificationType, TimeTicks,", "Agent = MibIdentifier((1, 3, 6, 1, 4, 1, 55532, 2))", "1)) Agent = MibIdentifier((1, 3, 6, 1, 4, 1, 55532,", "Notifications = MibIdentifier((1, 3, 6, 1, 4, 1, 55532, 4))", "\"ConstraintsIntersection\", \"ConstraintsUnion\", \"ValueRangeConstraint\", \"SingleValueConstraint\", \"ValueSizeConstraint\") NotificationGroup, ModuleCompliance = mibBuilder.importSymbols(\"SNMPv2-CONF\", \"NotificationGroup\",", "6, 1, 4, 1, 55532, 4, 1, 1)).setObjects((\"DABING-MIB\", \"genericPayload\")) if", "12:53:47 2022 # On host ? platform ? version ?", "ModuleIdentity((1, 3, 6, 1, 4, 1, 55532)) dabing.setRevisions(('2022-03-17 00:00',)) if", "interval.setStatus('current') trapEnabled = MibScalar((1, 3, 6, 1, 4, 1, 55532,", "? # Using Python version 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020,", "3, 2), Integer32().clone(162)).setMaxAccess(\"readonly\") if mibBuilder.loadTexts: managerPort.setStatus('current') genericPayload = MibScalar((1, 3,", "6, 1, 4, 1, 55532, 2, 1), Integer32()).setMaxAccess(\"readwrite\") if mibBuilder.loadTexts:", "MibScalar((1, 3, 6, 1, 4, 1, 55532, 4, 2, 1),", "if mibBuilder.loadTexts: managerHostname.setStatus('current') managerPort = MibScalar((1, 3, 6, 1, 4,", "ASN.1 source file://..\\DABING-MIB.mib # Produced by pysmi-0.3.4 at Tue Mar", "1, 4, 1, 55532, 4, 1)) NotificationObjects = MibIdentifier((1, 3,", "3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 22:45:29) [MSC v.1916 32 bit", "mibBuilder.loadTexts: channel.setStatus('current') interval = MibScalar((1, 3, 6, 1, 4, 1,", "1, 55532, 1)) Agent = MibIdentifier((1, 3, 6, 1, 4,", "2), OctetString()).setMaxAccess(\"readwrite\") if mibBuilder.loadTexts: agentLabel.setStatus('current') agentStatus = MibScalar((1, 3, 6,", "1, 55532, 2, 2), OctetString()).setMaxAccess(\"readwrite\") if mibBuilder.loadTexts: agentLabel.setStatus('current') agentStatus =", "= MibIdentifier((1, 3, 6, 1, 4, 1, 55532, 4, 1))", "trapEnabled = MibScalar((1, 3, 6, 1, 4, 1, 55532, 1,", "3, 6, 1, 4, 1, 55532, 4, 1, 2)).setObjects((\"DABING-MIB\", \"genericPayload\"))", "1, 4, 1, 55532, 3, 2), Integer32().clone(162)).setMaxAccess(\"readonly\") if mibBuilder.loadTexts: managerPort.setStatus('current')", "3, 6, 1, 4, 1, 55532, 1, 1), OctetString().clone('12C')).setMaxAccess(\"readonly\") if", "3, 6, 1, 4, 1, 55532, 2, 3), Integer32()).setMaxAccess(\"readonly\") if", "host ? platform ? version ? by user ? #", "Feb 25 2020, 22:45:29) [MSC v.1916 32 bit (Intel)] #", "6, 1, 4, 1, 55532, 3, 1), OctetString()).setMaxAccess(\"readonly\") if mibBuilder.loadTexts:", "6, 1, 4, 1, 55532, 1, 3), Integer32()).setMaxAccess(\"readonly\") if mibBuilder.loadTexts:", "PySNMP MIB module DABING-MIB (http://snmplabs.com/pysmi) # ASN.1 source file://..\\DABING-MIB.mib #", "if mibBuilder.loadTexts: agentLabel.setStatus('current') agentStatus = MibScalar((1, 3, 6, 1, 4,", "TimeTicks, Counter64, enterprises, MibIdentifier, Integer32 = mibBuilder.importSymbols(\"SNMPv2-SMI\", \"MibScalar\", \"MibTable\", \"MibTableRow\",", "source file://..\\DABING-MIB.mib # Produced by pysmi-0.3.4 at Tue Mar 22", "\"Integer32\") DisplayString, TextualConvention = mibBuilder.importSymbols(\"SNMPv2-TC\", \"DisplayString\", \"TextualConvention\") dabing = ModuleIdentity((1,", "55532, 1)) Agent = MibIdentifier((1, 3, 6, 1, 4, 1,", "6, 1, 4, 1, 55532, 4, 1)) NotificationObjects = MibIdentifier((1,", "if mibBuilder.loadTexts: agentIdentifier.setStatus('current') agentLabel = MibScalar((1, 3, 6, 1, 4,", "= mibBuilder.importSymbols(\"ASN1-ENUMERATION\", \"NamedValues\") ConstraintsIntersection, ConstraintsUnion, ValueRangeConstraint, SingleValueConstraint, ValueSizeConstraint = mibBuilder.importSymbols(\"ASN1-REFINEMENT\",", "\"TextualConvention\") dabing = ModuleIdentity((1, 3, 6, 1, 4, 1, 55532))", "Produced by pysmi-0.3.4 at Tue Mar 22 12:53:47 2022 #", "= MibIdentifier((1, 3, 6, 1, 4, 1, 55532, 4)) NotificationPrefix", "mibBuilder.loadTexts: managerHostname.setStatus('current') managerPort = MibScalar((1, 3, 6, 1, 4, 1,", "\"NotificationType\", \"TimeTicks\", \"Counter64\", \"enterprises\", \"MibIdentifier\", \"Integer32\") DisplayString, TextualConvention = mibBuilder.importSymbols(\"SNMPv2-TC\",", "MibIdentifier((1, 3, 6, 1, 4, 1, 55532, 2)) Manager =", "4, 1, 55532, 3)) Notifications = MibIdentifier((1, 3, 6, 1,", "4, 1, 1)).setObjects((\"DABING-MIB\", \"genericPayload\")) if mibBuilder.loadTexts: malfunctionTrap.setStatus('current') testTrap = NotificationType((1,", "3, 6, 1, 4, 1, 55532, 4, 2)) channel =", "mibBuilder.importSymbols(\"ASN1-REFINEMENT\", \"ConstraintsIntersection\", \"ConstraintsUnion\", \"ValueRangeConstraint\", \"SingleValueConstraint\", \"ValueSizeConstraint\") NotificationGroup, ModuleCompliance = mibBuilder.importSymbols(\"SNMPv2-CONF\",", "55532, 2, 1), Integer32()).setMaxAccess(\"readwrite\") if mibBuilder.loadTexts: agentIdentifier.setStatus('current') agentLabel = MibScalar((1,", "55532, 1, 3), Integer32()).setMaxAccess(\"readonly\") if mibBuilder.loadTexts: trapEnabled.setStatus('current') agentIdentifier = MibScalar((1,", "TextualConvention = mibBuilder.importSymbols(\"SNMPv2-TC\", \"DisplayString\", \"TextualConvention\") dabing = ModuleIdentity((1, 3, 6,", "MibScalar((1, 3, 6, 1, 4, 1, 55532, 3, 2), Integer32().clone(162)).setMaxAccess(\"readonly\")", "4, 1)) NotificationObjects = MibIdentifier((1, 3, 6, 1, 4, 1,", "55532, 4, 2, 1), OctetString()).setMaxAccess(\"accessiblefornotify\") if mibBuilder.loadTexts: genericPayload.setStatus('current') malfunctionTrap =", "3, 6, 1, 4, 1, 55532, 4, 1, 1)).setObjects((\"DABING-MIB\", \"genericPayload\"))", "1, 4, 1, 55532, 1, 2), Integer32().clone(960)).setMaxAccess(\"readonly\") if mibBuilder.loadTexts: interval.setStatus('current')", "3, 6, 1, 4, 1, 55532, 4)) NotificationPrefix = MibIdentifier((1,", "dabing.setRevisions(('2022-03-17 00:00',)) if mibBuilder.loadTexts: dabing.setLastUpdated('202203170000Z') if mibBuilder.loadTexts: dabing.setOrganization('www.stuba.sk') Parameters =", "\"IpAddress\", \"ObjectIdentity\", \"iso\", \"Counter32\", \"Unsigned32\", \"Bits\", \"NotificationType\", \"TimeTicks\", \"Counter64\", \"enterprises\",", "3, 6, 1, 4, 1, 55532, 2)) Manager = MibIdentifier((1,", "1, 55532, 2)) Manager = MibIdentifier((1, 3, 6, 1, 4,", "OctetString()).setMaxAccess(\"readonly\") if mibBuilder.loadTexts: managerHostname.setStatus('current') managerPort = MibScalar((1, 3, 6, 1,", "agentLabel = MibScalar((1, 3, 6, 1, 4, 1, 55532, 2,", "module DABING-MIB (http://snmplabs.com/pysmi) # ASN.1 source file://..\\DABING-MIB.mib # Produced by", "pysmi-0.3.4 at Tue Mar 22 12:53:47 2022 # On host", "Parameters=Parameters, agentLabel=agentLabel, managerPort=managerPort, trapEnabled=trapEnabled, managerHostname=managerHostname, Manager=Manager, NotificationPrefix=NotificationPrefix, Agent=Agent, genericPayload=genericPayload, NotificationObjects=NotificationObjects,", "# On host ? platform ? version ? by user", "= MibScalar((1, 3, 6, 1, 4, 1, 55532, 2, 1),", "1)).setObjects((\"DABING-MIB\", \"genericPayload\")) if mibBuilder.loadTexts: malfunctionTrap.setStatus('current') testTrap = NotificationType((1, 3, 6,", "\"Counter32\", \"Unsigned32\", \"Bits\", \"NotificationType\", \"TimeTicks\", \"Counter64\", \"enterprises\", \"MibIdentifier\", \"Integer32\") DisplayString,", "MibIdentifier((1, 3, 6, 1, 4, 1, 55532, 4)) NotificationPrefix =", "2, 1), OctetString()).setMaxAccess(\"accessiblefornotify\") if mibBuilder.loadTexts: genericPayload.setStatus('current') malfunctionTrap = NotificationType((1, 3,", "\"ModuleCompliance\") MibScalar, MibTable, MibTableRow, MibTableColumn, Gauge32, ModuleIdentity, IpAddress, ObjectIdentity, iso,", "1, 55532, 4, 2)) channel = MibScalar((1, 3, 6, 1,", "4, 1, 55532, 1, 3), Integer32()).setMaxAccess(\"readonly\") if mibBuilder.loadTexts: trapEnabled.setStatus('current') agentIdentifier", "Manager = MibIdentifier((1, 3, 6, 1, 4, 1, 55532, 3))", "NamedValues, = mibBuilder.importSymbols(\"ASN1-ENUMERATION\", \"NamedValues\") ConstraintsIntersection, ConstraintsUnion, ValueRangeConstraint, SingleValueConstraint, ValueSizeConstraint =", "if mibBuilder.loadTexts: interval.setStatus('current') trapEnabled = MibScalar((1, 3, 6, 1, 4,", "if mibBuilder.loadTexts: malfunctionTrap.setStatus('current') testTrap = NotificationType((1, 3, 6, 1, 4,", "1, 4, 1, 55532, 4, 2)) channel = MibScalar((1, 3,", "# Using Python version 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 22:45:29)", "if mibBuilder.loadTexts: agentStatus.setStatus('current') managerHostname = MibScalar((1, 3, 6, 1, 4,", "4, 1, 55532, 1, 1), OctetString().clone('12C')).setMaxAccess(\"readonly\") if mibBuilder.loadTexts: channel.setStatus('current') interval", "MibScalar((1, 3, 6, 1, 4, 1, 55532, 1, 3), Integer32()).setMaxAccess(\"readonly\")", "6, 1, 4, 1, 55532, 2, 2), OctetString()).setMaxAccess(\"readwrite\") if mibBuilder.loadTexts:", "\"ValueRangeConstraint\", \"SingleValueConstraint\", \"ValueSizeConstraint\") NotificationGroup, ModuleCompliance = mibBuilder.importSymbols(\"SNMPv2-CONF\", \"NotificationGroup\", \"ModuleCompliance\") MibScalar,", "4, 1, 55532, 1)) Agent = MibIdentifier((1, 3, 6, 1,", "\"MibTable\", \"MibTableRow\", \"MibTableColumn\", \"Gauge32\", \"ModuleIdentity\", \"IpAddress\", \"ObjectIdentity\", \"iso\", \"Counter32\", \"Unsigned32\",", "55532, 3)) Notifications = MibIdentifier((1, 3, 6, 1, 4, 1,", "6, 1, 4, 1, 55532, 1, 1), OctetString().clone('12C')).setMaxAccess(\"readonly\") if mibBuilder.loadTexts:", "Integer32().clone(960)).setMaxAccess(\"readonly\") if mibBuilder.loadTexts: interval.setStatus('current') trapEnabled = MibScalar((1, 3, 6, 1,", "4, 1, 55532, 2, 1), Integer32()).setMaxAccess(\"readwrite\") if mibBuilder.loadTexts: agentIdentifier.setStatus('current') agentLabel", "trapEnabled.setStatus('current') agentIdentifier = MibScalar((1, 3, 6, 1, 4, 1, 55532,", "agentIdentifier.setStatus('current') agentLabel = MibScalar((1, 3, 6, 1, 4, 1, 55532,", "1, 3), Integer32()).setMaxAccess(\"readonly\") if mibBuilder.loadTexts: trapEnabled.setStatus('current') agentIdentifier = MibScalar((1, 3,", "\"Bits\", \"NotificationType\", \"TimeTicks\", \"Counter64\", \"enterprises\", \"MibIdentifier\", \"Integer32\") DisplayString, TextualConvention =", "3), Integer32()).setMaxAccess(\"readonly\") if mibBuilder.loadTexts: trapEnabled.setStatus('current') agentIdentifier = MibScalar((1, 3, 6,", "mibBuilder.loadTexts: interval.setStatus('current') trapEnabled = MibScalar((1, 3, 6, 1, 4, 1,", "mibBuilder.loadTexts: managerPort.setStatus('current') genericPayload = MibScalar((1, 3, 6, 1, 4, 1,", "if mibBuilder.loadTexts: genericPayload.setStatus('current') malfunctionTrap = NotificationType((1, 3, 6, 1, 4,", "6, 1, 4, 1, 55532, 1)) Agent = MibIdentifier((1, 3,", "genericPayload.setStatus('current') malfunctionTrap = NotificationType((1, 3, 6, 1, 4, 1, 55532,", "Notifications=Notifications, channel=channel, PYSNMP_MODULE_ID=dabing, testTrap=testTrap, malfunctionTrap=malfunctionTrap, Parameters=Parameters, agentLabel=agentLabel, managerPort=managerPort, trapEnabled=trapEnabled, managerHostname=managerHostname,", "\"MibIdentifier\", \"Integer32\") DisplayString, TextualConvention = mibBuilder.importSymbols(\"SNMPv2-TC\", \"DisplayString\", \"TextualConvention\") dabing =", "1, 1)).setObjects((\"DABING-MIB\", \"genericPayload\")) if mibBuilder.loadTexts: malfunctionTrap.setStatus('current') testTrap = NotificationType((1, 3,", "ModuleIdentity, IpAddress, ObjectIdentity, iso, Counter32, Unsigned32, Bits, NotificationType, TimeTicks, Counter64,", "Counter32, Unsigned32, Bits, NotificationType, TimeTicks, Counter64, enterprises, MibIdentifier, Integer32 =", "PYSNMP_MODULE_ID=dabing, testTrap=testTrap, malfunctionTrap=malfunctionTrap, Parameters=Parameters, agentLabel=agentLabel, managerPort=managerPort, trapEnabled=trapEnabled, managerHostname=managerHostname, Manager=Manager, NotificationPrefix=NotificationPrefix,", "1, 55532, 1, 1), OctetString().clone('12C')).setMaxAccess(\"readonly\") if mibBuilder.loadTexts: channel.setStatus('current') interval =", "= MibIdentifier((1, 3, 6, 1, 4, 1, 55532, 4, 2))", "# Produced by pysmi-0.3.4 at Tue Mar 22 12:53:47 2022", "6, 1, 4, 1, 55532, 2, 3), Integer32()).setMaxAccess(\"readonly\") if mibBuilder.loadTexts:", "\"enterprises\", \"MibIdentifier\", \"Integer32\") DisplayString, TextualConvention = mibBuilder.importSymbols(\"SNMPv2-TC\", \"DisplayString\", \"TextualConvention\") dabing", "2, 1), Integer32()).setMaxAccess(\"readwrite\") if mibBuilder.loadTexts: agentIdentifier.setStatus('current') agentLabel = MibScalar((1, 3,", "Counter64, enterprises, MibIdentifier, Integer32 = mibBuilder.importSymbols(\"SNMPv2-SMI\", \"MibScalar\", \"MibTable\", \"MibTableRow\", \"MibTableColumn\",", "3, 6, 1, 4, 1, 55532, 3, 1), OctetString()).setMaxAccess(\"readonly\") if", "55532)) dabing.setRevisions(('2022-03-17 00:00',)) if mibBuilder.loadTexts: dabing.setLastUpdated('202203170000Z') if mibBuilder.loadTexts: dabing.setOrganization('www.stuba.sk') Parameters", "3, 6, 1, 4, 1, 55532, 1)) Agent = MibIdentifier((1,", "6, 1, 4, 1, 55532, 3, 2), Integer32().clone(162)).setMaxAccess(\"readonly\") if mibBuilder.loadTexts:", "MibScalar, MibTable, MibTableRow, MibTableColumn, Gauge32, ModuleIdentity, IpAddress, ObjectIdentity, iso, Counter32," ]
[ "'VISli','VISpor','VISrl','VISa'] lambda_list = np.logspace(3,12,10) scale_lambda=True min_vox=0 # save_file_name='visual_output.hdf5' #source_coverage=0.90 source_coverage=0.95", "lambda_list = np.logspace(3,12,10) scale_lambda=True min_vox=0 # save_file_name='visual_output.hdf5' #source_coverage=0.90 source_coverage=0.95 #source_shell", "solver=os.path.abspath('../smoothness_c/solve') cmdfile=os.path.join(save_dir,'model_fitting_cmds') selected_fit_cmds=os.path.join(save_dir,'model_fitting_after_selection_cmds') save_mtx=True cross_val_matrices=True cross_val=5 fit_gaussian=False select_one_lambda=False if select_one_lambda:", "scale_lambda=True min_vox=0 # save_file_name='visual_output.hdf5' #source_coverage=0.90 source_coverage=0.95 #source_shell = 1 source_shell=None", "cross_val_matrices=True cross_val=5 fit_gaussian=False select_one_lambda=False if select_one_lambda: lambda_fn='lambda_opt' else: lambda_fn='lambda_ipsi_contra_opt' laplacian='free'", "cmdfile=os.path.join(save_dir,'model_fitting_cmds') selected_fit_cmds=os.path.join(save_dir,'model_fitting_after_selection_cmds') save_mtx=True cross_val_matrices=True cross_val=5 fit_gaussian=False select_one_lambda=False if select_one_lambda: lambda_fn='lambda_opt'", "source_acronyms=['VISal','VISam','VISl','VISp','VISpl','VISpm', 'VISli','VISpor','VISrl','VISa'] lambda_list = np.logspace(3,12,10) scale_lambda=True min_vox=0 # save_file_name='visual_output.hdf5' #source_coverage=0.90", "save_stem='extra_vis_friday_harbor' data_dir='../../data/sdk_new_100' resolution=100 cre=False source_acronyms=['VISal','VISam','VISl','VISp','VISpl','VISpm', 'VISli','VISpor','VISrl','VISa'] lambda_list = np.logspace(3,12,10) scale_lambda=True", "#source_coverage=0.90 source_coverage=0.95 #source_shell = 1 source_shell=None save_dir=os.path.join('../../data/connectivities',save_stem) experiments_fn=None target_acronyms=source_acronyms solver=os.path.abspath('../smoothness_c/solve')", "resolution=100 cre=False source_acronyms=['VISal','VISam','VISl','VISp','VISpl','VISpm', 'VISli','VISpor','VISrl','VISa'] lambda_list = np.logspace(3,12,10) scale_lambda=True min_vox=0 #", "data_dir='../../data/sdk_new_100' resolution=100 cre=False source_acronyms=['VISal','VISam','VISl','VISp','VISpl','VISpm', 'VISli','VISpor','VISrl','VISa'] lambda_list = np.logspace(3,12,10) scale_lambda=True min_vox=0", "cre=False source_acronyms=['VISal','VISam','VISl','VISp','VISpl','VISpm', 'VISli','VISpor','VISrl','VISa'] lambda_list = np.logspace(3,12,10) scale_lambda=True min_vox=0 # save_file_name='visual_output.hdf5'", "np.logspace(3,12,10) scale_lambda=True min_vox=0 # save_file_name='visual_output.hdf5' #source_coverage=0.90 source_coverage=0.95 #source_shell = 1", "save_mtx=True cross_val_matrices=True cross_val=5 fit_gaussian=False select_one_lambda=False if select_one_lambda: lambda_fn='lambda_opt' else: lambda_fn='lambda_ipsi_contra_opt'", "import os import numpy as np save_stem='extra_vis_friday_harbor' data_dir='../../data/sdk_new_100' resolution=100 cre=False", "min_vox=0 # save_file_name='visual_output.hdf5' #source_coverage=0.90 source_coverage=0.95 #source_shell = 1 source_shell=None save_dir=os.path.join('../../data/connectivities',save_stem)", "source_coverage=0.95 #source_shell = 1 source_shell=None save_dir=os.path.join('../../data/connectivities',save_stem) experiments_fn=None target_acronyms=source_acronyms solver=os.path.abspath('../smoothness_c/solve') cmdfile=os.path.join(save_dir,'model_fitting_cmds')", "experiments_fn=None target_acronyms=source_acronyms solver=os.path.abspath('../smoothness_c/solve') cmdfile=os.path.join(save_dir,'model_fitting_cmds') selected_fit_cmds=os.path.join(save_dir,'model_fitting_after_selection_cmds') save_mtx=True cross_val_matrices=True cross_val=5 fit_gaussian=False select_one_lambda=False", "target_acronyms=source_acronyms solver=os.path.abspath('../smoothness_c/solve') cmdfile=os.path.join(save_dir,'model_fitting_cmds') selected_fit_cmds=os.path.join(save_dir,'model_fitting_after_selection_cmds') save_mtx=True cross_val_matrices=True cross_val=5 fit_gaussian=False select_one_lambda=False if", "# save_file_name='visual_output.hdf5' #source_coverage=0.90 source_coverage=0.95 #source_shell = 1 source_shell=None save_dir=os.path.join('../../data/connectivities',save_stem) experiments_fn=None", "fit_gaussian=False select_one_lambda=False if select_one_lambda: lambda_fn='lambda_opt' else: lambda_fn='lambda_ipsi_contra_opt' laplacian='free' shuffle_seed=666 max_injection_volume=0.7", "1 source_shell=None save_dir=os.path.join('../../data/connectivities',save_stem) experiments_fn=None target_acronyms=source_acronyms solver=os.path.abspath('../smoothness_c/solve') cmdfile=os.path.join(save_dir,'model_fitting_cmds') selected_fit_cmds=os.path.join(save_dir,'model_fitting_after_selection_cmds') save_mtx=True cross_val_matrices=True", "os import numpy as np save_stem='extra_vis_friday_harbor' data_dir='../../data/sdk_new_100' resolution=100 cre=False source_acronyms=['VISal','VISam','VISl','VISp','VISpl','VISpm',", "save_file_name='visual_output.hdf5' #source_coverage=0.90 source_coverage=0.95 #source_shell = 1 source_shell=None save_dir=os.path.join('../../data/connectivities',save_stem) experiments_fn=None target_acronyms=source_acronyms", "as np save_stem='extra_vis_friday_harbor' data_dir='../../data/sdk_new_100' resolution=100 cre=False source_acronyms=['VISal','VISam','VISl','VISp','VISpl','VISpm', 'VISli','VISpor','VISrl','VISa'] lambda_list =", "#source_shell = 1 source_shell=None save_dir=os.path.join('../../data/connectivities',save_stem) experiments_fn=None target_acronyms=source_acronyms solver=os.path.abspath('../smoothness_c/solve') cmdfile=os.path.join(save_dir,'model_fitting_cmds') selected_fit_cmds=os.path.join(save_dir,'model_fitting_after_selection_cmds')", "= np.logspace(3,12,10) scale_lambda=True min_vox=0 # save_file_name='visual_output.hdf5' #source_coverage=0.90 source_coverage=0.95 #source_shell =", "import numpy as np save_stem='extra_vis_friday_harbor' data_dir='../../data/sdk_new_100' resolution=100 cre=False source_acronyms=['VISal','VISam','VISl','VISp','VISpl','VISpm', 'VISli','VISpor','VISrl','VISa']", "selected_fit_cmds=os.path.join(save_dir,'model_fitting_after_selection_cmds') save_mtx=True cross_val_matrices=True cross_val=5 fit_gaussian=False select_one_lambda=False if select_one_lambda: lambda_fn='lambda_opt' else:", "cross_val=5 fit_gaussian=False select_one_lambda=False if select_one_lambda: lambda_fn='lambda_opt' else: lambda_fn='lambda_ipsi_contra_opt' laplacian='free' shuffle_seed=666", "source_shell=None save_dir=os.path.join('../../data/connectivities',save_stem) experiments_fn=None target_acronyms=source_acronyms solver=os.path.abspath('../smoothness_c/solve') cmdfile=os.path.join(save_dir,'model_fitting_cmds') selected_fit_cmds=os.path.join(save_dir,'model_fitting_after_selection_cmds') save_mtx=True cross_val_matrices=True cross_val=5", "numpy as np save_stem='extra_vis_friday_harbor' data_dir='../../data/sdk_new_100' resolution=100 cre=False source_acronyms=['VISal','VISam','VISl','VISp','VISpl','VISpm', 'VISli','VISpor','VISrl','VISa'] lambda_list", "np save_stem='extra_vis_friday_harbor' data_dir='../../data/sdk_new_100' resolution=100 cre=False source_acronyms=['VISal','VISam','VISl','VISp','VISpl','VISpm', 'VISli','VISpor','VISrl','VISa'] lambda_list = np.logspace(3,12,10)", "= 1 source_shell=None save_dir=os.path.join('../../data/connectivities',save_stem) experiments_fn=None target_acronyms=source_acronyms solver=os.path.abspath('../smoothness_c/solve') cmdfile=os.path.join(save_dir,'model_fitting_cmds') selected_fit_cmds=os.path.join(save_dir,'model_fitting_after_selection_cmds') save_mtx=True", "save_dir=os.path.join('../../data/connectivities',save_stem) experiments_fn=None target_acronyms=source_acronyms solver=os.path.abspath('../smoothness_c/solve') cmdfile=os.path.join(save_dir,'model_fitting_cmds') selected_fit_cmds=os.path.join(save_dir,'model_fitting_after_selection_cmds') save_mtx=True cross_val_matrices=True cross_val=5 fit_gaussian=False" ]
[ "20 09:42:39 2020 @author: niklas \"\"\" from mossepy.mosse_tracker import MOSSE", "by mouse click objPos = [256, 256] # choose tracker", "frame # that should be done by mouse click objPos", "# initialize object position in first frame tracker.setObjPos(objPos) # start", "Fri Nov 20 09:42:39 2020 @author: niklas \"\"\" from mossepy.mosse_tracker", "from mossepy.mosse_tracker import MOSSE # choose position of object in", "be done by mouse click objPos = [256, 256] #", "on Fri Nov 20 09:42:39 2020 @author: niklas \"\"\" from", "tracker type tracker = MOSSE() # initialize object position in", "MOSSE() # initialize object position in first frame tracker.setObjPos(objPos) #", "tracker = MOSSE() # initialize object position in first frame", "type tracker = MOSSE() # initialize object position in first", "# choose position of object in first frame # that", "mossepy.mosse_tracker import MOSSE # choose position of object in first", "first frame # that should be done by mouse click", "niklas \"\"\" from mossepy.mosse_tracker import MOSSE # choose position of", "09:42:39 2020 @author: niklas \"\"\" from mossepy.mosse_tracker import MOSSE #", "= [256, 256] # choose tracker type tracker = MOSSE()", "-*- coding: utf-8 -*- \"\"\" Created on Fri Nov 20", "\"\"\" Created on Fri Nov 20 09:42:39 2020 @author: niklas", "choose tracker type tracker = MOSSE() # initialize object position", "2020 @author: niklas \"\"\" from mossepy.mosse_tracker import MOSSE # choose", "256] # choose tracker type tracker = MOSSE() # initialize", "#!/usr/bin/env python3 # -*- coding: utf-8 -*- \"\"\" Created on", "of object in first frame # that should be done", "Created on Fri Nov 20 09:42:39 2020 @author: niklas \"\"\"", "\"\"\" from mossepy.mosse_tracker import MOSSE # choose position of object", "position of object in first frame # that should be", "in first frame # that should be done by mouse", "object in first frame # that should be done by", "# that should be done by mouse click objPos =", "click objPos = [256, 256] # choose tracker type tracker", "object position in first frame tracker.setObjPos(objPos) # start tracking tracker.trackImg()", "that should be done by mouse click objPos = [256,", "objPos = [256, 256] # choose tracker type tracker =", "should be done by mouse click objPos = [256, 256]", "# -*- coding: utf-8 -*- \"\"\" Created on Fri Nov", "python3 # -*- coding: utf-8 -*- \"\"\" Created on Fri", "# choose tracker type tracker = MOSSE() # initialize object", "= MOSSE() # initialize object position in first frame tracker.setObjPos(objPos)", "import MOSSE # choose position of object in first frame", "Nov 20 09:42:39 2020 @author: niklas \"\"\" from mossepy.mosse_tracker import", "mouse click objPos = [256, 256] # choose tracker type", "MOSSE # choose position of object in first frame #", "utf-8 -*- \"\"\" Created on Fri Nov 20 09:42:39 2020", "-*- \"\"\" Created on Fri Nov 20 09:42:39 2020 @author:", "coding: utf-8 -*- \"\"\" Created on Fri Nov 20 09:42:39", "done by mouse click objPos = [256, 256] # choose", "initialize object position in first frame tracker.setObjPos(objPos) # start tracking", "choose position of object in first frame # that should", "@author: niklas \"\"\" from mossepy.mosse_tracker import MOSSE # choose position", "[256, 256] # choose tracker type tracker = MOSSE() #" ]
[ "if len(polynomial.term_matrix) == 3: if polynomial.term_matrix[2][1] == 1: a, b", "roots[:] for i in range(len(roots)): q = 1 for j,", "<= max(rel_tol * max(abs(a), abs(b)), abs_tol) def Durand_Kerner(f): \"\"\" input", "if len(polynomial.term_matrix) == 2: return 0 else: return -polynomial.term_matrix[2][0]/polynomial.term_matrix[1][0] if", "for i in range(len(roots)): diff += abs(roots[i] - new_roots[i]) roots", "ans2: return ans1 return ans1, ans2 def isclose(a, b, rel_tol=1e-09,", "*= roots[i] - root new_roots[i] = roots[i] - f(roots[i])/q nonlocal", "Durand_Kerner(polynomial) def quadratic_formula(polynomial): \"\"\" input is single-variable polynomial of degree", "= diff diff = 0 for i in range(len(roots)): diff", "diff += abs(roots[i] - new_roots[i]) roots = new_roots while diff", "a, b, c = polynomial.term_matrix[1][0], polynomial.term_matrix[2][0], polynomial.term_matrix[3][0] ans1 = (-b", "temp = round(roots[i].real) roots[i] -= roots[i].real roots[i] += temp if", "numerical approximation of all complex roots \"\"\" roots = []", "than one variable, returns 'too many variables' looks for formula", "many variables' elif len(polynomial.term_matrix[0]) == 1: return polynomial.term_matrix[1][0] elif len(polynomial.term_matrix[0])", "c = polynomial.term_matrix[1][0], polynomial.term_matrix[2][0] return (-c/a)**.5, -(-c/a)**.5 if len(polynomial.term_matrix) ==", "'I cannot solve yet...' \"\"\" if len(polynomial.term_matrix[0]) > 2: return", "boolean whether abs(a-b) is less than abs_total or rel_total*max(a, b)", "of all complex roots \"\"\" roots = [] for i", "- 4*a*c)**.5)/2*a ans2 = (-b - (b**2 - 4*a*c)**.5)/2*a if", "polynomial.term_matrix[2][0] return 0, -b/a a, c = polynomial.term_matrix[1][0], polynomial.term_matrix[2][0] return", "than abs_total or rel_total*max(a, b) \"\"\" return abs(a-b) <= max(rel_tol", "= 0 for i in range(len(roots)): diff += abs(roots[i] -", "= quadratic_formula(polynomial) return ans if degree > 2: return Durand_Kerner(polynomial)", "b) \"\"\" return abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)", "elif len(polynomial.term_matrix[0]) == 2: degree = polynomial.term_matrix[1][1] if degree ==", "2 returns zeros \"\"\" if len(polynomial.term_matrix) == 3: if polynomial.term_matrix[2][1]", "degree == 2: ans = quadratic_formula(polynomial) return ans if degree", "= polynomial.term_matrix[1][0], polynomial.term_matrix[2][0], 0 else: a, b, c = polynomial.term_matrix[1][0],", "\"\"\" return abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol) def", "abs(b)), abs_tol) def Durand_Kerner(f): \"\"\" input polynomial returns numerical approximation", "a, c = polynomial.term_matrix[1][0], polynomial.term_matrix[2][0] return (-c/a)**.5, -(-c/a)**.5 if len(polynomial.term_matrix)", "input is polynomial if more than one variable, returns 'too", "if ans1 == ans2: return ans1 return ans1, ans2 def", "zeros \"\"\" if len(polynomial.term_matrix) == 3: if polynomial.term_matrix[2][1] == 1:", "0.9j)**i) diff = 1 diff_temp = 0 def iterate(): nonlocal", "is single-variable polynomial of degree 2 returns zeros \"\"\" if", "temp = round(roots[i].imag) roots[i] -= roots[i].imag*1j roots[i] += temp*1j return", "whether abs(a-b) is less than abs_total or rel_total*max(a, b) \"\"\"", "= [] for i in range(f.degree()): roots.append((0.4 + 0.9j)**i) diff", "roots[i] - root new_roots[i] = roots[i] - f(roots[i])/q nonlocal diff", "polynomial.term_matrix[3][0] ans1 = (-b + (b**2 - 4*a*c)**.5)/2*a ans2 =", "polynomial.term_matrix[2][0], 0 else: a, b, c = polynomial.term_matrix[1][0], polynomial.term_matrix[2][0], polynomial.term_matrix[3][0]", "round(roots[i].real)): temp = round(roots[i].real) roots[i] -= roots[i].real roots[i] += temp", "f(roots[i])/q nonlocal diff nonlocal diff_temp diff_temp = diff diff =", "polynomial.term_matrix[2][1] == 1: a, b = polynomial.term_matrix[1][0], polynomial.term_matrix[2][0] return 0,", "of degree 2 returns zeros \"\"\" if len(polynomial.term_matrix) == 3:", "degree > 2: return Durand_Kerner(polynomial) def quadratic_formula(polynomial): \"\"\" input is", "variables' looks for formula to apply to coefficients returns solution", "return ans if degree > 2: return Durand_Kerner(polynomial) def quadratic_formula(polynomial):", "diff_temp = 0 def iterate(): nonlocal roots new_roots = roots[:]", "'too many variables' elif len(polynomial.term_matrix[0]) == 1: return polynomial.term_matrix[1][0] elif", "[] for i in range(f.degree()): roots.append((0.4 + 0.9j)**i) diff =", "to coefficients returns solution or 'I cannot solve yet...' \"\"\"", "b, rel_tol=1e-09, abs_tol=0.0001): \"\"\" returns boolean whether abs(a-b) is less", "q = 1 for j, root in enumerate(roots): if j", "- (b**2 - 4*a*c)**.5)/2*a if ans1 == ans2: return ans1", "2: a, b, c, = polynomial.term_matrix[1][0], 0, 0 elif len(polynomial.term_matrix)", "rel_tol=1e-09, abs_tol=0.0001): \"\"\" returns boolean whether abs(a-b) is less than", "!= i: q *= roots[i] - root new_roots[i] = roots[i]", "roots new_roots = roots[:] for i in range(len(roots)): q =", "polynomial of degree 2 returns zeros \"\"\" if len(polynomial.term_matrix) ==", "degree = polynomial.term_matrix[1][1] if degree == 1: if len(polynomial.term_matrix) ==", "== 1: return polynomial.term_matrix[1][0] elif len(polynomial.term_matrix[0]) == 2: degree =", "one variable, returns 'too many variables' looks for formula to", "a, b, c = polynomial.term_matrix[1][0], polynomial.term_matrix[2][0], 0 else: a, b,", "= polynomial.term_matrix[1][1] if degree == 1: if len(polynomial.term_matrix) == 2:", "new_roots while diff > .00000001 and not isclose(diff_temp, diff): iterate()", "range(len(roots)): q = 1 for j, root in enumerate(roots): if", "2: degree = polynomial.term_matrix[1][1] if degree == 1: if len(polynomial.term_matrix)", "= round(roots[i].real) roots[i] -= roots[i].real roots[i] += temp if isclose(roots[i].imag,", "ans1 == ans2: return ans1 return ans1, ans2 def isclose(a,", "= (-b - (b**2 - 4*a*c)**.5)/2*a if ans1 == ans2:", "i in range(len(roots)): diff += abs(roots[i] - new_roots[i]) roots =", "return (-c/a)**.5, -(-c/a)**.5 if len(polynomial.term_matrix) == 2: a, b, c,", "return ans1 return ans1, ans2 def isclose(a, b, rel_tol=1e-09, abs_tol=0.0001):", "(-b - (b**2 - 4*a*c)**.5)/2*a if ans1 == ans2: return", "roots = new_roots while diff > .00000001 and not isclose(diff_temp,", "diff = 1 diff_temp = 0 def iterate(): nonlocal roots", "a, b = polynomial.term_matrix[1][0], polynomial.term_matrix[2][0] return 0, -b/a a, c", "to apply to coefficients returns solution or 'I cannot solve", "roots[i].imag*1j roots[i] += temp*1j return roots if __name__ == '__main__':", "== 1: if len(polynomial.term_matrix) == 2: return 0 else: return", "apply to coefficients returns solution or 'I cannot solve yet...'", "+= abs(roots[i] - new_roots[i]) roots = new_roots while diff >", "ans if degree > 2: return Durand_Kerner(polynomial) def quadratic_formula(polynomial): \"\"\"", "single-variable polynomial of degree 2 returns zeros \"\"\" if len(polynomial.term_matrix)", "roots[i] - f(roots[i])/q nonlocal diff nonlocal diff_temp diff_temp = diff", "\"\"\" input polynomial returns numerical approximation of all complex roots", "more than one variable, returns 'too many variables' looks for", "round(roots[i].real) roots[i] -= roots[i].real roots[i] += temp if isclose(roots[i].imag, round(roots[i].imag)):", "for i in range(len(roots)): q = 1 for j, root", "degree 2 returns zeros \"\"\" if len(polynomial.term_matrix) == 3: if", "polynomial.term_matrix[2][0], polynomial.term_matrix[3][0] ans1 = (-b + (b**2 - 4*a*c)**.5)/2*a ans2", "b = polynomial.term_matrix[1][0], polynomial.term_matrix[2][0] return 0, -b/a a, c =", "1: a, b = polynomial.term_matrix[1][0], polynomial.term_matrix[2][0] return 0, -b/a a,", "- 4*a*c)**.5)/2*a if ans1 == ans2: return ans1 return ans1,", "polynomial if more than one variable, returns 'too many variables'", "0 else: a, b, c = polynomial.term_matrix[1][0], polynomial.term_matrix[2][0], polynomial.term_matrix[3][0] ans1", "i: q *= roots[i] - root new_roots[i] = roots[i] -", "1: if len(polynomial.term_matrix) == 2: return 0 else: return -polynomial.term_matrix[2][0]/polynomial.term_matrix[1][0]", "i in range(len(roots)): q = 1 for j, root in", "ans2 = (-b - (b**2 - 4*a*c)**.5)/2*a if ans1 ==", "3: if polynomial.term_matrix[2][1] == 1: a, b = polynomial.term_matrix[1][0], polynomial.term_matrix[2][0]", "\"\"\" roots = [] for i in range(f.degree()): roots.append((0.4 +", "diff diff = 0 for i in range(len(roots)): diff +=", "len(polynomial.term_matrix) == 2: a, b, c, = polynomial.term_matrix[1][0], 0, 0", "cannot solve yet...' \"\"\" if len(polynomial.term_matrix[0]) > 2: return 'too", "temp if isclose(roots[i].imag, round(roots[i].imag)): temp = round(roots[i].imag) roots[i] -= roots[i].imag*1j", "returns solution or 'I cannot solve yet...' \"\"\" if len(polynomial.term_matrix[0])", "if degree > 2: return Durand_Kerner(polynomial) def quadratic_formula(polynomial): \"\"\" input", "+ 0.9j)**i) diff = 1 diff_temp = 0 def iterate():", "= polynomial.term_matrix[1][0], polynomial.term_matrix[2][0] return (-c/a)**.5, -(-c/a)**.5 if len(polynomial.term_matrix) == 2:", "= polynomial.term_matrix[1][0], polynomial.term_matrix[2][0] return 0, -b/a a, c = polynomial.term_matrix[1][0],", "(b**2 - 4*a*c)**.5)/2*a if ans1 == ans2: return ans1 return", "in range(len(roots)): q = 1 for j, root in enumerate(roots):", "max(rel_tol * max(abs(a), abs(b)), abs_tol) def Durand_Kerner(f): \"\"\" input polynomial", "new_roots[i]) roots = new_roots while diff > .00000001 and not", "iterate() for i in range(len(roots)): if isclose(roots[i].real, round(roots[i].real)): temp =", "diff): iterate() for i in range(len(roots)): if isclose(roots[i].real, round(roots[i].real)): temp", "polynomial.term_matrix[1][1] if degree == 1: if len(polynomial.term_matrix) == 2: return", "is polynomial if more than one variable, returns 'too many", "== 3: if polynomial.term_matrix[2][1] == 1: a, b = polynomial.term_matrix[1][0],", "- root new_roots[i] = roots[i] - f(roots[i])/q nonlocal diff nonlocal", "nonlocal roots new_roots = roots[:] for i in range(len(roots)): q", "0 for i in range(len(roots)): diff += abs(roots[i] - new_roots[i])", "is less than abs_total or rel_total*max(a, b) \"\"\" return abs(a-b)", "= 0 def iterate(): nonlocal roots new_roots = roots[:] for", "ans2 def isclose(a, b, rel_tol=1e-09, abs_tol=0.0001): \"\"\" returns boolean whether", "while diff > .00000001 and not isclose(diff_temp, diff): iterate() for", "-polynomial.term_matrix[2][0]/polynomial.term_matrix[1][0] if degree == 2: ans = quadratic_formula(polynomial) return ans", "input polynomial returns numerical approximation of all complex roots \"\"\"", "degree == 1: if len(polynomial.term_matrix) == 2: return 0 else:", "polynomial.term_matrix[1][0], polynomial.term_matrix[2][0] return 0, -b/a a, c = polynomial.term_matrix[1][0], polynomial.term_matrix[2][0]", "== 1: a, b = polynomial.term_matrix[1][0], polynomial.term_matrix[2][0] return 0, -b/a", "= polynomial.term_matrix[1][0], 0, 0 elif len(polynomial.term_matrix) == 3: a, b,", "j != i: q *= roots[i] - root new_roots[i] =", "polynomial.term_matrix[1][0] elif len(polynomial.term_matrix[0]) == 2: degree = polynomial.term_matrix[1][1] if degree", "* max(abs(a), abs(b)), abs_tol) def Durand_Kerner(f): \"\"\" input polynomial returns", "roots[i] -= roots[i].real roots[i] += temp if isclose(roots[i].imag, round(roots[i].imag)): temp", "elif len(polynomial.term_matrix) == 3: a, b, c = polynomial.term_matrix[1][0], polynomial.term_matrix[2][0],", "in range(f.degree()): roots.append((0.4 + 0.9j)**i) diff = 1 diff_temp =", "- new_roots[i]) roots = new_roots while diff > .00000001 and", "if j != i: q *= roots[i] - root new_roots[i]", "len(polynomial.term_matrix[0]) == 2: degree = polynomial.term_matrix[1][1] if degree == 1:", "roots[i] += temp if isclose(roots[i].imag, round(roots[i].imag)): temp = round(roots[i].imag) roots[i]", "or 'I cannot solve yet...' \"\"\" if len(polynomial.term_matrix[0]) > 2:", "approximation of all complex roots \"\"\" roots = [] for", "if degree == 1: if len(polynomial.term_matrix) == 2: return 0", "c, = polynomial.term_matrix[1][0], 0, 0 elif len(polynomial.term_matrix) == 3: a,", "roots.append((0.4 + 0.9j)**i) diff = 1 diff_temp = 0 def", "i in range(len(roots)): if isclose(roots[i].real, round(roots[i].real)): temp = round(roots[i].real) roots[i]", "= roots[:] for i in range(len(roots)): q = 1 for", "def solve(polynomial): \"\"\" input is polynomial if more than one", "if len(polynomial.term_matrix[0]) > 2: return 'too many variables' elif len(polynomial.term_matrix[0])", "(-c/a)**.5, -(-c/a)**.5 if len(polynomial.term_matrix) == 2: a, b, c, =", "variable, returns 'too many variables' looks for formula to apply", "= (-b + (b**2 - 4*a*c)**.5)/2*a ans2 = (-b -", "= polynomial.term_matrix[1][0], polynomial.term_matrix[2][0], polynomial.term_matrix[3][0] ans1 = (-b + (b**2 -", "return abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol) def Durand_Kerner(f):", "nonlocal diff nonlocal diff_temp diff_temp = diff diff = 0", "diff = 0 for i in range(len(roots)): diff += abs(roots[i]", "returns zeros \"\"\" if len(polynomial.term_matrix) == 3: if polynomial.term_matrix[2][1] ==", "return Durand_Kerner(polynomial) def quadratic_formula(polynomial): \"\"\" input is single-variable polynomial of", "-= roots[i].imag*1j roots[i] += temp*1j return roots if __name__ ==", "> 2: return 'too many variables' elif len(polynomial.term_matrix[0]) == 1:", "else: return -polynomial.term_matrix[2][0]/polynomial.term_matrix[1][0] if degree == 2: ans = quadratic_formula(polynomial)", "ans1 = (-b + (b**2 - 4*a*c)**.5)/2*a ans2 = (-b", "c = polynomial.term_matrix[1][0], polynomial.term_matrix[2][0], polynomial.term_matrix[3][0] ans1 = (-b + (b**2", "complex roots \"\"\" roots = [] for i in range(f.degree()):", "2: return 0 else: return -polynomial.term_matrix[2][0]/polynomial.term_matrix[1][0] if degree == 2:", "def isclose(a, b, rel_tol=1e-09, abs_tol=0.0001): \"\"\" returns boolean whether abs(a-b)", "+ (b**2 - 4*a*c)**.5)/2*a ans2 = (-b - (b**2 -", "root in enumerate(roots): if j != i: q *= roots[i]", "if more than one variable, returns 'too many variables' looks", "isclose(a, b, rel_tol=1e-09, abs_tol=0.0001): \"\"\" returns boolean whether abs(a-b) is", "round(roots[i].imag) roots[i] -= roots[i].imag*1j roots[i] += temp*1j return roots if", "polynomial.term_matrix[2][0] return (-c/a)**.5, -(-c/a)**.5 if len(polynomial.term_matrix) == 2: a, b,", "len(polynomial.term_matrix) == 3: a, b, c = polynomial.term_matrix[1][0], polynomial.term_matrix[2][0], 0", "c = polynomial.term_matrix[1][0], polynomial.term_matrix[2][0], 0 else: a, b, c =", "new_roots = roots[:] for i in range(len(roots)): q = 1", "-= roots[i].real roots[i] += temp if isclose(roots[i].imag, round(roots[i].imag)): temp =", "in range(len(roots)): diff += abs(roots[i] - new_roots[i]) roots = new_roots", "4*a*c)**.5)/2*a if ans1 == ans2: return ans1 return ans1, ans2", "b, c, = polynomial.term_matrix[1][0], 0, 0 elif len(polynomial.term_matrix) == 3:", "diff_temp diff_temp = diff diff = 0 for i in", "return -polynomial.term_matrix[2][0]/polynomial.term_matrix[1][0] if degree == 2: ans = quadratic_formula(polynomial) return", "0, -b/a a, c = polynomial.term_matrix[1][0], polynomial.term_matrix[2][0] return (-c/a)**.5, -(-c/a)**.5", "== 2: return 0 else: return -polynomial.term_matrix[2][0]/polynomial.term_matrix[1][0] if degree ==", "returns boolean whether abs(a-b) is less than abs_total or rel_total*max(a,", "return ans1, ans2 def isclose(a, b, rel_tol=1e-09, abs_tol=0.0001): \"\"\" returns", "\"\"\" if len(polynomial.term_matrix[0]) > 2: return 'too many variables' elif", "for i in range(f.degree()): roots.append((0.4 + 0.9j)**i) diff = 1", "all complex roots \"\"\" roots = [] for i in", "> 2: return Durand_Kerner(polynomial) def quadratic_formula(polynomial): \"\"\" input is single-variable", "abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol) def Durand_Kerner(f): \"\"\"", "'too many variables' looks for formula to apply to coefficients", "len(polynomial.term_matrix) == 3: if polynomial.term_matrix[2][1] == 1: a, b =", "formula to apply to coefficients returns solution or 'I cannot", "\"\"\" input is polynomial if more than one variable, returns", "roots = [] for i in range(f.degree()): roots.append((0.4 + 0.9j)**i)", "== 3: a, b, c = polynomial.term_matrix[1][0], polynomial.term_matrix[2][0], 0 else:", "return 'too many variables' elif len(polynomial.term_matrix[0]) == 1: return polynomial.term_matrix[1][0]", "0 elif len(polynomial.term_matrix) == 3: a, b, c = polynomial.term_matrix[1][0],", "roots[i].real roots[i] += temp if isclose(roots[i].imag, round(roots[i].imag)): temp = round(roots[i].imag)", "return 0, -b/a a, c = polynomial.term_matrix[1][0], polynomial.term_matrix[2][0] return (-c/a)**.5,", "1 for j, root in enumerate(roots): if j != i:", "else: a, b, c = polynomial.term_matrix[1][0], polynomial.term_matrix[2][0], polynomial.term_matrix[3][0] ans1 =", "-(-c/a)**.5 if len(polynomial.term_matrix) == 2: a, b, c, = polynomial.term_matrix[1][0],", "1: return polynomial.term_matrix[1][0] elif len(polynomial.term_matrix[0]) == 2: degree = polynomial.term_matrix[1][1]", "isclose(roots[i].imag, round(roots[i].imag)): temp = round(roots[i].imag) roots[i] -= roots[i].imag*1j roots[i] +=", "return 0 else: return -polynomial.term_matrix[2][0]/polynomial.term_matrix[1][0] if degree == 2: ans", "returns 'too many variables' looks for formula to apply to", "abs_total or rel_total*max(a, b) \"\"\" return abs(a-b) <= max(rel_tol *", "if isclose(roots[i].real, round(roots[i].real)): temp = round(roots[i].real) roots[i] -= roots[i].real roots[i]", "polynomial.term_matrix[1][0], polynomial.term_matrix[2][0], 0 else: a, b, c = polynomial.term_matrix[1][0], polynomial.term_matrix[2][0],", "0 else: return -polynomial.term_matrix[2][0]/polynomial.term_matrix[1][0] if degree == 2: ans =", "iterate(): nonlocal roots new_roots = roots[:] for i in range(len(roots)):", "len(polynomial.term_matrix[0]) > 2: return 'too many variables' elif len(polynomial.term_matrix[0]) ==", "0, 0 elif len(polynomial.term_matrix) == 3: a, b, c =", "1 diff_temp = 0 def iterate(): nonlocal roots new_roots =", "solution or 'I cannot solve yet...' \"\"\" if len(polynomial.term_matrix[0]) >", "yet...' \"\"\" if len(polynomial.term_matrix[0]) > 2: return 'too many variables'", "variables' elif len(polynomial.term_matrix[0]) == 1: return polynomial.term_matrix[1][0] elif len(polynomial.term_matrix[0]) ==", "roots[i] += temp*1j return roots if __name__ == '__main__': pass", "== ans2: return ans1 return ans1, ans2 def isclose(a, b,", "= 1 diff_temp = 0 def iterate(): nonlocal roots new_roots", "== 2: ans = quadratic_formula(polynomial) return ans if degree >", "def iterate(): nonlocal roots new_roots = roots[:] for i in", "2: return 'too many variables' elif len(polynomial.term_matrix[0]) == 1: return", "4*a*c)**.5)/2*a ans2 = (-b - (b**2 - 4*a*c)**.5)/2*a if ans1", "= round(roots[i].imag) roots[i] -= roots[i].imag*1j roots[i] += temp*1j return roots", "3: a, b, c = polynomial.term_matrix[1][0], polynomial.term_matrix[2][0], 0 else: a,", "== 2: degree = polynomial.term_matrix[1][1] if degree == 1: if", "(-b + (b**2 - 4*a*c)**.5)/2*a ans2 = (-b - (b**2", "if polynomial.term_matrix[2][1] == 1: a, b = polynomial.term_matrix[1][0], polynomial.term_matrix[2][0] return", "len(polynomial.term_matrix[0]) == 1: return polynomial.term_matrix[1][0] elif len(polynomial.term_matrix[0]) == 2: degree", "ans = quadratic_formula(polynomial) return ans if degree > 2: return", "diff nonlocal diff_temp diff_temp = diff diff = 0 for", "less than abs_total or rel_total*max(a, b) \"\"\" return abs(a-b) <=", "and not isclose(diff_temp, diff): iterate() for i in range(len(roots)): if", "i in range(f.degree()): roots.append((0.4 + 0.9j)**i) diff = 1 diff_temp", "abs_tol=0.0001): \"\"\" returns boolean whether abs(a-b) is less than abs_total", "= roots[i] - f(roots[i])/q nonlocal diff nonlocal diff_temp diff_temp =", "b, c = polynomial.term_matrix[1][0], polynomial.term_matrix[2][0], polynomial.term_matrix[3][0] ans1 = (-b +", "polynomial.term_matrix[1][0], polynomial.term_matrix[2][0] return (-c/a)**.5, -(-c/a)**.5 if len(polynomial.term_matrix) == 2: a,", "- f(roots[i])/q nonlocal diff nonlocal diff_temp diff_temp = diff diff", "def quadratic_formula(polynomial): \"\"\" input is single-variable polynomial of degree 2", "= new_roots while diff > .00000001 and not isclose(diff_temp, diff):", "polynomial.term_matrix[1][0], 0, 0 elif len(polynomial.term_matrix) == 3: a, b, c", "looks for formula to apply to coefficients returns solution or", "q *= roots[i] - root new_roots[i] = roots[i] - f(roots[i])/q", "ans1, ans2 def isclose(a, b, rel_tol=1e-09, abs_tol=0.0001): \"\"\" returns boolean", "elif len(polynomial.term_matrix[0]) == 1: return polynomial.term_matrix[1][0] elif len(polynomial.term_matrix[0]) == 2:", "if isclose(roots[i].imag, round(roots[i].imag)): temp = round(roots[i].imag) roots[i] -= roots[i].imag*1j roots[i]", "round(roots[i].imag)): temp = round(roots[i].imag) roots[i] -= roots[i].imag*1j roots[i] += temp*1j", "diff > .00000001 and not isclose(diff_temp, diff): iterate() for i", "new_roots[i] = roots[i] - f(roots[i])/q nonlocal diff nonlocal diff_temp diff_temp", "\"\"\" input is single-variable polynomial of degree 2 returns zeros", "many variables' looks for formula to apply to coefficients returns", "for j, root in enumerate(roots): if j != i: q", "quadratic_formula(polynomial): \"\"\" input is single-variable polynomial of degree 2 returns", "2: ans = quadratic_formula(polynomial) return ans if degree > 2:", "nonlocal diff_temp diff_temp = diff diff = 0 for i", "polynomial returns numerical approximation of all complex roots \"\"\" roots", "not isclose(diff_temp, diff): iterate() for i in range(len(roots)): if isclose(roots[i].real,", "in range(len(roots)): if isclose(roots[i].real, round(roots[i].real)): temp = round(roots[i].real) roots[i] -=", "isclose(diff_temp, diff): iterate() for i in range(len(roots)): if isclose(roots[i].real, round(roots[i].real)):", "\"\"\" returns boolean whether abs(a-b) is less than abs_total or", ".00000001 and not isclose(diff_temp, diff): iterate() for i in range(len(roots)):", "roots \"\"\" roots = [] for i in range(f.degree()): roots.append((0.4", "abs(roots[i] - new_roots[i]) roots = new_roots while diff > .00000001", "range(len(roots)): diff += abs(roots[i] - new_roots[i]) roots = new_roots while", "returns numerical approximation of all complex roots \"\"\" roots =", "rel_total*max(a, b) \"\"\" return abs(a-b) <= max(rel_tol * max(abs(a), abs(b)),", "abs_tol) def Durand_Kerner(f): \"\"\" input polynomial returns numerical approximation of", "roots[i] -= roots[i].imag*1j roots[i] += temp*1j return roots if __name__", "Durand_Kerner(f): \"\"\" input polynomial returns numerical approximation of all complex", "solve(polynomial): \"\"\" input is polynomial if more than one variable,", "enumerate(roots): if j != i: q *= roots[i] - root", "j, root in enumerate(roots): if j != i: q *=", "range(f.degree()): roots.append((0.4 + 0.9j)**i) diff = 1 diff_temp = 0", "isclose(roots[i].real, round(roots[i].real)): temp = round(roots[i].real) roots[i] -= roots[i].real roots[i] +=", "2: return Durand_Kerner(polynomial) def quadratic_formula(polynomial): \"\"\" input is single-variable polynomial", "diff_temp = diff diff = 0 for i in range(len(roots)):", "quadratic_formula(polynomial) return ans if degree > 2: return Durand_Kerner(polynomial) def", "= 1 for j, root in enumerate(roots): if j !=", "ans1 return ans1, ans2 def isclose(a, b, rel_tol=1e-09, abs_tol=0.0001): \"\"\"", "for formula to apply to coefficients returns solution or 'I", "solve yet...' \"\"\" if len(polynomial.term_matrix[0]) > 2: return 'too many", "(b**2 - 4*a*c)**.5)/2*a ans2 = (-b - (b**2 - 4*a*c)**.5)/2*a", "if degree == 2: ans = quadratic_formula(polynomial) return ans if", "== 2: a, b, c, = polynomial.term_matrix[1][0], 0, 0 elif", "for i in range(len(roots)): if isclose(roots[i].real, round(roots[i].real)): temp = round(roots[i].real)", "return polynomial.term_matrix[1][0] elif len(polynomial.term_matrix[0]) == 2: degree = polynomial.term_matrix[1][1] if", "-b/a a, c = polynomial.term_matrix[1][0], polynomial.term_matrix[2][0] return (-c/a)**.5, -(-c/a)**.5 if", "0 def iterate(): nonlocal roots new_roots = roots[:] for i", "a, b, c, = polynomial.term_matrix[1][0], 0, 0 elif len(polynomial.term_matrix) ==", "range(len(roots)): if isclose(roots[i].real, round(roots[i].real)): temp = round(roots[i].real) roots[i] -= roots[i].real", "abs(a-b) is less than abs_total or rel_total*max(a, b) \"\"\" return", "> .00000001 and not isclose(diff_temp, diff): iterate() for i in", "def Durand_Kerner(f): \"\"\" input polynomial returns numerical approximation of all", "or rel_total*max(a, b) \"\"\" return abs(a-b) <= max(rel_tol * max(abs(a),", "polynomial.term_matrix[1][0], polynomial.term_matrix[2][0], polynomial.term_matrix[3][0] ans1 = (-b + (b**2 - 4*a*c)**.5)/2*a", "\"\"\" if len(polynomial.term_matrix) == 3: if polynomial.term_matrix[2][1] == 1: a,", "input is single-variable polynomial of degree 2 returns zeros \"\"\"", "max(abs(a), abs(b)), abs_tol) def Durand_Kerner(f): \"\"\" input polynomial returns numerical", "if len(polynomial.term_matrix) == 2: a, b, c, = polynomial.term_matrix[1][0], 0,", "+= temp if isclose(roots[i].imag, round(roots[i].imag)): temp = round(roots[i].imag) roots[i] -=", "in enumerate(roots): if j != i: q *= roots[i] -", "coefficients returns solution or 'I cannot solve yet...' \"\"\" if", "root new_roots[i] = roots[i] - f(roots[i])/q nonlocal diff nonlocal diff_temp", "b, c = polynomial.term_matrix[1][0], polynomial.term_matrix[2][0], 0 else: a, b, c", "len(polynomial.term_matrix) == 2: return 0 else: return -polynomial.term_matrix[2][0]/polynomial.term_matrix[1][0] if degree" ]
[ "style_spec in style_specs.split(\";\"): try: key, value = style_spec.split(\":\") except ValueError", "arguments. Parameters ---------- element : :class:`MinidomElement` Element of the SVG", "element attributes (fill, stroke, etc) Returns ------- :class:`dict` Style attributes,", "fill color, if it exists. manim_style[\"stroke_width\"] = 0 if \"fill_color\"", "The default styling specifications for SVG images, # according to", "= float(svg_style[\"stroke-opacity\"]) # nones need to be handled specially if", "of the SVG parse tree inherited : :class:`dict` Dictionary of", "Parameters ---------- element : :class:`MinidomElement` Element of the SVG parse", "functions for parsing SVG styles.\"\"\" __all__ = [\"cascade_element_style\", \"parse_style\", \"parse_color_string\"]", "in svg_style: svg_style[key] = SVG_DEFAULT_ATTRIBUTES[key] def parse_style(svg_style: Dict[str, str]) ->", "Returns ------- :class:`str` Hexadecimal color string in the format `#rrggbb`", "def cascade_element_style( element: MinidomElement, inherited: Dict[str, str] ) -> Dict[str,", "stray semicolon at the end, producing an emptystring pass else:", "import Element as MinidomElement from colour import web2hex from ...utils.color", "the regular elements. for attr in CASCADING_STYLING_ATTRIBUTES: entry = element.getAttribute(attr)", "\"fill-opacity\", \"stroke-opacity\", ] # The default styling specifications for SVG", "\"stroke-opacity\", ] # The default styling specifications for SVG images,", "Note that this method only copies the values and does", "according to https://www.w3.org/TR/SVG/painting.html # (ctrl-F for \"initial\") SVG_DEFAULT_ATTRIBUTES: Dict[str, str]", "if \"fill-opacity\" in svg_style: manim_style[\"fill_opacity\"] = float(svg_style[\"fill-opacity\"]) if \"stroke-opacity\" in", "distant ancestor's style. In order to correctly calculate the styles,", "to not break animations.creation.Write, # we interpret no stroke as", "copies the values and does not parse them. See :meth:`parse_color_string`", "element. Returns ------- :class:`dict` Dictionary mapping svg attributes to values", "color the same as the fill color, if it exists.", "to convert color names like \"red\" to hex color hex_color", "\"none\", \"stroke-opacity\": \"1\", } def cascade_element_style( element: MinidomElement, inherited: Dict[str,", "in the style dictionary. Parameters ---------- svg_style : :class:`dict` Style", "\"fill-opacity\": \"1\", \"stroke\": \"none\", \"stroke-opacity\": \"1\", } def cascade_element_style( element:", "else: # attempt to convert color names like \"red\" to", "[int(i) / 255.0 for i in splits] hex_color = rgb_to_hex(parsed_rgbs)", "dictionary of SVG attributes to Manim VMobject keyword arguments. Parameters", "missing. \"\"\" for key in SVG_DEFAULT_ATTRIBUTES: if key not in", "Parameters ---------- svg_style : :class:`dict` Style dictionary with SVG property", "Dict[str, str] = { \"fill\": \"black\", \"fill-opacity\": \"1\", \"stroke\": \"none\",", "-> None: \"\"\" Fill in the default values for properties", "more distant ancestor's style. In order to correctly calculate the", ":class:`dict` Dictionary of SVG attributes inherited from the parent element.", "/ 255.0 for i in splits] hex_color = rgb_to_hex(parsed_rgbs) elif", "in manim kwargs form, e.g., keys are fill_color, stroke_color \"\"\"", "hex_color = web2hex(color_spec, force_long=True) return hex_color def fill_default_values(svg_style: Dict) ->", "dictionary. Parameters ---------- svg_style : :class:`dict` Style dictionary with SVG", "inherited : :class:`dict` Dictionary of SVG attributes inherited from the", "in manim_style: manim_style[\"stroke_color\"] = manim_style[\"fill_color\"] else: manim_style[\"stroke_color\"] = parse_color_string(svg_style[\"stroke\"]) return", "the default values for properties of SVG elements, if they", "0 if \"fill_color\" in manim_style: manim_style[\"stroke_color\"] = manim_style[\"fill_color\"] else: manim_style[\"stroke_color\"]", "currently set in the style dictionary. Parameters ---------- svg_style :", ":class:`dict` Style attributes; none are missing. \"\"\" for key in", "= rgb_to_hex(parsed_rgbs) elif color_spec[0] == \"#\": # its OK, parse", "in SVG_DEFAULT_ATTRIBUTES: if key not in svg_style: svg_style[key] = SVG_DEFAULT_ATTRIBUTES[key]", "from the parent element. Returns ------- :class:`dict` Dictionary mapping svg", "...utils.color import rgb_to_hex from typing import Dict, List CASCADING_STYLING_ATTRIBUTES: List[str]", "in splits] else: parsed_rgbs = [int(i) / 255.0 for i", "color hex_color = web2hex(color_spec, force_long=True) return hex_color def fill_default_values(svg_style: Dict)", "Style dictionary with SVG property names. Some may be missing.", "In order to correctly calculate the styles, the attributes are", "\"fill-opacity\" in svg_style: manim_style[\"fill_opacity\"] = float(svg_style[\"fill-opacity\"]) if \"stroke-opacity\" in svg_style:", ":class:`dict` Style dictionary with SVG property names. Some may be", "svg_style: manim_style[\"fill_opacity\"] = float(svg_style[\"fill-opacity\"]) if \"stroke-opacity\" in svg_style: manim_style[\"stroke_opacity\"] =", "styles, the attributes are passed down through the inheritance tree,", "they are not currently set in the style dictionary. Parameters", "\"none\": # In order to not break animations.creation.Write, # we", "if \"fill\" in svg_style: if svg_style[\"fill\"] == \"none\": manim_style[\"fill_opacity\"] =", "stroke as stroke-width of zero and # color the same", "# there was just a stray semicolon at the end,", "svg_style: if svg_style[\"stroke\"] == \"none\": # In order to not", "percentage parsed_rgbs = [float(i[:-1]) / 100.0 for i in splits]", "are fill_color, stroke_color \"\"\" manim_style = {} fill_default_values(svg_style) if \"fill-opacity\"", "key in SVG_DEFAULT_ATTRIBUTES: if key not in svg_style: svg_style[key] =", "manim_style[\"fill_color\"] = parse_color_string(svg_style[\"fill\"]) if \"stroke\" in svg_style: if svg_style[\"stroke\"] ==", "\"\"\"Collect the element's style attributes based upon both its inheritance", "Element of the SVG parse tree inherited : :class:`dict` Dictionary", "number as a percentage parsed_rgbs = [float(i[:-1]) / 100.0 for", "entry # the style attribute should be handled separately in", "same element. style_specs = element.getAttribute(\"style\") if style_specs: for style_spec in", "element. style_specs = element.getAttribute(\"style\") if style_specs: for style_spec in style_specs.split(\";\"):", "# break it up nicely. furthermore, style takes priority over", "Hexadecimal color string in the format `#rrggbb` \"\"\" if color_spec[0:3]", ": :class:`dict` Style attributes as a string-to-string dictionary. Keys are", "style takes precedence over a more distant ancestor's style. In", "attributes to manim keyword arguments. Parameters ---------- element : :class:`MinidomElement`", ": :class:`dict` Dictionary of SVG attributes inherited from the parent", "-> Dict: \"\"\"Convert a dictionary of SVG attributes to Manim", "the values and does not parse them. See :meth:`parse_color_string` for", "closer ancestor's style takes precedence over a more distant ancestor's", "elements. for attr in CASCADING_STYLING_ATTRIBUTES: entry = element.getAttribute(attr) if entry:", "style_specs: for style_spec in style_specs.split(\";\"): try: key, value = style_spec.split(\":\")", "updating where necessary. Note that this method only copies the", "hex color standard. hex_color = color_spec else: # attempt to", "the attributes are passed down through the inheritance tree, updating", "svg_style: manim_style[\"stroke_opacity\"] = float(svg_style[\"stroke-opacity\"]) # nones need to be handled", "for style_spec in style_specs.split(\";\"): try: key, value = style_spec.split(\":\") except", "are missing. \"\"\" for key in SVG_DEFAULT_ATTRIBUTES: if key not", "from xml.dom.minidom import Element as MinidomElement from colour import web2hex", "e else: style[key.strip()] = value.strip() return style def parse_color_string(color_spec: str)", "like \"red\" to hex color hex_color = web2hex(color_spec, force_long=True) return", "= [\"cascade_element_style\", \"parse_style\", \"parse_color_string\"] from xml.dom.minidom import Element as MinidomElement", "the first number is a percentage, # then interpret the", "from ...utils.color import rgb_to_hex from typing import Dict, List CASCADING_STYLING_ATTRIBUTES:", "be handled separately in order to # break it up", "SVG element attributes (fill, stroke, etc) Returns ------- :class:`dict` Style", "See :meth:`parse_color_string` for converting from SVG attributes to manim keyword", "= element.getAttribute(attr) if entry: style[attr] = entry # the style", "a percentage, # then interpret the number as a percentage", "# The default styling specifications for SVG images, # according", "# (ctrl-F for \"initial\") SVG_DEFAULT_ATTRIBUTES: Dict[str, str] = { \"fill\":", "to https://www.w3.org/TR/SVG/painting.html # (ctrl-F for \"initial\") SVG_DEFAULT_ATTRIBUTES: Dict[str, str] =", "= float(svg_style[\"fill-opacity\"]) if \"stroke-opacity\" in svg_style: manim_style[\"stroke_opacity\"] = float(svg_style[\"stroke-opacity\"]) #", "Returns ------- :class:`dict` Dictionary mapping svg attributes to values with", "SVG attributes to Manim VMobject keyword arguments. Parameters ---------- svg_style", "xml.dom.minidom import Element as MinidomElement from colour import web2hex from", "both its inheritance and its own attributes. SVG uses cascading", "else: parsed_rgbs = [int(i) / 255.0 for i in splits]", "this method only copies the values and does not parse", "a dictionary of SVG attributes to Manim VMobject keyword arguments.", "the same element. style_specs = element.getAttribute(\"style\") if style_specs: for style_spec", "MinidomElement, inherited: Dict[str, str] ) -> Dict[str, str]: \"\"\"Collect the", "the SVG parse tree inherited : :class:`dict` Dictionary of SVG", "dictionary with SVG property names. Some may be missing. Returns", "stroke, etc) Returns ------- :class:`dict` Style attributes, but in manim", "to correctly calculate the styles, the attributes are passed down", "converting from SVG attributes to manim keyword arguments. Parameters ----------", "and convert them to HTML #rrggbb format. Parameters ---------- color_spec", "default values for properties of SVG elements, if they are", "dictionary. Keys are valid SVG element attributes (fill, stroke, etc)", "= 0 else: manim_style[\"fill_color\"] = parse_color_string(svg_style[\"fill\"]) if \"stroke\" in svg_style:", "List[str] = [ \"fill\", \"stroke\", \"fill-opacity\", \"stroke-opacity\", ] # The", "A closer ancestor's style takes precedence over a more distant", "ValueError as e: if not style_spec.strip(): # there was just", "def parse_style(svg_style: Dict[str, str]) -> Dict: \"\"\"Convert a dictionary of", "\"stroke\" in svg_style: if svg_style[\"stroke\"] == \"none\": # In order", "svg_style: svg_style[key] = SVG_DEFAULT_ATTRIBUTES[key] def parse_style(svg_style: Dict[str, str]) -> Dict:", "with `element`'s values overriding inherited values. \"\"\" style = inherited.copy()", "the same as the fill color, if it exists. manim_style[\"stroke_width\"]", "float(svg_style[\"stroke-opacity\"]) # nones need to be handled specially if \"fill\"", "(fill, stroke, etc) Returns ------- :class:`dict` Style attributes, but in", "key not in svg_style: svg_style[key] = SVG_DEFAULT_ATTRIBUTES[key] def parse_style(svg_style: Dict[str,", "interpret the number as a percentage parsed_rgbs = [float(i[:-1]) /", "cascade the regular elements. for attr in CASCADING_STYLING_ATTRIBUTES: entry =", "def fill_default_values(svg_style: Dict) -> None: \"\"\" Fill in the default", "the inheritance tree, updating where necessary. Note that this method", "SVG attributes inherited from the parent element. Returns ------- :class:`dict`", "attributes to Manim VMobject keyword arguments. Parameters ---------- svg_style :", "color_spec : :class:`str` String in any web-compatible format Returns -------", "floats. splits = color_spec[4:-1].split(\",\") if splits[0][-1] == \"%\": # if", "inheritance and its own attributes. SVG uses cascading element styles.", "zero and # color the same as the fill color,", "attributes as a string-to-string dictionary. Keys are valid SVG element", "in CASCADING_STYLING_ATTRIBUTES: entry = element.getAttribute(attr) if entry: style[attr] = entry", "not style_spec.strip(): # there was just a stray semicolon at", "of SVG attributes to Manim VMobject keyword arguments. Parameters ----------", "style[attr] = entry # the style attribute should be handled", "string-to-string dictionary. Keys are valid SVG element attributes (fill, stroke,", "style. In order to correctly calculate the styles, the attributes", "are only in integer form, but the Colour module wants", "overriding inherited values. \"\"\" style = inherited.copy() # cascade the", "\"stroke-opacity\": \"1\", } def cascade_element_style( element: MinidomElement, inherited: Dict[str, str]", "(ctrl-F for \"initial\") SVG_DEFAULT_ATTRIBUTES: Dict[str, str] = { \"fill\": \"black\",", "the format `#rrggbb` \"\"\" if color_spec[0:3] == \"rgb\": # these", "color_spec[4:-1].split(\",\") if splits[0][-1] == \"%\": # if the last character", "up nicely. furthermore, style takes priority over other # attributes", "a more distant ancestor's style. In order to correctly calculate", "values overriding inherited values. \"\"\" style = inherited.copy() # cascade", "= { \"fill\": \"black\", \"fill-opacity\": \"1\", \"stroke\": \"none\", \"stroke-opacity\": \"1\",", "= 0 if \"fill_color\" in manim_style: manim_style[\"stroke_color\"] = manim_style[\"fill_color\"] else:", "# color the same as the fill color, if it", "from colour import web2hex from ...utils.color import rgb_to_hex from typing", "the end, producing an emptystring pass else: raise e else:", "`#rrggbb` \"\"\" if color_spec[0:3] == \"rgb\": # these are only", "images, # according to https://www.w3.org/TR/SVG/painting.html # (ctrl-F for \"initial\") SVG_DEFAULT_ATTRIBUTES:", "if style_specs: for style_spec in style_specs.split(\";\"): try: key, value =", "element.getAttribute(\"style\") if style_specs: for style_spec in style_specs.split(\";\"): try: key, value", "SVG_DEFAULT_ATTRIBUTES[key] def parse_style(svg_style: Dict[str, str]) -> Dict: \"\"\"Convert a dictionary", "names. Some may be missing. Returns ------- :class:`dict` Style attributes;", "its own attributes. SVG uses cascading element styles. A closer", "-> str: \"\"\"Handle the SVG-specific color strings and convert them", "\"%\": # if the last character of the first number", "== \"none\": manim_style[\"fill_opacity\"] = 0 else: manim_style[\"fill_color\"] = parse_color_string(svg_style[\"fill\"]) if", "[float(i[:-1]) / 100.0 for i in splits] else: parsed_rgbs =", "= SVG_DEFAULT_ATTRIBUTES[key] def parse_style(svg_style: Dict[str, str]) -> Dict: \"\"\"Convert a", "attributes based upon both its inheritance and its own attributes.", "# attributes in the same element. style_specs = element.getAttribute(\"style\") if", "key, value = style_spec.split(\":\") except ValueError as e: if not", "i in splits] hex_color = rgb_to_hex(parsed_rgbs) elif color_spec[0] == \"#\":", "color string in the format `#rrggbb` \"\"\" if color_spec[0:3] ==", "pass else: raise e else: style[key.strip()] = value.strip() return style", "them to HTML #rrggbb format. Parameters ---------- color_spec : :class:`str`", "Dict[str, str] ) -> Dict[str, str]: \"\"\"Collect the element's style", "SVG-specific color strings and convert them to HTML #rrggbb format.", "from typing import Dict, List CASCADING_STYLING_ATTRIBUTES: List[str] = [ \"fill\",", "Dict: \"\"\"Convert a dictionary of SVG attributes to Manim VMobject", "web2hex from ...utils.color import rgb_to_hex from typing import Dict, List", "not currently set in the style dictionary. Parameters ---------- svg_style", "`element`'s values overriding inherited values. \"\"\" style = inherited.copy() #", "return hex_color def fill_default_values(svg_style: Dict) -> None: \"\"\" Fill in", ") -> Dict[str, str]: \"\"\"Collect the element's style attributes based", "was just a stray semicolon at the end, producing an", "Some may be missing. Returns ------- :class:`dict` Style attributes; none", "as e: if not style_spec.strip(): # there was just a", "is a percentage, # then interpret the number as a", "svg_style[\"fill\"] == \"none\": manim_style[\"fill_opacity\"] = 0 else: manim_style[\"fill_color\"] = parse_color_string(svg_style[\"fill\"])", "styling specifications for SVG images, # according to https://www.w3.org/TR/SVG/painting.html #", "== \"rgb\": # these are only in integer form, but", "the last character of the first number is a percentage,", "Dictionary mapping svg attributes to values with `element`'s values overriding", "for parsing SVG styles.\"\"\" __all__ = [\"cascade_element_style\", \"parse_style\", \"parse_color_string\"] from", "SVG uses cascading element styles. A closer ancestor's style takes", "else: raise e else: style[key.strip()] = value.strip() return style def", "takes precedence over a more distant ancestor's style. In order", "style = inherited.copy() # cascade the regular elements. for attr", "it up nicely. furthermore, style takes priority over other #", "manim_style[\"stroke_width\"] = 0 if \"fill_color\" in manim_style: manim_style[\"stroke_color\"] = manim_style[\"fill_color\"]", "svg_style : :class:`dict` Style dictionary with SVG property names. Some", "and # color the same as the fill color, if", "style_spec.split(\":\") except ValueError as e: if not style_spec.strip(): # there", "necessary. Note that this method only copies the values and", "for attr in CASCADING_STYLING_ATTRIBUTES: entry = element.getAttribute(attr) if entry: style[attr]", "\"1\", \"stroke\": \"none\", \"stroke-opacity\": \"1\", } def cascade_element_style( element: MinidomElement,", "strings and convert them to HTML #rrggbb format. Parameters ----------", ":class:`dict` Style attributes as a string-to-string dictionary. Keys are valid", "colour import web2hex from ...utils.color import rgb_to_hex from typing import", "------- :class:`dict` Style attributes, but in manim kwargs form, e.g.,", "\"fill\", \"stroke\", \"fill-opacity\", \"stroke-opacity\", ] # The default styling specifications", "fill_color, stroke_color \"\"\" manim_style = {} fill_default_values(svg_style) if \"fill-opacity\" in", "manim_style = {} fill_default_values(svg_style) if \"fill-opacity\" in svg_style: manim_style[\"fill_opacity\"] =", "names like \"red\" to hex color hex_color = web2hex(color_spec, force_long=True)", "Dictionary of SVG attributes inherited from the parent element. Returns", "values and does not parse them. See :meth:`parse_color_string` for converting", "the parent element. Returns ------- :class:`dict` Dictionary mapping svg attributes", "# In order to not break animations.creation.Write, # we interpret", "parse tree inherited : :class:`dict` Dictionary of SVG attributes inherited", "its inheritance and its own attributes. SVG uses cascading element", "in style_specs.split(\";\"): try: key, value = style_spec.split(\":\") except ValueError as", "the Colour module wants them in floats. splits = color_spec[4:-1].split(\",\")", "furthermore, style takes priority over other # attributes in the", "= element.getAttribute(\"style\") if style_specs: for style_spec in style_specs.split(\";\"): try: key,", "not in svg_style: svg_style[key] = SVG_DEFAULT_ATTRIBUTES[key] def parse_style(svg_style: Dict[str, str])", "attribute should be handled separately in order to # break", "cascading element styles. A closer ancestor's style takes precedence over", "if color_spec[0:3] == \"rgb\": # these are only in integer", "fill_default_values(svg_style: Dict) -> None: \"\"\" Fill in the default values", ": :class:`str` String in any web-compatible format Returns ------- :class:`str`", "color standard. hex_color = color_spec else: # attempt to convert", "missing. Returns ------- :class:`dict` Style attributes; none are missing. \"\"\"", "handled specially if \"fill\" in svg_style: if svg_style[\"fill\"] == \"none\":", "Style attributes; none are missing. \"\"\" for key in SVG_DEFAULT_ATTRIBUTES:", "-> Dict[str, str]: \"\"\"Collect the element's style attributes based upon", ":meth:`parse_color_string` for converting from SVG attributes to manim keyword arguments.", "default styling specifications for SVG images, # according to https://www.w3.org/TR/SVG/painting.html", "in any web-compatible format Returns ------- :class:`str` Hexadecimal color string", "be missing. Returns ------- :class:`dict` Style attributes; none are missing.", "style attributes based upon both its inheritance and its own", "where necessary. Note that this method only copies the values", "in svg_style: if svg_style[\"fill\"] == \"none\": manim_style[\"fill_opacity\"] = 0 else:", "= parse_color_string(svg_style[\"fill\"]) if \"stroke\" in svg_style: if svg_style[\"stroke\"] == \"none\":", "are valid SVG element attributes (fill, stroke, etc) Returns -------", "to # break it up nicely. furthermore, style takes priority", "of SVG elements, if they are not currently set in", "manim_style[\"stroke_opacity\"] = float(svg_style[\"stroke-opacity\"]) # nones need to be handled specially", "elements, if they are not currently set in the style", "Dict) -> None: \"\"\" Fill in the default values for", "== \"%\": # if the last character of the first", "= value.strip() return style def parse_color_string(color_spec: str) -> str: \"\"\"Handle", "color, if it exists. manim_style[\"stroke_width\"] = 0 if \"fill_color\" in", "Element as MinidomElement from colour import web2hex from ...utils.color import", "these are only in integer form, but the Colour module", "hex_color = rgb_to_hex(parsed_rgbs) elif color_spec[0] == \"#\": # its OK,", "str]: \"\"\"Collect the element's style attributes based upon both its", "Colour module wants them in floats. splits = color_spec[4:-1].split(\",\") if", "# its OK, parse as hex color standard. hex_color =", "\"\"\" if color_spec[0:3] == \"rgb\": # these are only in", "e.g., keys are fill_color, stroke_color \"\"\" manim_style = {} fill_default_values(svg_style)", "SVG_DEFAULT_ATTRIBUTES: if key not in svg_style: svg_style[key] = SVG_DEFAULT_ATTRIBUTES[key] def", "to manim keyword arguments. Parameters ---------- element : :class:`MinidomElement` Element", "the SVG-specific color strings and convert them to HTML #rrggbb", "[\"cascade_element_style\", \"parse_style\", \"parse_color_string\"] from xml.dom.minidom import Element as MinidomElement from", "SVG images, # according to https://www.w3.org/TR/SVG/painting.html # (ctrl-F for \"initial\")", "priority over other # attributes in the same element. style_specs", ":class:`str` Hexadecimal color string in the format `#rrggbb` \"\"\" if", "if the last character of the first number is a", "SVG styles.\"\"\" __all__ = [\"cascade_element_style\", \"parse_style\", \"parse_color_string\"] from xml.dom.minidom import", "else: manim_style[\"fill_color\"] = parse_color_string(svg_style[\"fill\"]) if \"stroke\" in svg_style: if svg_style[\"stroke\"]", "its OK, parse as hex color standard. hex_color = color_spec", "__all__ = [\"cascade_element_style\", \"parse_style\", \"parse_color_string\"] from xml.dom.minidom import Element as", "the style dictionary. Parameters ---------- svg_style : :class:`dict` Style dictionary", "order to correctly calculate the styles, the attributes are passed", "str: \"\"\"Handle the SVG-specific color strings and convert them to", "Dict[str, str]: \"\"\"Collect the element's style attributes based upon both", "set in the style dictionary. Parameters ---------- svg_style : :class:`dict`", ":class:`MinidomElement` Element of the SVG parse tree inherited : :class:`dict`", "= inherited.copy() # cascade the regular elements. for attr in", "0 else: manim_style[\"fill_color\"] = parse_color_string(svg_style[\"fill\"]) if \"stroke\" in svg_style: if", "rgb_to_hex(parsed_rgbs) elif color_spec[0] == \"#\": # its OK, parse as", "only copies the values and does not parse them. See", "if entry: style[attr] = entry # the style attribute should", "attributes (fill, stroke, etc) Returns ------- :class:`dict` Style attributes, but", "attributes, but in manim kwargs form, e.g., keys are fill_color,", "if it exists. manim_style[\"stroke_width\"] = 0 if \"fill_color\" in manim_style:", "passed down through the inheritance tree, updating where necessary. Note", "color_spec[0:3] == \"rgb\": # these are only in integer form,", "value.strip() return style def parse_color_string(color_spec: str) -> str: \"\"\"Handle the", "Manim VMobject keyword arguments. Parameters ---------- svg_style : :class:`dict` Style", "cascade_element_style( element: MinidomElement, inherited: Dict[str, str] ) -> Dict[str, str]:", "style[key.strip()] = value.strip() return style def parse_color_string(color_spec: str) -> str:", "import Dict, List CASCADING_STYLING_ATTRIBUTES: List[str] = [ \"fill\", \"stroke\", \"fill-opacity\",", "\"initial\") SVG_DEFAULT_ATTRIBUTES: Dict[str, str] = { \"fill\": \"black\", \"fill-opacity\": \"1\",", "if not style_spec.strip(): # there was just a stray semicolon", "as stroke-width of zero and # color the same as", "[ \"fill\", \"stroke\", \"fill-opacity\", \"stroke-opacity\", ] # The default styling", "} def cascade_element_style( element: MinidomElement, inherited: Dict[str, str] ) ->", "str] ) -> Dict[str, str]: \"\"\"Collect the element's style attributes", "wants them in floats. splits = color_spec[4:-1].split(\",\") if splits[0][-1] ==", ": :class:`MinidomElement` Element of the SVG parse tree inherited :", "svg_style : :class:`dict` Style attributes as a string-to-string dictionary. Keys", "def parse_color_string(color_spec: str) -> str: \"\"\"Handle the SVG-specific color strings", "standard. hex_color = color_spec else: # attempt to convert color", "element: MinidomElement, inherited: Dict[str, str] ) -> Dict[str, str]: \"\"\"Collect", "regular elements. for attr in CASCADING_STYLING_ATTRIBUTES: entry = element.getAttribute(attr) if", "In order to not break animations.creation.Write, # we interpret no", "first number is a percentage, # then interpret the number", "kwargs form, e.g., keys are fill_color, stroke_color \"\"\" manim_style =", "parse as hex color standard. hex_color = color_spec else: #", "we interpret no stroke as stroke-width of zero and #", "= entry # the style attribute should be handled separately", "\"parse_style\", \"parse_color_string\"] from xml.dom.minidom import Element as MinidomElement from colour", "value = style_spec.split(\":\") except ValueError as e: if not style_spec.strip():", "same as the fill color, if it exists. manim_style[\"stroke_width\"] =", "in the format `#rrggbb` \"\"\" if color_spec[0:3] == \"rgb\": #", "for i in splits] else: parsed_rgbs = [int(i) / 255.0", "and its own attributes. SVG uses cascading element styles. A", "attributes inherited from the parent element. Returns ------- :class:`dict` Dictionary", "to HTML #rrggbb format. Parameters ---------- color_spec : :class:`str` String", "manim_style[\"fill_opacity\"] = 0 else: manim_style[\"fill_color\"] = parse_color_string(svg_style[\"fill\"]) if \"stroke\" in", "color names like \"red\" to hex color hex_color = web2hex(color_spec,", "calculate the styles, the attributes are passed down through the", "---------- svg_style : :class:`dict` Style attributes as a string-to-string dictionary.", "attributes. SVG uses cascading element styles. A closer ancestor's style", "= web2hex(color_spec, force_long=True) return hex_color def fill_default_values(svg_style: Dict) -> None:", "Style attributes as a string-to-string dictionary. Keys are valid SVG", "------- :class:`dict` Dictionary mapping svg attributes to values with `element`'s", ":class:`str` String in any web-compatible format Returns ------- :class:`str` Hexadecimal", "parsed_rgbs = [int(i) / 255.0 for i in splits] hex_color", "manim kwargs form, e.g., keys are fill_color, stroke_color \"\"\" manim_style", "---------- element : :class:`MinidomElement` Element of the SVG parse tree", "are passed down through the inheritance tree, updating where necessary.", "through the inheritance tree, updating where necessary. Note that this", "manim_style[\"fill_opacity\"] = float(svg_style[\"fill-opacity\"]) if \"stroke-opacity\" in svg_style: manim_style[\"stroke_opacity\"] = float(svg_style[\"stroke-opacity\"])", "of zero and # color the same as the fill", "if svg_style[\"fill\"] == \"none\": manim_style[\"fill_opacity\"] = 0 else: manim_style[\"fill_color\"] =", "it exists. manim_style[\"stroke_width\"] = 0 if \"fill_color\" in manim_style: manim_style[\"stroke_color\"]", "order to # break it up nicely. furthermore, style takes", "splits] else: parsed_rgbs = [int(i) / 255.0 for i in", "stroke-width of zero and # color the same as the", "float(svg_style[\"fill-opacity\"]) if \"stroke-opacity\" in svg_style: manim_style[\"stroke_opacity\"] = float(svg_style[\"stroke-opacity\"]) # nones", "https://www.w3.org/TR/SVG/painting.html # (ctrl-F for \"initial\") SVG_DEFAULT_ATTRIBUTES: Dict[str, str] = {", "svg_style[key] = SVG_DEFAULT_ATTRIBUTES[key] def parse_style(svg_style: Dict[str, str]) -> Dict: \"\"\"Convert", "parse_style(svg_style: Dict[str, str]) -> Dict: \"\"\"Convert a dictionary of SVG", "element styles. A closer ancestor's style takes precedence over a", "---------- svg_style : :class:`dict` Style dictionary with SVG property names.", "color_spec else: # attempt to convert color names like \"red\"", "from SVG attributes to manim keyword arguments. Parameters ---------- element", "splits = color_spec[4:-1].split(\",\") if splits[0][-1] == \"%\": # if the", "None: \"\"\" Fill in the default values for properties of", "String in any web-compatible format Returns ------- :class:`str` Hexadecimal color", "attempt to convert color names like \"red\" to hex color", "Fill in the default values for properties of SVG elements,", "str] = { \"fill\": \"black\", \"fill-opacity\": \"1\", \"stroke\": \"none\", \"stroke-opacity\":", "none are missing. \"\"\" for key in SVG_DEFAULT_ATTRIBUTES: if key", "ancestor's style takes precedence over a more distant ancestor's style.", "handled separately in order to # break it up nicely.", "str]) -> Dict: \"\"\"Convert a dictionary of SVG attributes to", "precedence over a more distant ancestor's style. In order to", "Returns ------- :class:`dict` Style attributes; none are missing. \"\"\" for", "= {} fill_default_values(svg_style) if \"fill-opacity\" in svg_style: manim_style[\"fill_opacity\"] = float(svg_style[\"fill-opacity\"])", "# nones need to be handled specially if \"fill\" in", "# attempt to convert color names like \"red\" to hex", "should be handled separately in order to # break it", "be handled specially if \"fill\" in svg_style: if svg_style[\"fill\"] ==", "Keys are valid SVG element attributes (fill, stroke, etc) Returns", "as the fill color, if it exists. manim_style[\"stroke_width\"] = 0", "in svg_style: manim_style[\"fill_opacity\"] = float(svg_style[\"fill-opacity\"]) if \"stroke-opacity\" in svg_style: manim_style[\"stroke_opacity\"]", "break animations.creation.Write, # we interpret no stroke as stroke-width of", "to be handled specially if \"fill\" in svg_style: if svg_style[\"fill\"]", "manim_style: manim_style[\"stroke_color\"] = manim_style[\"fill_color\"] else: manim_style[\"stroke_color\"] = parse_color_string(svg_style[\"stroke\"]) return manim_style", "uses cascading element styles. A closer ancestor's style takes precedence", "attributes; none are missing. \"\"\" for key in SVG_DEFAULT_ATTRIBUTES: if", "order to not break animations.creation.Write, # we interpret no stroke", "100.0 for i in splits] else: parsed_rgbs = [int(i) /", "import web2hex from ...utils.color import rgb_to_hex from typing import Dict,", "= color_spec else: # attempt to convert color names like", "if \"stroke\" in svg_style: if svg_style[\"stroke\"] == \"none\": # In", "try: key, value = style_spec.split(\":\") except ValueError as e: if", "in the same element. style_specs = element.getAttribute(\"style\") if style_specs: for", "parse_color_string(color_spec: str) -> str: \"\"\"Handle the SVG-specific color strings and", "\"stroke\": \"none\", \"stroke-opacity\": \"1\", } def cascade_element_style( element: MinidomElement, inherited:", "in svg_style: manim_style[\"stroke_opacity\"] = float(svg_style[\"stroke-opacity\"]) # nones need to be", "them. See :meth:`parse_color_string` for converting from SVG attributes to manim", "style takes priority over other # attributes in the same", "integer form, but the Colour module wants them in floats.", "to values with `element`'s values overriding inherited values. \"\"\" style", "CASCADING_STYLING_ATTRIBUTES: List[str] = [ \"fill\", \"stroke\", \"fill-opacity\", \"stroke-opacity\", ] #", "for SVG images, # according to https://www.w3.org/TR/SVG/painting.html # (ctrl-F for", "SVG elements, if they are not currently set in the", "the element's style attributes based upon both its inheritance and", "styles. A closer ancestor's style takes precedence over a more", "\"fill\": \"black\", \"fill-opacity\": \"1\", \"stroke\": \"none\", \"stroke-opacity\": \"1\", } def", "need to be handled specially if \"fill\" in svg_style: if", "# the style attribute should be handled separately in order", "animations.creation.Write, # we interpret no stroke as stroke-width of zero", "valid SVG element attributes (fill, stroke, etc) Returns ------- :class:`dict`", "\"parse_color_string\"] from xml.dom.minidom import Element as MinidomElement from colour import", "for key in SVG_DEFAULT_ATTRIBUTES: if key not in svg_style: svg_style[key]", "to Manim VMobject keyword arguments. Parameters ---------- svg_style : :class:`dict`", "\"\"\"Utility functions for parsing SVG styles.\"\"\" __all__ = [\"cascade_element_style\", \"parse_style\",", "OK, parse as hex color standard. hex_color = color_spec else:", "as a string-to-string dictionary. Keys are valid SVG element attributes", "CASCADING_STYLING_ATTRIBUTES: entry = element.getAttribute(attr) if entry: style[attr] = entry #", "as a percentage parsed_rgbs = [float(i[:-1]) / 100.0 for i", "SVG property names. Some may be missing. Returns ------- :class:`dict`", "does not parse them. See :meth:`parse_color_string` for converting from SVG", "#rrggbb format. Parameters ---------- color_spec : :class:`str` String in any", "in the default values for properties of SVG elements, if", "= [int(i) / 255.0 for i in splits] hex_color =", "Parameters ---------- svg_style : :class:`dict` Style attributes as a string-to-string", "<reponame>5Points7Edges/manim \"\"\"Utility functions for parsing SVG styles.\"\"\" __all__ = [\"cascade_element_style\",", "in svg_style: if svg_style[\"stroke\"] == \"none\": # In order to", "if splits[0][-1] == \"%\": # if the last character of", "color_spec[0] == \"#\": # its OK, parse as hex color", "\"none\": manim_style[\"fill_opacity\"] = 0 else: manim_style[\"fill_color\"] = parse_color_string(svg_style[\"fill\"]) if \"stroke\"", "\"stroke\", \"fill-opacity\", \"stroke-opacity\", ] # The default styling specifications for", "hex_color = color_spec else: # attempt to convert color names", "web-compatible format Returns ------- :class:`str` Hexadecimal color string in the", "values for properties of SVG elements, if they are not", "mapping svg attributes to values with `element`'s values overriding inherited", "\"black\", \"fill-opacity\": \"1\", \"stroke\": \"none\", \"stroke-opacity\": \"1\", } def cascade_element_style(", ": :class:`dict` Style dictionary with SVG property names. Some may", "for \"initial\") SVG_DEFAULT_ATTRIBUTES: Dict[str, str] = { \"fill\": \"black\", \"fill-opacity\":", "parsed_rgbs = [float(i[:-1]) / 100.0 for i in splits] else:", "svg attributes to values with `element`'s values overriding inherited values.", "convert color names like \"red\" to hex color hex_color =", "Dict[str, str]) -> Dict: \"\"\"Convert a dictionary of SVG attributes", "in splits] hex_color = rgb_to_hex(parsed_rgbs) elif color_spec[0] == \"#\": #", "but the Colour module wants them in floats. splits =", "parse them. See :meth:`parse_color_string` for converting from SVG attributes to", "\"\"\"Handle the SVG-specific color strings and convert them to HTML", "over a more distant ancestor's style. In order to correctly", "but in manim kwargs form, e.g., keys are fill_color, stroke_color", "that this method only copies the values and does not", "i in splits] else: parsed_rgbs = [int(i) / 255.0 for", "a string-to-string dictionary. Keys are valid SVG element attributes (fill,", "keyword arguments. Parameters ---------- element : :class:`MinidomElement` Element of the", "if \"stroke-opacity\" in svg_style: manim_style[\"stroke_opacity\"] = float(svg_style[\"stroke-opacity\"]) # nones need", "svg_style: if svg_style[\"fill\"] == \"none\": manim_style[\"fill_opacity\"] = 0 else: manim_style[\"fill_color\"]", "for properties of SVG elements, if they are not currently", "/ 100.0 for i in splits] else: parsed_rgbs = [int(i)", "\"fill\" in svg_style: if svg_style[\"fill\"] == \"none\": manim_style[\"fill_opacity\"] = 0", "convert them to HTML #rrggbb format. Parameters ---------- color_spec :", "\"\"\" style = inherited.copy() # cascade the regular elements. for", "== \"#\": # its OK, parse as hex color standard.", "MinidomElement from colour import web2hex from ...utils.color import rgb_to_hex from", "percentage, # then interpret the number as a percentage parsed_rgbs", "VMobject keyword arguments. Parameters ---------- svg_style : :class:`dict` Style attributes", "== \"none\": # In order to not break animations.creation.Write, #", "except ValueError as e: if not style_spec.strip(): # there was", "------- :class:`str` Hexadecimal color string in the format `#rrggbb` \"\"\"", "method only copies the values and does not parse them.", "if \"fill_color\" in manim_style: manim_style[\"stroke_color\"] = manim_style[\"fill_color\"] else: manim_style[\"stroke_color\"] =", "\"1\", } def cascade_element_style( element: MinidomElement, inherited: Dict[str, str] )", "just a stray semicolon at the end, producing an emptystring", "\"\"\" manim_style = {} fill_default_values(svg_style) if \"fill-opacity\" in svg_style: manim_style[\"fill_opacity\"]", "specially if \"fill\" in svg_style: if svg_style[\"fill\"] == \"none\": manim_style[\"fill_opacity\"]", "# according to https://www.w3.org/TR/SVG/painting.html # (ctrl-F for \"initial\") SVG_DEFAULT_ATTRIBUTES: Dict[str,", "specifications for SVG images, # according to https://www.w3.org/TR/SVG/painting.html # (ctrl-F", "] # The default styling specifications for SVG images, #", "e: if not style_spec.strip(): # there was just a stray", "there was just a stray semicolon at the end, producing", "not parse them. See :meth:`parse_color_string` for converting from SVG attributes", "SVG_DEFAULT_ATTRIBUTES: Dict[str, str] = { \"fill\": \"black\", \"fill-opacity\": \"1\", \"stroke\":", "semicolon at the end, producing an emptystring pass else: raise", "splits[0][-1] == \"%\": # if the last character of the", "number is a percentage, # then interpret the number as", "string in the format `#rrggbb` \"\"\" if color_spec[0:3] == \"rgb\":", "force_long=True) return hex_color def fill_default_values(svg_style: Dict) -> None: \"\"\" Fill", "element.getAttribute(attr) if entry: style[attr] = entry # the style attribute", "ancestor's style. In order to correctly calculate the styles, the", "\"#\": # its OK, parse as hex color standard. hex_color", "------- :class:`dict` Style attributes; none are missing. \"\"\" for key", "return style def parse_color_string(color_spec: str) -> str: \"\"\"Handle the SVG-specific", "are not currently set in the style dictionary. Parameters ----------", "and does not parse them. See :meth:`parse_color_string` for converting from", "typing import Dict, List CASCADING_STYLING_ATTRIBUTES: List[str] = [ \"fill\", \"stroke\",", "other # attributes in the same element. style_specs = element.getAttribute(\"style\")", "only in integer form, but the Colour module wants them", "\"stroke-opacity\" in svg_style: manim_style[\"stroke_opacity\"] = float(svg_style[\"stroke-opacity\"]) # nones need to", "style_specs.split(\";\"): try: key, value = style_spec.split(\":\") except ValueError as e:", "based upon both its inheritance and its own attributes. SVG", "of the first number is a percentage, # then interpret", "style dictionary. Parameters ---------- svg_style : :class:`dict` Style dictionary with", "an emptystring pass else: raise e else: style[key.strip()] = value.strip()", "parse_color_string(svg_style[\"fill\"]) if \"stroke\" in svg_style: if svg_style[\"stroke\"] == \"none\": #", "style def parse_color_string(color_spec: str) -> str: \"\"\"Handle the SVG-specific color", "\"rgb\": # these are only in integer form, but the", "form, but the Colour module wants them in floats. splits", "over other # attributes in the same element. style_specs =", "inherited from the parent element. Returns ------- :class:`dict` Dictionary mapping", "as MinidomElement from colour import web2hex from ...utils.color import rgb_to_hex", "SVG parse tree inherited : :class:`dict` Dictionary of SVG attributes", "keyword arguments. Parameters ---------- svg_style : :class:`dict` Style attributes as", "down through the inheritance tree, updating where necessary. Note that", "# if the last character of the first number is", "any web-compatible format Returns ------- :class:`str` Hexadecimal color string in", "if they are not currently set in the style dictionary.", "exists. manim_style[\"stroke_width\"] = 0 if \"fill_color\" in manim_style: manim_style[\"stroke_color\"] =", "takes priority over other # attributes in the same element.", "to hex color hex_color = web2hex(color_spec, force_long=True) return hex_color def", "attributes in the same element. style_specs = element.getAttribute(\"style\") if style_specs:", "# cascade the regular elements. for attr in CASCADING_STYLING_ATTRIBUTES: entry", "in order to # break it up nicely. furthermore, style", "the style attribute should be handled separately in order to", "svg_style[\"stroke\"] == \"none\": # In order to not break animations.creation.Write,", "str) -> str: \"\"\"Handle the SVG-specific color strings and convert", "etc) Returns ------- :class:`dict` Style attributes, but in manim kwargs", ":class:`dict` Style attributes, but in manim kwargs form, e.g., keys", "form, e.g., keys are fill_color, stroke_color \"\"\" manim_style = {}", "own attributes. SVG uses cascading element styles. A closer ancestor's", "the styles, the attributes are passed down through the inheritance", "color strings and convert them to HTML #rrggbb format. Parameters", "values with `element`'s values overriding inherited values. \"\"\" style =", "\"\"\" Fill in the default values for properties of SVG", "if key not in svg_style: svg_style[key] = SVG_DEFAULT_ATTRIBUTES[key] def parse_style(svg_style:", "tree inherited : :class:`dict` Dictionary of SVG attributes inherited from", "for i in splits] hex_color = rgb_to_hex(parsed_rgbs) elif color_spec[0] ==", "parsing SVG styles.\"\"\" __all__ = [\"cascade_element_style\", \"parse_style\", \"parse_color_string\"] from xml.dom.minidom", "with SVG property names. Some may be missing. Returns -------", "separately in order to # break it up nicely. furthermore,", "Style attributes, but in manim kwargs form, e.g., keys are", "{ \"fill\": \"black\", \"fill-opacity\": \"1\", \"stroke\": \"none\", \"stroke-opacity\": \"1\", }", "entry = element.getAttribute(attr) if entry: style[attr] = entry # the", "fill_default_values(svg_style) if \"fill-opacity\" in svg_style: manim_style[\"fill_opacity\"] = float(svg_style[\"fill-opacity\"]) if \"stroke-opacity\"", "= [ \"fill\", \"stroke\", \"fill-opacity\", \"stroke-opacity\", ] # The default", "the number as a percentage parsed_rgbs = [float(i[:-1]) / 100.0", "Parameters ---------- color_spec : :class:`str` String in any web-compatible format", "format `#rrggbb` \"\"\" if color_spec[0:3] == \"rgb\": # these are", "attributes are passed down through the inheritance tree, updating where", "255.0 for i in splits] hex_color = rgb_to_hex(parsed_rgbs) elif color_spec[0]", "format Returns ------- :class:`str` Hexadecimal color string in the format", "the fill color, if it exists. manim_style[\"stroke_width\"] = 0 if", "Returns ------- :class:`dict` Style attributes, but in manim kwargs form,", "a stray semicolon at the end, producing an emptystring pass", "last character of the first number is a percentage, #", "as hex color standard. hex_color = color_spec else: # attempt", "break it up nicely. furthermore, style takes priority over other", "inheritance tree, updating where necessary. Note that this method only", "a percentage parsed_rgbs = [float(i[:-1]) / 100.0 for i in", "style_specs = element.getAttribute(\"style\") if style_specs: for style_spec in style_specs.split(\";\"): try:", "SVG attributes to manim keyword arguments. Parameters ---------- element :", "keys are fill_color, stroke_color \"\"\" manim_style = {} fill_default_values(svg_style) if", "inherited.copy() # cascade the regular elements. for attr in CASCADING_STYLING_ATTRIBUTES:", "no stroke as stroke-width of zero and # color the", "character of the first number is a percentage, # then", "interpret no stroke as stroke-width of zero and # color", "HTML #rrggbb format. Parameters ---------- color_spec : :class:`str` String in", "if svg_style[\"stroke\"] == \"none\": # In order to not break", "module wants them in floats. splits = color_spec[4:-1].split(\",\") if splits[0][-1]", "---------- color_spec : :class:`str` String in any web-compatible format Returns", "styles.\"\"\" __all__ = [\"cascade_element_style\", \"parse_style\", \"parse_color_string\"] from xml.dom.minidom import Element", "= color_spec[4:-1].split(\",\") if splits[0][-1] == \"%\": # if the last", "= style_spec.split(\":\") except ValueError as e: if not style_spec.strip(): #", "format. Parameters ---------- color_spec : :class:`str` String in any web-compatible", "hex color hex_color = web2hex(color_spec, force_long=True) return hex_color def fill_default_values(svg_style:", "else: style[key.strip()] = value.strip() return style def parse_color_string(color_spec: str) ->", "Dict, List CASCADING_STYLING_ATTRIBUTES: List[str] = [ \"fill\", \"stroke\", \"fill-opacity\", \"stroke-opacity\",", "entry: style[attr] = entry # the style attribute should be", ":class:`dict` Dictionary mapping svg attributes to values with `element`'s values", "arguments. Parameters ---------- svg_style : :class:`dict` Style attributes as a", "inherited: Dict[str, str] ) -> Dict[str, str]: \"\"\"Collect the element's", "web2hex(color_spec, force_long=True) return hex_color def fill_default_values(svg_style: Dict) -> None: \"\"\"", "# these are only in integer form, but the Colour", "hex_color def fill_default_values(svg_style: Dict) -> None: \"\"\" Fill in the", "\"\"\"Convert a dictionary of SVG attributes to Manim VMobject keyword", "raise e else: style[key.strip()] = value.strip() return style def parse_color_string(color_spec:", "not break animations.creation.Write, # we interpret no stroke as stroke-width", "element's style attributes based upon both its inheritance and its", "import rgb_to_hex from typing import Dict, List CASCADING_STYLING_ATTRIBUTES: List[str] =", "rgb_to_hex from typing import Dict, List CASCADING_STYLING_ATTRIBUTES: List[str] = [", "List CASCADING_STYLING_ATTRIBUTES: List[str] = [ \"fill\", \"stroke\", \"fill-opacity\", \"stroke-opacity\", ]", "attr in CASCADING_STYLING_ATTRIBUTES: entry = element.getAttribute(attr) if entry: style[attr] =", "tree, updating where necessary. Note that this method only copies", "may be missing. Returns ------- :class:`dict` Style attributes; none are", "at the end, producing an emptystring pass else: raise e", "# then interpret the number as a percentage parsed_rgbs =", "attributes to values with `element`'s values overriding inherited values. \"\"\"", "producing an emptystring pass else: raise e else: style[key.strip()] =", "\"red\" to hex color hex_color = web2hex(color_spec, force_long=True) return hex_color", "manim keyword arguments. Parameters ---------- element : :class:`MinidomElement` Element of", "then interpret the number as a percentage parsed_rgbs = [float(i[:-1])", "for converting from SVG attributes to manim keyword arguments. Parameters", "in floats. splits = color_spec[4:-1].split(\",\") if splits[0][-1] == \"%\": #", "{} fill_default_values(svg_style) if \"fill-opacity\" in svg_style: manim_style[\"fill_opacity\"] = float(svg_style[\"fill-opacity\"]) if", "properties of SVG elements, if they are not currently set", "inherited values. \"\"\" style = inherited.copy() # cascade the regular", "of SVG attributes inherited from the parent element. Returns -------", "stroke_color \"\"\" manim_style = {} fill_default_values(svg_style) if \"fill-opacity\" in svg_style:", "\"\"\" for key in SVG_DEFAULT_ATTRIBUTES: if key not in svg_style:", "style_spec.strip(): # there was just a stray semicolon at the", "\"fill_color\" in manim_style: manim_style[\"stroke_color\"] = manim_style[\"fill_color\"] else: manim_style[\"stroke_color\"] = parse_color_string(svg_style[\"stroke\"])", "style attribute should be handled separately in order to #", "nones need to be handled specially if \"fill\" in svg_style:", "them in floats. splits = color_spec[4:-1].split(\",\") if splits[0][-1] == \"%\":", "emptystring pass else: raise e else: style[key.strip()] = value.strip() return", "splits] hex_color = rgb_to_hex(parsed_rgbs) elif color_spec[0] == \"#\": # its", "end, producing an emptystring pass else: raise e else: style[key.strip()]", "= [float(i[:-1]) / 100.0 for i in splits] else: parsed_rgbs", "elif color_spec[0] == \"#\": # its OK, parse as hex", "# we interpret no stroke as stroke-width of zero and", "property names. Some may be missing. Returns ------- :class:`dict` Style", "values. \"\"\" style = inherited.copy() # cascade the regular elements.", "upon both its inheritance and its own attributes. SVG uses", "in integer form, but the Colour module wants them in", "parent element. Returns ------- :class:`dict` Dictionary mapping svg attributes to", "correctly calculate the styles, the attributes are passed down through", "element : :class:`MinidomElement` Element of the SVG parse tree inherited", "nicely. furthermore, style takes priority over other # attributes in" ]
[ "f=open(\"tw_config.json\",'r') config=json.load(f) f.close() CONSUMER_KEY =config['consumer_key'] CONSUMER_SECRET =config['consumer_secret'] ACCESS_TOKEN =config['access_token'] ACCESS_SECRET", "'/opt/vc/bin/vcgencmd measure_temp' line = os.popen(cmd).readline().strip() temp = line.split('=')[1].split(\"'\")[0] direct_message='CPU:'+temp+'deg @'+current_time+'", "RPi.GPIO as GPIO # import json from time import sleep", "# from twython import Twython f=open(\"tw_config.json\",'r') config=json.load(f) f.close() CONSUMER_KEY =config['consumer_key']", "#time stamp timestamp = 'date +%F_%H:%M:%S' current_time=os.popen(timestamp).readline().strip() # get CPU", "ledstate if channel == trigger_input: ledstate = not ledstate GPIO.output(25,", "measure_temp' line = os.popen(cmd).readline().strip() temp = line.split('=')[1].split(\"'\")[0] direct_message='CPU:'+temp+'deg @'+current_time+' :", "timestamp = 'date +%F_%H:%M:%S' current_time=os.popen(timestamp).readline().strip() # get CPU temperature cmd", "not ledstate GPIO.output(25, ledstate) api.send_direct_message(text=direct_message ,screen_name=dist) api = Twython(CONSUMER_KEY,CONSUMER_SECRET,ACCESS_TOKEN,ACCESS_SECRET) trigger_input=21", "ledstate = GPIO.LOW try: while True: sleep(0.01) except KeyboardInterrupt: #", "import sleep # from twython import Twython f=open(\"tw_config.json\",'r') config=json.load(f) f.close()", "cmd = '/opt/vc/bin/vcgencmd measure_temp' line = os.popen(cmd).readline().strip() temp = line.split('=')[1].split(\"'\")[0]", "= GPIO.LOW try: while True: sleep(0.01) except KeyboardInterrupt: # pass", "os import RPi.GPIO as GPIO # import json from time", "= '/opt/vc/bin/vcgencmd measure_temp' line = os.popen(cmd).readline().strip() temp = line.split('=')[1].split(\"'\")[0] direct_message='CPU:'+temp+'deg", "= 'date +%F_%H:%M:%S' current_time=os.popen(timestamp).readline().strip() # get CPU temperature cmd =", "direct_message='CPU:'+temp+'deg @'+current_time+' : by Python script' global ledstate if channel", "bouncetime=1000) ledstate = GPIO.LOW try: while True: sleep(0.01) except KeyboardInterrupt:", "import RPi.GPIO as GPIO # import json from time import", "GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.add_event_detect(trigger_input, GPIO.RISING, callback=on_positive_edge, bouncetime=1000) ledstate = GPIO.LOW try:", "python #coding:utf-8 import os import RPi.GPIO as GPIO # import", "line = os.popen(cmd).readline().strip() temp = line.split('=')[1].split(\"'\")[0] direct_message='CPU:'+temp+'deg @'+current_time+' : by", "ledstate) api.send_direct_message(text=direct_message ,screen_name=dist) api = Twython(CONSUMER_KEY,CONSUMER_SECRET,ACCESS_TOKEN,ACCESS_SECRET) trigger_input=21 GPIO.setmode(GPIO.BCM) GPIO.setup(25, GPIO.OUT)", "f.close() CONSUMER_KEY =config['consumer_key'] CONSUMER_SECRET =config['consumer_secret'] ACCESS_TOKEN =config['access_token'] ACCESS_SECRET =config['access_secret'] dist=config['dist']", "CONSUMER_KEY =config['consumer_key'] CONSUMER_SECRET =config['consumer_secret'] ACCESS_TOKEN =config['access_token'] ACCESS_SECRET =config['access_secret'] dist=config['dist'] def", "as GPIO # import json from time import sleep #", "twython import Twython f=open(\"tw_config.json\",'r') config=json.load(f) f.close() CONSUMER_KEY =config['consumer_key'] CONSUMER_SECRET =config['consumer_secret']", "= os.popen(cmd).readline().strip() temp = line.split('=')[1].split(\"'\")[0] direct_message='CPU:'+temp+'deg @'+current_time+' : by Python", "CONSUMER_SECRET =config['consumer_secret'] ACCESS_TOKEN =config['access_token'] ACCESS_SECRET =config['access_secret'] dist=config['dist'] def on_positive_edge(channel): #time", "GPIO.RISING, callback=on_positive_edge, bouncetime=1000) ledstate = GPIO.LOW try: while True: sleep(0.01)", "import Twython f=open(\"tw_config.json\",'r') config=json.load(f) f.close() CONSUMER_KEY =config['consumer_key'] CONSUMER_SECRET =config['consumer_secret'] ACCESS_TOKEN", "stamp timestamp = 'date +%F_%H:%M:%S' current_time=os.popen(timestamp).readline().strip() # get CPU temperature", "GPIO.OUT) GPIO.setup(trigger_input, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.add_event_detect(trigger_input, GPIO.RISING, callback=on_positive_edge, bouncetime=1000) ledstate =", "= Twython(CONSUMER_KEY,CONSUMER_SECRET,ACCESS_TOKEN,ACCESS_SECRET) trigger_input=21 GPIO.setmode(GPIO.BCM) GPIO.setup(25, GPIO.OUT) GPIO.setup(trigger_input, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.add_event_detect(trigger_input,", "GPIO.setup(trigger_input, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.add_event_detect(trigger_input, GPIO.RISING, callback=on_positive_edge, bouncetime=1000) ledstate = GPIO.LOW", "config=json.load(f) f.close() CONSUMER_KEY =config['consumer_key'] CONSUMER_SECRET =config['consumer_secret'] ACCESS_TOKEN =config['access_token'] ACCESS_SECRET =config['access_secret']", "GPIO.LOW try: while True: sleep(0.01) except KeyboardInterrupt: # pass GPIO.cleanup()", "api.send_direct_message(text=direct_message ,screen_name=dist) api = Twython(CONSUMER_KEY,CONSUMER_SECRET,ACCESS_TOKEN,ACCESS_SECRET) trigger_input=21 GPIO.setmode(GPIO.BCM) GPIO.setup(25, GPIO.OUT) GPIO.setup(trigger_input,", "GPIO # import json from time import sleep # from", "line.split('=')[1].split(\"'\")[0] direct_message='CPU:'+temp+'deg @'+current_time+' : by Python script' global ledstate if", "GPIO.output(25, ledstate) api.send_direct_message(text=direct_message ,screen_name=dist) api = Twython(CONSUMER_KEY,CONSUMER_SECRET,ACCESS_TOKEN,ACCESS_SECRET) trigger_input=21 GPIO.setmode(GPIO.BCM) GPIO.setup(25,", "api = Twython(CONSUMER_KEY,CONSUMER_SECRET,ACCESS_TOKEN,ACCESS_SECRET) trigger_input=21 GPIO.setmode(GPIO.BCM) GPIO.setup(25, GPIO.OUT) GPIO.setup(trigger_input, GPIO.IN, pull_up_down=GPIO.PUD_UP)", "trigger_input: ledstate = not ledstate GPIO.output(25, ledstate) api.send_direct_message(text=direct_message ,screen_name=dist) api", "def on_positive_edge(channel): #time stamp timestamp = 'date +%F_%H:%M:%S' current_time=os.popen(timestamp).readline().strip() #", "'date +%F_%H:%M:%S' current_time=os.popen(timestamp).readline().strip() # get CPU temperature cmd = '/opt/vc/bin/vcgencmd", "temp = line.split('=')[1].split(\"'\")[0] direct_message='CPU:'+temp+'deg @'+current_time+' : by Python script' global", "= not ledstate GPIO.output(25, ledstate) api.send_direct_message(text=direct_message ,screen_name=dist) api = Twython(CONSUMER_KEY,CONSUMER_SECRET,ACCESS_TOKEN,ACCESS_SECRET)", "CPU temperature cmd = '/opt/vc/bin/vcgencmd measure_temp' line = os.popen(cmd).readline().strip() temp", "ACCESS_TOKEN =config['access_token'] ACCESS_SECRET =config['access_secret'] dist=config['dist'] def on_positive_edge(channel): #time stamp timestamp", "os.popen(cmd).readline().strip() temp = line.split('=')[1].split(\"'\")[0] direct_message='CPU:'+temp+'deg @'+current_time+' : by Python script'", "# get CPU temperature cmd = '/opt/vc/bin/vcgencmd measure_temp' line =", "=config['consumer_key'] CONSUMER_SECRET =config['consumer_secret'] ACCESS_TOKEN =config['access_token'] ACCESS_SECRET =config['access_secret'] dist=config['dist'] def on_positive_edge(channel):", ",screen_name=dist) api = Twython(CONSUMER_KEY,CONSUMER_SECRET,ACCESS_TOKEN,ACCESS_SECRET) trigger_input=21 GPIO.setmode(GPIO.BCM) GPIO.setup(25, GPIO.OUT) GPIO.setup(trigger_input, GPIO.IN,", "import os import RPi.GPIO as GPIO # import json from", "=config['access_secret'] dist=config['dist'] def on_positive_edge(channel): #time stamp timestamp = 'date +%F_%H:%M:%S'", "trigger_input=21 GPIO.setmode(GPIO.BCM) GPIO.setup(25, GPIO.OUT) GPIO.setup(trigger_input, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.add_event_detect(trigger_input, GPIO.RISING, callback=on_positive_edge,", "Python script' global ledstate if channel == trigger_input: ledstate =", ": by Python script' global ledstate if channel == trigger_input:", "time import sleep # from twython import Twython f=open(\"tw_config.json\",'r') config=json.load(f)", "GPIO.add_event_detect(trigger_input, GPIO.RISING, callback=on_positive_edge, bouncetime=1000) ledstate = GPIO.LOW try: while True:", "json from time import sleep # from twython import Twython", "script' global ledstate if channel == trigger_input: ledstate = not", "by Python script' global ledstate if channel == trigger_input: ledstate", "ACCESS_SECRET =config['access_secret'] dist=config['dist'] def on_positive_edge(channel): #time stamp timestamp = 'date", "GPIO.setup(25, GPIO.OUT) GPIO.setup(trigger_input, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.add_event_detect(trigger_input, GPIO.RISING, callback=on_positive_edge, bouncetime=1000) ledstate", "temperature cmd = '/opt/vc/bin/vcgencmd measure_temp' line = os.popen(cmd).readline().strip() temp =", "= line.split('=')[1].split(\"'\")[0] direct_message='CPU:'+temp+'deg @'+current_time+' : by Python script' global ledstate", "+%F_%H:%M:%S' current_time=os.popen(timestamp).readline().strip() # get CPU temperature cmd = '/opt/vc/bin/vcgencmd measure_temp'", "GPIO.setmode(GPIO.BCM) GPIO.setup(25, GPIO.OUT) GPIO.setup(trigger_input, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.add_event_detect(trigger_input, GPIO.RISING, callback=on_positive_edge, bouncetime=1000)", "sleep # from twython import Twython f=open(\"tw_config.json\",'r') config=json.load(f) f.close() CONSUMER_KEY", "#coding:utf-8 import os import RPi.GPIO as GPIO # import json", "Twython f=open(\"tw_config.json\",'r') config=json.load(f) f.close() CONSUMER_KEY =config['consumer_key'] CONSUMER_SECRET =config['consumer_secret'] ACCESS_TOKEN =config['access_token']", "@'+current_time+' : by Python script' global ledstate if channel ==", "get CPU temperature cmd = '/opt/vc/bin/vcgencmd measure_temp' line = os.popen(cmd).readline().strip()", "=config['consumer_secret'] ACCESS_TOKEN =config['access_token'] ACCESS_SECRET =config['access_secret'] dist=config['dist'] def on_positive_edge(channel): #time stamp", "if channel == trigger_input: ledstate = not ledstate GPIO.output(25, ledstate)", "try: while True: sleep(0.01) except KeyboardInterrupt: # pass GPIO.cleanup() #", "callback=on_positive_edge, bouncetime=1000) ledstate = GPIO.LOW try: while True: sleep(0.01) except", "from time import sleep # from twython import Twython f=open(\"tw_config.json\",'r')", "== trigger_input: ledstate = not ledstate GPIO.output(25, ledstate) api.send_direct_message(text=direct_message ,screen_name=dist)", "Twython(CONSUMER_KEY,CONSUMER_SECRET,ACCESS_TOKEN,ACCESS_SECRET) trigger_input=21 GPIO.setmode(GPIO.BCM) GPIO.setup(25, GPIO.OUT) GPIO.setup(trigger_input, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.add_event_detect(trigger_input, GPIO.RISING,", "ledstate = not ledstate GPIO.output(25, ledstate) api.send_direct_message(text=direct_message ,screen_name=dist) api =", "pull_up_down=GPIO.PUD_UP) GPIO.add_event_detect(trigger_input, GPIO.RISING, callback=on_positive_edge, bouncetime=1000) ledstate = GPIO.LOW try: while", "import json from time import sleep # from twython import", "ledstate GPIO.output(25, ledstate) api.send_direct_message(text=direct_message ,screen_name=dist) api = Twython(CONSUMER_KEY,CONSUMER_SECRET,ACCESS_TOKEN,ACCESS_SECRET) trigger_input=21 GPIO.setmode(GPIO.BCM)", "global ledstate if channel == trigger_input: ledstate = not ledstate", "current_time=os.popen(timestamp).readline().strip() # get CPU temperature cmd = '/opt/vc/bin/vcgencmd measure_temp' line", "=config['access_token'] ACCESS_SECRET =config['access_secret'] dist=config['dist'] def on_positive_edge(channel): #time stamp timestamp =", "from twython import Twython f=open(\"tw_config.json\",'r') config=json.load(f) f.close() CONSUMER_KEY =config['consumer_key'] CONSUMER_SECRET", "#!/usr/bin/env python #coding:utf-8 import os import RPi.GPIO as GPIO #", "dist=config['dist'] def on_positive_edge(channel): #time stamp timestamp = 'date +%F_%H:%M:%S' current_time=os.popen(timestamp).readline().strip()", "on_positive_edge(channel): #time stamp timestamp = 'date +%F_%H:%M:%S' current_time=os.popen(timestamp).readline().strip() # get", "# import json from time import sleep # from twython", "channel == trigger_input: ledstate = not ledstate GPIO.output(25, ledstate) api.send_direct_message(text=direct_message" ]
[ "\"\"\" from wheezy.template.utils import find_balanced assert 10 == find_balanced('test', 10)", "doesn't start with ``start_sep`` return. \"\"\" from wheezy.template.utils import find_balanced", "import unittest class FindAllBalancedTestCase(unittest.TestCase): \"\"\" Test the ``find_all_balanced``. \"\"\" def", "start index is out of range. \"\"\" from wheezy.template.utils import", "Separators are balanced. \"\"\" from wheezy.template.utils import find_balanced assert 10", "find_balanced('test(', 0) assert 3 == find_balanced('test(', 3) def test_not_balanced(self): \"\"\"", "0 == find_balanced('test(', 0) assert 3 == find_balanced('test(', 3) def", "find_all_balanced assert 4 == find_all_balanced('test(a, b', 4) assert 4 ==", "class FindBalancedTestCase(unittest.TestCase): \"\"\" Test the ``find_balanced``. \"\"\" def test_start_out(self): \"\"\"", "10 == find_all_balanced('test', 10) def test_start_separator(self): \"\"\" If text doesn't", "\"\"\" from wheezy.template.utils import find_balanced assert 10 == find_balanced('test(a, b)',", "17 == find_all_balanced('test(a, b())[0]()', 4) class FindBalancedTestCase(unittest.TestCase): \"\"\" Test the", "4 == find_all_balanced('test[a, b()', 4) def test_balanced(self): \"\"\" Separators are", "\"\"\" Test the ``find_balanced``. \"\"\" def test_start_out(self): \"\"\" The start", "\"\"\" Test the ``find_all_balanced``. \"\"\" def test_start_out(self): \"\"\" The start", "from wheezy.template.utils import find_all_balanced assert 10 == find_all_balanced('test(a, b)', 4)", "find_balanced('test', 10) def test_start_separator(self): \"\"\" If text doesn't start with", "wheezy.template.utils import find_balanced assert 10 == find_balanced('test', 10) def test_start_separator(self):", "from wheezy.template.utils import find_all_balanced assert 4 == find_all_balanced('test(a, b', 4)", "``find_all_balanced``. \"\"\" def test_start_out(self): \"\"\" The start index is out", "Separators are not balanced. \"\"\" from wheezy.template.utils import find_balanced assert", "range. \"\"\" from wheezy.template.utils import find_all_balanced assert 10 == find_all_balanced('test',", "assert 4 == find_all_balanced('test(a, b', 4) assert 4 == find_all_balanced('test[a,", "balanced. \"\"\" from wheezy.template.utils import find_all_balanced assert 10 == find_all_balanced('test(a,", "\"\"\" Separators are balanced. \"\"\" from wheezy.template.utils import find_all_balanced assert", "The start index is out of range. \"\"\" from wheezy.template.utils", "unittest class FindAllBalancedTestCase(unittest.TestCase): \"\"\" Test the ``find_all_balanced``. \"\"\" def test_start_out(self):", "import find_balanced assert 0 == find_balanced('test(', 0) assert 3 ==", "Separators are balanced. \"\"\" from wheezy.template.utils import find_all_balanced assert 10", "find_all_balanced assert 10 == find_all_balanced('test(a, b)', 4) assert 13 ==", "\"\"\" import unittest class FindAllBalancedTestCase(unittest.TestCase): \"\"\" Test the ``find_all_balanced``. \"\"\"", "test_balanced(self): \"\"\" Separators are balanced. \"\"\" from wheezy.template.utils import find_balanced", "start with ``([`` return. \"\"\" from wheezy.template.utils import find_all_balanced assert", "start with ``start_sep`` return. \"\"\" from wheezy.template.utils import find_balanced assert", "\"\"\" Separators are not balanced. \"\"\" from wheezy.template.utils import find_all_balanced", "find_all_balanced('test(a, b', 4) assert 4 == find_all_balanced('test[a, b()', 4) def", "are balanced. \"\"\" from wheezy.template.utils import find_all_balanced assert 10 ==", "== find_all_balanced('test([', 0) assert 3 == find_all_balanced('test([', 3) def test_not_balanced(self):", "Test the ``find_balanced``. \"\"\" def test_start_out(self): \"\"\" The start index", "10 == find_balanced('test(a, b)', 4) assert 12 == find_balanced('test(a, b())',", "find_balanced('test(a, b', 4) assert 4 == find_balanced('test(a, b()', 4) def", "are balanced. \"\"\" from wheezy.template.utils import find_balanced assert 10 ==", "find_all_balanced assert 10 == find_all_balanced('test', 10) def test_start_separator(self): \"\"\" If", "tests for ``wheezy.templates.utils``. \"\"\" import unittest class FindAllBalancedTestCase(unittest.TestCase): \"\"\" Test", "the ``find_balanced``. \"\"\" def test_start_out(self): \"\"\" The start index is", "not balanced. \"\"\" from wheezy.template.utils import find_balanced assert 4 ==", "test_balanced(self): \"\"\" Separators are balanced. \"\"\" from wheezy.template.utils import find_all_balanced", "0) assert 3 == find_all_balanced('test([', 3) def test_not_balanced(self): \"\"\" Separators", "def test_balanced(self): \"\"\" Separators are balanced. \"\"\" from wheezy.template.utils import", "import find_balanced assert 4 == find_balanced('test(a, b', 4) assert 4", "def test_start_out(self): \"\"\" The start index is out of range.", "with ``start_sep`` return. \"\"\" from wheezy.template.utils import find_balanced assert 0", "not balanced. \"\"\" from wheezy.template.utils import find_all_balanced assert 4 ==", "out of range. \"\"\" from wheezy.template.utils import find_balanced assert 10", "assert 4 == find_balanced('test(a, b', 4) assert 4 == find_balanced('test(a,", "13 == find_all_balanced('test(a, b)[0]', 4) assert 12 == find_all_balanced('test(a, b())',", "\"\"\" from wheezy.template.utils import find_all_balanced assert 4 == find_all_balanced('test(a, b',", "find_balanced assert 10 == find_balanced('test', 10) def test_start_separator(self): \"\"\" If", "wheezy.template.utils import find_all_balanced assert 10 == find_all_balanced('test', 10) def test_start_separator(self):", "3) def test_not_balanced(self): \"\"\" Separators are not balanced. \"\"\" from", "== find_balanced('test(a, b()', 4) def test_balanced(self): \"\"\" Separators are balanced.", "import find_all_balanced assert 10 == find_all_balanced('test', 10) def test_start_separator(self): \"\"\"", "is out of range. \"\"\" from wheezy.template.utils import find_balanced assert", "4 == find_all_balanced('test(a, b', 4) assert 4 == find_all_balanced('test[a, b()',", "find_all_balanced('test', 10) def test_start_separator(self): \"\"\" If text doesn't start with", "If text doesn't start with ``([`` return. \"\"\" from wheezy.template.utils", "doesn't start with ``([`` return. \"\"\" from wheezy.template.utils import find_all_balanced", "for ``wheezy.templates.utils``. \"\"\" import unittest class FindAllBalancedTestCase(unittest.TestCase): \"\"\" Test the", "``([`` return. \"\"\" from wheezy.template.utils import find_all_balanced assert 0 ==", "assert 0 == find_all_balanced('test([', 0) assert 3 == find_all_balanced('test([', 3)", "== find_all_balanced('test([', 3) def test_not_balanced(self): \"\"\" Separators are not balanced.", "b()', 4) def test_balanced(self): \"\"\" Separators are balanced. \"\"\" from", "assert 13 == find_all_balanced('test(a, b)[0]', 4) assert 12 == find_all_balanced('test(a,", "def test_not_balanced(self): \"\"\" Separators are not balanced. \"\"\" from wheezy.template.utils", "import find_balanced assert 10 == find_balanced('test', 10) def test_start_separator(self): \"\"\"", "from wheezy.template.utils import find_balanced assert 4 == find_balanced('test(a, b', 4)", "== find_balanced('test(a, b', 4) assert 4 == find_balanced('test(a, b()', 4)", "== find_all_balanced('test', 10) def test_start_separator(self): \"\"\" If text doesn't start", "10 == find_balanced('test', 10) def test_start_separator(self): \"\"\" If text doesn't", "== find_balanced('test', 10) def test_start_separator(self): \"\"\" If text doesn't start", "4) def test_balanced(self): \"\"\" Separators are balanced. \"\"\" from wheezy.template.utils", "find_balanced assert 10 == find_balanced('test(a, b)', 4) assert 12 ==", "== find_balanced('test(', 0) assert 3 == find_balanced('test(', 3) def test_not_balanced(self):", "== find_all_balanced('test[a, b()', 4) def test_balanced(self): \"\"\" Separators are balanced.", "If text doesn't start with ``start_sep`` return. \"\"\" from wheezy.template.utils", "index is out of range. \"\"\" from wheezy.template.utils import find_balanced", "from wheezy.template.utils import find_balanced assert 10 == find_balanced('test', 10) def", "assert 10 == find_all_balanced('test', 10) def test_start_separator(self): \"\"\" If text", "def test_start_separator(self): \"\"\" If text doesn't start with ``start_sep`` return.", "== find_balanced('test(a, b)', 4) assert 12 == find_balanced('test(a, b())', 4)", "balanced. \"\"\" from wheezy.template.utils import find_all_balanced assert 4 == find_all_balanced('test(a,", "class FindAllBalancedTestCase(unittest.TestCase): \"\"\" Test the ``find_all_balanced``. \"\"\" def test_start_out(self): \"\"\"", "assert 10 == find_balanced('test(a, b)', 4) assert 12 == find_balanced('test(a,", "find_all_balanced assert 0 == find_all_balanced('test([', 0) assert 3 == find_all_balanced('test([',", "\"\"\" from wheezy.template.utils import find_all_balanced assert 10 == find_all_balanced('test(a, b)',", "4) assert 13 == find_all_balanced('test(a, b)[0]', 4) assert 12 ==", "4 == find_balanced('test(a, b()', 4) def test_balanced(self): \"\"\" Separators are", "12 == find_all_balanced('test(a, b())', 4) assert 17 == find_all_balanced('test(a, b())[0]()',", "assert 0 == find_balanced('test(', 0) assert 3 == find_balanced('test(', 3)", "find_balanced assert 4 == find_balanced('test(a, b', 4) assert 4 ==", "the ``find_all_balanced``. \"\"\" def test_start_out(self): \"\"\" The start index is", "index is out of range. \"\"\" from wheezy.template.utils import find_all_balanced", "text doesn't start with ``start_sep`` return. \"\"\" from wheezy.template.utils import", "is out of range. \"\"\" from wheezy.template.utils import find_all_balanced assert", "assert 3 == find_balanced('test(', 3) def test_not_balanced(self): \"\"\" Separators are", "test_not_balanced(self): \"\"\" Separators are not balanced. \"\"\" from wheezy.template.utils import", "find_all_balanced('test(a, b())', 4) assert 17 == find_all_balanced('test(a, b())[0]()', 4) class", "``start_sep`` return. \"\"\" from wheezy.template.utils import find_balanced assert 0 ==", "\"\"\" from wheezy.template.utils import find_balanced assert 0 == find_balanced('test(', 0)", "are not balanced. \"\"\" from wheezy.template.utils import find_all_balanced assert 4", "Unit tests for ``wheezy.templates.utils``. \"\"\" import unittest class FindAllBalancedTestCase(unittest.TestCase): \"\"\"", "return. \"\"\" from wheezy.template.utils import find_all_balanced assert 0 == find_all_balanced('test([',", "``find_balanced``. \"\"\" def test_start_out(self): \"\"\" The start index is out", "b)[0]', 4) assert 12 == find_all_balanced('test(a, b())', 4) assert 17", "wheezy.template.utils import find_balanced assert 4 == find_balanced('test(a, b', 4) assert", "``wheezy.templates.utils``. \"\"\" import unittest class FindAllBalancedTestCase(unittest.TestCase): \"\"\" Test the ``find_all_balanced``.", "find_all_balanced('test(a, b)', 4) assert 13 == find_all_balanced('test(a, b)[0]', 4) assert", "\"\"\" Unit tests for ``wheezy.templates.utils``. \"\"\" import unittest class FindAllBalancedTestCase(unittest.TestCase):", "from wheezy.template.utils import find_balanced assert 0 == find_balanced('test(', 0) assert", "wheezy.template.utils import find_all_balanced assert 0 == find_all_balanced('test([', 0) assert 3", "10) def test_start_separator(self): \"\"\" If text doesn't start with ``([``", "balanced. \"\"\" from wheezy.template.utils import find_balanced assert 10 == find_balanced('test(a,", "== find_all_balanced('test(a, b)[0]', 4) assert 12 == find_all_balanced('test(a, b())', 4)", "4) assert 4 == find_all_balanced('test[a, b()', 4) def test_balanced(self): \"\"\"", "\"\"\" from wheezy.template.utils import find_all_balanced assert 10 == find_all_balanced('test', 10)", "find_all_balanced('test(a, b)[0]', 4) assert 12 == find_all_balanced('test(a, b())', 4) assert", "assert 10 == find_all_balanced('test(a, b)', 4) assert 13 == find_all_balanced('test(a,", "10 == find_all_balanced('test(a, b)', 4) assert 13 == find_all_balanced('test(a, b)[0]',", "range. \"\"\" from wheezy.template.utils import find_balanced assert 10 == find_balanced('test',", "import find_all_balanced assert 4 == find_all_balanced('test(a, b', 4) assert 4", "find_all_balanced('test([', 0) assert 3 == find_all_balanced('test([', 3) def test_not_balanced(self): \"\"\"", "Separators are not balanced. \"\"\" from wheezy.template.utils import find_all_balanced assert", "4) class FindBalancedTestCase(unittest.TestCase): \"\"\" Test the ``find_balanced``. \"\"\" def test_start_out(self):", "import find_balanced assert 10 == find_balanced('test(a, b)', 4) assert 12", "assert 17 == find_all_balanced('test(a, b())[0]()', 4) class FindBalancedTestCase(unittest.TestCase): \"\"\" Test", "4) assert 12 == find_all_balanced('test(a, b())', 4) assert 17 ==", "from wheezy.template.utils import find_all_balanced assert 10 == find_all_balanced('test', 10) def", "find_balanced('test(', 3) def test_not_balanced(self): \"\"\" Separators are not balanced. \"\"\"", "find_all_balanced('test(a, b())[0]()', 4) class FindBalancedTestCase(unittest.TestCase): \"\"\" Test the ``find_balanced``. \"\"\"", "wheezy.template.utils import find_all_balanced assert 4 == find_all_balanced('test(a, b', 4) assert", "b)', 4) assert 13 == find_all_balanced('test(a, b)[0]', 4) assert 12", "b())[0]()', 4) class FindBalancedTestCase(unittest.TestCase): \"\"\" Test the ``find_balanced``. \"\"\" def", "import find_all_balanced assert 10 == find_all_balanced('test(a, b)', 4) assert 13", "== find_balanced('test(', 3) def test_not_balanced(self): \"\"\" Separators are not balanced.", "are not balanced. \"\"\" from wheezy.template.utils import find_balanced assert 4", "\"\"\" from wheezy.template.utils import find_all_balanced assert 0 == find_all_balanced('test([', 0)", "assert 4 == find_balanced('test(a, b()', 4) def test_balanced(self): \"\"\" Separators", "FindAllBalancedTestCase(unittest.TestCase): \"\"\" Test the ``find_all_balanced``. \"\"\" def test_start_out(self): \"\"\" The", "== find_all_balanced('test(a, b())[0]()', 4) class FindBalancedTestCase(unittest.TestCase): \"\"\" Test the ``find_balanced``.", "b', 4) assert 4 == find_all_balanced('test[a, b()', 4) def test_balanced(self):", "== find_all_balanced('test(a, b())', 4) assert 17 == find_all_balanced('test(a, b())[0]()', 4)", "assert 4 == find_all_balanced('test[a, b()', 4) def test_balanced(self): \"\"\" Separators", "b())', 4) assert 17 == find_all_balanced('test(a, b())[0]()', 4) class FindBalancedTestCase(unittest.TestCase):", "balanced. \"\"\" from wheezy.template.utils import find_balanced assert 4 == find_balanced('test(a,", "b', 4) assert 4 == find_balanced('test(a, b()', 4) def test_balanced(self):", "wheezy.template.utils import find_balanced assert 10 == find_balanced('test(a, b)', 4) assert", "return. \"\"\" from wheezy.template.utils import find_balanced assert 0 == find_balanced('test(',", "out of range. \"\"\" from wheezy.template.utils import find_all_balanced assert 10", "0 == find_all_balanced('test([', 0) assert 3 == find_all_balanced('test([', 3) def", "find_all_balanced('test[a, b()', 4) def test_balanced(self): \"\"\" Separators are balanced. \"\"\"", "of range. \"\"\" from wheezy.template.utils import find_all_balanced assert 10 ==", "0) assert 3 == find_balanced('test(', 3) def test_not_balanced(self): \"\"\" Separators", "from wheezy.template.utils import find_balanced assert 10 == find_balanced('test(a, b)', 4)", "import find_all_balanced assert 0 == find_all_balanced('test([', 0) assert 3 ==", "wheezy.template.utils import find_balanced assert 0 == find_balanced('test(', 0) assert 3", "def test_start_separator(self): \"\"\" If text doesn't start with ``([`` return.", "4) assert 17 == find_all_balanced('test(a, b())[0]()', 4) class FindBalancedTestCase(unittest.TestCase): \"\"\"", "10) def test_start_separator(self): \"\"\" If text doesn't start with ``start_sep``", "from wheezy.template.utils import find_all_balanced assert 0 == find_all_balanced('test([', 0) assert", "FindBalancedTestCase(unittest.TestCase): \"\"\" Test the ``find_balanced``. \"\"\" def test_start_out(self): \"\"\" The", "3 == find_balanced('test(', 3) def test_not_balanced(self): \"\"\" Separators are not", "find_balanced('test(a, b()', 4) def test_balanced(self): \"\"\" Separators are balanced. \"\"\"", "\"\"\" def test_start_out(self): \"\"\" The start index is out of", "4 == find_balanced('test(a, b', 4) assert 4 == find_balanced('test(a, b()',", "text doesn't start with ``([`` return. \"\"\" from wheezy.template.utils import", "wheezy.template.utils import find_all_balanced assert 10 == find_all_balanced('test(a, b)', 4) assert", "find_balanced assert 0 == find_balanced('test(', 0) assert 3 == find_balanced('test(',", "assert 3 == find_all_balanced('test([', 3) def test_not_balanced(self): \"\"\" Separators are", "\"\"\" from wheezy.template.utils import find_balanced assert 4 == find_balanced('test(a, b',", "with ``([`` return. \"\"\" from wheezy.template.utils import find_all_balanced assert 0", "assert 10 == find_balanced('test', 10) def test_start_separator(self): \"\"\" If text", "\"\"\" If text doesn't start with ``start_sep`` return. \"\"\" from", "of range. \"\"\" from wheezy.template.utils import find_balanced assert 10 ==", "3 == find_all_balanced('test([', 3) def test_not_balanced(self): \"\"\" Separators are not", "\"\"\" Separators are balanced. \"\"\" from wheezy.template.utils import find_balanced assert", "== find_all_balanced('test(a, b)', 4) assert 13 == find_all_balanced('test(a, b)[0]', 4)", "\"\"\" If text doesn't start with ``([`` return. \"\"\" from", "assert 12 == find_all_balanced('test(a, b())', 4) assert 17 == find_all_balanced('test(a,", "test_start_separator(self): \"\"\" If text doesn't start with ``([`` return. \"\"\"", "test_start_out(self): \"\"\" The start index is out of range. \"\"\"", "Test the ``find_all_balanced``. \"\"\" def test_start_out(self): \"\"\" The start index", "\"\"\" Separators are not balanced. \"\"\" from wheezy.template.utils import find_balanced", "test_start_separator(self): \"\"\" If text doesn't start with ``start_sep`` return. \"\"\"", "4) assert 4 == find_balanced('test(a, b()', 4) def test_balanced(self): \"\"\"", "find_all_balanced('test([', 3) def test_not_balanced(self): \"\"\" Separators are not balanced. \"\"\"", "\"\"\" The start index is out of range. \"\"\" from", "== find_all_balanced('test(a, b', 4) assert 4 == find_all_balanced('test[a, b()', 4)" ]
[ "= pd.to_datetime(temp_df[\"index\"]) del temp_df[\"index\"] temp_df = temp_df[temp_df != 'Show All']", "macro_cons_gold_volume() print(macro_cons_gold_volume_df) macro_cons_gold_change_df = macro_cons_gold_change() print(macro_cons_gold_change_df) macro_cons_gold_amount_df = macro_cons_gold_amount() print(macro_cons_gold_amount_df)", "173.3 2019-06-13 102.9 147.1 52.9 21.1 237.0 472.4 271.0 117.4", ":return: pandas.Series 2004-11-18 0 2004-11-19 49.76 2004-11-22 29.24 2004-11-23 0.00", "= json.loads(res.text[res.text.find(\"{\"): res.text.rfind(\"}\") + 1]) date_list = [item[\"date\"] for item", "JS_CONS_SLIVER_ETF_URL, JS_CONS_OPEC_URL, ) def macro_cons_gold_volume(): \"\"\" 全球最大黄金ETF—SPDR Gold Trust持仓报告, 数据区间从20041118-至今", "inplace=True) temp_df = temp_df.squeeze() temp_df.index.name = None temp_df.name = \"silver_volume\"", "'安哥拉', '厄瓜多尔', '加蓬', '伊朗', '伊拉克', '科威特', '利比亚', '尼日利亚', '沙特', '阿联酋',", "-6.23 -2.60 -1.82 2017-06-13 0.23 -1.80 -0.77 33.61 2017-07-12 5.13", "2018-10-11 104.9 151.9 53.1 18.7 344.7 465.0 281.2 105.3 174.8", "= requests.get(url, params=params, headers=headers) temp_se = pd.DataFrame(r.json()[\"data\"][\"values\"]).iloc[:, [0, 1]] temp_se.index", "270.0 96.2 186.1 2018-04-12 98.4 152.4 51.8 18.3 381.4 442.6", "995.9 287.2 143.6 3193.0 2018-06-12 998.7 286.5 139.2 3186.9 2018-07-11", "2019-10-22 43907962483.56 2019-10-23 44120217405.82 2019-10-24 44120217405.82 \"\"\" t = time.time()", "-0.40 -14.20 -22.10 2019-04-10 -32.40 -0.90 -28.90 -53.40 2019-06-13 -7.60", "macro_cons_silver_change() print(macro_cons_silver_change_df) macro_cons_silver_amount_df = macro_cons_silver_amount() print(macro_cons_silver_amount_df) print(pd.concat([macro_cons_silver_volume_df, macro_cons_silver_change_df, macro_cons_silver_amount_df], axis=1))", "8.55 -0.63 -4.25 3.54 2018-07-11 40.54 3.51 -4.75 17.34 2018-08-13", "143.6 3193.0 2018-06-12 998.7 286.5 139.2 3186.9 2018-07-11 1042.0 289.7", "2018-04-12 -4.69 4.49 -5.53 -20.14 2018-05-14 4.65 0.61 -4.17 1.21", "0.18 -1.13 -13.10 -0.37 4.23 -5.44 2017-12-13 1.41 -10.87 -0.51", "temp_df = temp_df[['阿尔及利亚', '安哥拉', '厄瓜多尔', '加蓬', '伊朗', '伊拉克', '科威特', '利比亚',", "requests.get(url) data_json = r.json() append_temp_df = pd.DataFrame(data_json[\"values\"]).T append_temp_df.columns = [item[\"name\"]", "for item in data_json[\"keys\"]] temp_append_df = append_temp_df[\"增持/减持\"] temp_append_df.name = \"silver_change\"", "2.30 -22.70 9.40 1.30 -0.30 -9.20 沙特 阿联酋 委内瑞拉 欧佩克产量", "'委内瑞拉', '欧佩克产量']].iloc[-2, :] except: temp_df = temp_df[['阿尔及利亚', '安哥拉', '加蓬', '伊朗',", "270.1 95.5 171.1 2018-07-11 103.9 143.1 51.9 19.0 379.9 453.3", "70.8 166.0 2018-08-13 106.2 145.6 52.5 18.8 373.7 455.6 279.1", "0.03 -6.16 5.08 2017-06-13 0.96 -5.42 0.22 -0.13 0.45 4.44", "3.18 -0.67 -1.58 17.26 2017-09-12 -1.03 -2.02 -3.19 -7.91 2017-10-11", "2017-12-13 1.41 -10.87 -0.51 -0.47 -0.22 0.10 -0.53 0.61 9.58", "66.4 166.7 2018-09-12 104.5 144.8 52.9 18.7 358.4 464.9 280.2", "inplace=True) temp_df = temp_df.squeeze() temp_df.index.name = None temp_df.name = \"silver_amount\"", "temp_se.iloc[:, 1] temp_df = temp_df.append(temp_se) temp_df.dropna(inplace=True) temp_df.sort_index(inplace=True) temp_df = temp_df.reset_index()", "-22.10 2019-04-10 -32.40 -0.90 -28.90 -53.40 2019-06-13 -7.60 0.30 -3.50", "179.1 2018-06-12 103.1 152.5 51.9 18.9 382.9 445.5 270.1 95.5", "数据区间从 20170118-至今 这里返回的具体索引日期的数据为上一个月的数据, 由于某些国家的数据有缺失 只选择有数据的国家返回 20200312:fix:由于 “厄瓜多尔” 已经有几个月没有更新数据,在这里加以剔除 https://datacenter.jin10.com/reportType/dc_opec_report :return:", "value_df = pd.DataFrame(value_list) value_df.columns = json_data[\"kinds\"] value_df.index = pd.to_datetime(date_list) temp_df", "2017-05-11 104.7 169.2 52.4 20.6 375.9 437.3 270.2 55.0 150.8", "temp_df.append(temp_append_df.reset_index()) temp_df.drop_duplicates(subset=[\"index\"], keep=\"last\", inplace=True) temp_df.index = pd.to_datetime(temp_df[\"index\"]) del temp_df[\"index\"] temp_df", "bar = tqdm(reversed(all_date_list)) for item in bar: bar.set_description(f\"Please wait for", "74.1 2987.6 \"\"\" t = time.time() res = requests.get( JS_CONS_OPEC_URL.format(", "x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36\", \"x-app-id\": \"rU6QIu7JHe2gOUeR\", \"x-csrf-token\":", "105.4 153.3 52.5 18.6 329.6 465.4 276.4 111.4 175.1 2018-12-12", "t = time.time() res = requests.get( JS_CONS_GOLD_ETF_URL.format( str(int(round(t * 1000))),", "6.06 -0.02 12.70 9.67 2017-08-10 -0.10 -1.93 0.85 0.71 0.69", "0.08 0.69 -0.83 2018-06-12 3.90 1.40 0.06 0.18 0.56 2.77", "173.3 沙特 阿联酋 委内瑞拉 欧佩克产量 2017-01-18 1047.4 307.1 202.1 3308.5", "str(int(round(t * 1000)) + 90) ) ) json_data = json.loads(res.text[res.text.find(\"{\"):", "379.5 442.4 270.5 73.0 168.0 2017-07-12 106.0 166.8 52.7 19.7", "1000.0 291.1 186.3 3258.9 2017-12-13 999.6 288.3 183.4 3244.8 2018-01-18", "-14.12 6.47 10.18 2017-03-14 -0.02 -1.82 -0.44 -0.69 3.61 -6.20", "keep=\"last\", inplace=True) temp_df.index = pd.to_datetime(temp_df[\"index\"]) del temp_df[\"index\"] temp_df = temp_df[temp_df", "358.4 464.9 280.2 92.6 172.5 2018-10-11 104.9 151.9 53.1 18.7", "* 1000)))}\", headers=headers) # 日期序列 all_date_list = res.json()[\"data\"] need_date_list =", "342.11 2006-05-04 202.15 2006-05-05 108.86 ... 2019-10-17 -58.16 2019-10-18 0.00", "!= 'Show All'] temp_df.sort_index(inplace=True) temp_df = temp_df.astype(float) return temp_df def", "147.1 52.9 21.1 237.0 472.4 271.0 117.4 173.3 沙特 阿联酋", "-1.60 -13.95 2017-04-12 4.16 -3.27 -2.59 -15.27 2017-05-11 4.92 -6.23", "2019-10-17 -58.16 2019-10-18 0.00 2019-10-21 -34.89 2019-10-22 -61.06 2019-10-23 0.00", "\"cors\", \"sec-fetch-site\": \"same-site\", \"user-agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64)", "-0.40 2.20 -0.30 0.30 -15.60 465.30 -3.30 6.00 -1.70 2018-12-12", "-4.25 3.54 2018-07-11 40.54 3.51 -4.75 17.34 2018-08-13 -5.28 6.92", "2018-05-14 1.77 -0.78 0.31 -0.93 1.00 -0.07 0.08 0.69 -0.83", "= { \"max_date\": \"\", \"category\": \"etf\", \"attr_id\": \"1\", \"_\": str(int(round(t", "2018-07-11 1042.0 289.7 134.0 3232.7 2018-08-13 1038.7 295.9 127.8 3232.3", "-1.80 -0.77 33.61 2017-07-12 5.13 -0.07 -1.36 39.35 2017-08-10 3.18", "temp_df.columns = temp_df.iloc[0, :] temp_df = temp_df.iloc[1:, :] try: temp_df", "params = { \"max_date\": \"\", \"category\": \"etf\", \"attr_id\": \"2\", \"_\":", "0.88 -3.47 -3.91 0.03 -6.16 5.08 2017-06-13 0.96 -5.42 0.22", ":return: pandas.Series 阿尔及利亚 安哥拉 厄瓜多尔 加蓬 伊朗 伊拉克 科威特 利比亚", "headers=headers) temp_df = pd.DataFrame(res.json()[\"data\"][\"values\"], columns=pd.DataFrame(res.json()[\"data\"][\"keys\"])[\"name\"].tolist()).T temp_df.columns = temp_df.iloc[0, :] temp_df", "requests.get(url, params=params, headers=headers) temp_se = pd.DataFrame(r.json()[\"data\"][\"values\"]).iloc[:, :2] temp_se.index = pd.to_datetime(temp_se.iloc[:,", "270.2 62.2 154.5 2017-05-11 104.7 169.2 52.4 20.6 375.9 437.3", "2018-01-18 991.8 287.8 174.5 3241.6 2018-04-12 993.4 286.4 148.8 3195.8", "21.4 269.8 452.2 270.9 109.8 173.3 2019-06-13 102.9 147.1 52.9", "= value_df[\"总价值(美元)\"] url = \"https://datacenter-api.jin10.com/reports/list_v2\" params = { \"max_date\": \"\",", "279.1 66.4 166.7 2018-09-12 104.5 144.8 52.9 18.7 358.4 464.9", "= pd.DataFrame(res.json()[\"data\"][\"values\"], columns=pd.DataFrame(res.json()[\"data\"][\"keys\"])[\"name\"].tolist()).T temp_df.columns = temp_df.iloc[0, :] temp_df = temp_df[['阿尔及利亚',", "* 1000)))}\", headers=headers) temp_df = pd.DataFrame(res.json()[\"data\"][\"values\"], columns=pd.DataFrame(res.json()[\"data\"][\"keys\"])[\"name\"].tolist()).T temp_df.columns = temp_df.iloc[0,", "} headers = { \"accept\": \"*/*\", \"accept-encoding\": \"gzip, deflate, br\",", "295.4 463.1 280.9 110.4 173.6 2019-03-14 102.6 145.7 52.2 20.3", "temp_df.iloc[1:, :] try: temp_df = temp_df[['阿尔及利亚', '安哥拉', '加蓬', '伊朗', '伊拉克',", "return big_df.T def macro_cons_opec_month(): \"\"\" 欧佩克报告-月度, 数据区间从 20170118-至今 这里返回的具体索引日期的数据为上一个月的数据, 由于某些国家的数据有缺失", "temp_df.squeeze() temp_df.index.name = None temp_df.name = \"silver_change\" url = \"https://cdn.jin10.com/data_center/reports/etf_2.json\"", "= pd.to_datetime(date_list) temp_df = value_df[\"上个月\"] temp_df.name = country big_df =", ":] big_df[item] = temp_df return big_df.T def macro_cons_opec_month(): \"\"\" 欧佩克报告-月度,", "= big_df.T big_df.columns.name = \"日期\" big_df = big_df.astype(float) return big_df", "-0.17 5.39 5.08 2017-11-13 -3.84 6.98 0.71 0.18 -1.13 -13.10", "999.4 289.5 197.2 3192.8 2017-05-11 995.4 284.2 195.6 3173.2 2017-06-13", ":] big_df[temp_df.name] = temp_df big_df = big_df.T big_df.columns.name = \"日期\"", "Silver Trust持仓报告, 数据区间从20060429-至今 :return: pandas.Series 2006-04-29 263651152 2006-05-02 263651152 2006-05-03", "2019-10-21 -34.89 2019-10-22 -61.06 2019-10-23 0.00 \"\"\" t = time.time()", "169.2 52.4 20.6 375.9 437.3 270.2 55.0 150.8 2017-06-13 105.9", "= temp_df.iloc[0, :] temp_df = temp_df[['阿尔及利亚', '安哥拉', '厄瓜多尔', '加蓬', '伊朗',", "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36\", \"x-app-id\": \"rU6QIu7JHe2gOUeR\", \"x-csrf-token\": \"\",", "== \"__main__\": macro_cons_gold_volume_df = macro_cons_gold_volume() print(macro_cons_gold_volume_df) macro_cons_gold_change_df = macro_cons_gold_change() print(macro_cons_gold_change_df)", "0.56 2.77 -0.57 -2.43 -5.35 2018-07-11 0.46 -8.83 -0.09 0.35", "6.92 -4.77 4.07 2018-09-12 3.80 1.20 -3.60 27.80 2018-10-11 10.80", "= \"silver_change\" url = \"https://cdn.jin10.com/data_center/reports/etf_2.json\" r = requests.get(url) data_json =", "6.00 -1.70 2018-12-12 -0.50 0.30 0.10 -1.10 -38.00 -2.30 4.50", "数据区间从20060429-至今 :return: pandas.Series 2006-04-29 653.17 2006-05-02 653.17 2006-05-03 995.28 2006-05-04", "-0.37 4.23 -5.44 2017-12-13 1.41 -10.87 -0.51 -0.47 -0.22 0.10", "1000)))}\", headers=headers) # 日期序列 all_date_list = res.json()[\"data\"] need_date_list = [item", "1000)))}\", headers=headers) temp_df = pd.DataFrame(res.json()[\"data\"][\"values\"], columns=pd.DataFrame(res.json()[\"data\"][\"keys\"])[\"name\"].tolist()).T temp_df.columns = temp_df.iloc[0, :]", "[item[\"datas\"][country] for item in json_data[\"list\"]] value_df = pd.DataFrame(value_list) value_df.columns =", "-0.28 0.19 -2.87 -0.85 -0.95 -6.08 -2.98 2017-05-11 -0.75 9.71", "-4.20 13.20 2018-11-13 12.70 14.20 -4.00 12.70 2018-12-12 37.70 7.10", "\"gold_change\" temp_df = temp_df.astype(float) return temp_df def macro_cons_gold_amount(): \"\"\" 全球最大黄金ETF—SPDR", "temp_df = temp_df.squeeze() temp_df.index.name = None temp_df.name = \"gold_amount\" temp_df", "-0.22 0.10 -0.53 0.61 9.58 2018-01-18 3.03 4.48 -0.72 -0.01", "in data_json[\"keys\"]] temp_append_df = append_temp_df[\"总库存\"] temp_append_df.name = \"silver_volume\" temp_df =", "-1.70 2018-12-12 -0.50 0.30 0.10 -1.10 -38.00 -2.30 4.50 -1.10", "2017-10-11 -0.07 -0.84 -5.19 8.85 2017-11-13 1.69 -0.60 -4.36 -15.09", "+ 1]) date_list = [item[\"date\"] for item in json_data[\"list\"]] value_list", "0.22 -0.13 0.45 4.44 0.00 17.82 17.42 2017-07-12 -0.09 6.60", "0 2004-11-19 49.76 2004-11-22 29.24 2004-11-23 0.00 2004-11-24 9.33 ...", "temp_df = temp_df.squeeze() temp_df.index.name = None temp_df.name = \"gold_change\" temp_df", "\"category\": \"etf\", \"attr_id\": \"1\", \"_\": str(int(round(t * 1000))), } headers", "-3.72 1.82 2018-05-14 1.77 -0.78 0.31 -0.93 1.00 -0.07 0.08", "381.4 441.4 270.9 66.9 160.8 2017-04-12 105.6 161.4 52.6 19.8", "temp_df.index.name = None temp_df.name = \"gold_volume\" temp_df = temp_df.astype(float) return", "3186.9 2018-07-11 1042.0 289.7 134.0 3232.7 2018-08-13 1038.7 295.9 127.8", "欧佩克报告-月度, 数据区间从 20170118-至今 这里返回的具体索引日期的数据为上一个月的数据, 由于某些国家的数据有缺失 只选择有数据的国家返回 20200312:fix:由于 “厄瓜多尔” 已经有几个月没有更新数据,在这里加以剔除 https://datacenter.jin10.com/reportType/dc_opec_report", "52.6 19.4 381.4 441.4 270.9 66.9 160.8 2017-04-12 105.6 161.4", "这里返回的具体索引日期的数据为上一个月的数据, 由于某些国家的数据有缺失, 只选择有数据的国家返回 :return: pandas.Series 阿尔及利亚 安哥拉 厄瓜多尔 加蓬 伊朗", "JS_CONS_GOLD_ETF_URL, JS_CONS_SLIVER_ETF_URL, JS_CONS_OPEC_URL, ) def macro_cons_gold_volume(): \"\"\" 全球最大黄金ETF—SPDR Gold Trust持仓报告,", "沙特 阿联酋 委内瑞拉 欧佩克产量 2017-01-18 1047.4 307.1 202.1 3308.5 2017-02-13", "= macro_cons_silver_amount() print(macro_cons_silver_amount_df) print(pd.concat([macro_cons_silver_volume_df, macro_cons_silver_change_df, macro_cons_silver_amount_df], axis=1)) macro_cons_opec_near_change_df = macro_cons_opec_near_change()", ":return: pandas.Series 2004-11-18 114920000.00 2004-11-19 828806907.20 2004-11-22 1253785205.50 2004-11-23 1254751438.19", "= [item[\"name\"] for item in data_json[\"keys\"]] temp_append_df = append_temp_df[\"总价值\"] temp_append_df.name", "temp_df.squeeze() temp_df.index.name = None temp_df.name = \"gold_amount\" temp_df = temp_df.astype(float)", "return temp_df def macro_cons_gold_amount(): \"\"\" 全球最大黄金ETF—SPDR Gold Trust持仓报告, 数据区间从20041118-至今 :return:", "995.28 2006-05-04 1197.43 2006-05-05 1306.29 ... 2019-10-17 11847.91 2019-10-18 11847.91", "44120217405.82 \"\"\" t = time.time() res = requests.get( JS_CONS_GOLD_ETF_URL.format( str(int(round(t", "temp_df = value_df[\"上个月\"] temp_df.name = country big_df = big_df.append(temp_df) except:", "104.9 151.9 53.1 18.7 344.7 465.0 281.2 105.3 174.8 2018-11-13", "-3.91 0.03 -6.16 5.08 2017-06-13 0.96 -5.42 0.22 -0.13 0.45", "329.6 465.4 276.4 111.4 175.1 2018-12-12 105.2 152.1 52.5 17.6", "3256.5 2018-10-11 1051.2 300.4 119.7 3276.1 2018-11-13 1063.0 316.0 117.1", "-13.95 2017-04-12 4.16 -3.27 -2.59 -15.27 2017-05-11 4.92 -6.23 -2.60", "2017-07-12 995.0 289.8 193.8 3261.1 2017-08-10 1006.7 290.5 193.2 3286.9", "temp_append_df = append_temp_df[\"总价值\"] temp_append_df.name = \"silver_amount\" temp_df = temp_df.reset_index() temp_df[\"index\"]", "-1.00 5.02 -16.57 -14.12 6.47 10.18 2017-03-14 -0.02 -1.82 -0.44", "270.0 92.3 185.5 2017-11-13 101.2 171.1 54.1 20.3 382.3 438.3", "306.1 74.1 2987.6 \"\"\" t = time.time() big_df = pd.DataFrame()", "-1.18 2019-10-24 0.00 \"\"\" t = time.time() res = requests.get(", "'委内瑞拉', '欧佩克产量']].iloc[-1, :] big_df[temp_df.name] = temp_df big_df = big_df.T big_df.columns.name", "2987.6 \"\"\" t = time.time() big_df = pd.DataFrame() headers =", "19.7 381.8 439.6 270.3 97.3 179.0 2018-01-18 103.7 163.3 52.6", "headers=headers) # 日期序列 all_date_list = res.json()[\"data\"] need_date_list = [item for", "166.7 2018-09-12 104.5 144.8 52.9 18.7 358.4 464.9 280.2 92.6", "2019-10-21 44333677232.68 2019-10-22 43907962483.56 2019-10-23 44120217405.82 2019-10-24 44120217405.82 \"\"\" t", "[0, 2]] temp_se.index = pd.to_datetime(temp_se.iloc[:, 0]) temp_se = temp_se.iloc[:, 1]", "} r = requests.get(url, params=params, headers=headers) temp_se = pd.DataFrame(r.json()[\"data\"][\"values\"]).iloc[:, :2]", "'科威特', '利比亚', '尼日利亚', '沙特', '阿联酋', '委内瑞拉', '欧佩克产量']].iloc[-2, :] big_df[item] =", "1.41 -10.87 -0.51 -0.47 -0.22 0.10 -0.53 0.61 9.58 2018-01-18", "= [item[\"date\"] for item in json_data[\"list\"]] value_list = [item[\"datas\"][\"黄金\"] for", "2018-09-12 -1.40 -0.80 0.40 18.80 -15.00 9.00 0.80 25.60 7.40", ":] except: temp_df = temp_df[['阿尔及利亚', '安哥拉', '加蓬', '伊朗', '伊拉克', '科威特',", "-4.77 4.07 2018-09-12 3.80 1.20 -3.60 27.80 2018-10-11 10.80 3.00", "None temp_df.name = \"gold_change\" temp_df = temp_df.astype(float) return temp_df def", "2018-10-11 1051.2 300.4 119.7 3276.1 2018-11-13 1063.0 316.0 117.1 3290.0", "\"no-cache\", \"origin\": \"https://datacenter.jin10.com\", \"pragma\": \"no-cache\", \"referer\": \"https://datacenter.jin10.com/reportType/dc_usa_michigan_consumer_sentiment\", \"sec-fetch-dest\": \"empty\", \"sec-fetch-mode\":", "= [item[\"date\"] for item in json_data[\"list\"]] big_df = pd.DataFrame() for", "日期序列 all_date_list = res.json()[\"data\"] bar = tqdm(reversed(all_date_list[:-1])) for item in", "2017-10-11 997.5 290.5 189.0 3274.8 2017-11-13 1000.0 291.1 186.3 3258.9", "\"accept-language\": \"zh-CN,zh;q=0.9,en;q=0.8\", \"cache-control\": \"no-cache\", \"origin\": \"https://datacenter.jin10.com\", \"pragma\": \"no-cache\", \"referer\": \"https://datacenter.jin10.com/reportType/dc_usa_michigan_consumer_sentiment\",", "10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.117 Safari/537.36\", \"x-app-id\":", "105.6 161.4 52.6 19.8 379.0 440.2 270.2 62.2 154.5 2017-05-11", "1047.4 307.1 202.1 3308.5 2017-02-13 994.6 293.1 200.4 3213.9 2017-03-14", "0.50 0.70 1.20 -7.00 -1.40 2.30 1.00 2019-04-10 -0.70 0.70", "阿尔及利亚 安哥拉 厄瓜多尔 加蓬 伊朗 伊拉克 科威特 利比亚 尼日利亚 \\", "104.6 164.1 53.6 20.1 382.7 449.4 270.0 92.3 185.5 2017-11-13", "-1.31 0.23 -3.72 1.82 2018-05-14 1.77 -0.78 0.31 -0.93 1.00", "-1.10 2019-03-14 -8.60 -0.40 -14.20 -22.10 2019-04-10 -32.40 -0.90 -28.90", "19.9 377.5 447.6 271.8 67.5 157.6 2017-03-14 105.3 164.1 52.6", "160.8 2017-04-12 105.6 161.4 52.6 19.8 379.0 440.2 270.2 62.2", "\"__main__\": macro_cons_gold_volume_df = macro_cons_gold_volume() print(macro_cons_gold_volume_df) macro_cons_gold_change_df = macro_cons_gold_change() print(macro_cons_gold_change_df) macro_cons_gold_amount_df", "979.4 305.9 73.2 3002.2 2019-06-13 969.0 306.1 74.1 2987.6 \"\"\"", "19.60 1.10 2019-06-13 0.60 7.40 -0.10 2.30 -22.70 9.40 1.30", "5.70 53.10 -0.10 -15.00 0.80 0.60 10.30 2.60 2018-11-13 -0.40", "\"cache-control\": \"no-cache\", \"origin\": \"https://datacenter.jin10.com\", \"pragma\": \"no-cache\", \"referer\": \"https://datacenter.jin10.com/reportType/dc_opec_report\", \"sec-fetch-mode\": \"cors\",", "-1.82 2017-06-13 0.23 -1.80 -0.77 33.61 2017-07-12 5.13 -0.07 -1.36", "+ 90) ) ) json_data = json.loads(res.text[res.text.find(\"{\"): res.text.rfind(\"}\") + 1])", "270.2 89.0 186.1 2017-10-11 104.6 164.1 53.6 20.1 382.7 449.4", "pd.to_datetime(date_list) temp_df = value_df[\"增持/减持(吨)\"] url = \"https://datacenter-api.jin10.com/reports/list_v2\" params = {", "37.70 7.10 -5.20 -1.10 2019-03-14 -8.60 -0.40 -14.20 -22.10 2019-04-10", "101.2 171.1 54.1 20.3 382.3 438.3 270.8 96.2 173.8 2017-12-13", "2017-04-12 4.16 -3.27 -2.59 -15.27 2017-05-11 4.92 -6.23 -2.60 -1.82", ":return: pandas.Series 2006-04-29 653.17 2006-05-02 653.17 2006-05-03 995.28 2006-05-04 1197.43", "979.7 292.5 198.7 3195.8 2017-04-12 999.4 289.5 197.2 3192.8 2017-05-11", "172.4 54.5 21.3 372.0 463.2 281.2 60.8 154.2 2017-02-13 104.5", "157.6 2017-03-14 105.3 164.1 52.6 19.4 381.4 441.4 270.9 66.9", "3195.8 2017-04-12 999.4 289.5 197.2 3192.8 2017-05-11 995.4 284.2 195.6", "379.9 453.3 273.1 70.8 166.0 2018-08-13 106.2 145.6 52.5 18.8", "= requests.get(url, params=params, headers=headers) temp_se = pd.DataFrame(r.json()[\"data\"][\"values\"]).iloc[:, [0, 2]] temp_se.index", "for item in data_json[\"keys\"]] temp_append_df = append_temp_df[\"总库存\"] temp_append_df.name = \"silver_volume\"", "3274.8 2017-11-13 1000.0 291.1 186.3 3258.9 2017-12-13 999.6 288.3 183.4", "1197.43 2006-05-05 1306.29 ... 2019-10-17 11847.91 2019-10-18 11847.91 2019-10-21 11813.02", "except: continue headers = { \"accept\": \"*/*\", \"accept-encoding\": \"gzip, deflate,", "数据区间从20170118-至今 :return: pandas.Series 阿尔及利亚 安哥拉 厄瓜多尔 加蓬 伊朗 伊拉克 科威特", "-1.10 -38.00 -2.30 4.50 -1.10 -3.00 2019-03-14 0.20 2.20 0.50", "-5.63 2.41 7.85 -5.67 7.05 2018-09-12 -1.40 -0.80 0.40 18.80", "2017-07-12 5.13 -0.07 -1.36 39.35 2017-08-10 3.18 -0.67 -1.58 17.26", "287.2 143.6 3193.0 2018-06-12 998.7 286.5 139.2 3186.9 2018-07-11 1042.0", "tqdm from akshare.economic.cons import ( JS_CONS_GOLD_ETF_URL, JS_CONS_SLIVER_ETF_URL, JS_CONS_OPEC_URL, ) def", "-0.25 -0.87 0.95 4.26 0.20 3.13 -11.35 2017-02-13 -4.17 -2.32", "295.9 127.8 3232.3 2018-09-12 1040.1 297.2 123.5 3256.5 2018-10-11 1051.2", "[item[\"name\"] for item in data_json[\"keys\"]] temp_append_df = append_temp_df[\"增持/减持\"] temp_append_df.name =", "-3.31 -0.74 15.43 3.43 2017-09-12 0.41 0.83 -0.03 -3.23 -0.23", "154.2 2017-02-13 104.5 165.1 52.7 19.9 377.5 447.6 271.8 67.5", "-0.47 -0.22 0.10 -0.53 0.61 9.58 2018-01-18 3.03 4.48 -0.72", "'沙特', '阿联酋', '委内瑞拉', '欧佩克产量']].iloc[-2, :] except: temp_df = temp_df[['阿尔及利亚', '安哥拉',", "append_temp_df.columns = [item[\"name\"] for item in data_json[\"keys\"]] temp_append_df = append_temp_df[\"总库存\"]", "2018-04-12 98.4 152.4 51.8 18.3 381.4 442.6 270.4 96.8 181.0", "-10.87 -0.51 -0.47 -0.22 0.10 -0.53 0.61 9.58 2018-01-18 3.03", "pd.DataFrame(r.json()[\"data\"][\"values\"]).iloc[:, [0, 1]] temp_se.index = pd.to_datetime(temp_se.iloc[:, 0]) temp_se = temp_se.iloc[:,", "temp_df.astype(float) return temp_df def macro_cons_silver_change(): \"\"\" 全球最大白银ETF--iShares Silver Trust持仓报告, 数据区间从20060429-至今", "item.split(\"-\")[0] + item.split(\"-\")[1] + item.split(\"-\")[2] not in date_list] for item", "\"gold_volume\" temp_df = temp_df.astype(float) return temp_df def macro_cons_gold_change(): \"\"\" 全球最大黄金ETF—SPDR", "2018-07-11 40.54 3.51 -4.75 17.34 2018-08-13 -5.28 6.92 -4.77 4.07", "179.0 2018-01-18 103.7 163.3 52.6 19.7 382.9 440.5 270.0 96.2", "data_json[\"keys\"]] temp_append_df = append_temp_df[\"总价值\"] temp_append_df.name = \"silver_amount\" temp_df = temp_df.reset_index()", "temp_df = value_df[\"总价值(美元)\"] url = \"https://datacenter-api.jin10.com/reports/list_v2\" params = { \"max_date\":", "1.10 2019-06-13 0.60 7.40 -0.10 2.30 -22.70 9.40 1.30 -0.30", "2017-08-10 105.9 164.6 53.6 20.5 382.4 446.8 270.3 100.1 174.8", "-3.27 -2.59 -15.27 2017-05-11 4.92 -6.23 -2.60 -1.82 2017-06-13 0.23", "All'] temp_df.sort_index(inplace=True) temp_df = temp_df.astype(float) return temp_df def macro_cons_silver_amount(): \"\"\"", "= macro_cons_gold_volume() print(macro_cons_gold_volume_df) macro_cons_gold_change_df = macro_cons_gold_change() print(macro_cons_gold_change_df) macro_cons_gold_amount_df = macro_cons_gold_amount()", "\"category\": \"etf\", \"attr_id\": \"2\", \"_\": str(int(round(t * 1000))), } headers", "= country big_df = big_df.append(temp_df) except: continue headers = {", "379.0 450.2 270.9 85.2 173.3 2017-08-10 105.9 164.6 53.6 20.5", "189.0 3274.8 2017-11-13 1000.0 291.1 186.3 3258.9 2017-12-13 999.6 288.3", "append_temp_df.columns = [item[\"name\"] for item in data_json[\"keys\"]] temp_append_df = append_temp_df[\"总价值\"]", "value_list = [item[\"datas\"][country] for item in json_data[\"list\"]] value_df = pd.DataFrame(value_list)", "\"accept-language\": \"zh-CN,zh;q=0.9,en;q=0.8\", \"cache-control\": \"no-cache\", \"origin\": \"https://datacenter.jin10.com\", \"pragma\": \"no-cache\", \"referer\": \"https://datacenter.jin10.com/reportType/dc_opec_report\",", "temp_df = temp_df.astype(float) return temp_df def macro_cons_gold_amount(): \"\"\" 全球最大黄金ETF—SPDR Gold", "0.60 7.40 -0.10 2.30 -22.70 9.40 1.30 -0.30 -9.20 沙特", "\"\"\" 全球最大白银ETF--iShares Silver Trust持仓报告, 数据区间从20060429-至今 :return: pandas.Series 2006-04-29 263651152 2006-05-02", "-0.06 0.88 -3.47 -3.91 0.03 -6.16 5.08 2017-06-13 0.96 -5.42", "\"pragma\": \"no-cache\", \"referer\": \"https://datacenter.jin10.com/reportType/dc_usa_michigan_consumer_sentiment\", \"sec-fetch-dest\": \"empty\", \"sec-fetch-mode\": \"cors\", \"sec-fetch-site\": \"same-site\",", "import ( JS_CONS_GOLD_ETF_URL, JS_CONS_SLIVER_ETF_URL, JS_CONS_OPEC_URL, ) def macro_cons_gold_volume(): \"\"\" 全球最大黄金ETF—SPDR", "macro_cons_opec_month(): \"\"\" 欧佩克报告-月度, 数据区间从 20170118-至今 这里返回的具体索引日期的数据为上一个月的数据, 由于某些国家的数据有缺失 只选择有数据的国家返回 20200312:fix:由于 “厄瓜多尔”", "2017-04-12 999.4 289.5 197.2 3192.8 2017-05-11 995.4 284.2 195.6 3173.2", "7.05 2018-09-12 -1.40 -0.80 0.40 18.80 -15.00 9.00 0.80 25.60", "temp_df = temp_df.squeeze() temp_df.index.name = None temp_df.name = \"gold_volume\" temp_df", "\"\"\" import json import time import pandas as pd import", "temp_append_df.name = \"silver_change\" temp_df = temp_df.reset_index() temp_df[\"index\"] = temp_df[\"index\"].astype(str) temp_df", "117.4 173.3 沙特 阿联酋 委内瑞拉 欧佩克产量 2017-01-18 1047.4 307.1 202.1", "0]) temp_se = temp_se.iloc[:, 1] temp_df = temp_df.append(temp_se) temp_df.dropna(inplace=True) temp_df.sort_index(inplace=True)", "temp_df.squeeze() temp_df.index.name = None temp_df.name = \"silver_volume\" url = \"https://cdn.jin10.com/data_center/reports/etf_2.json\"", "270.9 85.2 173.3 2017-08-10 105.9 164.6 53.6 20.5 382.4 446.8", "0.85 0.71 0.69 -3.31 -0.74 15.43 3.43 2017-09-12 0.41 0.83", "big_df.columns.name = \"日期\" big_df = big_df.astype(float) return big_df if __name__", "big_df.T big_df.columns.name = \"日期\" big_df = big_df.astype(float) return big_df if", "4.50 -1.10 -3.00 2019-03-14 0.20 2.20 0.50 0.70 1.20 -7.00", "\"user-agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like", "2018-06-12 103.1 152.5 51.9 18.9 382.9 445.5 270.1 95.5 171.1", "6.60 -0.21 -0.77 1.67 6.06 -0.02 12.70 9.67 2017-08-10 -0.10", "params=params, headers=headers) temp_se = pd.DataFrame(r.json()[\"data\"][\"values\"]).iloc[:, [0, 2]] temp_se.index = pd.to_datetime(temp_se.iloc[:,", "temp_df.name = \"silver_volume\" url = \"https://cdn.jin10.com/data_center/reports/etf_2.json\" r = requests.get(url) data_json", "52.5 18.6 329.6 465.4 276.4 111.4 175.1 2018-12-12 105.2 152.1", "2019-06-13 969.0 306.1 74.1 2987.6 \"\"\" t = time.time() res", "-5.20 -1.10 2019-03-14 -8.60 -0.40 -14.20 -22.10 2019-04-10 -32.40 -0.90", "= temp_df.iloc[1:, :] try: temp_df = temp_df[['阿尔及利亚', '安哥拉', '加蓬', '伊朗',", "0.23 -1.80 -0.77 33.61 2017-07-12 5.13 -0.07 -1.36 39.35 2017-08-10", "None temp_df.name = \"silver_amount\" url = \"https://cdn.jin10.com/data_center/reports/etf_2.json\" r = requests.get(url)", "154.5 2017-05-11 104.7 169.2 52.4 20.6 375.9 437.3 270.2 55.0", "2019-10-22 -61.06 2019-10-23 0.00 \"\"\" t = time.time() res =", "8.85 2017-11-13 1.69 -0.60 -4.36 -15.09 2017-12-13 -4.54 -3.55 -4.16", "macro_cons_silver_volume() print(macro_cons_silver_volume_df) macro_cons_silver_change_df = macro_cons_silver_change() print(macro_cons_silver_change_df) macro_cons_silver_amount_df = macro_cons_silver_amount() print(macro_cons_silver_amount_df)", "438.3 270.8 96.2 173.8 2017-12-13 101.3 158.1 53.3 19.7 381.8", "-0.30 -9.20 沙特 阿联酋 委内瑞拉 欧佩克产量 2017-01-18 -14.93 -0.63 -4.52", "2017-05-11 4.92 -6.23 -2.60 -1.82 2017-06-13 0.23 -1.80 -0.77 33.61", "-89.02 2017-03-14 -6.81 -3.69 -1.60 -13.95 2017-04-12 4.16 -3.27 -2.59", "1000))), str(int(round(t * 1000)) + 90) ) ) json_data =", "r = requests.get(url, params=params, headers=headers) temp_se = pd.DataFrame(r.json()[\"data\"][\"values\"]).iloc[:, :2] temp_se.index", "44286078486.23 2019-10-21 44333677232.68 2019-10-22 43907962483.56 2019-10-23 44120217405.82 2019-10-24 44120217405.82 \"\"\"", "-1.11 5.80 2017-04-12 0.45 -1.87 -0.28 0.19 -2.87 -0.85 -0.95", "2017-09-12 1002.2 290.1 191.8 3275.5 2017-10-11 997.5 290.5 189.0 3274.8", "json.loads(res.text[res.text.find(\"{\"): res.text.rfind(\"}\") + 1]) date_list = [item[\"date\"] for item in", "big_df[item] = temp_df return big_df.T def macro_cons_opec_month(): \"\"\" 欧佩克报告-月度, 数据区间从", "193.8 3261.1 2017-08-10 1006.7 290.5 193.2 3286.9 2017-09-12 1002.2 290.1", "= macro_cons_silver_change() print(macro_cons_silver_change_df) macro_cons_silver_amount_df = macro_cons_silver_amount() print(macro_cons_silver_amount_df) print(pd.concat([macro_cons_silver_volume_df, macro_cons_silver_change_df, macro_cons_silver_amount_df],", "-0.53 0.61 9.58 2018-01-18 3.03 4.48 -0.72 -0.01 1.32 0.79", "33.61 2017-07-12 5.13 -0.07 -1.36 39.35 2017-08-10 3.18 -0.67 -1.58", "969.0 306.1 74.1 2987.6 \"\"\" t = time.time() big_df =", "-0.77 1.67 6.06 -0.02 12.70 9.67 2017-08-10 -0.10 -1.93 0.85", "4.16 -3.27 -2.59 -15.27 2017-05-11 4.92 -6.23 -2.60 -1.82 2017-06-13", "-49.62 -15.93 -3.05 -89.02 2017-03-14 -6.81 -3.69 -1.60 -13.95 2017-04-12", "from tqdm import tqdm from akshare.economic.cons import ( JS_CONS_GOLD_ETF_URL, JS_CONS_SLIVER_ETF_URL,", "# 日期序列 all_date_list = res.json()[\"data\"] bar = tqdm(reversed(all_date_list[:-1])) for item", "temp_df.iloc[0, :] temp_df = temp_df[['阿尔及利亚', '安哥拉', '厄瓜多尔', '加蓬', '伊朗', '伊拉克',", "-*- # /usr/bin/env python \"\"\" Date: 2019/10/21 12:08 Desc: 获取金十数据-数据中心-主要机构-宏观经济", "'加蓬', '伊朗', '伊拉克', '科威特', '利比亚', '尼日利亚', '沙特', '阿联酋', '委内瑞拉', '欧佩克产量']].iloc[-2,", "temp_df.name = \"gold_amount\" temp_df = temp_df.astype(float) return temp_df def macro_cons_silver_volume():", "\"accept-encoding\": \"gzip, deflate, br\", \"accept-language\": \"zh-CN,zh;q=0.9,en;q=0.8\", \"cache-control\": \"no-cache\", \"origin\": \"https://datacenter.jin10.com\",", "19.7 379.0 450.2 270.9 85.2 173.3 2017-08-10 105.9 164.6 53.6", "temp_df = temp_df.astype(float) return temp_df def macro_cons_gold_change(): \"\"\" 全球最大黄金ETF—SPDR Gold", "21.3 372.0 463.2 281.2 60.8 154.2 2017-02-13 104.5 165.1 52.7", "= [item[\"name\"] for item in data_json[\"keys\"]] temp_append_df = append_temp_df[\"总库存\"] temp_append_df.name", "value_df[\"总库存(吨)\"] url = \"https://datacenter-api.jin10.com/reports/list_v2\" params = { \"max_date\": \"\", \"category\":", "temp_df = value_df[\"总库存(吨)\"] url = \"https://datacenter-api.jin10.com/reports/list_v2\" params = { \"max_date\":", "append_temp_df[\"总价值\"] temp_append_df.name = \"silver_amount\" temp_df = temp_df.reset_index() temp_df[\"index\"] = temp_df[\"index\"].astype(str)", "+ item.split(\"-\")[2] not in date_list] for item in reversed(need_date_list): res", "-4.17 -2.32 -1.67 -1.00 5.02 -16.57 -14.12 6.47 10.18 2017-03-14", "0.00 2019-10-21 -34.89 2019-10-22 -61.06 2019-10-23 0.00 \"\"\" t =", "temp_df.index.name = None temp_df.name = \"gold_amount\" temp_df = temp_df.astype(float) return", "date_list = [item[\"date\"] for item in json_data[\"list\"]] big_df = pd.DataFrame()", "173.8 2017-12-13 101.3 158.1 53.3 19.7 381.8 439.6 270.3 97.3", "\"pragma\": \"no-cache\", \"referer\": \"https://datacenter.jin10.com/reportType/dc_opec_report\", \"sec-fetch-mode\": \"cors\", \"sec-fetch-site\": \"same-site\", \"user-agent\": \"Mozilla/5.0", "= json_data[\"kinds\"] value_df.index = pd.to_datetime(date_list) temp_df = value_df[\"总库存(吨)\"] url =", "2.41 7.85 -5.67 7.05 2018-09-12 -1.40 -0.80 0.40 18.80 -15.00", "pd.to_datetime(temp_df[\"index\"]) del temp_df[\"index\"] temp_df = temp_df[temp_df != 'Show All'] temp_df.sort_index(inplace=True)", "加蓬 伊朗 伊拉克 科威特 利比亚 尼日利亚 \\ 2017-01-18 -0.87 3.56", "1000))), } headers = { \"accept\": \"*/*\", \"accept-encoding\": \"gzip, deflate,", "-0.02 -1.82 -0.44 -0.69 3.61 -6.20 -0.93 -1.11 5.80 2017-04-12", "2006-05-03 995.28 2006-05-04 1197.43 2006-05-05 1306.29 ... 2019-10-17 11847.91 2019-10-18", "-3.84 6.98 0.71 0.18 -1.13 -13.10 -0.37 4.23 -5.44 2017-12-13", "(KHTML, like Gecko) Chrome/79.0.3945.117 Safari/537.36\", \"x-app-id\": \"rU6QIu7JHe2gOUeR\", \"x-csrf-token\": \"\", \"x-version\":", "'阿联酋', '委内瑞拉', '欧佩克产量']].iloc[-1, :] except: temp_df = temp_df[['阿尔及利亚', '安哥拉', '加蓬',", "2017-11-13 1000.0 291.1 186.3 3258.9 2017-12-13 999.6 288.3 183.4 3244.8", "日期序列 all_date_list = res.json()[\"data\"] bar = tqdm(reversed(all_date_list)) for item in", "2017-07-12 -0.09 6.60 -0.21 -0.77 1.67 6.06 -0.02 12.70 9.67", "-0.93 -1.11 5.80 2017-04-12 0.45 -1.87 -0.28 0.19 -2.87 -0.85", "( JS_CONS_GOLD_ETF_URL, JS_CONS_SLIVER_ETF_URL, JS_CONS_OPEC_URL, ) def macro_cons_gold_volume(): \"\"\" 全球最大黄金ETF—SPDR Gold", "inplace=True) temp_df = temp_df.squeeze() temp_df.index.name = None temp_df.name = \"gold_amount\"", "= big_df.astype(float) return big_df if __name__ == \"__main__\": macro_cons_gold_volume_df =", "= requests.get( JS_CONS_OPEC_URL.format( str(int(round(t * 1000))), str(int(round(t * 1000)) +", "macro_cons_silver_amount_df = macro_cons_silver_amount() print(macro_cons_silver_amount_df) print(pd.concat([macro_cons_silver_volume_df, macro_cons_silver_change_df, macro_cons_silver_amount_df], axis=1)) macro_cons_opec_near_change_df =", "Gold Trust持仓报告, 数据区间从20041118-至今 :return: pandas.Series 2004-11-18 0 2004-11-19 49.76 2004-11-22", "4.24 2018-04-12 -4.69 4.49 -5.53 -20.14 2018-05-14 4.65 0.61 -4.17", "-0.10 2.30 -22.70 9.40 1.30 -0.30 -9.20 沙特 阿联酋 委内瑞拉", "164.6 53.6 20.5 382.4 446.8 270.3 100.1 174.8 2017-09-12 106.5", "pd.DataFrame(res.json()[\"data\"][\"values\"], columns=pd.DataFrame(res.json()[\"data\"][\"keys\"])[\"name\"].tolist()).T temp_df.columns = temp_df.iloc[0, :] temp_df = temp_df.iloc[1:, :]", "2017-09-12 106.5 164.6 53.7 17.3 382.8 444.8 270.2 89.0 186.1", "44333677232.68 2019-10-22 43907962483.56 2019-10-23 44120217405.82 2019-10-24 44120217405.82 \"\"\" t =", "= pd.DataFrame(r.json()[\"data\"][\"values\"]).iloc[:, [0, 1]] temp_se.index = pd.to_datetime(temp_se.iloc[:, 0]) temp_se =", "39.35 2017-08-10 3.18 -0.67 -1.58 17.26 2017-09-12 -1.03 -2.02 -3.19", "= json_data[\"kinds\"] value_df.index = pd.to_datetime(date_list) temp_df = value_df[\"总价值(美元)\"] url =", "-58.16 2019-10-18 0.00 2019-10-21 -34.89 2019-10-22 -61.06 2019-10-23 0.00 \"\"\"", "174.8 2017-09-12 106.5 164.6 53.7 17.3 382.8 444.8 270.2 89.0", "3232.3 2018-09-12 1040.1 297.2 123.5 3256.5 2018-10-11 1051.2 300.4 119.7", "tqdm(reversed(all_date_list)) for item in bar: bar.set_description(f\"Please wait for a moment,", "res = requests.get( JS_CONS_GOLD_ETF_URL.format( str(int(round(t * 1000))), str(int(round(t * 1000))", "沙特 阿联酋 委内瑞拉 欧佩克产量 2017-01-18 -14.93 -0.63 -4.52 -22.09 2017-02-13", "in json_data[\"list\"]] value_df = pd.DataFrame(value_list) value_df.columns = json_data[\"kinds\"] value_df.index =", "2018-10-11 10.80 3.00 -4.20 13.20 2018-11-13 12.70 14.20 -4.00 12.70", "value_df.index = pd.to_datetime(date_list) temp_df = value_df[\"增持/减持(吨)\"] url = \"https://datacenter-api.jin10.com/reports/list_v2\" params", "value_df.columns = json_data[\"kinds\"] value_df.index = pd.to_datetime(date_list) temp_df = value_df[\"总价值(美元)\"] url", "0.00 2006-05-03 342.11 2006-05-04 202.15 2006-05-05 108.86 ... 2019-10-17 -58.16", "17.26 2017-09-12 -1.03 -2.02 -3.19 -7.91 2017-10-11 -0.07 -0.84 -5.19", "[item[\"date\"] for item in json_data[\"list\"]] big_df = pd.DataFrame() for country", "-0.13 0.45 4.44 0.00 17.82 17.42 2017-07-12 -0.09 6.60 -0.21", "All 2019-10-22 Show All 2019-10-23 Show All \"\"\" t =", "temp_df.astype(float) return temp_df def macro_cons_silver_amount(): \"\"\" 全球最大白银ETF--iShares Silver Trust持仓报告, 数据区间从20060429-至今", "3.90 1.40 0.06 0.18 0.56 2.77 -0.57 -2.43 -5.35 2018-07-11", "53.6 20.5 382.4 446.8 270.3 100.1 174.8 2017-09-12 106.5 164.6", "temp_df.dropna(inplace=True) temp_df.sort_index(inplace=True) temp_df = temp_df.reset_index() temp_df.drop_duplicates(subset=\"index\", keep=\"last\", inplace=True) temp_df.set_index(\"index\", inplace=True)", "'沙特', '阿联酋', '委内瑞拉', '欧佩克产量']].iloc[-1, :] except: temp_df = temp_df[['阿尔及利亚', '安哥拉',", "-2.60 -1.82 2017-06-13 0.23 -1.80 -0.77 33.61 2017-07-12 5.13 -0.07", "= pd.to_datetime(date_list) temp_df = value_df[\"总价值(美元)\"] url = \"https://datacenter-api.jin10.com/reports/list_v2\" params =", "1390568824.08 ... 2019-10-20 44286078486.23 2019-10-21 44333677232.68 2019-10-22 43907962483.56 2019-10-23 44120217405.82", "x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.117 Safari/537.36\", \"x-app-id\": \"rU6QIu7JHe2gOUeR\", \"x-csrf-token\":", "\"\"\" 欧佩克报告-月度, 数据区间从20170118-至今 这里返回的具体索引日期的数据为上一个月的数据, 由于某些国家的数据有缺失, 只选择有数据的国家返回 :return: pandas.Series 阿尔及利亚 安哥拉", "1000)) + 90) ) ) json_data = json.loads(res.text[res.text.find(\"{\"): res.text.rfind(\"}\") +", "2.73 -25.43 2.78 2018-08-13 1.38 1.17 0.42 -0.34 -5.63 2.41", "200.4 3213.9 2017-03-14 979.7 292.5 198.7 3195.8 2017-04-12 999.4 289.5", "452.2 270.9 109.8 173.3 2019-06-13 102.9 147.1 52.9 21.1 237.0", "date_list = [item[\"date\"] for item in json_data[\"list\"]] value_list = [item[\"datas\"][\"白银\"]", "2019-10-22 919.66 2019-10-23 918.48 2019-10-24 918.48 \"\"\" t = time.time()", "return big_df if __name__ == \"__main__\": macro_cons_gold_volume_df = macro_cons_gold_volume() print(macro_cons_gold_volume_df)", "2017-11-13 -3.84 6.98 0.71 0.18 -1.13 -13.10 -0.37 4.23 -5.44", "2006-05-02 263651152 2006-05-03 445408550 2006-05-04 555123947 2006-05-05 574713264 ... 2019-10-17", "292.5 198.7 3195.8 2017-04-12 999.4 289.5 197.2 3192.8 2017-05-11 995.4", "0.31 -0.93 1.00 -0.07 0.08 0.69 -0.83 2018-06-12 3.90 1.40", "pd.to_datetime(date_list) temp_df = value_df[\"增持/减持(吨)\"] temp_df.name = \"silver_change\" url = \"https://datacenter-api.jin10.com/reports/list_v2\"", "270.4 96.8 181.0 2018-05-14 99.7 151.5 52.0 18.3 382.3 442.9", "273.1 70.8 166.0 2018-08-13 106.2 145.6 52.5 18.8 373.7 455.6", "197.2 3192.8 2017-05-11 995.4 284.2 195.6 3173.2 2017-06-13 994.0 288.5", "2018-01-18 3.03 4.48 -0.72 -0.01 1.32 0.79 -0.25 -0.70 7.57", "3.00 -4.20 13.20 2018-11-13 12.70 14.20 -4.00 12.70 2018-12-12 37.70", "Safari/537.36\", \"x-app-id\": \"rU6QIu7JHe2gOUeR\", \"x-csrf-token\": \"\", \"x-version\": \"1.0.0\", } res =", "= time.time() res = requests.get( JS_CONS_SLIVER_ETF_URL.format( str(int(round(t * 1000))), str(int(round(t", "-7.00 -1.40 2.30 1.00 2019-04-10 -0.70 0.70 52.40 0.90 -2.80", "1254751438.19 2004-11-24 1390568824.08 ... 2019-10-20 44286078486.23 2019-10-21 44333677232.68 2019-10-22 43907962483.56", "time.time() big_df = pd.DataFrame() headers = { \"accept\": \"*/*\", \"accept-encoding\":", "-5.42 0.22 -0.13 0.45 4.44 0.00 17.82 17.42 2017-07-12 -0.09", "res = requests.get(f\"https://datacenter-api.jin10.com/reports/dates?category=opec&_={str(int(round(t * 1000)))}\", headers=headers) # 日期序列 all_date_list =", "270.9 90.6 174.1 2019-04-10 101.8 145.4 52.4 21.4 269.8 452.2", "0.10 -1.10 -38.00 -2.30 4.50 -1.10 -3.00 2019-03-14 0.20 2.20", "json_data[\"kinds\"] value_df.index = pd.to_datetime(date_list) temp_df = value_df[\"上个月\"] temp_df.name = country", "101.8 145.4 52.4 21.4 269.8 452.2 270.9 109.8 173.3 2019-06-13", "big_df def _macro_cons_opec_month(): \"\"\" 欧佩克报告-月度, 数据区间从20170118-至今 这里返回的具体索引日期的数据为上一个月的数据, 由于某些国家的数据有缺失, 只选择有数据的国家返回 :return:", "2019-10-23 11751.96 \"\"\" t = time.time() res = requests.get( JS_CONS_SLIVER_ETF_URL.format(", "pd.DataFrame(r.json()[\"data\"][\"values\"]).iloc[:, [0, 2]] temp_se.index = pd.to_datetime(temp_se.iloc[:, 0]) temp_se = temp_se.iloc[:,", "All 2019-10-21 Show All 2019-10-22 Show All 2019-10-23 Show All", "\"etf\", \"attr_id\": \"1\", \"_\": str(int(round(t * 1000))), } headers =", "-0.72 -0.01 1.32 0.79 -0.25 -0.70 7.57 2018-04-12 -4.95 -8.17", "-1.67 -1.00 5.02 -16.57 -14.12 6.47 10.18 2017-03-14 -0.02 -1.82", "\"_\": str(int(round(t * 1000))), } headers = { \"accept\": \"*/*\",", "+ 1]) date_list = [item[\"date\"] for item in json_data[\"list\"]] big_df", "-7.60 0.30 -3.50 -23.60 \"\"\" t = time.time() big_df =", "value_df[\"增持/减持(吨)\"] temp_df.name = \"silver_change\" url = \"https://datacenter-api.jin10.com/reports/list_v2\" params = {", "temp_df = temp_df.reset_index() temp_df[\"index\"] = temp_df[\"index\"].astype(str) temp_df = temp_df.append(temp_append_df.reset_index()) temp_df.drop_duplicates(subset=[\"index\"],", "macro_cons_gold_change(): \"\"\" 全球最大黄金ETF—SPDR Gold Trust持仓报告, 数据区间从20041118-至今 :return: pandas.Series 2004-11-18 0", "... 2019-10-17 -58.16 2019-10-18 0.00 2019-10-21 -34.89 2019-10-22 -61.06 2019-10-23", "0.90 -2.80 -12.60 -0.10 19.60 1.10 2019-06-13 0.60 7.40 -0.10", "-1.87 -0.28 0.19 -2.87 -0.85 -0.95 -6.08 -2.98 2017-05-11 -0.75", "[item[\"name\"] for item in data_json[\"keys\"]] temp_append_df = append_temp_df[\"总价值\"] temp_append_df.name =", "\\ 2017-01-18 -0.87 3.56 -0.25 -0.87 0.95 4.26 0.20 3.13", "downing {item}'s data\") res = requests.get( f\"https://datacenter-api.jin10.com/reports/list?category=opec&date={item}&_={str(int(round(t * 1000)))}\", headers=headers)", "全球最大黄金ETF—SPDR Gold Trust持仓报告, 数据区间从20041118-至今 :return: pandas.Series 2004-11-18 0 2004-11-19 49.76", "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.117 Safari/537.36\", \"x-app-id\": \"rU6QIu7JHe2gOUeR\", \"x-csrf-token\": \"\",", "= append_temp_df[\"总价值\"] temp_append_df.name = \"silver_amount\" temp_df = temp_df.reset_index() temp_df[\"index\"] =", "2019/10/21 12:08 Desc: 获取金十数据-数据中心-主要机构-宏观经济 \"\"\" import json import time import", "= res.json()[\"data\"] bar = tqdm(reversed(all_date_list)) for item in bar: bar.set_description(f\"Please", "12:08 Desc: 获取金十数据-数据中心-主要机构-宏观经济 \"\"\" import json import time import pandas", "2017-02-13 104.5 165.1 52.7 19.9 377.5 447.6 271.8 67.5 157.6", "0.96 -5.42 0.22 -0.13 0.45 4.44 0.00 17.82 17.42 2017-07-12", "67.5 157.6 2017-03-14 105.3 164.1 52.6 19.4 381.4 441.4 270.9", "params=params, headers=headers) temp_se = pd.DataFrame(r.json()[\"data\"][\"values\"]).iloc[:, :2] temp_se.index = pd.to_datetime(temp_se.iloc[:, 0])", "2019-10-23 Show All \"\"\" t = time.time() res = requests.get(", "-2.80 -12.60 -0.10 19.60 1.10 2019-06-13 0.60 7.40 -0.10 2.30", "= pd.to_datetime(temp_se.iloc[:, 0]) temp_se = temp_se.iloc[:, 1] temp_df = temp_df.append(temp_se)", "2017-10-11 -0.85 -0.29 -0.05 1.44 0.09 3.16 -0.17 5.39 5.08", "324.6 113.7 3296.5 2019-03-14 1008.7 307.2 100.8 3054.9 2019-04-10 979.4", "175.1 2018-12-12 105.2 152.1 52.5 17.6 295.4 463.1 280.9 110.4", "55.0 150.8 2017-06-13 105.9 161.3 52.8 20.4 379.5 442.4 270.5", "2018-09-12 3.80 1.20 -3.60 27.80 2018-10-11 10.80 3.00 -4.20 13.20", "\"attr_id\": \"1\", \"_\": str(int(round(t * 1000))), } headers = {", "全球最大白银ETF--iShares Silver Trust持仓报告, 数据区间从20060429-至今 :return: pandas.Series 2006-04-29 653.17 2006-05-02 653.17", ") json_data = json.loads(res.text[res.text.find(\"{\"): res.text.rfind(\"}\") + 1]) date_list = [item[\"date\"]", "10.30 2.60 2018-11-13 -0.40 2.20 -0.30 0.30 -15.60 465.30 -3.30", "123.5 3256.5 2018-10-11 1051.2 300.4 119.7 3276.1 2018-11-13 1063.0 316.0", "= temp_df.squeeze() temp_df.index.name = None temp_df.name = \"silver_volume\" url =", "json_data[\"kinds\"] value_df.index = pd.to_datetime(date_list) temp_df = value_df[\"增持/减持(吨)\"] temp_df.name = \"silver_change\"", "3.56 -0.25 -0.87 0.95 4.26 0.20 3.13 -11.35 2017-02-13 -4.17", "291.1 186.3 3258.9 2017-12-13 999.6 288.3 183.4 3244.8 2018-01-18 991.8", "'伊拉克', '科威特', '利比亚', '尼日利亚', '沙特', '阿联酋', '委内瑞拉', '欧佩克产量']].iloc[-2, :] except:", "2004-11-24 1390568824.08 ... 2019-10-20 44286078486.23 2019-10-21 44333677232.68 2019-10-22 43907962483.56 2019-10-23", "\"zh-CN,zh;q=0.9,en;q=0.8\", \"cache-control\": \"no-cache\", \"origin\": \"https://datacenter.jin10.com\", \"pragma\": \"no-cache\", \"referer\": \"https://datacenter.jin10.com/reportType/dc_usa_michigan_consumer_sentiment\", \"sec-fetch-dest\":", "-0.25 -0.70 7.57 2018-04-12 -4.95 -8.17 0.26 -0.91 0.33 -1.31", "465.30 -3.30 6.00 -1.70 2018-12-12 -0.50 0.30 0.10 -1.10 -38.00", "'欧佩克产量']].iloc[-1, :] big_df[temp_df.name] = temp_df big_df = big_df.T big_df.columns.name =", "54.1 20.3 382.3 438.3 270.8 96.2 173.8 2017-12-13 101.3 158.1", "只选择有数据的国家返回 20200312:fix:由于 “厄瓜多尔” 已经有几个月没有更新数据,在这里加以剔除 https://datacenter.jin10.com/reportType/dc_opec_report :return: pandas.Series 阿尔及利亚 安哥拉 厄瓜多尔", "3232.7 2018-08-13 1038.7 295.9 127.8 3232.3 2018-09-12 1040.1 297.2 123.5", "-2.43 -5.35 2018-07-11 0.46 -8.83 -0.09 0.35 -2.27 7.15 2.73", "5.02 -16.57 -14.12 6.47 10.18 2017-03-14 -0.02 -1.82 -0.44 -0.69", "289.8 193.8 3261.1 2017-08-10 1006.7 290.5 193.2 3286.9 2017-09-12 1002.2", "[item[\"datas\"] for item in json_data[\"list\"]][0].keys(): try: value_list = [item[\"datas\"][country] for", "2019-10-23 -1.18 2019-10-24 0.00 \"\"\" t = time.time() res =", "11847.91 2019-10-18 11847.91 2019-10-21 11813.02 2019-10-22 11751.96 2019-10-23 11751.96 \"\"\"", "= requests.get(url, params=params, headers=headers) temp_se = pd.DataFrame(r.json()[\"data\"][\"values\"]).iloc[:, [0, 3]] temp_se.index", "382.7 449.4 270.0 92.3 185.5 2017-11-13 101.2 171.1 54.1 20.3", "108.86 ... 2019-10-17 -58.16 2019-10-18 0.00 2019-10-21 -34.89 2019-10-22 -61.06", "\"日期\" big_df = big_df.astype(float) return big_df if __name__ == \"__main__\":", "item in json_data[\"list\"]] value_df = pd.DataFrame(value_list) value_df.columns = json_data[\"kinds\"] value_df.index", "= macro_cons_gold_amount() print(macro_cons_gold_amount_df) print(pd.concat([macro_cons_gold_volume_df, macro_cons_gold_change_df, macro_cons_gold_amount_df], axis=1)) macro_cons_silver_volume_df = macro_cons_silver_volume()", "'安哥拉', '加蓬', '伊朗', '伊拉克', '科威特', '利比亚', '尼日利亚', '沙特', '阿联酋', '委内瑞拉',", "big_df if __name__ == \"__main__\": macro_cons_gold_volume_df = macro_cons_gold_volume() print(macro_cons_gold_volume_df) macro_cons_gold_change_df", "2018-11-13 -0.40 2.20 -0.30 0.30 -15.60 465.30 -3.30 6.00 -1.70", "def _macro_cons_opec_month(): \"\"\" 欧佩克报告-月度, 数据区间从20170118-至今 这里返回的具体索引日期的数据为上一个月的数据, 由于某些国家的数据有缺失, 只选择有数据的国家返回 :return: pandas.Series", "-0.60 -4.36 -15.09 2017-12-13 -4.54 -3.55 -4.16 -13.35 2018-01-18 -1.09", "2006-04-29 653.17 2006-05-02 653.17 2006-05-03 995.28 2006-05-04 1197.43 2006-05-05 1306.29", "2018-11-13 105.4 153.3 52.5 18.6 329.6 465.4 276.4 111.4 175.1", "-0.51 -0.47 -0.22 0.10 -0.53 0.61 9.58 2018-01-18 3.03 4.48", "-53.40 2019-06-13 -7.60 0.30 -3.50 -23.60 \"\"\" t = time.time()", "-2.87 -0.85 -0.95 -6.08 -2.98 2017-05-11 -0.75 9.71 -0.06 0.88", "date_list] for item in reversed(need_date_list): res = requests.get( f\"https://datacenter-api.jin10.com/reports/list?category=opec&date={item}&_={str(int(round(t *", "152.5 51.9 18.9 382.9 445.5 270.1 95.5 171.1 2018-07-11 103.9", ") def macro_cons_gold_volume(): \"\"\" 全球最大黄金ETF—SPDR Gold Trust持仓报告, 数据区间从20041118-至今 :return: pandas.Series", "7.57 2018-04-12 -4.95 -8.17 0.26 -0.91 0.33 -1.31 0.23 -3.72", "2004-11-24 9.33 ... 2019-10-20 0.00 2019-10-21 0.00 2019-10-22 -4.98 2019-10-23", "171.1 2018-07-11 103.9 143.1 51.9 19.0 379.9 453.3 273.1 70.8", "307.1 202.1 3308.5 2017-02-13 994.6 293.1 200.4 3213.9 2017-03-14 979.7", "data_json = r.json() append_temp_df = pd.DataFrame(data_json[\"values\"]).T append_temp_df.columns = [item[\"name\"] for", "big_df.astype(float) return big_df if __name__ == \"__main__\": macro_cons_gold_volume_df = macro_cons_gold_volume()", "11813.02 2019-10-22 11751.96 2019-10-23 11751.96 \"\"\" t = time.time() res", "json_data[\"list\"]] value_df = pd.DataFrame(value_list) value_df.columns = json_data[\"kinds\"] value_df.index = pd.to_datetime(date_list)", "由于某些国家的数据有缺失, 只选择有数据的国家返回 :return: pandas.Series 阿尔及利亚 安哥拉 厄瓜多尔 加蓬 伊朗 伊拉克", "-0.09 6.60 -0.21 -0.77 1.67 6.06 -0.02 12.70 9.67 2017-08-10", "value_df[\"总价值(美元)\"] url = \"https://datacenter-api.jin10.com/reports/list_v2\" params = { \"max_date\": \"\", \"category\":", "阿联酋 委内瑞拉 欧佩克产量 2017-01-18 -14.93 -0.63 -4.52 -22.09 2017-02-13 -49.62", "尼日利亚 \\ 2017-01-18 108.0 172.4 54.5 21.3 372.0 463.2 281.2", "106.0 166.8 52.7 19.7 379.0 450.2 270.9 85.2 173.3 2017-08-10", "macro_cons_gold_volume_df = macro_cons_gold_volume() print(macro_cons_gold_volume_df) macro_cons_gold_change_df = macro_cons_gold_change() print(macro_cons_gold_change_df) macro_cons_gold_amount_df =", "20170118-至今 这里返回的具体索引日期的数据为上一个月的数据, 由于某些国家的数据有缺失 只选择有数据的国家返回 20200312:fix:由于 “厄瓜多尔” 已经有几个月没有更新数据,在这里加以剔除 https://datacenter.jin10.com/reportType/dc_opec_report :return: pandas.Series", "= json_data[\"kinds\"] value_df.index = pd.to_datetime(date_list) temp_df = value_df[\"增持/减持(吨)\"] url =", "= r.json() append_temp_df = pd.DataFrame(data_json[\"values\"]).T append_temp_df.columns = [item[\"name\"] for item", "= pd.DataFrame() for country in [item[\"datas\"] for item in json_data[\"list\"]][0].keys():", "3290.0 2018-12-12 1101.6 324.6 113.7 3296.5 2019-03-14 1008.7 307.2 100.8", "\"\"\" t = time.time() big_df = pd.DataFrame() headers = {", "big_df.T def macro_cons_opec_month(): \"\"\" 欧佩克报告-月度, 数据区间从 20170118-至今 这里返回的具体索引日期的数据为上一个月的数据, 由于某些国家的数据有缺失 只选择有数据的国家返回", "temp_df = temp_df.astype(float) return temp_df def macro_cons_opec_near_change(): \"\"\" 欧佩克报告-变动, 数据区间从20170118-至今", "= [item[\"name\"] for item in data_json[\"keys\"]] temp_append_df = append_temp_df[\"增持/减持\"] temp_append_df.name", "465.4 276.4 111.4 175.1 2018-12-12 105.2 152.1 52.5 17.6 295.4", "inplace=True) temp_df = temp_df.squeeze() temp_df.index.name = None temp_df.name = \"silver_change\"", "3173.2 2017-06-13 994.0 288.5 196.3 3213.9 2017-07-12 995.0 289.8 193.8", "2019-10-23 918.48 2019-10-24 918.48 \"\"\" t = time.time() res =", "macro_cons_gold_amount() print(macro_cons_gold_amount_df) print(pd.concat([macro_cons_gold_volume_df, macro_cons_gold_change_df, macro_cons_gold_amount_df], axis=1)) macro_cons_silver_volume_df = macro_cons_silver_volume() print(macro_cons_silver_volume_df)", "'加蓬', '伊朗', '伊拉克', '科威特', '利比亚', '尼日利亚', '沙特', '阿联酋', '委内瑞拉', '欧佩克产量']].iloc[-1,", "temp_df.drop_duplicates(subset=\"index\", keep=\"last\", inplace=True) temp_df.set_index(\"index\", inplace=True) temp_df = temp_df.squeeze() temp_df.index.name =", "-5.44 2017-12-13 1.41 -10.87 -0.51 -0.47 -0.22 0.10 -0.53 0.61", "json_data[\"list\"]][0].keys(): try: value_list = [item[\"datas\"][country] for item in json_data[\"list\"]] value_df", "2019-06-13 969.0 306.1 74.1 2987.6 \"\"\" t = time.time() big_df", "2006-05-03 445408550 2006-05-04 555123947 2006-05-05 574713264 ... 2019-10-17 Show All", "2017-03-14 -0.02 -1.82 -0.44 -0.69 3.61 -6.20 -0.93 -1.11 5.80", "pandas.Series 2006-04-29 0 2006-05-02 0.00 2006-05-03 342.11 2006-05-04 202.15 2006-05-05", "-32.40 -0.90 -28.90 -53.40 2019-06-13 -7.60 0.30 -3.50 -23.60 \"\"\"", "-13.10 -0.37 4.23 -5.44 2017-12-13 1.41 -10.87 -0.51 -0.47 -0.22", "-23.60 \"\"\" t = time.time() big_df = pd.DataFrame() headers =", "62.2 154.5 2017-05-11 104.7 169.2 52.4 20.6 375.9 437.3 270.2", "196.3 3213.9 2017-07-12 995.0 289.8 193.8 3261.1 2017-08-10 1006.7 290.5", "item in json_data[\"list\"]] value_list = [item[\"datas\"][\"黄金\"] for item in json_data[\"list\"]]", "= temp_df.squeeze() temp_df.index.name = None temp_df.name = \"gold_change\" temp_df =", "2019-10-24 918.48 \"\"\" t = time.time() res = requests.get( JS_CONS_GOLD_ETF_URL.format(", "Trust持仓报告, 数据区间从20041118-至今 :return: pandas.Series 2004-11-18 8.09 2004-11-19 57.85 2004-11-22 87.09", "555123947 2006-05-05 574713264 ... 2019-10-17 Show All 2019-10-18 Show All", "item in data_json[\"keys\"]] temp_append_df = append_temp_df[\"总库存\"] temp_append_df.name = \"silver_volume\" temp_df", "\"sec-fetch-site\": \"same-site\", \"user-agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36", "time.time() res = requests.get( JS_CONS_OPEC_URL.format( str(int(round(t * 1000))), str(int(round(t *", "'科威特', '利比亚', '尼日利亚', '沙特', '阿联酋', '委内瑞拉', '欧佩克产量']].iloc[-1, :] big_df[temp_df.name] =", "All \"\"\" t = time.time() res = requests.get( JS_CONS_SLIVER_ETF_URL.format( str(int(round(t", "10.18 2017-03-14 -0.02 -1.82 -0.44 -0.69 3.61 -6.20 -0.93 -1.11", "2019-10-21 924.64 2019-10-22 919.66 2019-10-23 918.48 2019-10-24 918.48 \"\"\" t", "\"cache-control\": \"no-cache\", \"origin\": \"https://datacenter.jin10.com\", \"pragma\": \"no-cache\", \"referer\": \"https://datacenter.jin10.com/reportType/dc_usa_michigan_consumer_sentiment\", \"sec-fetch-dest\": \"empty\",", "pd.DataFrame(r.json()[\"data\"][\"values\"]).iloc[:, [0, 3]] temp_se.index = pd.to_datetime(temp_se.iloc[:, 0]) temp_se = temp_se.iloc[:,", "924.64 2019-10-22 919.66 2019-10-23 918.48 2019-10-24 918.48 \"\"\" t =", "r = requests.get(url, params=params, headers=headers) temp_se = pd.DataFrame(r.json()[\"data\"][\"values\"]).iloc[:, [0, 2]]", "0.09 3.16 -0.17 5.39 5.08 2017-11-13 -3.84 6.98 0.71 0.18", "temp_df = pd.DataFrame(res.json()[\"data\"][\"values\"], columns=pd.DataFrame(res.json()[\"data\"][\"keys\"])[\"name\"].tolist()).T temp_df.columns = temp_df.iloc[0, :] temp_df =", "for item in json_data[\"list\"]] big_df = pd.DataFrame() for country in", "105.3 164.1 52.6 19.4 381.4 441.4 270.9 66.9 160.8 2017-04-12", "17.42 2017-07-12 -0.09 6.60 -0.21 -0.77 1.67 6.06 -0.02 12.70", "value_df.columns = json_data[\"kinds\"] value_df.index = pd.to_datetime(date_list) temp_df = value_df[\"总库存(吨)\"] url", "10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36\", \"x-app-id\":", "= temp_df.astype(float) return temp_df def macro_cons_silver_volume(): \"\"\" 全球最大白银ETF--iShares Silver Trust持仓报告,", "-0.90 -28.90 -53.40 2019-06-13 -7.60 0.30 -3.50 -23.60 \"\"\" t", "52.7 19.7 379.0 450.2 270.9 85.2 173.3 2017-08-10 105.9 164.6", "* 1000))), } headers = { \"accept\": \"*/*\", \"accept-encoding\": \"gzip,", "4.07 2018-09-12 3.80 1.20 -3.60 27.80 2018-10-11 10.80 3.00 -4.20", "2019-10-22 Show All 2019-10-23 Show All \"\"\" t = time.time()", "big_df[temp_df.name] = temp_df big_df = big_df.T big_df.columns.name = \"日期\" big_df", "2018-06-12 3.90 1.40 0.06 0.18 0.56 2.77 -0.57 -2.43 -5.35", "18.6 329.6 465.4 276.4 111.4 175.1 2018-12-12 105.2 152.1 52.5", "for item in all_date_list if item.split(\"-\")[0] + item.split(\"-\")[1] + item.split(\"-\")[2]", "\"no-cache\", \"referer\": \"https://datacenter.jin10.com/reportType/dc_usa_michigan_consumer_sentiment\", \"sec-fetch-dest\": \"empty\", \"sec-fetch-mode\": \"cors\", \"sec-fetch-site\": \"same-site\", \"user-agent\":", "= temp_df.astype(float) return temp_df def macro_cons_gold_change(): \"\"\" 全球最大黄金ETF—SPDR Gold Trust持仓报告,", "'伊拉克', '科威特', '利比亚', '尼日利亚', '沙特', '阿联酋', '委内瑞拉', '欧佩克产量']].iloc[-1, :] big_df[temp_df.name]", "temp_df.squeeze() temp_df.index.name = None temp_df.name = \"gold_change\" temp_df = temp_df.astype(float)", "19.7 382.9 440.5 270.0 96.2 186.1 2018-04-12 98.4 152.4 51.8", "json_data[\"kinds\"] value_df.index = pd.to_datetime(date_list) temp_df = value_df[\"增持/减持(吨)\"] url = \"https://datacenter-api.jin10.com/reports/list_v2\"", "try: temp_df = temp_df[['阿尔及利亚', '安哥拉', '加蓬', '伊朗', '伊拉克', '科威特', '利比亚',", "temp_df.squeeze() temp_df.index.name = None temp_df.name = \"gold_volume\" temp_df = temp_df.astype(float)", "# -*- coding:utf-8 -*- # /usr/bin/env python \"\"\" Date: 2019/10/21", "1]) date_list = [item[\"date\"] for item in json_data[\"list\"]] big_df =", "-22.09 2017-02-13 -49.62 -15.93 -3.05 -89.02 2017-03-14 -6.81 -3.69 -1.60", "need_date_list = [item for item in all_date_list if item.split(\"-\")[0] +", "-0.01 1.32 0.79 -0.25 -0.70 7.57 2018-04-12 -4.95 -8.17 0.26", "-1.82 -0.44 -0.69 3.61 -6.20 -0.93 -1.11 5.80 2017-04-12 0.45", "value_df.columns = json_data[\"kinds\"] value_df.index = pd.to_datetime(date_list) temp_df = value_df[\"增持/减持(吨)\"] temp_df.name", "2019-04-10 979.4 305.9 73.2 3002.2 2019-06-13 969.0 306.1 74.1 2987.6", "value_df.columns = json_data[\"kinds\"] value_df.index = pd.to_datetime(date_list) temp_df = value_df[\"上个月\"] temp_df.name", "\"\"\" t = time.time() res = requests.get( JS_CONS_GOLD_ETF_URL.format( str(int(round(t *", "2019-10-24 44120217405.82 \"\"\" t = time.time() res = requests.get( JS_CONS_GOLD_ETF_URL.format(", "445408550 2006-05-04 555123947 2006-05-05 574713264 ... 2019-10-17 Show All 2019-10-18", "440.2 270.2 62.2 154.5 2017-05-11 104.7 169.2 52.4 20.6 375.9", "= temp_df.astype(float) return temp_df def macro_cons_gold_amount(): \"\"\" 全球最大黄金ETF—SPDR Gold Trust持仓报告,", "item.split(\"-\")[1] + item.split(\"-\")[2] not in date_list] for item in reversed(need_date_list):", "temp_df.sort_index(inplace=True) temp_df = temp_df.reset_index() temp_df.drop_duplicates(subset=\"index\", keep=\"last\", inplace=True) temp_df.set_index(\"index\", inplace=True) temp_df", "= None temp_df.name = \"silver_change\" url = \"https://cdn.jin10.com/data_center/reports/etf_2.json\" r =", "166.0 2018-08-13 106.2 145.6 52.5 18.8 373.7 455.6 279.1 66.4", "in [item[\"datas\"] for item in json_data[\"list\"]][0].keys(): try: value_list = [item[\"datas\"][country]", "Date: 2019/10/21 12:08 Desc: 获取金十数据-数据中心-主要机构-宏观经济 \"\"\" import json import time", "2018-07-11 0.46 -8.83 -0.09 0.35 -2.27 7.15 2.73 -25.43 2.78", "NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.117 Safari/537.36\",", "pd.DataFrame() headers = { \"accept\": \"*/*\", \"accept-encoding\": \"gzip, deflate, br\",", "165.1 52.7 19.9 377.5 447.6 271.8 67.5 157.6 2017-03-14 105.3", "pandas.Series 2004-11-18 8.09 2004-11-19 57.85 2004-11-22 87.09 2004-11-23 87.09 2004-11-24", "deflate, br\", \"accept-language\": \"zh-CN,zh;q=0.9,en;q=0.8\", \"cache-control\": \"no-cache\", \"origin\": \"https://datacenter.jin10.com\", \"pragma\": \"no-cache\",", "requests.get( JS_CONS_SLIVER_ETF_URL.format( str(int(round(t * 1000))), str(int(round(t * 1000)) + 90)", "0.26 -0.91 0.33 -1.31 0.23 -3.72 1.82 2018-05-14 1.77 -0.78", "0.06 0.18 0.56 2.77 -0.57 -2.43 -5.35 2018-07-11 0.46 -8.83", "995.0 289.8 193.8 3261.1 2017-08-10 1006.7 290.5 193.2 3286.9 2017-09-12", "temp_df = temp_df.astype(float) return temp_df def macro_cons_silver_change(): \"\"\" 全球最大白银ETF--iShares Silver", "117.1 3290.0 2018-12-12 1101.6 324.6 113.7 3296.5 2019-03-14 1008.7 307.2", "1.20 -7.00 -1.40 2.30 1.00 2019-04-10 -0.70 0.70 52.40 0.90", "2006-05-04 202.15 2006-05-05 108.86 ... 2019-10-17 -58.16 2019-10-18 0.00 2019-10-21", "'沙特', '阿联酋', '委内瑞拉', '欧佩克产量']].iloc[-2, :] big_df[item] = temp_df return big_df.T", "inplace=True) temp_df = temp_df.squeeze() temp_df.index.name = None temp_df.name = \"gold_volume\"", "2019-06-13 0.60 7.40 -0.10 2.30 -22.70 9.40 1.30 -0.30 -9.20", "Chrome/79.0.3945.117 Safari/537.36\", \"x-app-id\": \"rU6QIu7JHe2gOUeR\", \"x-csrf-token\": \"\", \"x-version\": \"1.0.0\", } res", "15.43 3.43 2017-09-12 0.41 0.83 -0.03 -3.23 -0.23 -2.31 0.01", "2019-10-18 11847.91 2019-10-21 11813.02 2019-10-22 11751.96 2019-10-23 11751.96 \"\"\" t", "4.65 0.61 -4.17 1.21 2018-06-12 8.55 -0.63 -4.25 3.54 2018-07-11", "-0.44 -0.69 3.61 -6.20 -0.93 -1.11 5.80 2017-04-12 0.45 -1.87", "2017-12-13 999.6 288.3 183.4 3244.8 2018-01-18 991.8 287.8 174.5 3241.6", "https://datacenter.jin10.com/reportType/dc_opec_report :return: pandas.Series 阿尔及利亚 安哥拉 厄瓜多尔 加蓬 伊朗 伊拉克 科威特", "big_df = pd.DataFrame() for country in [item[\"datas\"] for item in", "value_df[\"上个月\"] temp_df.name = country big_df = big_df.append(temp_df) except: continue headers", "t = time.time() big_df = pd.DataFrame() headers = { \"accept\":", "2006-04-29 0 2006-05-02 0.00 2006-05-03 342.11 2006-05-04 202.15 2006-05-05 108.86", "like Gecko) Chrome/79.0.3945.117 Safari/537.36\", \"x-app-id\": \"rU6QIu7JHe2gOUeR\", \"x-csrf-token\": \"\", \"x-version\": \"1.0.0\",", "3.13 -11.35 2017-02-13 -4.17 -2.32 -1.67 -1.00 5.02 -16.57 -14.12", "Trust持仓报告, 数据区间从20060429-至今 :return: pandas.Series 2006-04-29 0 2006-05-02 0.00 2006-05-03 342.11", "9.33 ... 2019-10-20 0.00 2019-10-21 0.00 2019-10-22 -4.98 2019-10-23 -1.18", "macro_cons_silver_amount(): \"\"\" 全球最大白银ETF--iShares Silver Trust持仓报告, 数据区间从20060429-至今 :return: pandas.Series 2006-04-29 263651152", "* 1000)))}\", headers=headers) # 日期序列 all_date_list = res.json()[\"data\"] bar =", "\"https://cdn.jin10.com/data_center/reports/etf_2.json\" r = requests.get(url) data_json = r.json() append_temp_df = pd.DataFrame(data_json[\"values\"]).T", "57.85 2004-11-22 87.09 2004-11-23 87.09 2004-11-24 96.42 ... 2019-10-20 924.64", "import json import time import pandas as pd import requests", "macro_cons_opec_near_change(): \"\"\" 欧佩克报告-变动, 数据区间从20170118-至今 :return: pandas.Series 阿尔及利亚 安哥拉 厄瓜多尔 加蓬", "\"empty\", \"sec-fetch-mode\": \"cors\", \"sec-fetch-site\": \"same-site\", \"user-agent\": \"Mozilla/5.0 (Windows NT 10.0;", "574713264 ... 2019-10-17 Show All 2019-10-18 Show All 2019-10-21 Show", "-15.27 2017-05-11 4.92 -6.23 -2.60 -1.82 2017-06-13 0.23 -1.80 -0.77", "168.0 2017-07-12 106.0 166.8 52.7 19.7 379.0 450.2 270.9 85.2", "= temp_df.reset_index() temp_df[\"index\"] = temp_df[\"index\"].astype(str) temp_df = temp_df.append(temp_append_df.reset_index()) temp_df.drop_duplicates(subset=[\"index\"], keep=\"last\",", "382.4 446.8 270.3 100.1 174.8 2017-09-12 106.5 164.6 53.7 17.3", "in data_json[\"keys\"]] temp_append_df = append_temp_df[\"增持/减持\"] temp_append_df.name = \"silver_change\" temp_df =", "375.9 437.3 270.2 55.0 150.8 2017-06-13 105.9 161.3 52.8 20.4", "2017-08-10 3.18 -0.67 -1.58 17.26 2017-09-12 -1.03 -2.02 -3.19 -7.91", "= [item[\"datas\"][\"黄金\"] for item in json_data[\"list\"]] value_df = pd.DataFrame(value_list) value_df.columns", "3.51 -4.75 17.34 2018-08-13 -5.28 6.92 -4.77 4.07 2018-09-12 3.80", "\"x-app-id\": \"rU6QIu7JHe2gOUeR\", \"x-csrf-token\": \"\", \"x-version\": \"1.0.0\", } r = requests.get(url,", "463.1 280.9 110.4 173.6 2019-03-14 102.6 145.7 52.2 20.3 274.3", "49.76 2004-11-22 29.24 2004-11-23 0.00 2004-11-24 9.33 ... 2019-10-20 0.00", "2017-05-11 995.4 284.2 195.6 3173.2 2017-06-13 994.0 288.5 196.3 3213.9", "a moment, now downing {item}'s data\") res = requests.get( f\"https://datacenter-api.jin10.com/reports/list?category=opec&date={item}&_={str(int(round(t", "997.5 290.5 189.0 3274.8 2017-11-13 1000.0 291.1 186.3 3258.9 2017-12-13", "1.21 2018-06-12 8.55 -0.63 -4.25 3.54 2018-07-11 40.54 3.51 -4.75", "991.8 287.8 174.5 3241.6 2018-04-12 993.4 286.4 148.8 3195.8 2018-05-14", "All'] temp_df.sort_index(inplace=True) temp_df = temp_df.astype(float) return temp_df def macro_cons_silver_change(): \"\"\"", "'利比亚', '尼日利亚', '沙特', '阿联酋', '委内瑞拉', '欧佩克产量']].iloc[-1, :] big_df[temp_df.name] = temp_df", "2017-06-13 0.96 -5.42 0.22 -0.13 0.45 4.44 0.00 17.82 17.42", "temp_df def macro_cons_silver_amount(): \"\"\" 全球最大白银ETF--iShares Silver Trust持仓报告, 数据区间从20060429-至今 :return: pandas.Series", "Silver Trust持仓报告, 数据区间从20060429-至今 :return: pandas.Series 2006-04-29 0 2006-05-02 0.00 2006-05-03", "382.9 445.5 270.1 95.5 171.1 2018-07-11 103.9 143.1 51.9 19.0", "2018-12-12 -0.50 0.30 0.10 -1.10 -38.00 -2.30 4.50 -1.10 -3.00", "temp_df = temp_df.append(temp_append_df.reset_index()) temp_df.drop_duplicates(subset=[\"index\"], keep=\"last\", inplace=True) temp_df.index = pd.to_datetime(temp_df[\"index\"]) del", "185.5 2017-11-13 101.2 171.1 54.1 20.3 382.3 438.3 270.8 96.2", "-5.28 6.92 -4.77 4.07 2018-09-12 3.80 1.20 -3.60 27.80 2018-10-11", "54.5 21.3 372.0 463.2 281.2 60.8 154.2 2017-02-13 104.5 165.1", "\"1\", \"_\": str(int(round(t * 1000))), } headers = { \"accept\":", "= time.time() res = requests.get( JS_CONS_GOLD_ETF_URL.format( str(int(round(t * 1000))), str(int(round(t", "= json_data[\"kinds\"] value_df.index = pd.to_datetime(date_list) temp_df = value_df[\"上个月\"] temp_df.name =", "= \"silver_change\" temp_df = temp_df.reset_index() temp_df[\"index\"] = temp_df[\"index\"].astype(str) temp_df =", "temp_df.astype(float) return temp_df def macro_cons_opec_near_change(): \"\"\" 欧佩克报告-变动, 数据区间从20170118-至今 :return: pandas.Series", "463.3 270.9 90.6 174.1 2019-04-10 101.8 145.4 52.4 21.4 269.8", "263651152 2006-05-03 445408550 2006-05-04 555123947 2006-05-05 574713264 ... 2019-10-17 Show", "183.4 3244.8 2018-01-18 991.8 287.8 174.5 3241.6 2018-04-12 993.4 286.4", "temp_df[['阿尔及利亚', '安哥拉', '加蓬', '伊朗', '伊拉克', '科威特', '利比亚', '尼日利亚', '沙特', '阿联酋',", "270.9 66.9 160.8 2017-04-12 105.6 161.4 52.6 19.8 379.0 440.2", "-4.52 -22.09 2017-02-13 -49.62 -15.93 -3.05 -89.02 2017-03-14 -6.81 -3.69", "数据区间从20060429-至今 :return: pandas.Series 2006-04-29 0 2006-05-02 0.00 2006-05-03 342.11 2006-05-04", "in data_json[\"keys\"]] temp_append_df = append_temp_df[\"总价值\"] temp_append_df.name = \"silver_amount\" temp_df =", "0.83 -0.03 -3.23 -0.23 -2.31 0.01 -11.23 13.83 2017-10-11 -0.85", "2004-11-19 57.85 2004-11-22 87.09 2004-11-23 87.09 2004-11-24 96.42 ... 2019-10-20", "pd.DataFrame(value_list) value_df.columns = json_data[\"kinds\"] value_df.index = pd.to_datetime(date_list) temp_df = value_df[\"增持/减持(吨)\"]", "tqdm(reversed(all_date_list[:-1])) for item in bar: bar.set_description(f\"Please wait for a moment,", "111.4 175.1 2018-12-12 105.2 152.1 52.5 17.6 295.4 463.1 280.9", "127.8 3232.3 2018-09-12 1040.1 297.2 123.5 3256.5 2018-10-11 1051.2 300.4", "18.7 344.7 465.0 281.2 105.3 174.8 2018-11-13 105.4 153.3 52.5", "'利比亚', '尼日利亚', '沙特', '阿联酋', '委内瑞拉', '欧佩克产量']].iloc[-2, :] big_df[item] = temp_df", "2018-06-12 998.7 286.5 139.2 3186.9 2018-07-11 1042.0 289.7 134.0 3232.7", "2004-11-19 49.76 2004-11-22 29.24 2004-11-23 0.00 2004-11-24 9.33 ... 2019-10-20", "for item in reversed(need_date_list): res = requests.get( f\"https://datacenter-api.jin10.com/reports/list?category=opec&date={item}&_={str(int(round(t * 1000)))}\",", "Show All 2019-10-18 Show All 2019-10-21 Show All 2019-10-22 Show", "“厄瓜多尔” 已经有几个月没有更新数据,在这里加以剔除 https://datacenter.jin10.com/reportType/dc_opec_report :return: pandas.Series 阿尔及利亚 安哥拉 厄瓜多尔 加蓬 伊朗", "0.40 18.80 -15.00 9.00 0.80 25.60 7.40 2018-10-11 -0.80 5.70", "-0.07 -1.36 39.35 2017-08-10 3.18 -0.67 -1.58 17.26 2017-09-12 -1.03", "Show All 2019-10-21 Show All 2019-10-22 Show All 2019-10-23 Show", "109.8 173.3 2019-06-13 102.9 147.1 52.9 21.1 237.0 472.4 271.0", "174.5 3241.6 2018-04-12 993.4 286.4 148.8 3195.8 2018-05-14 995.9 287.2", "2019-04-10 -0.70 0.70 52.40 0.90 -2.80 -12.60 -0.10 19.60 1.10", "-11.23 13.83 2017-10-11 -0.85 -0.29 -0.05 1.44 0.09 3.16 -0.17", "= pd.to_datetime(date_list) temp_df = value_df[\"增持/减持(吨)\"] temp_df.name = \"silver_change\" url =", "[0, 1]] temp_se.index = pd.to_datetime(temp_se.iloc[:, 0]) temp_se = temp_se.iloc[:, 1]", "akshare.economic.cons import ( JS_CONS_GOLD_ETF_URL, JS_CONS_SLIVER_ETF_URL, JS_CONS_OPEC_URL, ) def macro_cons_gold_volume(): \"\"\"", "2004-11-23 0.00 2004-11-24 9.33 ... 2019-10-20 0.00 2019-10-21 0.00 2019-10-22", "2017-05-11 -0.75 9.71 -0.06 0.88 -3.47 -3.91 0.03 -6.16 5.08", "2006-05-04 555123947 2006-05-05 574713264 ... 2019-10-17 Show All 2019-10-18 Show", "2017-09-12 -1.03 -2.02 -3.19 -7.91 2017-10-11 -0.07 -0.84 -5.19 8.85", "\"2\", \"_\": str(int(round(t * 1000))), } headers = { \"accept\":", "= [item[\"datas\"][country] for item in json_data[\"list\"]] value_df = pd.DataFrame(value_list) value_df.columns", "171.1 54.1 20.3 382.3 438.3 270.8 96.2 173.8 2017-12-13 101.3", "1.00 -0.07 0.08 0.69 -0.83 2018-06-12 3.90 1.40 0.06 0.18", "151.5 52.0 18.3 382.3 442.9 270.5 98.2 179.1 2018-06-12 103.1", "1.67 6.06 -0.02 12.70 9.67 2017-08-10 -0.10 -1.93 0.85 0.71", "2019-10-22 11751.96 2019-10-23 11751.96 \"\"\" t = time.time() res =", "\"silver_volume\" temp_df = temp_df.reset_index() temp_df[\"index\"] = temp_df[\"index\"].astype(str) temp_df = temp_df.append(temp_append_df.reset_index())", "113.7 3296.5 2019-03-14 1008.7 307.2 100.8 3054.9 2019-04-10 979.4 305.9", "150.8 2017-06-13 105.9 161.3 52.8 20.4 379.5 442.4 270.5 73.0", "-3.60 27.80 2018-10-11 10.80 3.00 -4.20 13.20 2018-11-13 12.70 14.20", "-6.20 -0.93 -1.11 5.80 2017-04-12 0.45 -1.87 -0.28 0.19 -2.87", "res.json()[\"data\"] need_date_list = [item for item in all_date_list if item.split(\"-\")[0]", "\"sec-fetch-dest\": \"empty\", \"sec-fetch-mode\": \"cors\", \"sec-fetch-site\": \"same-site\", \"user-agent\": \"Mozilla/5.0 (Windows NT", "br\", \"accept-language\": \"zh-CN,zh;q=0.9,en;q=0.8\", \"cache-control\": \"no-cache\", \"origin\": \"https://datacenter.jin10.com\", \"pragma\": \"no-cache\", \"referer\":", "macro_cons_silver_change(): \"\"\" 全球最大白银ETF--iShares Silver Trust持仓报告, 数据区间从20060429-至今 :return: pandas.Series 2006-04-29 0", "in all_date_list if item.split(\"-\")[0] + item.split(\"-\")[1] + item.split(\"-\")[2] not in", "macro_cons_gold_change_df, macro_cons_gold_amount_df], axis=1)) macro_cons_silver_volume_df = macro_cons_silver_volume() print(macro_cons_silver_volume_df) macro_cons_silver_change_df = macro_cons_silver_change()", "918.48 \"\"\" t = time.time() res = requests.get( JS_CONS_GOLD_ETF_URL.format( str(int(round(t", "9.67 2017-08-10 -0.10 -1.93 0.85 0.71 0.69 -3.31 -0.74 15.43", "= tqdm(reversed(all_date_list)) for item in bar: bar.set_description(f\"Please wait for a", "0.61 9.58 2018-01-18 3.03 4.48 -0.72 -0.01 1.32 0.79 -0.25", "53.10 -0.10 -15.00 0.80 0.60 10.30 2.60 2018-11-13 -0.40 2.20", "'科威特', '利比亚', '尼日利亚', '沙特', '阿联酋', '委内瑞拉', '欧佩克产量']].iloc[-1, :] except: temp_df", "-0.10 -15.00 0.80 0.60 10.30 2.60 2018-11-13 -0.40 2.20 -0.30", "4.48 -0.72 -0.01 1.32 0.79 -0.25 -0.70 7.57 2018-04-12 -4.95", "import time import pandas as pd import requests from tqdm", "-0.84 -5.19 8.85 2017-11-13 1.69 -0.60 -4.36 -15.09 2017-12-13 -4.54", "969.0 306.1 74.1 2987.6 \"\"\" t = time.time() res =", "'沙特', '阿联酋', '委内瑞拉', '欧佩克产量']].iloc[-1, :] big_df[temp_df.name] = temp_df big_df =", "temp_df = temp_df.astype(float) return temp_df def macro_cons_silver_volume(): \"\"\" 全球最大白银ETF--iShares Silver", "1063.0 316.0 117.1 3290.0 2018-12-12 1101.6 324.6 113.7 3296.5 2019-03-14", "284.2 195.6 3173.2 2017-06-13 994.0 288.5 196.3 3213.9 2017-07-12 995.0", "all_date_list = res.json()[\"data\"] bar = tqdm(reversed(all_date_list)) for item in bar:", "2019-10-18 Show All 2019-10-21 Show All 2019-10-22 Show All 2019-10-23", "449.4 270.0 92.3 185.5 2017-11-13 101.2 171.1 54.1 20.3 382.3", "for item in json_data[\"list\"]][0].keys(): try: value_list = [item[\"datas\"][country] for item", "\"\"\" 全球最大黄金ETF—SPDR Gold Trust持仓报告, 数据区间从20041118-至今 :return: pandas.Series 2004-11-18 0 2004-11-19", "2019-10-21 0.00 2019-10-22 -4.98 2019-10-23 -1.18 2019-10-24 0.00 \"\"\" t", "macro_cons_gold_change_df = macro_cons_gold_change() print(macro_cons_gold_change_df) macro_cons_gold_amount_df = macro_cons_gold_amount() print(macro_cons_gold_amount_df) print(pd.concat([macro_cons_gold_volume_df, macro_cons_gold_change_df,", "= None temp_df.name = \"gold_amount\" temp_df = temp_df.astype(float) return temp_df", "-0.10 19.60 1.10 2019-06-13 0.60 7.40 -0.10 2.30 -22.70 9.40", "174.1 2019-04-10 101.8 145.4 52.4 21.4 269.8 452.2 270.9 109.8", "139.2 3186.9 2018-07-11 1042.0 289.7 134.0 3232.7 2018-08-13 1038.7 295.9", "all_date_list = res.json()[\"data\"] need_date_list = [item for item in all_date_list", "requests.get(url, params=params, headers=headers) temp_se = pd.DataFrame(r.json()[\"data\"][\"values\"]).iloc[:, [0, 3]] temp_se.index =", "993.4 286.4 148.8 3195.8 2018-05-14 995.9 287.2 143.6 3193.0 2018-06-12", "2017-03-14 979.7 292.5 198.7 3195.8 2017-04-12 999.4 289.5 197.2 3192.8", "macro_cons_silver_amount() print(macro_cons_silver_amount_df) print(pd.concat([macro_cons_silver_volume_df, macro_cons_silver_change_df, macro_cons_silver_amount_df], axis=1)) macro_cons_opec_near_change_df = macro_cons_opec_near_change() print(macro_cons_opec_near_change_df)", "2019-10-18 0.00 2019-10-21 -34.89 2019-10-22 -61.06 2019-10-23 0.00 \"\"\" t", "利比亚 尼日利亚 \\ 2017-01-18 -0.87 3.56 -0.25 -0.87 0.95 4.26", "145.7 52.2 20.3 274.3 463.3 270.9 90.6 174.1 2019-04-10 101.8", "requests.get( f\"https://datacenter-api.jin10.com/reports/list?category=opec&date={item}&_={str(int(round(t * 1000)))}\", headers=headers) temp_df = pd.DataFrame(res.json()[\"data\"][\"values\"], columns=pd.DataFrame(res.json()[\"data\"][\"keys\"])[\"name\"].tolist()).T temp_df.columns", "0.18 0.56 2.77 -0.57 -2.43 -5.35 2018-07-11 0.46 -8.83 -0.09", "92.3 185.5 2017-11-13 101.2 171.1 54.1 20.3 382.3 438.3 270.8", "日期序列 all_date_list = res.json()[\"data\"] need_date_list = [item for item in", "2019-10-23 0.00 \"\"\" t = time.time() res = requests.get( JS_CONS_SLIVER_ETF_URL.format(", "0.00 17.82 17.42 2017-07-12 -0.09 6.60 -0.21 -0.77 1.67 6.06", "\"日期\" big_df = big_df.astype(float) return big_df def _macro_cons_opec_month(): \"\"\" 欧佩克报告-月度,", "-5.19 8.85 2017-11-13 1.69 -0.60 -4.36 -15.09 2017-12-13 -4.54 -3.55", "pd.DataFrame() for country in [item[\"datas\"] for item in json_data[\"list\"]][0].keys(): try:", "0.30 -3.50 -23.60 \"\"\" t = time.time() big_df = pd.DataFrame()", "= \"silver_change\" url = \"https://datacenter-api.jin10.com/reports/list_v2\" params = { \"max_date\": \"\",", "\"silver_change\" temp_df = temp_df.reset_index() temp_df[\"index\"] = temp_df[\"index\"].astype(str) temp_df = temp_df.append(temp_append_df.reset_index())", "53.6 20.1 382.7 449.4 270.0 92.3 185.5 2017-11-13 101.2 171.1", "= temp_df.squeeze() temp_df.index.name = None temp_df.name = \"gold_volume\" temp_df =", "1008.7 307.2 100.8 3054.9 2019-04-10 979.4 305.9 73.2 3002.2 2019-06-13", "-3.05 -89.02 2017-03-14 -6.81 -3.69 -1.60 -13.95 2017-04-12 4.16 -3.27", "def macro_cons_gold_volume(): \"\"\" 全球最大黄金ETF—SPDR Gold Trust持仓报告, 数据区间从20041118-至今 :return: pandas.Series 2004-11-18", "13.83 2017-10-11 -0.85 -0.29 -0.05 1.44 0.09 3.16 -0.17 5.39", "= temp_df[\"index\"].astype(str) temp_df = temp_df.append(temp_append_df.reset_index()) temp_df.drop_duplicates(subset=[\"index\"], keep=\"last\", inplace=True) temp_df.index =", "temp_df = temp_df.iloc[1:, :] try: temp_df = temp_df[['阿尔及利亚', '安哥拉', '加蓬',", "... 2019-10-17 Show All 2019-10-18 Show All 2019-10-21 Show All", "2018-12-12 105.2 152.1 52.5 17.6 295.4 463.1 280.9 110.4 173.6", "big_df = pd.DataFrame() headers = { \"accept\": \"*/*\", \"accept-encoding\": \"gzip,", "0.20 2.20 0.50 0.70 1.20 -7.00 -1.40 2.30 1.00 2019-04-10", "axis=1)) macro_cons_silver_volume_df = macro_cons_silver_volume() print(macro_cons_silver_volume_df) macro_cons_silver_change_df = macro_cons_silver_change() print(macro_cons_silver_change_df) macro_cons_silver_amount_df", "temp_append_df = append_temp_df[\"总库存\"] temp_append_df.name = \"silver_volume\" temp_df = temp_df.reset_index() temp_df[\"index\"]", "-2.32 -1.67 -1.00 5.02 -16.57 -14.12 6.47 10.18 2017-03-14 -0.02", "2018-12-12 37.70 7.10 -5.20 -1.10 2019-03-14 -8.60 -0.40 -14.20 -22.10", "data_json[\"keys\"]] temp_append_df = append_temp_df[\"增持/减持\"] temp_append_df.name = \"silver_change\" temp_df = temp_df.reset_index()", "item in reversed(need_date_list): res = requests.get( f\"https://datacenter-api.jin10.com/reports/list?category=opec&date={item}&_={str(int(round(t * 1000)))}\", headers=headers)", "temp_df.name = \"silver_change\" url = \"https://cdn.jin10.com/data_center/reports/etf_2.json\" r = requests.get(url) data_json", "276.4 111.4 175.1 2018-12-12 105.2 152.1 52.5 17.6 295.4 463.1", "2019-03-14 102.6 145.7 52.2 20.3 274.3 463.3 270.9 90.6 174.1", "pd.DataFrame(res.json()[\"data\"][\"values\"], columns=pd.DataFrame(res.json()[\"data\"][\"keys\"])[\"name\"].tolist()).T temp_df.columns = temp_df.iloc[0, :] temp_df = temp_df[['阿尔及利亚', '安哥拉',", "293.1 200.4 3213.9 2017-03-14 979.7 292.5 198.7 3195.8 2017-04-12 999.4", "2017-01-18 1047.4 307.1 202.1 3308.5 2017-02-13 994.6 293.1 200.4 3213.9", "3296.5 2019-03-14 1008.7 307.2 100.8 3054.9 2019-04-10 979.4 305.9 73.2", "t = time.time() res = requests.get( JS_CONS_SLIVER_ETF_URL.format( str(int(round(t * 1000))),", "pd.DataFrame(value_list) value_df.columns = json_data[\"kinds\"] value_df.index = pd.to_datetime(date_list) temp_df = value_df[\"总库存(吨)\"]", "2017-02-13 994.6 293.1 200.4 3213.9 2017-03-14 979.7 292.5 198.7 3195.8", "item in json_data[\"list\"]][0].keys(): try: value_list = [item[\"datas\"][country] for item in", "= macro_cons_gold_change() print(macro_cons_gold_change_df) macro_cons_gold_amount_df = macro_cons_gold_amount() print(macro_cons_gold_amount_df) print(pd.concat([macro_cons_gold_volume_df, macro_cons_gold_change_df, macro_cons_gold_amount_df],", "temp_df = value_df[\"增持/减持(吨)\"] temp_df.name = \"silver_change\" url = \"https://datacenter-api.jin10.com/reports/list_v2\" params", "params=params, headers=headers) temp_se = pd.DataFrame(r.json()[\"data\"][\"values\"]).iloc[:, [0, 3]] temp_se.index = pd.to_datetime(temp_se.iloc[:,", "r = requests.get(url, params=params, headers=headers) temp_se = pd.DataFrame(r.json()[\"data\"][\"values\"]).iloc[:, [0, 3]]", "if item.split(\"-\")[0] + item.split(\"-\")[1] + item.split(\"-\")[2] not in date_list] for", "271.8 67.5 157.6 2017-03-14 105.3 164.1 52.6 19.4 381.4 441.4", "'利比亚', '尼日利亚', '沙特', '阿联酋', '委内瑞拉', '欧佩克产量']].iloc[-1, :] except: temp_df =", "307.2 100.8 3054.9 2019-04-10 979.4 305.9 73.2 3002.2 2019-06-13 969.0", "= pd.DataFrame(r.json()[\"data\"][\"values\"]).iloc[:, [0, 3]] temp_se.index = pd.to_datetime(temp_se.iloc[:, 0]) temp_se =", "445.5 270.1 95.5 171.1 2018-07-11 103.9 143.1 51.9 19.0 379.9", "20.3 274.3 463.3 270.9 90.6 174.1 2019-04-10 101.8 145.4 52.4", "92.6 172.5 2018-10-11 104.9 151.9 53.1 18.7 344.7 465.0 281.2", "2017-06-13 994.0 288.5 196.3 3213.9 2017-07-12 995.0 289.8 193.8 3261.1", "0.45 -1.87 -0.28 0.19 -2.87 -0.85 -0.95 -6.08 -2.98 2017-05-11", "for country in [item[\"datas\"] for item in json_data[\"list\"]][0].keys(): try: value_list", "尼日利亚 \\ 2017-01-18 -0.87 3.56 -0.25 -0.87 0.95 4.26 0.20", "2019-06-13 102.9 147.1 52.9 21.1 237.0 472.4 271.0 117.4 173.3", "2004-11-18 114920000.00 2004-11-19 828806907.20 2004-11-22 1253785205.50 2004-11-23 1254751438.19 2004-11-24 1390568824.08", "\"https://datacenter.jin10.com\", \"pragma\": \"no-cache\", \"referer\": \"https://datacenter.jin10.com/reportType/dc_usa_michigan_consumer_sentiment\", \"sec-fetch-dest\": \"empty\", \"sec-fetch-mode\": \"cors\", \"sec-fetch-site\":", "\"\"\" 全球最大白银ETF--iShares Silver Trust持仓报告, 数据区间从20060429-至今 :return: pandas.Series 2006-04-29 653.17 2006-05-02", "'尼日利亚', '沙特', '阿联酋', '委内瑞拉', '欧佩克产量']].iloc[-2, :] except: temp_df = temp_df[['阿尔及利亚',", "110.4 173.6 2019-03-14 102.6 145.7 52.2 20.3 274.3 463.3 270.9", "10.80 3.00 -4.20 13.20 2018-11-13 12.70 14.20 -4.00 12.70 2018-12-12", "1000)))}\", headers=headers) # 日期序列 all_date_list = res.json()[\"data\"] bar = tqdm(reversed(all_date_list[:-1]))", "bar = tqdm(reversed(all_date_list[:-1])) for item in bar: bar.set_description(f\"Please wait for", "1] temp_df = temp_df.append(temp_se) temp_df.dropna(inplace=True) temp_df.sort_index(inplace=True) temp_df = temp_df.reset_index() temp_df.drop_duplicates(subset=\"index\",", "151.9 53.1 18.7 344.7 465.0 281.2 105.3 174.8 2018-11-13 105.4", "29.24 2004-11-23 0.00 2004-11-24 9.33 ... 2019-10-20 0.00 2019-10-21 0.00", "2017-07-12 106.0 166.8 52.7 19.7 379.0 450.2 270.9 85.2 173.3", "288.5 196.3 3213.9 2017-07-12 995.0 289.8 193.8 3261.1 2017-08-10 1006.7", "temp_df.name = \"silver_amount\" url = \"https://cdn.jin10.com/data_center/reports/etf_2.json\" r = requests.get(url) data_json", "\"*/*\", \"accept-encoding\": \"gzip, deflate, br\", \"accept-language\": \"zh-CN,zh;q=0.9,en;q=0.8\", \"cache-control\": \"no-cache\", \"origin\":", "big_df.T big_df.columns.name = \"日期\" big_df = big_df.astype(float) return big_df def", "450.2 270.9 85.2 173.3 2017-08-10 105.9 164.6 53.6 20.5 382.4", "2019-10-24 0.00 \"\"\" t = time.time() res = requests.get( JS_CONS_GOLD_ETF_URL.format(", "requests.get( JS_CONS_OPEC_URL.format( str(int(round(t * 1000))), str(int(round(t * 1000)) + 90)", "/usr/bin/env python \"\"\" Date: 2019/10/21 12:08 Desc: 获取金十数据-数据中心-主要机构-宏观经济 \"\"\" import", "All'] temp_df.sort_index(inplace=True) temp_df = temp_df.astype(float) return temp_df def macro_cons_opec_near_change(): \"\"\"", "919.66 2019-10-23 918.48 2019-10-24 918.48 \"\"\" t = time.time() res", "1.44 0.09 3.16 -0.17 5.39 5.08 2017-11-13 -3.84 6.98 0.71", "2017-01-18 -14.93 -0.63 -4.52 -22.09 2017-02-13 -49.62 -15.93 -3.05 -89.02", "temp_df[temp_df != 'Show All'] temp_df.sort_index(inplace=True) temp_df = temp_df.astype(float) return temp_df", "* 1000)) + 90) ) ) json_data = json.loads(res.text[res.text.find(\"{\"): res.text.rfind(\"}\")", "= temp_df big_df = big_df.T big_df.columns.name = \"日期\" big_df =", "270.5 73.0 168.0 2017-07-12 106.0 166.8 52.7 19.7 379.0 450.2", "\"max_date\": \"\", \"category\": \"etf\", \"attr_id\": \"2\", \"_\": str(int(round(t * 1000))),", "temp_df[\"index\"].astype(str) temp_df = temp_df.append(temp_append_df.reset_index()) temp_df.drop_duplicates(subset=[\"index\"], keep=\"last\", inplace=True) temp_df.index = pd.to_datetime(temp_df[\"index\"])", "20.4 379.5 442.4 270.5 73.0 168.0 2017-07-12 106.0 166.8 52.7", "2019-03-14 -8.60 -0.40 -14.20 -22.10 2019-04-10 -32.40 -0.90 -28.90 -53.40", "t = time.time() res = requests.get( JS_CONS_OPEC_URL.format( str(int(round(t * 1000))),", "\"https://datacenter.jin10.com/reportType/dc_usa_michigan_consumer_sentiment\", \"sec-fetch-dest\": \"empty\", \"sec-fetch-mode\": \"cors\", \"sec-fetch-site\": \"same-site\", \"user-agent\": \"Mozilla/5.0 (Windows", "= temp_se.iloc[:, 1] temp_df = temp_df.append(temp_se) temp_df.dropna(inplace=True) temp_df.sort_index(inplace=True) temp_df =", "18.3 382.3 442.9 270.5 98.2 179.1 2018-06-12 103.1 152.5 51.9", "7.10 -5.20 -1.10 2019-03-14 -8.60 -0.40 -14.20 -22.10 2019-04-10 -32.40", "wait for a moment, now downing {item}'s data\") res =", "from akshare.economic.cons import ( JS_CONS_GOLD_ETF_URL, JS_CONS_SLIVER_ETF_URL, JS_CONS_OPEC_URL, ) def macro_cons_gold_volume():", "= [item[\"datas\"][\"白银\"] for item in json_data[\"list\"]] value_df = pd.DataFrame(value_list) value_df.columns", "temp_df.index.name = None temp_df.name = \"silver_volume\" url = \"https://cdn.jin10.com/data_center/reports/etf_2.json\" r", "= requests.get(f\"https://datacenter-api.jin10.com/reports/dates?category=opec&_={str(int(round(t * 1000)))}\", headers=headers) # 日期序列 all_date_list = res.json()[\"data\"]", "2006-04-29 263651152 2006-05-02 263651152 2006-05-03 445408550 2006-05-04 555123947 2006-05-05 574713264", "json_data = json.loads(res.text[res.text.find(\"{\"): res.text.rfind(\"}\") + 1]) date_list = [item[\"date\"] for", "-8.60 -0.40 -14.20 -22.10 2019-04-10 -32.40 -0.90 -28.90 -53.40 2019-06-13", "in json_data[\"list\"]][0].keys(): try: value_list = [item[\"datas\"][country] for item in json_data[\"list\"]]", "653.17 2006-05-03 995.28 2006-05-04 1197.43 2006-05-05 1306.29 ... 2019-10-17 11847.91", "2017-12-13 101.3 158.1 53.3 19.7 381.8 439.6 270.3 97.3 179.0", "big_df = big_df.astype(float) return big_df def _macro_cons_opec_month(): \"\"\" 欧佩克报告-月度, 数据区间从20170118-至今", "6.47 10.18 2017-03-14 -0.02 -1.82 -0.44 -0.69 3.61 -6.20 -0.93", "__name__ == \"__main__\": macro_cons_gold_volume_df = macro_cons_gold_volume() print(macro_cons_gold_volume_df) macro_cons_gold_change_df = macro_cons_gold_change()", "52.0 18.3 382.3 442.9 270.5 98.2 179.1 2018-06-12 103.1 152.5", "def macro_cons_opec_month(): \"\"\" 欧佩克报告-月度, 数据区间从 20170118-至今 这里返回的具体索引日期的数据为上一个月的数据, 由于某些国家的数据有缺失 只选择有数据的国家返回 20200312:fix:由于", "\"https://datacenter-api.jin10.com/reports/list_v2\" params = { \"max_date\": \"\", \"category\": \"etf\", \"attr_id\": \"2\",", "-3.50 -23.60 \"\"\" t = time.time() big_df = pd.DataFrame() headers", "270.3 97.3 179.0 2018-01-18 103.7 163.3 52.6 19.7 382.9 440.5", "json_data[\"kinds\"] value_df.index = pd.to_datetime(date_list) temp_df = value_df[\"总价值(美元)\"] url = \"https://datacenter-api.jin10.com/reports/list_v2\"", "'委内瑞拉', '欧佩克产量']].iloc[-1, :] except: temp_df = temp_df[['阿尔及利亚', '安哥拉', '加蓬', '伊朗',", "temp_se = pd.DataFrame(r.json()[\"data\"][\"values\"]).iloc[:, [0, 1]] temp_se.index = pd.to_datetime(temp_se.iloc[:, 0]) temp_se", "... 2019-10-20 44286078486.23 2019-10-21 44333677232.68 2019-10-22 43907962483.56 2019-10-23 44120217405.82 2019-10-24", "11751.96 2019-10-23 11751.96 \"\"\" t = time.time() res = requests.get(", "= requests.get( f\"https://datacenter-api.jin10.com/reports/list?category=opec&date={item}&_={str(int(round(t * 1000)))}\", headers=headers) temp_df = pd.DataFrame(res.json()[\"data\"][\"values\"], columns=pd.DataFrame(res.json()[\"data\"][\"keys\"])[\"name\"].tolist()).T", "1051.2 300.4 119.7 3276.1 2018-11-13 1063.0 316.0 117.1 3290.0 2018-12-12", "4.44 0.00 17.82 17.42 2017-07-12 -0.09 6.60 -0.21 -0.77 1.67", "4.23 -5.44 2017-12-13 1.41 -10.87 -0.51 -0.47 -0.22 0.10 -0.53", "json_data[\"list\"]] value_list = [item[\"datas\"][\"白银\"] for item in json_data[\"list\"]] value_df =", "103.1 152.5 51.9 18.9 382.9 445.5 270.1 95.5 171.1 2018-07-11", "for item in json_data[\"list\"]] value_list = [item[\"datas\"][\"黄金\"] for item in", "pd.to_datetime(date_list) temp_df = value_df[\"总价值(美元)\"] url = \"https://datacenter-api.jin10.com/reports/list_v2\" params = {", "97.3 179.0 2018-01-18 103.7 163.3 52.6 19.7 382.9 440.5 270.0", "0.41 0.83 -0.03 -3.23 -0.23 -2.31 0.01 -11.23 13.83 2017-10-11", "inplace=True) temp_df.set_index(\"index\", inplace=True) temp_df = temp_df.squeeze() temp_df.index.name = None temp_df.name", "阿联酋 委内瑞拉 欧佩克产量 2017-01-18 1047.4 307.1 202.1 3308.5 2017-02-13 994.6", "7.40 2018-10-11 -0.80 5.70 53.10 -0.10 -15.00 0.80 0.60 10.30", "3244.8 2018-01-18 991.8 287.8 174.5 3241.6 2018-04-12 993.4 286.4 148.8", "-0.74 15.43 3.43 2017-09-12 0.41 0.83 -0.03 -3.23 -0.23 -2.31", "53.3 19.7 381.8 439.6 270.3 97.3 179.0 2018-01-18 103.7 163.3", "174.8 2018-11-13 105.4 153.3 52.5 18.6 329.6 465.4 276.4 111.4", "2019-06-13 -7.60 0.30 -3.50 -23.60 \"\"\" t = time.time() big_df", "98.2 179.1 2018-06-12 103.1 152.5 51.9 18.9 382.9 445.5 270.1", "-0.70 7.57 2018-04-12 -4.95 -8.17 0.26 -0.91 0.33 -1.31 0.23", "166.8 52.7 19.7 379.0 450.2 270.9 85.2 173.3 2017-08-10 105.9", "2018-06-12 8.55 -0.63 -4.25 3.54 2018-07-11 40.54 3.51 -4.75 17.34", "0.00 \"\"\" t = time.time() res = requests.get( JS_CONS_GOLD_ETF_URL.format( str(int(round(t", "2018-01-18 103.7 163.3 52.6 19.7 382.9 440.5 270.0 96.2 186.1", "3.54 2018-07-11 40.54 3.51 -4.75 17.34 2018-08-13 -5.28 6.92 -4.77", "0.70 52.40 0.90 -2.80 -12.60 -0.10 19.60 1.10 2019-06-13 0.60", "{item}'s data\") res = requests.get( f\"https://datacenter-api.jin10.com/reports/list?category=opec&date={item}&_={str(int(round(t * 1000)))}\", headers=headers) temp_df", "3]] temp_se.index = pd.to_datetime(temp_se.iloc[:, 0]) temp_se = temp_se.iloc[:, 1] temp_df", "\"\"\" 全球最大白银ETF--iShares Silver Trust持仓报告, 数据区间从20060429-至今 :return: pandas.Series 2006-04-29 0 2006-05-02", "= None temp_df.name = \"gold_volume\" temp_df = temp_df.astype(float) return temp_df", "3002.2 2019-06-13 969.0 306.1 74.1 2987.6 \"\"\" t = time.time()", "0.20 3.13 -11.35 2017-02-13 -4.17 -2.32 -1.67 -1.00 5.02 -16.57", "item in json_data[\"list\"]] big_df = pd.DataFrame() for country in [item[\"datas\"]", "-9.20 沙特 阿联酋 委内瑞拉 欧佩克产量 2017-01-18 -14.93 -0.63 -4.52 -22.09", "del temp_df[\"index\"] temp_df = temp_df[temp_df != 'Show All'] temp_df.sort_index(inplace=True) temp_df", "like Gecko) Chrome/80.0.3987.149 Safari/537.36\", \"x-app-id\": \"rU6QIu7JHe2gOUeR\", \"x-csrf-token\": \"\", \"x-version\": \"1.0.0\",", "headers=headers) # 日期序列 all_date_list = res.json()[\"data\"] bar = tqdm(reversed(all_date_list)) for", "44120217405.82 2019-10-24 44120217405.82 \"\"\" t = time.time() res = requests.get(", "temp_df def macro_cons_gold_amount(): \"\"\" 全球最大黄金ETF—SPDR Gold Trust持仓报告, 数据区间从20041118-至今 :return: pandas.Series", "305.9 73.2 3002.2 2019-06-13 969.0 306.1 74.1 2987.6 \"\"\" t", "999.6 288.3 183.4 3244.8 2018-01-18 991.8 287.8 174.5 3241.6 2018-04-12", "-0.87 3.56 -0.25 -0.87 0.95 4.26 0.20 3.13 -11.35 2017-02-13", "\"gold_amount\" temp_df = temp_df.astype(float) return temp_df def macro_cons_silver_volume(): \"\"\" 全球最大白银ETF--iShares", "欧佩克报告-变动, 数据区间从20170118-至今 :return: pandas.Series 阿尔及利亚 安哥拉 厄瓜多尔 加蓬 伊朗 伊拉克", "379.0 440.2 270.2 62.2 154.5 2017-05-11 104.7 169.2 52.4 20.6", "-1.40 2.30 1.00 2019-04-10 -0.70 0.70 52.40 0.90 -2.80 -12.60", "102.9 147.1 52.9 21.1 237.0 472.4 271.0 117.4 173.3 沙特", "3275.5 2017-10-11 997.5 290.5 189.0 3274.8 2017-11-13 1000.0 291.1 186.3", "这里返回的具体索引日期的数据为上一个月的数据, 由于某些国家的数据有缺失 只选择有数据的国家返回 20200312:fix:由于 “厄瓜多尔” 已经有几个月没有更新数据,在这里加以剔除 https://datacenter.jin10.com/reportType/dc_opec_report :return: pandas.Series 阿尔及利亚", "temp_append_df.name = \"silver_amount\" temp_df = temp_df.reset_index() temp_df[\"index\"] = temp_df[\"index\"].astype(str) temp_df", "-3.69 -1.60 -13.95 2017-04-12 4.16 -3.27 -2.59 -15.27 2017-05-11 4.92", "if __name__ == \"__main__\": macro_cons_gold_volume_df = macro_cons_gold_volume() print(macro_cons_gold_volume_df) macro_cons_gold_change_df =", "0.00 \"\"\" t = time.time() res = requests.get( JS_CONS_SLIVER_ETF_URL.format( str(int(round(t", "print(macro_cons_silver_volume_df) macro_cons_silver_change_df = macro_cons_silver_change() print(macro_cons_silver_change_df) macro_cons_silver_amount_df = macro_cons_silver_amount() print(macro_cons_silver_amount_df) print(pd.concat([macro_cons_silver_volume_df,", "2017-04-12 105.6 161.4 52.6 19.8 379.0 440.2 270.2 62.2 154.5", "def macro_cons_opec_near_change(): \"\"\" 欧佩克报告-变动, 数据区间从20170118-至今 :return: pandas.Series 阿尔及利亚 安哥拉 厄瓜多尔", "-0.75 9.71 -0.06 0.88 -3.47 -3.91 0.03 -6.16 5.08 2017-06-13", "pd import requests from tqdm import tqdm from akshare.economic.cons import", "params = { \"max_date\": \"\", \"category\": \"etf\", \"attr_id\": \"1\", \"_\":", "1042.0 289.7 134.0 3232.7 2018-08-13 1038.7 295.9 127.8 3232.3 2018-09-12", "\"no-cache\", \"origin\": \"https://datacenter.jin10.com\", \"pragma\": \"no-cache\", \"referer\": \"https://datacenter.jin10.com/reportType/dc_opec_report\", \"sec-fetch-mode\": \"cors\", \"sec-fetch-site\":", "3258.9 2017-12-13 999.6 288.3 183.4 3244.8 2018-01-18 991.8 287.8 174.5", "value_df.index = pd.to_datetime(date_list) temp_df = value_df[\"增持/减持(吨)\"] temp_df.name = \"silver_change\" url", "2019-10-17 11847.91 2019-10-18 11847.91 2019-10-21 11813.02 2019-10-22 11751.96 2019-10-23 11751.96", "-15.09 2017-12-13 -4.54 -3.55 -4.16 -13.35 2018-01-18 -1.09 -0.70 -8.22", "return temp_df def macro_cons_opec_near_change(): \"\"\" 欧佩克报告-变动, 数据区间从20170118-至今 :return: pandas.Series 阿尔及利亚", "-5.67 7.05 2018-09-12 -1.40 -0.80 0.40 18.80 -15.00 9.00 0.80", "[item for item in all_date_list if item.split(\"-\")[0] + item.split(\"-\")[1] +", "厄瓜多尔 加蓬 伊朗 伊拉克 科威特 利比亚 尼日利亚 \\ 2017-01-18 -0.87", "= None temp_df.name = \"gold_change\" temp_df = temp_df.astype(float) return temp_df", "= value_df[\"总库存(吨)\"] url = \"https://datacenter-api.jin10.com/reports/list_v2\" params = { \"max_date\": \"\",", "52.5 18.8 373.7 455.6 279.1 66.4 166.7 2018-09-12 104.5 144.8", ":] try: temp_df = temp_df[['阿尔及利亚', '安哥拉', '加蓬', '伊朗', '伊拉克', '科威特',", "-0.67 -1.58 17.26 2017-09-12 -1.03 -2.02 -3.19 -7.91 2017-10-11 -0.07", "1.69 -0.60 -4.36 -15.09 2017-12-13 -4.54 -3.55 -4.16 -13.35 2018-01-18", "big_df = big_df.T big_df.columns.name = \"日期\" big_df = big_df.astype(float) return", "144.8 52.9 18.7 358.4 464.9 280.2 92.6 172.5 2018-10-11 104.9", "print(pd.concat([macro_cons_silver_volume_df, macro_cons_silver_change_df, macro_cons_silver_amount_df], axis=1)) macro_cons_opec_near_change_df = macro_cons_opec_near_change() print(macro_cons_opec_near_change_df) macro_cons_opec_month_df =", "-1.09 -0.70 -8.22 4.24 2018-04-12 -4.69 4.49 -5.53 -20.14 2018-05-14", "145.6 52.5 18.8 373.7 455.6 279.1 66.4 166.7 2018-09-12 104.5", ":return: pandas.Series 2004-11-18 8.09 2004-11-19 57.85 2004-11-22 87.09 2004-11-23 87.09", "4.26 0.20 3.13 -11.35 2017-02-13 -4.17 -2.32 -1.67 -1.00 5.02", "101.3 158.1 53.3 19.7 381.8 439.6 270.3 97.3 179.0 2018-01-18", "2018-04-12 993.4 286.4 148.8 3195.8 2018-05-14 995.9 287.2 143.6 3193.0", "-1.58 17.26 2017-09-12 -1.03 -2.02 -3.19 -7.91 2017-10-11 -0.07 -0.84", "country big_df = big_df.append(temp_df) except: continue headers = { \"accept\":", "temp_df.sort_index(inplace=True) temp_df = temp_df.astype(float) return temp_df def macro_cons_opec_near_change(): \"\"\" 欧佩克报告-变动,", "52.9 18.7 358.4 464.9 280.2 92.6 172.5 2018-10-11 104.9 151.9", "3241.6 2018-04-12 993.4 286.4 148.8 3195.8 2018-05-14 995.9 287.2 143.6", "headers=headers) temp_se = pd.DataFrame(r.json()[\"data\"][\"values\"]).iloc[:, :2] temp_se.index = pd.to_datetime(temp_se.iloc[:, 0]) temp_se", "\"x-app-id\": \"rU6QIu7JHe2gOUeR\", \"x-csrf-token\": \"\", \"x-version\": \"1.0.0\", } res = requests.get(f\"https://datacenter-api.jin10.com/reports/dates?category=opec&_={str(int(round(t", "= append_temp_df[\"总库存\"] temp_append_df.name = \"silver_volume\" temp_df = temp_df.reset_index() temp_df[\"index\"] =", "18.8 373.7 455.6 279.1 66.4 166.7 2018-09-12 104.5 144.8 52.9", "19.4 381.4 441.4 270.9 66.9 160.8 2017-04-12 105.6 161.4 52.6", "append_temp_df[\"增持/减持\"] temp_append_df.name = \"silver_change\" temp_df = temp_df.reset_index() temp_df[\"index\"] = temp_df[\"index\"].astype(str)", "-11.35 2017-02-13 -4.17 -2.32 -1.67 -1.00 5.02 -16.57 -14.12 6.47", "\"\", \"category\": \"etf\", \"attr_id\": \"2\", \"_\": str(int(round(t * 1000))), }", "item in data_json[\"keys\"]] temp_append_df = append_temp_df[\"总价值\"] temp_append_df.name = \"silver_amount\" temp_df", "465.0 281.2 105.3 174.8 2018-11-13 105.4 153.3 52.5 18.6 329.6", "Chrome/80.0.3987.149 Safari/537.36\", \"x-app-id\": \"rU6QIu7JHe2gOUeR\", \"x-csrf-token\": \"\", \"x-version\": \"1.0.0\", } r", "-0.95 -6.08 -2.98 2017-05-11 -0.75 9.71 -0.06 0.88 -3.47 -3.91", "105.9 161.3 52.8 20.4 379.5 442.4 270.5 73.0 168.0 2017-07-12", "requests.get(f\"https://datacenter-api.jin10.com/reports/dates?category=opec&_={str(int(round(t * 1000)))}\", headers=headers) # 日期序列 all_date_list = res.json()[\"data\"] bar", "0.33 -1.31 0.23 -3.72 1.82 2018-05-14 1.77 -0.78 0.31 -0.93", "2018-04-12 -4.95 -8.17 0.26 -0.91 0.33 -1.31 0.23 -3.72 1.82", "653.17 2006-05-02 653.17 2006-05-03 995.28 2006-05-04 1197.43 2006-05-05 1306.29 ...", "temp_se = pd.DataFrame(r.json()[\"data\"][\"values\"]).iloc[:, :2] temp_se.index = pd.to_datetime(temp_se.iloc[:, 0]) temp_se =", "202.15 2006-05-05 108.86 ... 2019-10-17 -58.16 2019-10-18 0.00 2019-10-21 -34.89", "temp_append_df = append_temp_df[\"增持/减持\"] temp_append_df.name = \"silver_change\" temp_df = temp_df.reset_index() temp_df[\"index\"]", "1040.1 297.2 123.5 3256.5 2018-10-11 1051.2 300.4 119.7 3276.1 2018-11-13", "{ \"max_date\": \"\", \"category\": \"etf\", \"attr_id\": \"2\", \"_\": str(int(round(t *", "temp_df.name = \"gold_change\" temp_df = temp_df.astype(float) return temp_df def macro_cons_gold_amount():", "= value_df[\"增持/减持(吨)\"] url = \"https://datacenter-api.jin10.com/reports/list_v2\" params = { \"max_date\": \"\",", "2004-11-22 29.24 2004-11-23 0.00 2004-11-24 9.33 ... 2019-10-20 0.00 2019-10-21", "temp_df def macro_cons_opec_near_change(): \"\"\" 欧佩克报告-变动, 数据区间从20170118-至今 :return: pandas.Series 阿尔及利亚 安哥拉", "= { \"max_date\": \"\", \"category\": \"etf\", \"attr_id\": \"2\", \"_\": str(int(round(t", "-4.00 12.70 2018-12-12 37.70 7.10 -5.20 -1.10 2019-03-14 -8.60 -0.40", "-6.08 -2.98 2017-05-11 -0.75 9.71 -0.06 0.88 -3.47 -3.91 0.03", "temp_se = pd.DataFrame(r.json()[\"data\"][\"values\"]).iloc[:, [0, 3]] temp_se.index = pd.to_datetime(temp_se.iloc[:, 0]) temp_se", "\"https://datacenter.jin10.com/reportType/dc_opec_report\", \"sec-fetch-mode\": \"cors\", \"sec-fetch-site\": \"same-site\", \"user-agent\": \"Mozilla/5.0 (Windows NT 10.0;", "temp_se = pd.DataFrame(r.json()[\"data\"][\"values\"]).iloc[:, [0, 2]] temp_se.index = pd.to_datetime(temp_se.iloc[:, 0]) temp_se", "-0.91 0.33 -1.31 0.23 -3.72 1.82 2018-05-14 1.77 -0.78 0.31", "加蓬 伊朗 伊拉克 科威特 利比亚 尼日利亚 \\ 2017-01-18 108.0 172.4", "macro_cons_silver_amount_df], axis=1)) macro_cons_opec_near_change_df = macro_cons_opec_near_change() print(macro_cons_opec_near_change_df) macro_cons_opec_month_df = macro_cons_opec_month() print(macro_cons_opec_month_df)", "\"1.0.0\", } res = requests.get(f\"https://datacenter-api.jin10.com/reports/dates?category=opec&_={str(int(round(t * 1000)))}\", headers=headers) # 日期序列", "1038.7 295.9 127.8 3232.3 2018-09-12 1040.1 297.2 123.5 3256.5 2018-10-11", "return temp_df def macro_cons_silver_amount(): \"\"\" 全球最大白银ETF--iShares Silver Trust持仓报告, 数据区间从20060429-至今 :return:", "Desc: 获取金十数据-数据中心-主要机构-宏观经济 \"\"\" import json import time import pandas as", "446.8 270.3 100.1 174.8 2017-09-12 106.5 164.6 53.7 17.3 382.8", "2018-05-14 4.65 0.61 -4.17 1.21 2018-06-12 8.55 -0.63 -4.25 3.54", "1]) date_list = [item[\"date\"] for item in json_data[\"list\"]] value_list =", "json_data[\"list\"]] big_df = pd.DataFrame() for country in [item[\"datas\"] for item", "\"1.0.0\", } r = requests.get(url, params=params, headers=headers) temp_se = pd.DataFrame(r.json()[\"data\"][\"values\"]).iloc[:,", "0 2006-05-02 0.00 2006-05-03 342.11 2006-05-04 202.15 2006-05-05 108.86 ...", "big_df = big_df.append(temp_df) except: continue headers = { \"accept\": \"*/*\",", "json_data[\"kinds\"] value_df.index = pd.to_datetime(date_list) temp_df = value_df[\"总库存(吨)\"] url = \"https://datacenter-api.jin10.com/reports/list_v2\"", "数据区间从20060429-至今 :return: pandas.Series 2006-04-29 263651152 2006-05-02 263651152 2006-05-03 445408550 2006-05-04", "164.1 53.6 20.1 382.7 449.4 270.0 92.3 185.5 2017-11-13 101.2", "3276.1 2018-11-13 1063.0 316.0 117.1 3290.0 2018-12-12 1101.6 324.6 113.7", "998.7 286.5 139.2 3186.9 2018-07-11 1042.0 289.7 134.0 3232.7 2018-08-13", "\"origin\": \"https://datacenter.jin10.com\", \"pragma\": \"no-cache\", \"referer\": \"https://datacenter.jin10.com/reportType/dc_opec_report\", \"sec-fetch-mode\": \"cors\", \"sec-fetch-site\": \"same-site\",", "66.9 160.8 2017-04-12 105.6 161.4 52.6 19.8 379.0 440.2 270.2", "-0.63 -4.52 -22.09 2017-02-13 -49.62 -15.93 -3.05 -89.02 2017-03-14 -6.81", "JS_CONS_GOLD_ETF_URL.format( str(int(round(t * 1000))), str(int(round(t * 1000)) + 90) )", "= requests.get( JS_CONS_GOLD_ETF_URL.format( str(int(round(t * 1000))), str(int(round(t * 1000)) +", "in json_data[\"list\"]] value_list = [item[\"datas\"][\"白银\"] for item in json_data[\"list\"]] value_df", "96.2 173.8 2017-12-13 101.3 158.1 53.3 19.7 381.8 439.6 270.3", "51.8 18.3 381.4 442.6 270.4 96.8 181.0 2018-05-14 99.7 151.5", "0.19 -2.87 -0.85 -0.95 -6.08 -2.98 2017-05-11 -0.75 9.71 -0.06", "Trust持仓报告, 数据区间从20041118-至今 :return: pandas.Series 2004-11-18 114920000.00 2004-11-19 828806907.20 2004-11-22 1253785205.50", "0.45 4.44 0.00 17.82 17.42 2017-07-12 -0.09 6.60 -0.21 -0.77", "not in date_list] for item in reversed(need_date_list): res = requests.get(", "1002.2 290.1 191.8 3275.5 2017-10-11 997.5 290.5 189.0 3274.8 2017-11-13", "macro_cons_silver_volume(): \"\"\" 全球最大白银ETF--iShares Silver Trust持仓报告, 数据区间从20060429-至今 :return: pandas.Series 2006-04-29 653.17", "108.0 172.4 54.5 21.3 372.0 463.2 281.2 60.8 154.2 2017-02-13", "105.3 174.8 2018-11-13 105.4 153.3 52.5 18.6 329.6 465.4 276.4", "270.5 98.2 179.1 2018-06-12 103.1 152.5 51.9 18.9 382.9 445.5", "伊朗 伊拉克 科威特 利比亚 尼日利亚 \\ 2017-01-18 108.0 172.4 54.5", "= \"gold_volume\" temp_df = temp_df.astype(float) return temp_df def macro_cons_gold_change(): \"\"\"", "2006-05-05 108.86 ... 2019-10-17 -58.16 2019-10-18 0.00 2019-10-21 -34.89 2019-10-22", "'科威特', '利比亚', '尼日利亚', '沙特', '阿联酋', '委内瑞拉', '欧佩克产量']].iloc[-2, :] except: temp_df", "193.2 3286.9 2017-09-12 1002.2 290.1 191.8 3275.5 2017-10-11 997.5 290.5", "print(macro_cons_silver_amount_df) print(pd.concat([macro_cons_silver_volume_df, macro_cons_silver_change_df, macro_cons_silver_amount_df], axis=1)) macro_cons_opec_near_change_df = macro_cons_opec_near_change() print(macro_cons_opec_near_change_df) macro_cons_opec_month_df", "2.78 2018-08-13 1.38 1.17 0.42 -0.34 -5.63 2.41 7.85 -5.67", "temp_df = value_df[\"增持/减持(吨)\"] url = \"https://datacenter-api.jin10.com/reports/list_v2\" params = { \"max_date\":", "temp_df = temp_df.reset_index() temp_df.drop_duplicates(subset=\"index\", keep=\"last\", inplace=True) temp_df.set_index(\"index\", inplace=True) temp_df =", "3195.8 2018-05-14 995.9 287.2 143.6 3193.0 2018-06-12 998.7 286.5 139.2", "2.20 0.50 0.70 1.20 -7.00 -1.40 2.30 1.00 2019-04-10 -0.70", "20.5 382.4 446.8 270.3 100.1 174.8 2017-09-12 106.5 164.6 53.7", "173.6 2019-03-14 102.6 145.7 52.2 20.3 274.3 463.3 270.9 90.6", "\"\", \"x-version\": \"1.0.0\", } r = requests.get(url, params=params, headers=headers) temp_se", "0.35 -2.27 7.15 2.73 -25.43 2.78 2018-08-13 1.38 1.17 0.42", "= pd.DataFrame(res.json()[\"data\"][\"values\"], columns=pd.DataFrame(res.json()[\"data\"][\"keys\"])[\"name\"].tolist()).T temp_df.columns = temp_df.iloc[0, :] temp_df = temp_df.iloc[1:,", "7.40 -0.10 2.30 -22.70 9.40 1.30 -0.30 -9.20 沙特 阿联酋", "-1.10 -3.00 2019-03-14 0.20 2.20 0.50 0.70 1.20 -7.00 -1.40", "item.split(\"-\")[2] not in date_list] for item in reversed(need_date_list): res =", "\"silver_volume\" url = \"https://cdn.jin10.com/data_center/reports/etf_2.json\" r = requests.get(url) data_json = r.json()", "1.82 2018-05-14 1.77 -0.78 0.31 -0.93 1.00 -0.07 0.08 0.69", "(Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149", "Trust持仓报告, 数据区间从20060429-至今 :return: pandas.Series 2006-04-29 263651152 2006-05-02 263651152 2006-05-03 445408550", "= tqdm(reversed(all_date_list[:-1])) for item in bar: bar.set_description(f\"Please wait for a", "pd.to_datetime(temp_se.iloc[:, 0]) temp_se = temp_se.iloc[:, 1] temp_df = temp_df.append(temp_se) temp_df.dropna(inplace=True)", "18.80 -15.00 9.00 0.80 25.60 7.40 2018-10-11 -0.80 5.70 53.10", "-4.98 2019-10-23 -1.18 2019-10-24 0.00 \"\"\" t = time.time() res", "macro_cons_gold_amount(): \"\"\" 全球最大黄金ETF—SPDR Gold Trust持仓报告, 数据区间从20041118-至今 :return: pandas.Series 2004-11-18 114920000.00", "143.1 51.9 19.0 379.9 453.3 273.1 70.8 166.0 2018-08-13 106.2", "# 日期序列 all_date_list = res.json()[\"data\"] bar = tqdm(reversed(all_date_list)) for item", "2017-12-13 -4.54 -3.55 -4.16 -13.35 2018-01-18 -1.09 -0.70 -8.22 4.24", "297.2 123.5 3256.5 2018-10-11 1051.2 300.4 119.7 3276.1 2018-11-13 1063.0", "9.40 1.30 -0.30 -9.20 沙特 阿联酋 委内瑞拉 欧佩克产量 2017-01-18 -14.93", "= temp_df return big_df.T def macro_cons_opec_month(): \"\"\" 欧佩克报告-月度, 数据区间从 20170118-至今", "由于某些国家的数据有缺失 只选择有数据的国家返回 20200312:fix:由于 “厄瓜多尔” 已经有几个月没有更新数据,在这里加以剔除 https://datacenter.jin10.com/reportType/dc_opec_report :return: pandas.Series 阿尔及利亚 安哥拉", "2018-09-12 104.5 144.8 52.9 18.7 358.4 464.9 280.2 92.6 172.5", "-2.59 -15.27 2017-05-11 4.92 -6.23 -2.60 -1.82 2017-06-13 0.23 -1.80", "2018-08-13 1038.7 295.9 127.8 3232.3 2018-09-12 1040.1 297.2 123.5 3256.5", "\"\"\" 全球最大黄金ETF—SPDR Gold Trust持仓报告, 数据区间从20041118-至今 :return: pandas.Series 2004-11-18 114920000.00 2004-11-19", "104.5 144.8 52.9 18.7 358.4 464.9 280.2 92.6 172.5 2018-10-11", "12.70 14.20 -4.00 12.70 2018-12-12 37.70 7.10 -5.20 -1.10 2019-03-14", "只选择有数据的国家返回 :return: pandas.Series 阿尔及利亚 安哥拉 厄瓜多尔 加蓬 伊朗 伊拉克 科威特", "pd.to_datetime(date_list) temp_df = value_df[\"总库存(吨)\"] url = \"https://datacenter-api.jin10.com/reports/list_v2\" params = {", "= [item for item in all_date_list if item.split(\"-\")[0] + item.split(\"-\")[1]", "382.3 442.9 270.5 98.2 179.1 2018-06-12 103.1 152.5 51.9 18.9", "17.34 2018-08-13 -5.28 6.92 -4.77 4.07 2018-09-12 3.80 1.20 -3.60", "828806907.20 2004-11-22 1253785205.50 2004-11-23 1254751438.19 2004-11-24 1390568824.08 ... 2019-10-20 44286078486.23", "288.3 183.4 3244.8 2018-01-18 991.8 287.8 174.5 3241.6 2018-04-12 993.4", "全球最大白银ETF--iShares Silver Trust持仓报告, 数据区间从20060429-至今 :return: pandas.Series 2006-04-29 263651152 2006-05-02 263651152", "temp_df.sort_index(inplace=True) temp_df = temp_df.astype(float) return temp_df def macro_cons_silver_amount(): \"\"\" 全球最大白银ETF--iShares", "164.1 52.6 19.4 381.4 441.4 270.9 66.9 160.8 2017-04-12 105.6", "153.3 52.5 18.6 329.6 465.4 276.4 111.4 175.1 2018-12-12 105.2", "'尼日利亚', '沙特', '阿联酋', '委内瑞拉', '欧佩克产量']].iloc[-1, :] except: temp_df = temp_df[['阿尔及利亚',", "53.7 17.3 382.8 444.8 270.2 89.0 186.1 2017-10-11 104.6 164.1", "import pandas as pd import requests from tqdm import tqdm", "0.00 2004-11-24 9.33 ... 2019-10-20 0.00 2019-10-21 0.00 2019-10-22 -4.98", "'欧佩克产量']].iloc[-2, :] big_df[item] = temp_df return big_df.T def macro_cons_opec_month(): \"\"\"", "temp_df def macro_cons_silver_change(): \"\"\" 全球最大白银ETF--iShares Silver Trust持仓报告, 数据区间从20060429-至今 :return: pandas.Series", "macro_cons_gold_volume(): \"\"\" 全球最大黄金ETF—SPDR Gold Trust持仓报告, 数据区间从20041118-至今 :return: pandas.Series 2004-11-18 8.09", "3054.9 2019-04-10 979.4 305.9 73.2 3002.2 2019-06-13 969.0 306.1 74.1", "macro_cons_silver_change_df, macro_cons_silver_amount_df], axis=1)) macro_cons_opec_near_change_df = macro_cons_opec_near_change() print(macro_cons_opec_near_change_df) macro_cons_opec_month_df = macro_cons_opec_month()", "20.6 375.9 437.3 270.2 55.0 150.8 2017-06-13 105.9 161.3 52.8", "0.01 -11.23 13.83 2017-10-11 -0.85 -0.29 -0.05 1.44 0.09 3.16", "274.3 463.3 270.9 90.6 174.1 2019-04-10 101.8 145.4 52.4 21.4", "-8.22 4.24 2018-04-12 -4.69 4.49 -5.53 -20.14 2018-05-14 4.65 0.61", "temp_df = temp_df[['阿尔及利亚', '安哥拉', '加蓬', '伊朗', '伊拉克', '科威特', '利比亚', '尼日利亚',", "444.8 270.2 89.0 186.1 2017-10-11 104.6 164.1 53.6 20.1 382.7", "0.60 10.30 2.60 2018-11-13 -0.40 2.20 -0.30 0.30 -15.60 465.30", "0.00 2019-10-21 0.00 2019-10-22 -4.98 2019-10-23 -1.18 2019-10-24 0.00 \"\"\"", "\"max_date\": \"\", \"category\": \"etf\", \"attr_id\": \"1\", \"_\": str(int(round(t * 1000))),", "temp_df[['阿尔及利亚', '安哥拉', '厄瓜多尔', '加蓬', '伊朗', '伊拉克', '科威特', '利比亚', '尼日利亚', '沙特',", "2017-09-12 0.41 0.83 -0.03 -3.23 -0.23 -2.31 0.01 -11.23 13.83", "2017-02-13 -4.17 -2.32 -1.67 -1.00 5.02 -16.57 -14.12 6.47 10.18", "'伊朗', '伊拉克', '科威特', '利比亚', '尼日利亚', '沙特', '阿联酋', '委内瑞拉', '欧佩克产量']].iloc[-2, :]", "in json_data[\"list\"]] big_df = pd.DataFrame() for country in [item[\"datas\"] for", "... 2019-10-20 924.64 2019-10-21 924.64 2019-10-22 919.66 2019-10-23 918.48 2019-10-24", "已经有几个月没有更新数据,在这里加以剔除 https://datacenter.jin10.com/reportType/dc_opec_report :return: pandas.Series 阿尔及利亚 安哥拉 厄瓜多尔 加蓬 伊朗 伊拉克", "= temp_df.squeeze() temp_df.index.name = None temp_df.name = \"silver_change\" url =", "macro_cons_gold_amount_df = macro_cons_gold_amount() print(macro_cons_gold_amount_df) print(pd.concat([macro_cons_gold_volume_df, macro_cons_gold_change_df, macro_cons_gold_amount_df], axis=1)) macro_cons_silver_volume_df =", "= time.time() res = requests.get( JS_CONS_OPEC_URL.format( str(int(round(t * 1000))), str(int(round(t", "str(int(round(t * 1000))), str(int(round(t * 1000)) + 90) ) )", "18.9 382.9 445.5 270.1 95.5 171.1 2018-07-11 103.9 143.1 51.9", "-0.93 1.00 -0.07 0.08 0.69 -0.83 2018-06-12 3.90 1.40 0.06", "\"no-cache\", \"referer\": \"https://datacenter.jin10.com/reportType/dc_opec_report\", \"sec-fetch-mode\": \"cors\", \"sec-fetch-site\": \"same-site\", \"user-agent\": \"Mozilla/5.0 (Windows", "res.json()[\"data\"] bar = tqdm(reversed(all_date_list[:-1])) for item in bar: bar.set_description(f\"Please wait", "186.1 2018-04-12 98.4 152.4 51.8 18.3 381.4 442.6 270.4 96.8", "172.5 2018-10-11 104.9 151.9 53.1 18.7 344.7 465.0 281.2 105.3", "= value_df[\"增持/减持(吨)\"] temp_df.name = \"silver_change\" url = \"https://datacenter-api.jin10.com/reports/list_v2\" params =", "-0.57 -2.43 -5.35 2018-07-11 0.46 -8.83 -0.09 0.35 -2.27 7.15", "\\ 2017-01-18 108.0 172.4 54.5 21.3 372.0 463.2 281.2 60.8", "19.8 379.0 440.2 270.2 62.2 154.5 2017-05-11 104.7 169.2 52.4", "2019-03-14 1008.7 307.2 100.8 3054.9 2019-04-10 979.4 305.9 73.2 3002.2", "'欧佩克产量']].iloc[-1, :] except: temp_df = temp_df[['阿尔及利亚', '安哥拉', '加蓬', '伊朗', '伊拉克',", "temp_df.index.name = None temp_df.name = \"silver_amount\" url = \"https://cdn.jin10.com/data_center/reports/etf_2.json\" r", "441.4 270.9 66.9 160.8 2017-04-12 105.6 161.4 52.6 19.8 379.0", "value_df.index = pd.to_datetime(date_list) temp_df = value_df[\"总价值(美元)\"] url = \"https://datacenter-api.jin10.com/reports/list_v2\" params", "-1.93 0.85 0.71 0.69 -3.31 -0.74 15.43 3.43 2017-09-12 0.41", "0.79 -0.25 -0.70 7.57 2018-04-12 -4.95 -8.17 0.26 -0.91 0.33", "\"attr_id\": \"2\", \"_\": str(int(round(t * 1000))), } headers = {", "2018-08-13 -5.28 6.92 -4.77 4.07 2018-09-12 3.80 1.20 -3.60 27.80", "'伊朗', '伊拉克', '科威特', '利比亚', '尼日利亚', '沙特', '阿联酋', '委内瑞拉', '欧佩克产量']].iloc[-1, :]", "287.8 174.5 3241.6 2018-04-12 993.4 286.4 148.8 3195.8 2018-05-14 995.9", "数据区间从20041118-至今 :return: pandas.Series 2004-11-18 114920000.00 2004-11-19 828806907.20 2004-11-22 1253785205.50 2004-11-23", "-20.14 2018-05-14 4.65 0.61 -4.17 1.21 2018-06-12 8.55 -0.63 -4.25", "All 2019-10-23 Show All \"\"\" t = time.time() res =", "[item[\"date\"] for item in json_data[\"list\"]] value_list = [item[\"datas\"][\"黄金\"] for item", "'伊拉克', '科威特', '利比亚', '尼日利亚', '沙特', '阿联酋', '委内瑞拉', '欧佩克产量']].iloc[-2, :] big_df[item]", "-14.20 -22.10 2019-04-10 -32.40 -0.90 -28.90 -53.40 2019-06-13 -7.60 0.30", "3213.9 2017-03-14 979.7 292.5 198.7 3195.8 2017-04-12 999.4 289.5 197.2", "-1.03 -2.02 -3.19 -7.91 2017-10-11 -0.07 -0.84 -5.19 8.85 2017-11-13", "time.time() res = requests.get( JS_CONS_SLIVER_ETF_URL.format( str(int(round(t * 1000))), str(int(round(t *", "macro_cons_gold_amount_df], axis=1)) macro_cons_silver_volume_df = macro_cons_silver_volume() print(macro_cons_silver_volume_df) macro_cons_silver_change_df = macro_cons_silver_change() print(macro_cons_silver_change_df)", "20200312:fix:由于 “厄瓜多尔” 已经有几个月没有更新数据,在这里加以剔除 https://datacenter.jin10.com/reportType/dc_opec_report :return: pandas.Series 阿尔及利亚 安哥拉 厄瓜多尔 加蓬", "100.8 3054.9 2019-04-10 979.4 305.9 73.2 3002.2 2019-06-13 969.0 306.1", "temp_append_df.name = \"silver_volume\" temp_df = temp_df.reset_index() temp_df[\"index\"] = temp_df[\"index\"].astype(str) temp_df", "= pd.DataFrame(r.json()[\"data\"][\"values\"]).iloc[:, [0, 2]] temp_se.index = pd.to_datetime(temp_se.iloc[:, 0]) temp_se =", "res.text.rfind(\"}\") + 1]) date_list = [item[\"date\"] for item in json_data[\"list\"]]", "-3.30 6.00 -1.70 2018-12-12 -0.50 0.30 0.10 -1.10 -38.00 -2.30", "= macro_cons_silver_volume() print(macro_cons_silver_volume_df) macro_cons_silver_change_df = macro_cons_silver_change() print(macro_cons_silver_change_df) macro_cons_silver_amount_df = macro_cons_silver_amount()", "params=params, headers=headers) temp_se = pd.DataFrame(r.json()[\"data\"][\"values\"]).iloc[:, [0, 1]] temp_se.index = pd.to_datetime(temp_se.iloc[:,", "json import time import pandas as pd import requests from", "res = requests.get( JS_CONS_OPEC_URL.format( str(int(round(t * 1000))), str(int(round(t * 1000))", "98.4 152.4 51.8 18.3 381.4 442.6 270.4 96.8 181.0 2018-05-14", "科威特 利比亚 尼日利亚 \\ 2017-01-18 -0.87 3.56 -0.25 -0.87 0.95", "52.5 17.6 295.4 463.1 280.9 110.4 173.6 2019-03-14 102.6 145.7", "tqdm import tqdm from akshare.economic.cons import ( JS_CONS_GOLD_ETF_URL, JS_CONS_SLIVER_ETF_URL, JS_CONS_OPEC_URL,", "3286.9 2017-09-12 1002.2 290.1 191.8 3275.5 2017-10-11 997.5 290.5 189.0", "def macro_cons_silver_change(): \"\"\" 全球最大白银ETF--iShares Silver Trust持仓报告, 数据区间从20060429-至今 :return: pandas.Series 2006-04-29", "463.2 281.2 60.8 154.2 2017-02-13 104.5 165.1 52.7 19.9 377.5", "2006-05-05 1306.29 ... 2019-10-17 11847.91 2019-10-18 11847.91 2019-10-21 11813.02 2019-10-22", "12.70 2018-12-12 37.70 7.10 -5.20 -1.10 2019-03-14 -8.60 -0.40 -14.20", "append_temp_df = pd.DataFrame(data_json[\"values\"]).T append_temp_df.columns = [item[\"name\"] for item in data_json[\"keys\"]]", "4.92 -6.23 -2.60 -1.82 2017-06-13 0.23 -1.80 -0.77 33.61 2017-07-12", "-3.00 2019-03-14 0.20 2.20 0.50 0.70 1.20 -7.00 -1.40 2.30", "-12.60 -0.10 19.60 1.10 2019-06-13 0.60 7.40 -0.10 2.30 -22.70", "1.32 0.79 -0.25 -0.70 7.57 2018-04-12 -4.95 -8.17 0.26 -0.91", "19.0 379.9 453.3 273.1 70.8 166.0 2018-08-13 106.2 145.6 52.5", "3.43 2017-09-12 0.41 0.83 -0.03 -3.23 -0.23 -2.31 0.01 -11.23", "85.2 173.3 2017-08-10 105.9 164.6 53.6 20.5 382.4 446.8 270.3", "[item[\"date\"] for item in json_data[\"list\"]] value_list = [item[\"datas\"][\"白银\"] for item", "52.2 20.3 274.3 463.3 270.9 90.6 174.1 2019-04-10 101.8 145.4", "temp_df = temp_df.squeeze() temp_df.index.name = None temp_df.name = \"silver_volume\" url", "res = requests.get( f\"https://datacenter-api.jin10.com/reports/list?category=opec&date={item}&_={str(int(round(t * 1000)))}\", headers=headers) temp_df = pd.DataFrame(res.json()[\"data\"][\"values\"],", "164.6 53.7 17.3 382.8 444.8 270.2 89.0 186.1 2017-10-11 104.6", "requests.get(url, params=params, headers=headers) temp_se = pd.DataFrame(r.json()[\"data\"][\"values\"]).iloc[:, [0, 2]] temp_se.index =", "2017-10-11 104.6 164.1 53.6 20.1 382.7 449.4 270.0 92.3 185.5", "temp_df.astype(float) return temp_df def macro_cons_silver_volume(): \"\"\" 全球最大白银ETF--iShares Silver Trust持仓报告, 数据区间从20060429-至今", "temp_df def macro_cons_silver_volume(): \"\"\" 全球最大白银ETF--iShares Silver Trust持仓报告, 数据区间从20060429-至今 :return: pandas.Series", "_macro_cons_opec_month(): \"\"\" 欧佩克报告-月度, 数据区间从20170118-至今 这里返回的具体索引日期的数据为上一个月的数据, 由于某些国家的数据有缺失, 只选择有数据的国家返回 :return: pandas.Series 阿尔及利亚", "pandas.Series 2006-04-29 263651152 2006-05-02 263651152 2006-05-03 445408550 2006-05-04 555123947 2006-05-05", "-4.69 4.49 -5.53 -20.14 2018-05-14 4.65 0.61 -4.17 1.21 2018-06-12", "in reversed(need_date_list): res = requests.get( f\"https://datacenter-api.jin10.com/reports/list?category=opec&date={item}&_={str(int(round(t * 1000)))}\", headers=headers) temp_df", "= \"gold_amount\" temp_df = temp_df.astype(float) return temp_df def macro_cons_silver_volume(): \"\"\"", "281.2 60.8 154.2 2017-02-13 104.5 165.1 52.7 19.9 377.5 447.6", "-0.78 0.31 -0.93 1.00 -0.07 0.08 0.69 -0.83 2018-06-12 3.90", "280.2 92.6 172.5 2018-10-11 104.9 151.9 53.1 18.7 344.7 465.0", "-28.90 -53.40 2019-06-13 -7.60 0.30 -3.50 -23.60 \"\"\" t =", "= pd.DataFrame(value_list) value_df.columns = json_data[\"kinds\"] value_df.index = pd.to_datetime(date_list) temp_df =", "1.77 -0.78 0.31 -0.93 1.00 -0.07 0.08 0.69 -0.83 2018-06-12", "temp_df = temp_df.append(temp_se) temp_df.dropna(inplace=True) temp_df.sort_index(inplace=True) temp_df = temp_df.reset_index() temp_df.drop_duplicates(subset=\"index\", keep=\"last\",", "= big_df.astype(float) return big_df def _macro_cons_opec_month(): \"\"\" 欧佩克报告-月度, 数据区间从20170118-至今 这里返回的具体索引日期的数据为上一个月的数据,", "52.40 0.90 -2.80 -12.60 -0.10 19.60 1.10 2019-06-13 0.60 7.40", "data_json[\"keys\"]] temp_append_df = append_temp_df[\"总库存\"] temp_append_df.name = \"silver_volume\" temp_df = temp_df.reset_index()", "JS_CONS_SLIVER_ETF_URL.format( str(int(round(t * 1000))), str(int(round(t * 1000)) + 90) )", "52.8 20.4 379.5 442.4 270.5 73.0 168.0 2017-07-12 106.0 166.8", "[item[\"name\"] for item in data_json[\"keys\"]] temp_append_df = append_temp_df[\"总库存\"] temp_append_df.name =", "-0.70 -8.22 4.24 2018-04-12 -4.69 4.49 -5.53 -20.14 2018-05-14 4.65", "-4.16 -13.35 2018-01-18 -1.09 -0.70 -8.22 4.24 2018-04-12 -4.69 4.49", "keep=\"last\", inplace=True) temp_df.set_index(\"index\", inplace=True) temp_df = temp_df.squeeze() temp_df.index.name = None", "18.3 381.4 442.6 270.4 96.8 181.0 2018-05-14 99.7 151.5 52.0", "\"\"\" t = time.time() res = requests.get( JS_CONS_OPEC_URL.format( str(int(round(t *", "13.20 2018-11-13 12.70 14.20 -4.00 12.70 2018-12-12 37.70 7.10 -5.20", "-0.85 -0.29 -0.05 1.44 0.09 3.16 -0.17 5.39 5.08 2017-11-13", "} r = requests.get(url, params=params, headers=headers) temp_se = pd.DataFrame(r.json()[\"data\"][\"values\"]).iloc[:, [0,", "52.4 21.4 269.8 452.2 270.9 109.8 173.3 2019-06-13 102.9 147.1", "2017-08-10 -0.10 -1.93 0.85 0.71 0.69 -3.31 -0.74 15.43 3.43", "119.7 3276.1 2018-11-13 1063.0 316.0 117.1 3290.0 2018-12-12 1101.6 324.6", "5.13 -0.07 -1.36 39.35 2017-08-10 3.18 -0.67 -1.58 17.26 2017-09-12", "73.0 168.0 2017-07-12 106.0 166.8 52.7 19.7 379.0 450.2 270.9", "152.4 51.8 18.3 381.4 442.6 270.4 96.8 181.0 2018-05-14 99.7", "temp_df.reset_index() temp_df[\"index\"] = temp_df[\"index\"].astype(str) temp_df = temp_df.append(temp_append_df.reset_index()) temp_df.drop_duplicates(subset=[\"index\"], keep=\"last\", inplace=True)", "-34.89 2019-10-22 -61.06 2019-10-23 0.00 \"\"\" t = time.time() res", "2006-05-03 342.11 2006-05-04 202.15 2006-05-05 108.86 ... 2019-10-17 -58.16 2019-10-18", "-5.35 2018-07-11 0.46 -8.83 -0.09 0.35 -2.27 7.15 2.73 -25.43", "27.80 2018-10-11 10.80 3.00 -4.20 13.20 2018-11-13 12.70 14.20 -4.00", ":] temp_df = temp_df.iloc[1:, :] try: temp_df = temp_df[['阿尔及利亚', '安哥拉',", "-0.83 2018-06-12 3.90 1.40 0.06 0.18 0.56 2.77 -0.57 -2.43", ":] temp_df = temp_df[['阿尔及利亚', '安哥拉', '厄瓜多尔', '加蓬', '伊朗', '伊拉克', '科威特',", "... 2019-10-17 11847.91 2019-10-18 11847.91 2019-10-21 11813.02 2019-10-22 11751.96 2019-10-23", "2017-01-18 -0.87 3.56 -0.25 -0.87 0.95 4.26 0.20 3.13 -11.35", "0.69 -3.31 -0.74 15.43 3.43 2017-09-12 0.41 0.83 -0.03 -3.23", "1006.7 290.5 193.2 3286.9 2017-09-12 1002.2 290.1 191.8 3275.5 2017-10-11", "'Show All'] temp_df.sort_index(inplace=True) temp_df = temp_df.astype(float) return temp_df def macro_cons_opec_near_change():", "value_list = [item[\"datas\"][\"黄金\"] for item in json_data[\"list\"]] value_df = pd.DataFrame(value_list)", "1.00 2019-04-10 -0.70 0.70 52.40 0.90 -2.80 -12.60 -0.10 19.60", "'尼日利亚', '沙特', '阿联酋', '委内瑞拉', '欧佩克产量']].iloc[-2, :] big_df[item] = temp_df return", "-25.43 2.78 2018-08-13 1.38 1.17 0.42 -0.34 -5.63 2.41 7.85", "requests.get(url, params=params, headers=headers) temp_se = pd.DataFrame(r.json()[\"data\"][\"values\"]).iloc[:, [0, 1]] temp_se.index =", "\"\"\" 欧佩克报告-变动, 数据区间从20170118-至今 :return: pandas.Series 阿尔及利亚 安哥拉 厄瓜多尔 加蓬 伊朗", "237.0 472.4 271.0 117.4 173.3 沙特 阿联酋 委内瑞拉 欧佩克产量 2017-01-18", "pandas.Series 2004-11-18 0 2004-11-19 49.76 2004-11-22 29.24 2004-11-23 0.00 2004-11-24", "'阿联酋', '委内瑞拉', '欧佩克产量']].iloc[-2, :] except: temp_df = temp_df[['阿尔及利亚', '安哥拉', '加蓬',", "pandas.Series 2004-11-18 114920000.00 2004-11-19 828806907.20 2004-11-22 1253785205.50 2004-11-23 1254751438.19 2004-11-24", "columns=pd.DataFrame(res.json()[\"data\"][\"keys\"])[\"name\"].tolist()).T temp_df.columns = temp_df.iloc[0, :] temp_df = temp_df.iloc[1:, :] try:", "r = requests.get(url) data_json = r.json() append_temp_df = pd.DataFrame(data_json[\"values\"]).T append_temp_df.columns", "2004-11-18 8.09 2004-11-19 57.85 2004-11-22 87.09 2004-11-23 87.09 2004-11-24 96.42", "temp_df.drop_duplicates(subset=[\"index\"], keep=\"last\", inplace=True) temp_df.index = pd.to_datetime(temp_df[\"index\"]) del temp_df[\"index\"] temp_df =", "186.1 2017-10-11 104.6 164.1 53.6 20.1 382.7 449.4 270.0 92.3", "= \"https://datacenter-api.jin10.com/reports/list_v2\" params = { \"max_date\": \"\", \"category\": \"etf\", \"attr_id\":", "'阿联酋', '委内瑞拉', '欧佩克产量']].iloc[-1, :] big_df[temp_df.name] = temp_df big_df = big_df.T", "372.0 463.2 281.2 60.8 154.2 2017-02-13 104.5 165.1 52.7 19.9", "= \"gold_change\" temp_df = temp_df.astype(float) return temp_df def macro_cons_gold_amount(): \"\"\"", "{ \"accept\": \"*/*\", \"accept-encoding\": \"gzip, deflate, br\", \"accept-language\": \"zh-CN,zh;q=0.9,en;q=0.8\", \"cache-control\":", "item in json_data[\"list\"]] value_list = [item[\"datas\"][\"白银\"] for item in json_data[\"list\"]]", "106.5 164.6 53.7 17.3 382.8 444.8 270.2 89.0 186.1 2017-10-11", "145.4 52.4 21.4 269.8 452.2 270.9 109.8 173.3 2019-06-13 102.9", "columns=pd.DataFrame(res.json()[\"data\"][\"keys\"])[\"name\"].tolist()).T temp_df.columns = temp_df.iloc[0, :] temp_df = temp_df[['阿尔及利亚', '安哥拉', '厄瓜多尔',", "bar: bar.set_description(f\"Please wait for a moment, now downing {item}'s data\")", "\"x-version\": \"1.0.0\", } res = requests.get(f\"https://datacenter-api.jin10.com/reports/dates?category=opec&_={str(int(round(t * 1000)))}\", headers=headers) #", "big_df.columns.name = \"日期\" big_df = big_df.astype(float) return big_df def _macro_cons_opec_month():", "2017-03-14 -6.81 -3.69 -1.60 -13.95 2017-04-12 4.16 -3.27 -2.59 -15.27", "Gecko) Chrome/79.0.3945.117 Safari/537.36\", \"x-app-id\": \"rU6QIu7JHe2gOUeR\", \"x-csrf-token\": \"\", \"x-version\": \"1.0.0\", }", "委内瑞拉 欧佩克产量 2017-01-18 1047.4 307.1 202.1 3308.5 2017-02-13 994.6 293.1", "python \"\"\" Date: 2019/10/21 12:08 Desc: 获取金十数据-数据中心-主要机构-宏观经济 \"\"\" import json", "<gh_stars>1-10 # -*- coding:utf-8 -*- # /usr/bin/env python \"\"\" Date:", "temp_df.sort_index(inplace=True) temp_df = temp_df.astype(float) return temp_df def macro_cons_silver_change(): \"\"\" 全球最大白银ETF--iShares", "14.20 -4.00 12.70 2018-12-12 37.70 7.10 -5.20 -1.10 2019-03-14 -8.60", "print(macro_cons_gold_amount_df) print(pd.concat([macro_cons_gold_volume_df, macro_cons_gold_change_df, macro_cons_gold_amount_df], axis=1)) macro_cons_silver_volume_df = macro_cons_silver_volume() print(macro_cons_silver_volume_df) macro_cons_silver_change_df", "= pd.to_datetime(date_list) temp_df = value_df[\"总库存(吨)\"] url = \"https://datacenter-api.jin10.com/reports/list_v2\" params =", "= temp_df[temp_df != 'Show All'] temp_df.sort_index(inplace=True) temp_df = temp_df.astype(float) return", "382.9 440.5 270.0 96.2 186.1 2018-04-12 98.4 152.4 51.8 18.3", "全球最大黄金ETF—SPDR Gold Trust持仓报告, 数据区间从20041118-至今 :return: pandas.Series 2004-11-18 8.09 2004-11-19 57.85", "value_df.index = pd.to_datetime(date_list) temp_df = value_df[\"总库存(吨)\"] url = \"https://datacenter-api.jin10.com/reports/list_v2\" params", "2017-06-13 0.23 -1.80 -0.77 33.61 2017-07-12 5.13 -0.07 -1.36 39.35", "464.9 280.2 92.6 172.5 2018-10-11 104.9 151.9 53.1 18.7 344.7", "'厄瓜多尔', '加蓬', '伊朗', '伊拉克', '科威特', '利比亚', '尼日利亚', '沙特', '阿联酋', '委内瑞拉',", "2017-08-10 1006.7 290.5 193.2 3286.9 2017-09-12 1002.2 290.1 191.8 3275.5", "-8.83 -0.09 0.35 -2.27 7.15 2.73 -25.43 2.78 2018-08-13 1.38", "coding:utf-8 -*- # /usr/bin/env python \"\"\" Date: 2019/10/21 12:08 Desc:", "[0, 3]] temp_se.index = pd.to_datetime(temp_se.iloc[:, 0]) temp_se = temp_se.iloc[:, 1]", "pd.DataFrame(r.json()[\"data\"][\"values\"]).iloc[:, :2] temp_se.index = pd.to_datetime(temp_se.iloc[:, 0]) temp_se = temp_se.iloc[:, 1]", "data\") res = requests.get( f\"https://datacenter-api.jin10.com/reports/list?category=opec&date={item}&_={str(int(round(t * 1000)))}\", headers=headers) temp_df =", "temp_se.index = pd.to_datetime(temp_se.iloc[:, 0]) temp_se = temp_se.iloc[:, 1] temp_df =", "-0.02 12.70 9.67 2017-08-10 -0.10 -1.93 0.85 0.71 0.69 -3.31", "-0.10 -1.93 0.85 0.71 0.69 -3.31 -0.74 15.43 3.43 2017-09-12", "270.2 55.0 150.8 2017-06-13 105.9 161.3 52.8 20.4 379.5 442.4", "return temp_df def macro_cons_silver_change(): \"\"\" 全球最大白银ETF--iShares Silver Trust持仓报告, 数据区间从20060429-至今 :return:", "344.7 465.0 281.2 105.3 174.8 2018-11-13 105.4 153.3 52.5 18.6", "\"x-version\": \"1.0.0\", } r = requests.get(url, params=params, headers=headers) temp_se =", "import tqdm from akshare.economic.cons import ( JS_CONS_GOLD_ETF_URL, JS_CONS_SLIVER_ETF_URL, JS_CONS_OPEC_URL, )", "欧佩克报告-月度, 数据区间从20170118-至今 这里返回的具体索引日期的数据为上一个月的数据, 由于某些国家的数据有缺失, 只选择有数据的国家返回 :return: pandas.Series 阿尔及利亚 安哥拉 厄瓜多尔", "99.7 151.5 52.0 18.3 382.3 442.9 270.5 98.2 179.1 2018-06-12", "-2.30 4.50 -1.10 -3.00 2019-03-14 0.20 2.20 0.50 0.70 1.20", "url = \"https://cdn.jin10.com/data_center/reports/etf_2.json\" r = requests.get(url) data_json = r.json() append_temp_df", "2019-10-21 11813.02 2019-10-22 11751.96 2019-10-23 11751.96 \"\"\" t = time.time()", "0.71 0.69 -3.31 -0.74 15.43 3.43 2017-09-12 0.41 0.83 -0.03", "Silver Trust持仓报告, 数据区间从20060429-至今 :return: pandas.Series 2006-04-29 653.17 2006-05-02 653.17 2006-05-03", "安哥拉 厄瓜多尔 加蓬 伊朗 伊拉克 科威特 利比亚 尼日利亚 \\ 2017-01-18", "-1.13 -13.10 -0.37 4.23 -5.44 2017-12-13 1.41 -10.87 -0.51 -0.47", "-0.77 33.61 2017-07-12 5.13 -0.07 -1.36 39.35 2017-08-10 3.18 -0.67", "temp_df = temp_df[temp_df != 'Show All'] temp_df.sort_index(inplace=True) temp_df = temp_df.astype(float)", "186.3 3258.9 2017-12-13 999.6 288.3 183.4 3244.8 2018-01-18 991.8 287.8", "2019-10-22 -4.98 2019-10-23 -1.18 2019-10-24 0.00 \"\"\" t = time.time()", "temp_df.index = pd.to_datetime(temp_df[\"index\"]) del temp_df[\"index\"] temp_df = temp_df[temp_df != 'Show", "447.6 271.8 67.5 157.6 2017-03-14 105.3 164.1 52.6 19.4 381.4", "8.09 2004-11-19 57.85 2004-11-22 87.09 2004-11-23 87.09 2004-11-24 96.42 ...", "\"\"\" t = time.time() res = requests.get( JS_CONS_SLIVER_ETF_URL.format( str(int(round(t *", "\"referer\": \"https://datacenter.jin10.com/reportType/dc_opec_report\", \"sec-fetch-mode\": \"cors\", \"sec-fetch-site\": \"same-site\", \"user-agent\": \"Mozilla/5.0 (Windows NT", "json_data[\"list\"]] value_list = [item[\"datas\"][\"黄金\"] for item in json_data[\"list\"]] value_df =", "3193.0 2018-06-12 998.7 286.5 139.2 3186.9 2018-07-11 1042.0 289.7 134.0", "= { \"accept\": \"*/*\", \"accept-encoding\": \"gzip, deflate, br\", \"accept-language\": \"zh-CN,zh;q=0.9,en;q=0.8\",", "3213.9 2017-07-12 995.0 289.8 193.8 3261.1 2017-08-10 1006.7 290.5 193.2", "-61.06 2019-10-23 0.00 \"\"\" t = time.time() res = requests.get(", "2006-05-04 1197.43 2006-05-05 1306.29 ... 2019-10-17 11847.91 2019-10-18 11847.91 2019-10-21", "2018-11-13 1063.0 316.0 117.1 3290.0 2018-12-12 1101.6 324.6 113.7 3296.5", "0.95 4.26 0.20 3.13 -11.35 2017-02-13 -4.17 -2.32 -1.67 -1.00", "95.5 171.1 2018-07-11 103.9 143.1 51.9 19.0 379.9 453.3 273.1", "382.3 438.3 270.8 96.2 173.8 2017-12-13 101.3 158.1 53.3 19.7", "9.00 0.80 25.60 7.40 2018-10-11 -0.80 5.70 53.10 -0.10 -15.00", "\"silver_change\" url = \"https://cdn.jin10.com/data_center/reports/etf_2.json\" r = requests.get(url) data_json = r.json()", "2018-10-11 -0.80 5.70 53.10 -0.10 -15.00 0.80 0.60 10.30 2.60", "289.7 134.0 3232.7 2018-08-13 1038.7 295.9 127.8 3232.3 2018-09-12 1040.1", ":return: pandas.Series 2006-04-29 263651152 2006-05-02 263651152 2006-05-03 445408550 2006-05-04 555123947", "temp_df.squeeze() temp_df.index.name = None temp_df.name = \"silver_amount\" url = \"https://cdn.jin10.com/data_center/reports/etf_2.json\"", "2019-03-14 0.20 2.20 0.50 0.70 1.20 -7.00 -1.40 2.30 1.00", "-13.35 2018-01-18 -1.09 -0.70 -8.22 4.24 2018-04-12 -4.69 4.49 -5.53", "-3.47 -3.91 0.03 -6.16 5.08 2017-06-13 0.96 -5.42 0.22 -0.13", "\"\", \"category\": \"etf\", \"attr_id\": \"1\", \"_\": str(int(round(t * 1000))), }", "2018-12-12 1101.6 324.6 113.7 3296.5 2019-03-14 1008.7 307.2 100.8 3054.9", "-0.69 3.61 -6.20 -0.93 -1.11 5.80 2017-04-12 0.45 -1.87 -0.28", "52.4 20.6 375.9 437.3 270.2 55.0 150.8 2017-06-13 105.9 161.3", "-0.80 5.70 53.10 -0.10 -15.00 0.80 0.60 10.30 2.60 2018-11-13", "995.4 284.2 195.6 3173.2 2017-06-13 994.0 288.5 196.3 3213.9 2017-07-12", "\"silver_amount\" temp_df = temp_df.reset_index() temp_df[\"index\"] = temp_df[\"index\"].astype(str) temp_df = temp_df.append(temp_append_df.reset_index())", "1.20 -3.60 27.80 2018-10-11 10.80 3.00 -4.20 13.20 2018-11-13 12.70", "requests.get(f\"https://datacenter-api.jin10.com/reports/dates?category=opec&_={str(int(round(t * 1000)))}\", headers=headers) # 日期序列 all_date_list = res.json()[\"data\"] need_date_list", "103.9 143.1 51.9 19.0 379.9 453.3 273.1 70.8 166.0 2018-08-13", "382.8 444.8 270.2 89.0 186.1 2017-10-11 104.6 164.1 53.6 20.1", "2019-04-10 101.8 145.4 52.4 21.4 269.8 452.2 270.9 109.8 173.3", "in date_list] for item in reversed(need_date_list): res = requests.get( f\"https://datacenter-api.jin10.com/reports/list?category=opec&date={item}&_={str(int(round(t", "-0.85 -0.95 -6.08 -2.98 2017-05-11 -0.75 9.71 -0.06 0.88 -3.47", "\"referer\": \"https://datacenter.jin10.com/reportType/dc_usa_michigan_consumer_sentiment\", \"sec-fetch-dest\": \"empty\", \"sec-fetch-mode\": \"cors\", \"sec-fetch-site\": \"same-site\", \"user-agent\": \"Mozilla/5.0", "\"https://datacenter.jin10.com\", \"pragma\": \"no-cache\", \"referer\": \"https://datacenter.jin10.com/reportType/dc_opec_report\", \"sec-fetch-mode\": \"cors\", \"sec-fetch-site\": \"same-site\", \"user-agent\":", "\"accept\": \"*/*\", \"accept-encoding\": \"gzip, deflate, br\", \"accept-language\": \"zh-CN,zh;q=0.9,en;q=0.8\", \"cache-control\": \"no-cache\",", "= pd.to_datetime(date_list) temp_df = value_df[\"增持/减持(吨)\"] url = \"https://datacenter-api.jin10.com/reports/list_v2\" params =", "temp_df return big_df.T def macro_cons_opec_month(): \"\"\" 欧佩克报告-月度, 数据区间从 20170118-至今 这里返回的具体索引日期的数据为上一个月的数据,", "= temp_df.reset_index() temp_df.drop_duplicates(subset=\"index\", keep=\"last\", inplace=True) temp_df.set_index(\"index\", inplace=True) temp_df = temp_df.squeeze()", "40.54 3.51 -4.75 17.34 2018-08-13 -5.28 6.92 -4.77 4.07 2018-09-12", "value_list = [item[\"datas\"][\"白银\"] for item in json_data[\"list\"]] value_df = pd.DataFrame(value_list)", "= temp_df.append(temp_se) temp_df.dropna(inplace=True) temp_df.sort_index(inplace=True) temp_df = temp_df.reset_index() temp_df.drop_duplicates(subset=\"index\", keep=\"last\", inplace=True)", "18.7 358.4 464.9 280.2 92.6 172.5 2018-10-11 104.9 151.9 53.1", "2.20 -0.30 0.30 -15.60 465.30 -3.30 6.00 -1.70 2018-12-12 -0.50", "148.8 3195.8 2018-05-14 995.9 287.2 143.6 3193.0 2018-06-12 998.7 286.5", "\"gzip, deflate, br\", \"accept-language\": \"zh-CN,zh;q=0.9,en;q=0.8\", \"cache-control\": \"no-cache\", \"origin\": \"https://datacenter.jin10.com\", \"pragma\":", "\"https://datacenter-api.jin10.com/reports/list_v2\" params = { \"max_date\": \"\", \"category\": \"etf\", \"attr_id\": \"1\",", "\"x-csrf-token\": \"\", \"x-version\": \"1.0.0\", } r = requests.get(url, params=params, headers=headers)", "-1.36 39.35 2017-08-10 3.18 -0.67 -1.58 17.26 2017-09-12 -1.03 -2.02", "472.4 271.0 117.4 173.3 沙特 阿联酋 委内瑞拉 欧佩克产量 2017-01-18 1047.4", "headers = { \"accept\": \"*/*\", \"accept-encoding\": \"gzip, deflate, br\", \"accept-language\":", "-0.80 0.40 18.80 -15.00 9.00 0.80 25.60 7.40 2018-10-11 -0.80", "7.15 2.73 -25.43 2.78 2018-08-13 1.38 1.17 0.42 -0.34 -5.63", "263651152 2006-05-02 263651152 2006-05-03 445408550 2006-05-04 555123947 2006-05-05 574713264 ...", "\"\"\" 全球最大黄金ETF—SPDR Gold Trust持仓报告, 数据区间从20041118-至今 :return: pandas.Series 2004-11-18 8.09 2004-11-19", "0.10 -0.53 0.61 9.58 2018-01-18 3.03 4.48 -0.72 -0.01 1.32", "0.30 0.10 -1.10 -38.00 -2.30 4.50 -1.10 -3.00 2019-03-14 0.20", "442.6 270.4 96.8 181.0 2018-05-14 99.7 151.5 52.0 18.3 382.3", "def macro_cons_gold_amount(): \"\"\" 全球最大黄金ETF—SPDR Gold Trust持仓报告, 数据区间从20041118-至今 :return: pandas.Series 2004-11-18", "def macro_cons_silver_amount(): \"\"\" 全球最大白银ETF--iShares Silver Trust持仓报告, 数据区间从20060429-至今 :return: pandas.Series 2006-04-29", "-0.09 0.35 -2.27 7.15 2.73 -25.43 2.78 2018-08-13 1.38 1.17", "2018-08-13 106.2 145.6 52.5 18.8 373.7 455.6 279.1 66.4 166.7", "924.64 2019-10-21 924.64 2019-10-22 919.66 2019-10-23 918.48 2019-10-24 918.48 \"\"\"", "455.6 279.1 66.4 166.7 2018-09-12 104.5 144.8 52.9 18.7 358.4", "requests from tqdm import tqdm from akshare.economic.cons import ( JS_CONS_GOLD_ETF_URL,", "-3.55 -4.16 -13.35 2018-01-18 -1.09 -0.70 -8.22 4.24 2018-04-12 -4.69", "= temp_df[['阿尔及利亚', '安哥拉', '加蓬', '伊朗', '伊拉克', '科威特', '利比亚', '尼日利亚', '沙特',", "厄瓜多尔 加蓬 伊朗 伊拉克 科威特 利比亚 尼日利亚 \\ 2017-01-18 108.0", "-0.05 1.44 0.09 3.16 -0.17 5.39 5.08 2017-11-13 -3.84 6.98", "获取金十数据-数据中心-主要机构-宏观经济 \"\"\" import json import time import pandas as pd", "'委内瑞拉', '欧佩克产量']].iloc[-2, :] big_df[item] = temp_df return big_df.T def macro_cons_opec_month():", "'Show All'] temp_df.sort_index(inplace=True) temp_df = temp_df.astype(float) return temp_df def macro_cons_silver_amount():", "res = requests.get( JS_CONS_SLIVER_ETF_URL.format( str(int(round(t * 1000))), str(int(round(t * 1000))", "440.5 270.0 96.2 186.1 2018-04-12 98.4 152.4 51.8 18.3 381.4", "inplace=True) temp_df.index = pd.to_datetime(temp_df[\"index\"]) del temp_df[\"index\"] temp_df = temp_df[temp_df !=", "2006-05-02 0.00 2006-05-03 342.11 2006-05-04 202.15 2006-05-05 108.86 ... 2019-10-17", "2]] temp_se.index = pd.to_datetime(temp_se.iloc[:, 0]) temp_se = temp_se.iloc[:, 1] temp_df", "20.1 382.7 449.4 270.0 92.3 185.5 2017-11-13 101.2 171.1 54.1", "2004-11-24 96.42 ... 2019-10-20 924.64 2019-10-21 924.64 2019-10-22 919.66 2019-10-23", "= res.json()[\"data\"] bar = tqdm(reversed(all_date_list[:-1])) for item in bar: bar.set_description(f\"Please", "51.9 19.0 379.9 453.3 273.1 70.8 166.0 2018-08-13 106.2 145.6", "value_df[\"增持/减持(吨)\"] url = \"https://datacenter-api.jin10.com/reports/list_v2\" params = { \"max_date\": \"\", \"category\":", "87.09 2004-11-24 96.42 ... 2019-10-20 924.64 2019-10-21 924.64 2019-10-22 919.66", "'Show All'] temp_df.sort_index(inplace=True) temp_df = temp_df.astype(float) return temp_df def macro_cons_silver_change():", "headers=headers) temp_se = pd.DataFrame(r.json()[\"data\"][\"values\"]).iloc[:, [0, 1]] temp_se.index = pd.to_datetime(temp_se.iloc[:, 0])", "104.5 165.1 52.7 19.9 377.5 447.6 271.8 67.5 157.6 2017-03-14", "96.2 186.1 2018-04-12 98.4 152.4 51.8 18.3 381.4 442.6 270.4", "All 2019-10-18 Show All 2019-10-21 Show All 2019-10-22 Show All", "Safari/537.36\", \"x-app-id\": \"rU6QIu7JHe2gOUeR\", \"x-csrf-token\": \"\", \"x-version\": \"1.0.0\", } r =", "temp_df def macro_cons_gold_change(): \"\"\" 全球最大黄金ETF—SPDR Gold Trust持仓报告, 数据区间从20041118-至今 :return: pandas.Series", "def macro_cons_gold_change(): \"\"\" 全球最大黄金ETF—SPDR Gold Trust持仓报告, 数据区间从20041118-至今 :return: pandas.Series 2004-11-18", "0.46 -8.83 -0.09 0.35 -2.27 7.15 2.73 -25.43 2.78 2018-08-13", "-4.54 -3.55 -4.16 -13.35 2018-01-18 -1.09 -0.70 -8.22 4.24 2018-04-12", "87.09 2004-11-23 87.09 2004-11-24 96.42 ... 2019-10-20 924.64 2019-10-21 924.64", "\"zh-CN,zh;q=0.9,en;q=0.8\", \"cache-control\": \"no-cache\", \"origin\": \"https://datacenter.jin10.com\", \"pragma\": \"no-cache\", \"referer\": \"https://datacenter.jin10.com/reportType/dc_opec_report\", \"sec-fetch-mode\":", "item in all_date_list if item.split(\"-\")[0] + item.split(\"-\")[1] + item.split(\"-\")[2] not", "0.80 0.60 10.30 2.60 2018-11-13 -0.40 2.20 -0.30 0.30 -15.60", "-0.34 -5.63 2.41 7.85 -5.67 7.05 2018-09-12 -1.40 -0.80 0.40", "-0.87 0.95 4.26 0.20 3.13 -11.35 2017-02-13 -4.17 -2.32 -1.67", "r.json() append_temp_df = pd.DataFrame(data_json[\"values\"]).T append_temp_df.columns = [item[\"name\"] for item in", "append_temp_df.columns = [item[\"name\"] for item in data_json[\"keys\"]] temp_append_df = append_temp_df[\"增持/减持\"]", "headers=headers) temp_se = pd.DataFrame(r.json()[\"data\"][\"values\"]).iloc[:, [0, 2]] temp_se.index = pd.to_datetime(temp_se.iloc[:, 0])", "= json_data[\"kinds\"] value_df.index = pd.to_datetime(date_list) temp_df = value_df[\"增持/减持(吨)\"] temp_df.name =", "11751.96 \"\"\" t = time.time() res = requests.get( JS_CONS_SLIVER_ETF_URL.format( str(int(round(t", "2006-05-02 653.17 2006-05-03 995.28 2006-05-04 1197.43 2006-05-05 1306.29 ... 2019-10-17", "数据区间从20170118-至今 这里返回的具体索引日期的数据为上一个月的数据, 由于某些国家的数据有缺失, 只选择有数据的国家返回 :return: pandas.Series 阿尔及利亚 安哥拉 厄瓜多尔 加蓬", "2019-10-23 44120217405.82 2019-10-24 44120217405.82 \"\"\" t = time.time() res =", "数据区间从20041118-至今 :return: pandas.Series 2004-11-18 0 2004-11-19 49.76 2004-11-22 29.24 2004-11-23", "2019-10-17 Show All 2019-10-18 Show All 2019-10-21 Show All 2019-10-22", "0.00 2019-10-22 -4.98 2019-10-23 -1.18 2019-10-24 0.00 \"\"\" t =", "-15.00 0.80 0.60 10.30 2.60 2018-11-13 -0.40 2.20 -0.30 0.30", "-22.70 9.40 1.30 -0.30 -9.20 沙特 阿联酋 委内瑞拉 欧佩克产量 2017-01-18", "def macro_cons_silver_volume(): \"\"\" 全球最大白银ETF--iShares Silver Trust持仓报告, 数据区间从20060429-至今 :return: pandas.Series 2006-04-29", "value_df.columns = json_data[\"kinds\"] value_df.index = pd.to_datetime(date_list) temp_df = value_df[\"增持/减持(吨)\"] url", "89.0 186.1 2017-10-11 104.6 164.1 53.6 20.1 382.7 449.4 270.0", "373.7 455.6 279.1 66.4 166.7 2018-09-12 104.5 144.8 52.9 18.7", "Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36\", \"x-app-id\": \"rU6QIu7JHe2gOUeR\",", "数据区间从20041118-至今 :return: pandas.Series 2004-11-18 8.09 2004-11-19 57.85 2004-11-22 87.09 2004-11-23", "5.80 2017-04-12 0.45 -1.87 -0.28 0.19 -2.87 -0.85 -0.95 -6.08", "439.6 270.3 97.3 179.0 2018-01-18 103.7 163.3 52.6 19.7 382.9", "1000)))}\", headers=headers) # 日期序列 all_date_list = res.json()[\"data\"] bar = tqdm(reversed(all_date_list))", "= \"日期\" big_df = big_df.astype(float) return big_df if __name__ ==", "161.4 52.6 19.8 379.0 440.2 270.2 62.2 154.5 2017-05-11 104.7", "科威特 利比亚 尼日利亚 \\ 2017-01-18 108.0 172.4 54.5 21.3 372.0", "-0.07 0.08 0.69 -0.83 2018-06-12 3.90 1.40 0.06 0.18 0.56", "temp_se = temp_se.iloc[:, 1] temp_df = temp_df.append(temp_se) temp_df.dropna(inplace=True) temp_df.sort_index(inplace=True) temp_df", "JS_CONS_OPEC_URL.format( str(int(round(t * 1000))), str(int(round(t * 1000)) + 90) )", "temp_df.columns = temp_df.iloc[0, :] temp_df = temp_df[['阿尔及利亚', '安哥拉', '厄瓜多尔', '加蓬',", "pandas.Series 阿尔及利亚 安哥拉 厄瓜多尔 加蓬 伊朗 伊拉克 科威特 利比亚 尼日利亚", "moment, now downing {item}'s data\") res = requests.get( f\"https://datacenter-api.jin10.com/reports/list?category=opec&date={item}&_={str(int(round(t *", "2004-11-23 87.09 2004-11-24 96.42 ... 2019-10-20 924.64 2019-10-21 924.64 2019-10-22", "except: temp_df = temp_df[['阿尔及利亚', '安哥拉', '加蓬', '伊朗', '伊拉克', '科威特', '利比亚',", "134.0 3232.7 2018-08-13 1038.7 295.9 127.8 3232.3 2018-09-12 1040.1 297.2", "-0.21 -0.77 1.67 6.06 -0.02 12.70 9.67 2017-08-10 -0.10 -1.93", "= temp_df.astype(float) return temp_df def macro_cons_silver_change(): \"\"\" 全球最大白银ETF--iShares Silver Trust持仓报告,", "2004-11-22 1253785205.50 2004-11-23 1254751438.19 2004-11-24 1390568824.08 ... 2019-10-20 44286078486.23 2019-10-21", "271.0 117.4 173.3 沙特 阿联酋 委内瑞拉 欧佩克产量 2017-01-18 1047.4 307.1", "52.7 19.9 377.5 447.6 271.8 67.5 157.6 2017-03-14 105.3 164.1", "181.0 2018-05-14 99.7 151.5 52.0 18.3 382.3 442.9 270.5 98.2", "-15.60 465.30 -3.30 6.00 -1.70 2018-12-12 -0.50 0.30 0.10 -1.10", "3.61 -6.20 -0.93 -1.11 5.80 2017-04-12 0.45 -1.87 -0.28 0.19", "381.4 442.6 270.4 96.8 181.0 2018-05-14 99.7 151.5 52.0 18.3", "[item[\"datas\"][\"黄金\"] for item in json_data[\"list\"]] value_df = pd.DataFrame(value_list) value_df.columns =", "value_df.index = pd.to_datetime(date_list) temp_df = value_df[\"上个月\"] temp_df.name = country big_df", "2004-11-18 0 2004-11-19 49.76 2004-11-22 29.24 2004-11-23 0.00 2004-11-24 9.33", "bar.set_description(f\"Please wait for a moment, now downing {item}'s data\") res", "'尼日利亚', '沙特', '阿联酋', '委内瑞拉', '欧佩克产量']].iloc[-1, :] big_df[temp_df.name] = temp_df big_df", "-6.16 5.08 2017-06-13 0.96 -5.42 0.22 -0.13 0.45 4.44 0.00", "temp_df = temp_df.astype(float) return temp_df def macro_cons_silver_amount(): \"\"\" 全球最大白银ETF--iShares Silver", "利比亚 尼日利亚 \\ 2017-01-18 108.0 172.4 54.5 21.3 372.0 463.2", "2987.6 \"\"\" t = time.time() res = requests.get( JS_CONS_OPEC_URL.format( str(int(round(t", "-6.81 -3.69 -1.60 -13.95 2017-04-12 4.16 -3.27 -2.59 -15.27 2017-05-11", "2017-11-13 101.2 171.1 54.1 20.3 382.3 438.3 270.8 96.2 173.8", "pandas as pd import requests from tqdm import tqdm from", ") ) json_data = json.loads(res.text[res.text.find(\"{\"): res.text.rfind(\"}\") + 1]) date_list =", "[item[\"datas\"][\"白银\"] for item in json_data[\"list\"]] value_df = pd.DataFrame(value_list) value_df.columns =", "欧佩克产量 2017-01-18 -14.93 -0.63 -4.52 -22.09 2017-02-13 -49.62 -15.93 -3.05", "'欧佩克产量']].iloc[-2, :] except: temp_df = temp_df[['阿尔及利亚', '安哥拉', '加蓬', '伊朗', '伊拉克',", "2017-11-13 1.69 -0.60 -4.36 -15.09 2017-12-13 -4.54 -3.55 -4.16 -13.35", "# /usr/bin/env python \"\"\" Date: 2019/10/21 12:08 Desc: 获取金十数据-数据中心-主要机构-宏观经济 \"\"\"", "5.39 5.08 2017-11-13 -3.84 6.98 0.71 0.18 -1.13 -13.10 -0.37", "\"silver_change\" url = \"https://datacenter-api.jin10.com/reports/list_v2\" params = { \"max_date\": \"\", \"category\":", "281.2 105.3 174.8 2018-11-13 105.4 153.3 52.5 18.6 329.6 465.4", "-15.93 -3.05 -89.02 2017-03-14 -6.81 -3.69 -1.60 -13.95 2017-04-12 4.16", "1.40 0.06 0.18 0.56 2.77 -0.57 -2.43 -5.35 2018-07-11 0.46", "102.6 145.7 52.2 20.3 274.3 463.3 270.9 90.6 174.1 2019-04-10", "269.8 452.2 270.9 109.8 173.3 2019-06-13 102.9 147.1 52.9 21.1", "\"sec-fetch-mode\": \"cors\", \"sec-fetch-site\": \"same-site\", \"user-agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64;", "reversed(need_date_list): res = requests.get( f\"https://datacenter-api.jin10.com/reports/list?category=opec&date={item}&_={str(int(round(t * 1000)))}\", headers=headers) temp_df =", "198.7 3195.8 2017-04-12 999.4 289.5 197.2 3192.8 2017-05-11 995.4 284.2", "2017-03-14 105.3 164.1 52.6 19.4 381.4 441.4 270.9 66.9 160.8", "918.48 2019-10-24 918.48 \"\"\" t = time.time() res = requests.get(", "伊朗 伊拉克 科威特 利比亚 尼日利亚 \\ 2017-01-18 -0.87 3.56 -0.25", "\"rU6QIu7JHe2gOUeR\", \"x-csrf-token\": \"\", \"x-version\": \"1.0.0\", } res = requests.get(f\"https://datacenter-api.jin10.com/reports/dates?category=opec&_={str(int(round(t *", "'阿联酋', '委内瑞拉', '欧佩克产量']].iloc[-2, :] big_df[item] = temp_df return big_df.T def", "161.3 52.8 20.4 379.5 442.4 270.5 73.0 168.0 2017-07-12 106.0", "= temp_df.squeeze() temp_df.index.name = None temp_df.name = \"gold_amount\" temp_df =", ":2] temp_se.index = pd.to_datetime(temp_se.iloc[:, 0]) temp_se = temp_se.iloc[:, 1] temp_df", "欧佩克产量 2017-01-18 1047.4 307.1 202.1 3308.5 2017-02-13 994.6 293.1 200.4", "= \"silver_amount\" url = \"https://cdn.jin10.com/data_center/reports/etf_2.json\" r = requests.get(url) data_json =", "headers=headers) temp_se = pd.DataFrame(r.json()[\"data\"][\"values\"]).iloc[:, [0, 3]] temp_se.index = pd.to_datetime(temp_se.iloc[:, 0])", "(KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36\", \"x-app-id\": \"rU6QIu7JHe2gOUeR\", \"x-csrf-token\": \"\", \"x-version\":", "= \"https://cdn.jin10.com/data_center/reports/etf_2.json\" r = requests.get(url) data_json = r.json() append_temp_df =", "9.58 2018-01-18 3.03 4.48 -0.72 -0.01 1.32 0.79 -0.25 -0.70", "2.60 2018-11-13 -0.40 2.20 -0.30 0.30 -15.60 465.30 -3.30 6.00", "1.30 -0.30 -9.20 沙特 阿联酋 委内瑞拉 欧佩克产量 2017-01-18 -14.93 -0.63", "-15.00 9.00 0.80 25.60 7.40 2018-10-11 -0.80 5.70 53.10 -0.10", "6.98 0.71 0.18 -1.13 -13.10 -0.37 4.23 -5.44 2017-12-13 1.41", "headers=headers) # 日期序列 all_date_list = res.json()[\"data\"] bar = tqdm(reversed(all_date_list[:-1])) for", "17.82 17.42 2017-07-12 -0.09 6.60 -0.21 -0.77 1.67 6.06 -0.02", "print(pd.concat([macro_cons_gold_volume_df, macro_cons_gold_change_df, macro_cons_gold_amount_df], axis=1)) macro_cons_silver_volume_df = macro_cons_silver_volume() print(macro_cons_silver_volume_df) macro_cons_silver_change_df =", "continue headers = { \"accept\": \"*/*\", \"accept-encoding\": \"gzip, deflate, br\",", "-4.75 17.34 2018-08-13 -5.28 6.92 -4.77 4.07 2018-09-12 3.80 1.20", "= temp_df.astype(float) return temp_df def macro_cons_silver_amount(): \"\"\" 全球最大白银ETF--iShares Silver Trust持仓报告,", "伊拉克 科威特 利比亚 尼日利亚 \\ 2017-01-18 108.0 172.4 54.5 21.3", "106.2 145.6 52.5 18.8 373.7 455.6 279.1 66.4 166.7 2018-09-12", "Gecko) Chrome/80.0.3987.149 Safari/537.36\", \"x-app-id\": \"rU6QIu7JHe2gOUeR\", \"x-csrf-token\": \"\", \"x-version\": \"1.0.0\", }", "96.8 181.0 2018-05-14 99.7 151.5 52.0 18.3 382.3 442.9 270.5", "= res.json()[\"data\"] need_date_list = [item for item in all_date_list if", "51.9 18.9 382.9 445.5 270.1 95.5 171.1 2018-07-11 103.9 143.1", "74.1 2987.6 \"\"\" t = time.time() big_df = pd.DataFrame() headers", "0.70 1.20 -7.00 -1.40 2.30 1.00 2019-04-10 -0.70 0.70 52.40", "temp_df.index.name = None temp_df.name = \"silver_change\" url = \"https://cdn.jin10.com/data_center/reports/etf_2.json\" r", "-8.17 0.26 -0.91 0.33 -1.31 0.23 -3.72 1.82 2018-05-14 1.77", "\"etf\", \"attr_id\": \"2\", \"_\": str(int(round(t * 1000))), } headers =", "2019-10-20 44286078486.23 2019-10-21 44333677232.68 2019-10-22 43907962483.56 2019-10-23 44120217405.82 2019-10-24 44120217405.82", "2004-11-19 828806907.20 2004-11-22 1253785205.50 2004-11-23 1254751438.19 2004-11-24 1390568824.08 ... 2019-10-20", "158.1 53.3 19.7 381.8 439.6 270.3 97.3 179.0 2018-01-18 103.7", "21.1 237.0 472.4 271.0 117.4 173.3 沙特 阿联酋 委内瑞拉 欧佩克产量", "0.42 -0.34 -5.63 2.41 7.85 -5.67 7.05 2018-09-12 -1.40 -0.80", "str(int(round(t * 1000))), } headers = { \"accept\": \"*/*\", \"accept-encoding\":", "= time.time() big_df = pd.DataFrame() headers = { \"accept\": \"*/*\",", "0.23 -3.72 1.82 2018-05-14 1.77 -0.78 0.31 -0.93 1.00 -0.07", "in json_data[\"list\"]] value_list = [item[\"datas\"][\"黄金\"] for item in json_data[\"list\"]] value_df", "print(macro_cons_gold_volume_df) macro_cons_gold_change_df = macro_cons_gold_change() print(macro_cons_gold_change_df) macro_cons_gold_amount_df = macro_cons_gold_amount() print(macro_cons_gold_amount_df) print(pd.concat([macro_cons_gold_volume_df,", "114920000.00 2004-11-19 828806907.20 2004-11-22 1253785205.50 2004-11-23 1254751438.19 2004-11-24 1390568824.08 ...", "JS_CONS_OPEC_URL, ) def macro_cons_gold_volume(): \"\"\" 全球最大黄金ETF—SPDR Gold Trust持仓报告, 数据区间从20041118-至今 :return:", "= temp_df.iloc[0, :] temp_df = temp_df.iloc[1:, :] try: temp_df =", "60.8 154.2 2017-02-13 104.5 165.1 52.7 19.9 377.5 447.6 271.8", "as pd import requests from tqdm import tqdm from akshare.economic.cons", "3308.5 2017-02-13 994.6 293.1 200.4 3213.9 2017-03-14 979.7 292.5 198.7", "-0.70 0.70 52.40 0.90 -2.80 -12.60 -0.10 19.60 1.10 2019-06-13", "for item in json_data[\"list\"]] value_df = pd.DataFrame(value_list) value_df.columns = json_data[\"kinds\"]", "\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)", "= requests.get(url, params=params, headers=headers) temp_se = pd.DataFrame(r.json()[\"data\"][\"values\"]).iloc[:, :2] temp_se.index =", "-38.00 -2.30 4.50 -1.10 -3.00 2019-03-14 0.20 2.20 0.50 0.70", "2004-11-23 1254751438.19 2004-11-24 1390568824.08 ... 2019-10-20 44286078486.23 2019-10-21 44333677232.68 2019-10-22", "temp_df.index.name = None temp_df.name = \"gold_change\" temp_df = temp_df.astype(float) return", "= requests.get(url) data_json = r.json() append_temp_df = pd.DataFrame(data_json[\"values\"]).T append_temp_df.columns =", "big_df.astype(float) return big_df def _macro_cons_opec_month(): \"\"\" 欧佩克报告-月度, 数据区间从20170118-至今 这里返回的具体索引日期的数据为上一个月的数据, 由于某些国家的数据有缺失,", "Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.117 Safari/537.36\", \"x-app-id\": \"rU6QIu7JHe2gOUeR\",", "date_list = [item[\"date\"] for item in json_data[\"list\"]] value_list = [item[\"datas\"][\"黄金\"]", "-5.53 -20.14 2018-05-14 4.65 0.61 -4.17 1.21 2018-06-12 8.55 -0.63", "temp_df.astype(float) return temp_df def macro_cons_gold_amount(): \"\"\" 全球最大黄金ETF—SPDR Gold Trust持仓报告, 数据区间从20041118-至今", "2.30 1.00 2019-04-10 -0.70 0.70 52.40 0.90 -2.80 -12.60 -0.10", "-3.23 -0.23 -2.31 0.01 -11.23 13.83 2017-10-11 -0.85 -0.29 -0.05", "temp_df = temp_df.squeeze() temp_df.index.name = None temp_df.name = \"silver_change\" url", "item in data_json[\"keys\"]] temp_append_df = append_temp_df[\"增持/减持\"] temp_append_df.name = \"silver_change\" temp_df", "52.9 21.1 237.0 472.4 271.0 117.4 173.3 沙特 阿联酋 委内瑞拉", "in bar: bar.set_description(f\"Please wait for a moment, now downing {item}'s", "f\"https://datacenter-api.jin10.com/reports/list?category=opec&date={item}&_={str(int(round(t * 1000)))}\", headers=headers) temp_df = pd.DataFrame(res.json()[\"data\"][\"values\"], columns=pd.DataFrame(res.json()[\"data\"][\"keys\"])[\"name\"].tolist()).T temp_df.columns =", "0.30 -15.60 465.30 -3.30 6.00 -1.70 2018-12-12 -0.50 0.30 0.10", "2018-05-14 995.9 287.2 143.6 3193.0 2018-06-12 998.7 286.5 139.2 3186.9", "377.5 447.6 271.8 67.5 157.6 2017-03-14 105.3 164.1 52.6 19.4", "print(macro_cons_gold_change_df) macro_cons_gold_amount_df = macro_cons_gold_amount() print(macro_cons_gold_amount_df) print(pd.concat([macro_cons_gold_volume_df, macro_cons_gold_change_df, macro_cons_gold_amount_df], axis=1)) macro_cons_silver_volume_df", "pandas.Series 2006-04-29 653.17 2006-05-02 653.17 2006-05-03 995.28 2006-05-04 1197.43 2006-05-05", "for item in data_json[\"keys\"]] temp_append_df = append_temp_df[\"总价值\"] temp_append_df.name = \"silver_amount\"", "-4.36 -15.09 2017-12-13 -4.54 -3.55 -4.16 -13.35 2018-01-18 -1.09 -0.70", "442.9 270.5 98.2 179.1 2018-06-12 103.1 152.5 51.9 18.9 382.9", "-0.07 -0.84 -5.19 8.85 2017-11-13 1.69 -0.60 -4.36 -15.09 2017-12-13", "pd.DataFrame(value_list) value_df.columns = json_data[\"kinds\"] value_df.index = pd.to_datetime(date_list) temp_df = value_df[\"上个月\"]", "all_date_list = res.json()[\"data\"] bar = tqdm(reversed(all_date_list[:-1])) for item in bar:", "'利比亚', '尼日利亚', '沙特', '阿联酋', '委内瑞拉', '欧佩克产量']].iloc[-2, :] except: temp_df =", "173.3 2017-08-10 105.9 164.6 53.6 20.5 382.4 446.8 270.3 100.1", "\"\"\" Date: 2019/10/21 12:08 Desc: 获取金十数据-数据中心-主要机构-宏观经济 \"\"\" import json import", "0.69 -0.83 2018-06-12 3.90 1.40 0.06 0.18 0.56 2.77 -0.57", "195.6 3173.2 2017-06-13 994.0 288.5 196.3 3213.9 2017-07-12 995.0 289.8", "163.3 52.6 19.7 382.9 440.5 270.0 96.2 186.1 2018-04-12 98.4", "-2.98 2017-05-11 -0.75 9.71 -0.06 0.88 -3.47 -3.91 0.03 -6.16", "pd.to_datetime(date_list) temp_df = value_df[\"上个月\"] temp_df.name = country big_df = big_df.append(temp_df)", "Show All 2019-10-22 Show All 2019-10-23 Show All \"\"\" t", "2019-04-10 -32.40 -0.90 -28.90 -53.40 2019-06-13 -7.60 0.30 -3.50 -23.60", "-4.17 1.21 2018-06-12 8.55 -0.63 -4.25 3.54 2018-07-11 40.54 3.51", "442.4 270.5 73.0 168.0 2017-07-12 106.0 166.8 52.7 19.7 379.0", "1.38 1.17 0.42 -0.34 -5.63 2.41 7.85 -5.67 7.05 2018-09-12", "270.8 96.2 173.8 2017-12-13 101.3 158.1 53.3 19.7 381.8 439.6", "item in bar: bar.set_description(f\"Please wait for a moment, now downing", "437.3 270.2 55.0 150.8 2017-06-13 105.9 161.3 52.8 20.4 379.5", "-*- coding:utf-8 -*- # /usr/bin/env python \"\"\" Date: 2019/10/21 12:08", "Gold Trust持仓报告, 数据区间从20041118-至今 :return: pandas.Series 2004-11-18 114920000.00 2004-11-19 828806907.20 2004-11-22", "152.1 52.5 17.6 295.4 463.1 280.9 110.4 173.6 2019-03-14 102.6", "202.1 3308.5 2017-02-13 994.6 293.1 200.4 3213.9 2017-03-14 979.7 292.5", "-14.93 -0.63 -4.52 -22.09 2017-02-13 -49.62 -15.93 -3.05 -89.02 2017-03-14", "2018-01-18 -1.09 -0.70 -8.22 4.24 2018-04-12 -4.69 4.49 -5.53 -20.14", "103.7 163.3 52.6 19.7 382.9 440.5 270.0 96.2 186.1 2018-04-12", "191.8 3275.5 2017-10-11 997.5 290.5 189.0 3274.8 2017-11-13 1000.0 291.1", "1306.29 ... 2019-10-17 11847.91 2019-10-18 11847.91 2019-10-21 11813.02 2019-10-22 11751.96", ":return: pandas.Series 2006-04-29 0 2006-05-02 0.00 2006-05-03 342.11 2006-05-04 202.15", "= pd.DataFrame() headers = { \"accept\": \"*/*\", \"accept-encoding\": \"gzip, deflate,", "290.5 189.0 3274.8 2017-11-13 1000.0 291.1 186.3 3258.9 2017-12-13 999.6", "3192.8 2017-05-11 995.4 284.2 195.6 3173.2 2017-06-13 994.0 288.5 196.3", "= big_df.append(temp_df) except: continue headers = { \"accept\": \"*/*\", \"accept-encoding\":", "'伊拉克', '科威特', '利比亚', '尼日利亚', '沙特', '阿联酋', '委内瑞拉', '欧佩克产量']].iloc[-1, :] except:", "* 1000))), str(int(round(t * 1000)) + 90) ) ) json_data", "270.3 100.1 174.8 2017-09-12 106.5 164.6 53.7 17.3 382.8 444.8", "pd.DataFrame(data_json[\"values\"]).T append_temp_df.columns = [item[\"name\"] for item in data_json[\"keys\"]] temp_append_df =", "280.9 110.4 173.6 2019-03-14 102.6 145.7 52.2 20.3 274.3 463.3", "temp_df[\"index\"] = temp_df[\"index\"].astype(str) temp_df = temp_df.append(temp_append_df.reset_index()) temp_df.drop_duplicates(subset=[\"index\"], keep=\"last\", inplace=True) temp_df.index", "= requests.get( JS_CONS_SLIVER_ETF_URL.format( str(int(round(t * 1000))), str(int(round(t * 1000)) +", "1101.6 324.6 113.7 3296.5 2019-03-14 1008.7 307.2 100.8 3054.9 2019-04-10", "time import pandas as pd import requests from tqdm import", "100.1 174.8 2017-09-12 106.5 164.6 53.7 17.3 382.8 444.8 270.2", "0.80 25.60 7.40 2018-10-11 -0.80 5.70 53.10 -0.10 -15.00 0.80", "-0.23 -2.31 0.01 -11.23 13.83 2017-10-11 -0.85 -0.29 -0.05 1.44", "7.85 -5.67 7.05 2018-09-12 -1.40 -0.80 0.40 18.80 -15.00 9.00", "381.8 439.6 270.3 97.3 179.0 2018-01-18 103.7 163.3 52.6 19.7", "Show All 2019-10-23 Show All \"\"\" t = time.time() res", "res.json()[\"data\"] bar = tqdm(reversed(all_date_list)) for item in bar: bar.set_description(f\"Please wait", "306.1 74.1 2987.6 \"\"\" t = time.time() res = requests.get(", "全球最大白银ETF--iShares Silver Trust持仓报告, 数据区间从20060429-至今 :return: pandas.Series 2006-04-29 0 2006-05-02 0.00", "12.70 9.67 2017-08-10 -0.10 -1.93 0.85 0.71 0.69 -3.31 -0.74", "import requests from tqdm import tqdm from akshare.economic.cons import (", "-16.57 -14.12 6.47 10.18 2017-03-14 -0.02 -1.82 -0.44 -0.69 3.61", "-1.40 -0.80 0.40 18.80 -15.00 9.00 0.80 25.60 7.40 2018-10-11", "\"rU6QIu7JHe2gOUeR\", \"x-csrf-token\": \"\", \"x-version\": \"1.0.0\", } r = requests.get(url, params=params,", "3261.1 2017-08-10 1006.7 290.5 193.2 3286.9 2017-09-12 1002.2 290.1 191.8", "} res = requests.get(f\"https://datacenter-api.jin10.com/reports/dates?category=opec&_={str(int(round(t * 1000)))}\", headers=headers) # 日期序列 all_date_list", "290.5 193.2 3286.9 2017-09-12 1002.2 290.1 191.8 3275.5 2017-10-11 997.5", "inplace=True) temp_df = temp_df.squeeze() temp_df.index.name = None temp_df.name = \"gold_change\"", "290.1 191.8 3275.5 2017-10-11 997.5 290.5 189.0 3274.8 2017-11-13 1000.0", "9.71 -0.06 0.88 -3.47 -3.91 0.03 -6.16 5.08 2017-06-13 0.96", "\"\", \"x-version\": \"1.0.0\", } res = requests.get(f\"https://datacenter-api.jin10.com/reports/dates?category=opec&_={str(int(round(t * 1000)))}\", headers=headers)", "temp_df = temp_df.squeeze() temp_df.index.name = None temp_df.name = \"silver_amount\" url", "52.6 19.8 379.0 440.2 270.2 62.2 154.5 2017-05-11 104.7 169.2", "994.0 288.5 196.3 3213.9 2017-07-12 995.0 289.8 193.8 3261.1 2017-08-10", "append_temp_df[\"总库存\"] temp_append_df.name = \"silver_volume\" temp_df = temp_df.reset_index() temp_df[\"index\"] = temp_df[\"index\"].astype(str)", "0.71 0.18 -1.13 -13.10 -0.37 4.23 -5.44 2017-12-13 1.41 -10.87", "-7.91 2017-10-11 -0.07 -0.84 -5.19 8.85 2017-11-13 1.69 -0.60 -4.36", "17.3 382.8 444.8 270.2 89.0 186.1 2017-10-11 104.6 164.1 53.6", "994.6 293.1 200.4 3213.9 2017-03-14 979.7 292.5 198.7 3195.8 2017-04-12", "= temp_df.astype(float) return temp_df def macro_cons_opec_near_change(): \"\"\" 欧佩克报告-变动, 数据区间从20170118-至今 :return:", "453.3 273.1 70.8 166.0 2018-08-13 106.2 145.6 52.5 18.8 373.7", "# 日期序列 all_date_list = res.json()[\"data\"] need_date_list = [item for item", "= \"silver_volume\" temp_df = temp_df.reset_index() temp_df[\"index\"] = temp_df[\"index\"].astype(str) temp_df =", "2017-06-13 105.9 161.3 52.8 20.4 379.5 442.4 270.5 73.0 168.0", "1253785205.50 2004-11-23 1254751438.19 2004-11-24 1390568824.08 ... 2019-10-20 44286078486.23 2019-10-21 44333677232.68", "2018-07-11 103.9 143.1 51.9 19.0 379.9 453.3 273.1 70.8 166.0", "2018-08-13 1.38 1.17 0.42 -0.34 -5.63 2.41 7.85 -5.67 7.05", "105.9 164.6 53.6 20.5 382.4 446.8 270.3 100.1 174.8 2017-09-12", "(Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.117", "Trust持仓报告, 数据区间从20060429-至今 :return: pandas.Series 2006-04-29 653.17 2006-05-02 653.17 2006-05-03 995.28", "0.61 -4.17 1.21 2018-06-12 8.55 -0.63 -4.25 3.54 2018-07-11 40.54", "{ \"max_date\": \"\", \"category\": \"etf\", \"attr_id\": \"1\", \"_\": str(int(round(t *", "-4.95 -8.17 0.26 -0.91 0.33 -1.31 0.23 -3.72 1.82 2018-05-14", "temp_df.name = country big_df = big_df.append(temp_df) except: continue headers =", "= temp_df.append(temp_append_df.reset_index()) temp_df.drop_duplicates(subset=[\"index\"], keep=\"last\", inplace=True) temp_df.index = pd.to_datetime(temp_df[\"index\"]) del temp_df[\"index\"]", "105.2 152.1 52.5 17.6 295.4 463.1 280.9 110.4 173.6 2019-03-14", "country in [item[\"datas\"] for item in json_data[\"list\"]][0].keys(): try: value_list =", "3.80 1.20 -3.60 27.80 2018-10-11 10.80 3.00 -4.20 13.20 2018-11-13", "temp_df[\"index\"] temp_df = temp_df[temp_df != 'Show All'] temp_df.sort_index(inplace=True) temp_df =", "for item in json_data[\"list\"]] value_list = [item[\"datas\"][\"白银\"] for item in", "\"silver_amount\" url = \"https://cdn.jin10.com/data_center/reports/etf_2.json\" r = requests.get(url) data_json = r.json()", "temp_df.append(temp_se) temp_df.dropna(inplace=True) temp_df.sort_index(inplace=True) temp_df = temp_df.reset_index() temp_df.drop_duplicates(subset=\"index\", keep=\"last\", inplace=True) temp_df.set_index(\"index\",", "None temp_df.name = \"gold_volume\" temp_df = temp_df.astype(float) return temp_df def", "1]] temp_se.index = pd.to_datetime(temp_se.iloc[:, 0]) temp_se = temp_se.iloc[:, 1] temp_df", "3.16 -0.17 5.39 5.08 2017-11-13 -3.84 6.98 0.71 0.18 -1.13", "= append_temp_df[\"增持/减持\"] temp_append_df.name = \"silver_change\" temp_df = temp_df.reset_index() temp_df[\"index\"] =", "2017-02-13 -49.62 -15.93 -3.05 -89.02 2017-03-14 -6.81 -3.69 -1.60 -13.95", "3.03 4.48 -0.72 -0.01 1.32 0.79 -0.25 -0.70 7.57 2018-04-12", "... 2019-10-20 0.00 2019-10-21 0.00 2019-10-22 -4.98 2019-10-23 -1.18 2019-10-24", "-3.19 -7.91 2017-10-11 -0.07 -0.84 -5.19 8.85 2017-11-13 1.69 -0.60", "2018-11-13 12.70 14.20 -4.00 12.70 2018-12-12 37.70 7.10 -5.20 -1.10", "= None temp_df.name = \"silver_amount\" url = \"https://cdn.jin10.com/data_center/reports/etf_2.json\" r =", "-0.30 0.30 -15.60 465.30 -3.30 6.00 -1.70 2018-12-12 -0.50 0.30", "macro_cons_gold_change() print(macro_cons_gold_change_df) macro_cons_gold_amount_df = macro_cons_gold_amount() print(macro_cons_gold_amount_df) print(pd.concat([macro_cons_gold_volume_df, macro_cons_gold_change_df, macro_cons_gold_amount_df], axis=1))", "try: value_list = [item[\"datas\"][country] for item in json_data[\"list\"]] value_df =", "96.42 ... 2019-10-20 924.64 2019-10-21 924.64 2019-10-22 919.66 2019-10-23 918.48", "5.08 2017-11-13 -3.84 6.98 0.71 0.18 -1.13 -13.10 -0.37 4.23", "big_df = big_df.astype(float) return big_df if __name__ == \"__main__\": macro_cons_gold_volume_df", "53.1 18.7 344.7 465.0 281.2 105.3 174.8 2018-11-13 105.4 153.3", "temp_df.astype(float) return temp_df def macro_cons_gold_change(): \"\"\" 全球最大黄金ETF—SPDR Gold Trust持仓报告, 数据区间从20041118-至今", "temp_df.reset_index() temp_df.drop_duplicates(subset=\"index\", keep=\"last\", inplace=True) temp_df.set_index(\"index\", inplace=True) temp_df = temp_df.squeeze() temp_df.index.name", "1.17 0.42 -0.34 -5.63 2.41 7.85 -5.67 7.05 2018-09-12 -1.40", "-0.63 -4.25 3.54 2018-07-11 40.54 3.51 -4.75 17.34 2018-08-13 -5.28", "Show All \"\"\" t = time.time() res = requests.get( JS_CONS_SLIVER_ETF_URL.format(", "= pd.DataFrame(data_json[\"values\"]).T append_temp_df.columns = [item[\"name\"] for item in data_json[\"keys\"]] temp_append_df", "2019-10-20 0.00 2019-10-21 0.00 2019-10-22 -4.98 2019-10-23 -1.18 2019-10-24 0.00", "2017-01-18 108.0 172.4 54.5 21.3 372.0 463.2 281.2 60.8 154.2", "\"same-site\", \"user-agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML,", "= \"日期\" big_df = big_df.astype(float) return big_df def _macro_cons_opec_month(): \"\"\"", "None temp_df.name = \"silver_volume\" url = \"https://cdn.jin10.com/data_center/reports/etf_2.json\" r = requests.get(url)", "52.6 19.7 382.9 440.5 270.0 96.2 186.1 2018-04-12 98.4 152.4", "Trust持仓报告, 数据区间从20041118-至今 :return: pandas.Series 2004-11-18 0 2004-11-19 49.76 2004-11-22 29.24", "= pd.DataFrame(r.json()[\"data\"][\"values\"]).iloc[:, :2] temp_se.index = pd.to_datetime(temp_se.iloc[:, 0]) temp_se = temp_se.iloc[:,", "temp_df.iloc[0, :] temp_df = temp_df.iloc[1:, :] try: temp_df = temp_df[['阿尔及利亚',", "= \"silver_amount\" temp_df = temp_df.reset_index() temp_df[\"index\"] = temp_df[\"index\"].astype(str) temp_df =", "2.77 -0.57 -2.43 -5.35 2018-07-11 0.46 -8.83 -0.09 0.35 -2.27", "286.4 148.8 3195.8 2018-05-14 995.9 287.2 143.6 3193.0 2018-06-12 998.7", "time.time() res = requests.get( JS_CONS_GOLD_ETF_URL.format( str(int(round(t * 1000))), str(int(round(t *", "= temp_df.squeeze() temp_df.index.name = None temp_df.name = \"silver_amount\" url =", "now downing {item}'s data\") res = requests.get( f\"https://datacenter-api.jin10.com/reports/list?category=opec&date={item}&_={str(int(round(t * 1000)))}\",", "20.3 382.3 438.3 270.8 96.2 173.8 2017-12-13 101.3 158.1 53.3", "+ item.split(\"-\")[1] + item.split(\"-\")[2] not in date_list] for item in", "-2.31 0.01 -11.23 13.83 2017-10-11 -0.85 -0.29 -0.05 1.44 0.09", "r = requests.get(url, params=params, headers=headers) temp_se = pd.DataFrame(r.json()[\"data\"][\"values\"]).iloc[:, [0, 1]]", "return big_df def _macro_cons_opec_month(): \"\"\" 欧佩克报告-月度, 数据区间从20170118-至今 这里返回的具体索引日期的数据为上一个月的数据, 由于某些国家的数据有缺失, 只选择有数据的国家返回", "2019-10-20 924.64 2019-10-21 924.64 2019-10-22 919.66 2019-10-23 918.48 2019-10-24 918.48", "print(macro_cons_silver_change_df) macro_cons_silver_amount_df = macro_cons_silver_amount() print(macro_cons_silver_amount_df) print(pd.concat([macro_cons_silver_volume_df, macro_cons_silver_change_df, macro_cons_silver_amount_df], axis=1)) macro_cons_opec_near_change_df", "300.4 119.7 3276.1 2018-11-13 1063.0 316.0 117.1 3290.0 2018-12-12 1101.6", "5.08 2017-06-13 0.96 -5.42 0.22 -0.13 0.45 4.44 0.00 17.82", "委内瑞拉 欧佩克产量 2017-01-18 -14.93 -0.63 -4.52 -22.09 2017-02-13 -49.62 -15.93", "None temp_df.name = \"gold_amount\" temp_df = temp_df.astype(float) return temp_df def", "return temp_df def macro_cons_gold_change(): \"\"\" 全球最大黄金ETF—SPDR Gold Trust持仓报告, 数据区间从20041118-至今 :return:", "\"\"\" 欧佩克报告-月度, 数据区间从 20170118-至今 这里返回的具体索引日期的数据为上一个月的数据, 由于某些国家的数据有缺失 只选择有数据的国家返回 20200312:fix:由于 “厄瓜多尔” 已经有几个月没有更新数据,在这里加以剔除", "2004-11-22 87.09 2004-11-23 87.09 2004-11-24 96.42 ... 2019-10-20 924.64 2019-10-21", "url = \"https://datacenter-api.jin10.com/reports/list_v2\" params = { \"max_date\": \"\", \"category\": \"etf\",", "-0.50 0.30 0.10 -1.10 -38.00 -2.30 4.50 -1.10 -3.00 2019-03-14", "\"x-csrf-token\": \"\", \"x-version\": \"1.0.0\", } res = requests.get(f\"https://datacenter-api.jin10.com/reports/dates?category=opec&_={str(int(round(t * 1000)))}\",", "return temp_df def macro_cons_silver_volume(): \"\"\" 全球最大白银ETF--iShares Silver Trust持仓报告, 数据区间从20060429-至今 :return:", "2019-10-21 Show All 2019-10-22 Show All 2019-10-23 Show All \"\"\"", "macro_cons_silver_change_df = macro_cons_silver_change() print(macro_cons_silver_change_df) macro_cons_silver_amount_df = macro_cons_silver_amount() print(macro_cons_silver_amount_df) print(pd.concat([macro_cons_silver_volume_df, macro_cons_silver_change_df,", "-0.29 -0.05 1.44 0.09 3.16 -0.17 5.39 5.08 2017-11-13 -3.84", "43907962483.56 2019-10-23 44120217405.82 2019-10-24 44120217405.82 \"\"\" t = time.time() res", "big_df.append(temp_df) except: continue headers = { \"accept\": \"*/*\", \"accept-encoding\": \"gzip,", "316.0 117.1 3290.0 2018-12-12 1101.6 324.6 113.7 3296.5 2019-03-14 1008.7", "Gold Trust持仓报告, 数据区间从20041118-至今 :return: pandas.Series 2004-11-18 8.09 2004-11-19 57.85 2004-11-22", "for a moment, now downing {item}'s data\") res = requests.get(", "NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36\",", "2006-05-05 574713264 ... 2019-10-17 Show All 2019-10-18 Show All 2019-10-21", "4.49 -5.53 -20.14 2018-05-14 4.65 0.61 -4.17 1.21 2018-06-12 8.55", "\"origin\": \"https://datacenter.jin10.com\", \"pragma\": \"no-cache\", \"referer\": \"https://datacenter.jin10.com/reportType/dc_usa_michigan_consumer_sentiment\", \"sec-fetch-dest\": \"empty\", \"sec-fetch-mode\": \"cors\",", "2018-09-12 1040.1 297.2 123.5 3256.5 2018-10-11 1051.2 300.4 119.7 3276.1", "73.2 3002.2 2019-06-13 969.0 306.1 74.1 2987.6 \"\"\" t =", "for item in bar: bar.set_description(f\"Please wait for a moment, now", "2018-05-14 99.7 151.5 52.0 18.3 382.3 442.9 270.5 98.2 179.1", "289.5 197.2 3192.8 2017-05-11 995.4 284.2 195.6 3173.2 2017-06-13 994.0", "pd.DataFrame(value_list) value_df.columns = json_data[\"kinds\"] value_df.index = pd.to_datetime(date_list) temp_df = value_df[\"总价值(美元)\"]", "= \"silver_volume\" url = \"https://cdn.jin10.com/data_center/reports/etf_2.json\" r = requests.get(url) data_json =", "None temp_df.name = \"silver_change\" url = \"https://cdn.jin10.com/data_center/reports/etf_2.json\" r = requests.get(url)", "2017-04-12 0.45 -1.87 -0.28 0.19 -2.87 -0.85 -0.95 -6.08 -2.98", "286.5 139.2 3186.9 2018-07-11 1042.0 289.7 134.0 3232.7 2018-08-13 1038.7", "17.6 295.4 463.1 280.9 110.4 173.6 2019-03-14 102.6 145.7 52.2", "= None temp_df.name = \"silver_volume\" url = \"https://cdn.jin10.com/data_center/reports/etf_2.json\" r =", "-2.27 7.15 2.73 -25.43 2.78 2018-08-13 1.38 1.17 0.42 -0.34", "requests.get( JS_CONS_GOLD_ETF_URL.format( str(int(round(t * 1000))), str(int(round(t * 1000)) + 90)", "= [item[\"date\"] for item in json_data[\"list\"]] value_list = [item[\"datas\"][\"白银\"] for", "-0.03 -3.23 -0.23 -2.31 0.01 -11.23 13.83 2017-10-11 -0.85 -0.29", "-2.02 -3.19 -7.91 2017-10-11 -0.07 -0.84 -5.19 8.85 2017-11-13 1.69", "= temp_df[['阿尔及利亚', '安哥拉', '厄瓜多尔', '加蓬', '伊朗', '伊拉克', '科威特', '利比亚', '尼日利亚',", "temp_df.name = \"gold_volume\" temp_df = temp_df.astype(float) return temp_df def macro_cons_gold_change():", "25.60 7.40 2018-10-11 -0.80 5.70 53.10 -0.10 -15.00 0.80 0.60", "temp_df big_df = big_df.T big_df.columns.name = \"日期\" big_df = big_df.astype(float)", "90.6 174.1 2019-04-10 101.8 145.4 52.4 21.4 269.8 452.2 270.9", "temp_df.name = \"silver_change\" url = \"https://datacenter-api.jin10.com/reports/list_v2\" params = { \"max_date\":", "macro_cons_silver_volume_df = macro_cons_silver_volume() print(macro_cons_silver_volume_df) macro_cons_silver_change_df = macro_cons_silver_change() print(macro_cons_silver_change_df) macro_cons_silver_amount_df =", "temp_df.set_index(\"index\", inplace=True) temp_df = temp_df.squeeze() temp_df.index.name = None temp_df.name =", "= value_df[\"上个月\"] temp_df.name = country big_df = big_df.append(temp_df) except: continue", "伊拉克 科威特 利比亚 尼日利亚 \\ 2017-01-18 -0.87 3.56 -0.25 -0.87", "104.7 169.2 52.4 20.6 375.9 437.3 270.2 55.0 150.8 2017-06-13", "11847.91 2019-10-21 11813.02 2019-10-22 11751.96 2019-10-23 11751.96 \"\"\" t =", "270.9 109.8 173.3 2019-06-13 102.9 147.1 52.9 21.1 237.0 472.4", "全球最大黄金ETF—SPDR Gold Trust持仓报告, 数据区间从20041118-至今 :return: pandas.Series 2004-11-18 114920000.00 2004-11-19 828806907.20", "all_date_list if item.split(\"-\")[0] + item.split(\"-\")[1] + item.split(\"-\")[2] not in date_list]", "90) ) ) json_data = json.loads(res.text[res.text.find(\"{\"): res.text.rfind(\"}\") + 1]) date_list" ]
[ "wrong' if exe is None: # make sure we can", "args = [exe] (app, subproc) = cache.launchApplication(args=args, name='ipy', wait=config.LONG_DELAY) scrollbar", "a reference to the scrollBar window' super(ScrollBar, self).__init__(accessible, subproc) self.findFrame(re.compile('^ScrollBar", "# Description: Application wrapper for scrollbar.py # Used by the", "harness_dir[:i].rfind(\"/\") uiaqa_path = harness_dir[:j] if uiaqa_path is None: raise IOError,", "<<EMAIL>> # Date: 08/06/2008 # Description: Application wrapper for scrollbar.py", "scrollbar-*.py tests ##############################################################################$ 'Application wrapper for scrollbar' from strongwind import", "is None: # make sure we can find the sample", "raise IOError, \"%s does not exist\" % exe args =", "if exe is None: # make sure we can find", "None: raise IOError, \"When launching an application you must provide", "##############################################################################$ 'Application wrapper for scrollbar' from strongwind import * from", "wrapper for scrollbar' from strongwind import * from os.path import", "if something goes wrong' if exe is None: # make", "ScrollBar(app, subproc) cache.addApplication(scrollbar) scrollbar.scrollBarFrame.app = scrollbar return scrollbar # class", "j = harness_dir[:i].rfind(\"/\") uiaqa_path = harness_dir[:j] if uiaqa_path is None:", "__init__(self, accessible, subproc=None): 'Get a reference to the scrollBar window'", "# class to represent the application class ScrollBar(accessibles.Application): #checkShowing=False def", "scrollbar # class to represent the application class ScrollBar(accessibles.Application): #checkShowing=False", "raise IOError, \"When launching an application you must provide the", "exist\" % exe args = [exe] (app, subproc) = cache.launchApplication(args=args,", "% exe args = [exe] (app, subproc) = cache.launchApplication(args=args, name='ipy',", "= scrollbar return scrollbar # class to represent the application", "Log an error and return None if something goes wrong'", "exe is None: # make sure we can find the", "make sure we can find the sample application harness_dir =", "to the scrollBar window' super(ScrollBar, self).__init__(accessible, subproc) self.findFrame(re.compile('^ScrollBar control'), logName='Scroll", "path or set the\\nUIAQA_HOME environment \"\\ \"variable.\" exe = '%s/samples/winforms/scrollbar.py'", "return None if something goes wrong' if exe is None:", "= [exe] (app, subproc) = cache.launchApplication(args=args, name='ipy', wait=config.LONG_DELAY) scrollbar =", "application harness_dir = path[0] i = harness_dir.rfind(\"/\") j = harness_dir[:i].rfind(\"/\")", "Description: Application wrapper for scrollbar.py # Used by the scrollbar-*.py", "scrollbar return scrollbar # class to represent the application class", "= harness_dir[:i].rfind(\"/\") uiaqa_path = harness_dir[:j] if uiaqa_path is None: raise", "class ScrollBar(accessibles.Application): #checkShowing=False def __init__(self, accessible, subproc=None): 'Get a reference", "something goes wrong' if exe is None: # make sure", "environment \"\\ \"variable.\" exe = '%s/samples/winforms/scrollbar.py' % uiaqa_path if not", "i = harness_dir.rfind(\"/\") j = harness_dir[:i].rfind(\"/\") uiaqa_path = harness_dir[:j] if", "for scrollbar.py # Used by the scrollbar-*.py tests ##############################################################################$ 'Application", "tests ##############################################################################$ 'Application wrapper for scrollbar' from strongwind import *", "uiaqa_path is None: raise IOError, \"When launching an application you", "exists from sys import path def launchScrollBar(exe=None): 'Launch ScrollBar with", "Date: 08/06/2008 # Description: Application wrapper for scrollbar.py # Used", "application class ScrollBar(accessibles.Application): #checkShowing=False def __init__(self, accessible, subproc=None): 'Get a", "subproc) cache.addApplication(scrollbar) scrollbar.scrollBarFrame.app = scrollbar return scrollbar # class to", "the scrollbar-*.py tests ##############################################################################$ 'Application wrapper for scrollbar' from strongwind", "strongwind import * from os.path import exists from sys import", "Application wrapper for scrollbar.py # Used by the scrollbar-*.py tests", "harness_dir.rfind(\"/\") j = harness_dir[:i].rfind(\"/\") uiaqa_path = harness_dir[:j] if uiaqa_path is", "= cache.launchApplication(args=args, name='ipy', wait=config.LONG_DELAY) scrollbar = ScrollBar(app, subproc) cache.addApplication(scrollbar) scrollbar.scrollBarFrame.app", "sample application harness_dir = path[0] i = harness_dir.rfind(\"/\") j =", "is None: raise IOError, \"When launching an application you must", "set the\\nUIAQA_HOME environment \"\\ \"variable.\" exe = '%s/samples/winforms/scrollbar.py' % uiaqa_path", "# Written by: <NAME> <<EMAIL>> # Date: 08/06/2008 # Description:", "# Used by the scrollbar-*.py tests ##############################################################################$ 'Application wrapper for", "Written by: <NAME> <<EMAIL>> # Date: 08/06/2008 # Description: Application", "the scrollBar window' super(ScrollBar, self).__init__(accessible, subproc) self.findFrame(re.compile('^ScrollBar control'), logName='Scroll Bar')", "goes wrong' if exe is None: # make sure we", "path[0] i = harness_dir.rfind(\"/\") j = harness_dir[:i].rfind(\"/\") uiaqa_path = harness_dir[:j]", "#checkShowing=False def __init__(self, accessible, subproc=None): 'Get a reference to the", "import * from os.path import exists from sys import path", "an application you must provide the \"\\ \"full path or", "and return None if something goes wrong' if exe is", "harness_dir[:j] if uiaqa_path is None: raise IOError, \"When launching an", "\"\\ \"full path or set the\\nUIAQA_HOME environment \"\\ \"variable.\" exe", "def launchScrollBar(exe=None): 'Launch ScrollBar with accessibility enabled and return a", "find the sample application harness_dir = path[0] i = harness_dir.rfind(\"/\")", "# make sure we can find the sample application harness_dir", "we can find the sample application harness_dir = path[0] i", "the\\nUIAQA_HOME environment \"\\ \"variable.\" exe = '%s/samples/winforms/scrollbar.py' % uiaqa_path if", "object. Log an error and return None if something goes", "subproc=None): 'Get a reference to the scrollBar window' super(ScrollBar, self).__init__(accessible,", "enabled and return a scrollbar object. Log an error and", "harness_dir = path[0] i = harness_dir.rfind(\"/\") j = harness_dir[:i].rfind(\"/\") uiaqa_path", "exe = '%s/samples/winforms/scrollbar.py' % uiaqa_path if not os.path.exists(exe): raise IOError,", "scrollbar' from strongwind import * from os.path import exists from", "from os.path import exists from sys import path def launchScrollBar(exe=None):", "[exe] (app, subproc) = cache.launchApplication(args=args, name='ipy', wait=config.LONG_DELAY) scrollbar = ScrollBar(app,", "launchScrollBar(exe=None): 'Launch ScrollBar with accessibility enabled and return a scrollbar", "ScrollBar with accessibility enabled and return a scrollbar object. Log", "ScrollBar(accessibles.Application): #checkShowing=False def __init__(self, accessible, subproc=None): 'Get a reference to", "a scrollbar object. Log an error and return None if", "os.path import exists from sys import path def launchScrollBar(exe=None): 'Launch", "scrollbar = ScrollBar(app, subproc) cache.addApplication(scrollbar) scrollbar.scrollBarFrame.app = scrollbar return scrollbar", "from strongwind import * from os.path import exists from sys", "can find the sample application harness_dir = path[0] i =", "with accessibility enabled and return a scrollbar object. Log an", "None if something goes wrong' if exe is None: #", "\"variable.\" exe = '%s/samples/winforms/scrollbar.py' % uiaqa_path if not os.path.exists(exe): raise", "class to represent the application class ScrollBar(accessibles.Application): #checkShowing=False def __init__(self,", "does not exist\" % exe args = [exe] (app, subproc)", "<NAME> <<EMAIL>> # Date: 08/06/2008 # Description: Application wrapper for", "= '%s/samples/winforms/scrollbar.py' % uiaqa_path if not os.path.exists(exe): raise IOError, \"%s", "return scrollbar # class to represent the application class ScrollBar(accessibles.Application):", "path def launchScrollBar(exe=None): 'Launch ScrollBar with accessibility enabled and return", "\"full path or set the\\nUIAQA_HOME environment \"\\ \"variable.\" exe =", "# Date: 08/06/2008 # Description: Application wrapper for scrollbar.py #", "must provide the \"\\ \"full path or set the\\nUIAQA_HOME environment", "os.path.exists(exe): raise IOError, \"%s does not exist\" % exe args", "an error and return None if something goes wrong' if", "import exists from sys import path def launchScrollBar(exe=None): 'Launch ScrollBar", "def __init__(self, accessible, subproc=None): 'Get a reference to the scrollBar", "accessibility enabled and return a scrollbar object. Log an error", "scrollbar object. Log an error and return None if something", "% uiaqa_path if not os.path.exists(exe): raise IOError, \"%s does not", "not exist\" % exe args = [exe] (app, subproc) =", "'Get a reference to the scrollBar window' super(ScrollBar, self).__init__(accessible, subproc)", "represent the application class ScrollBar(accessibles.Application): #checkShowing=False def __init__(self, accessible, subproc=None):", "sure we can find the sample application harness_dir = path[0]", "from sys import path def launchScrollBar(exe=None): 'Launch ScrollBar with accessibility", "if uiaqa_path is None: raise IOError, \"When launching an application", "'Launch ScrollBar with accessibility enabled and return a scrollbar object.", "or set the\\nUIAQA_HOME environment \"\\ \"variable.\" exe = '%s/samples/winforms/scrollbar.py' %", "Used by the scrollbar-*.py tests ##############################################################################$ 'Application wrapper for scrollbar'", "cache.launchApplication(args=args, name='ipy', wait=config.LONG_DELAY) scrollbar = ScrollBar(app, subproc) cache.addApplication(scrollbar) scrollbar.scrollBarFrame.app =", "to represent the application class ScrollBar(accessibles.Application): #checkShowing=False def __init__(self, accessible,", "for scrollbar' from strongwind import * from os.path import exists", "scrollbar.py # Used by the scrollbar-*.py tests ##############################################################################$ 'Application wrapper", "= harness_dir.rfind(\"/\") j = harness_dir[:i].rfind(\"/\") uiaqa_path = harness_dir[:j] if uiaqa_path", "= harness_dir[:j] if uiaqa_path is None: raise IOError, \"When launching", "reference to the scrollBar window' super(ScrollBar, self).__init__(accessible, subproc) self.findFrame(re.compile('^ScrollBar control'),", "return a scrollbar object. Log an error and return None", "\"When launching an application you must provide the \"\\ \"full", "\"\\ \"variable.\" exe = '%s/samples/winforms/scrollbar.py' % uiaqa_path if not os.path.exists(exe):", "'Application wrapper for scrollbar' from strongwind import * from os.path", "import path def launchScrollBar(exe=None): 'Launch ScrollBar with accessibility enabled and", "subproc) = cache.launchApplication(args=args, name='ipy', wait=config.LONG_DELAY) scrollbar = ScrollBar(app, subproc) cache.addApplication(scrollbar)", "wait=config.LONG_DELAY) scrollbar = ScrollBar(app, subproc) cache.addApplication(scrollbar) scrollbar.scrollBarFrame.app = scrollbar return", "by the scrollbar-*.py tests ##############################################################################$ 'Application wrapper for scrollbar' from", "the sample application harness_dir = path[0] i = harness_dir.rfind(\"/\") j", "(app, subproc) = cache.launchApplication(args=args, name='ipy', wait=config.LONG_DELAY) scrollbar = ScrollBar(app, subproc)", "IOError, \"When launching an application you must provide the \"\\", "launching an application you must provide the \"\\ \"full path", "name='ipy', wait=config.LONG_DELAY) scrollbar = ScrollBar(app, subproc) cache.addApplication(scrollbar) scrollbar.scrollBarFrame.app = scrollbar", "if not os.path.exists(exe): raise IOError, \"%s does not exist\" %", "exe args = [exe] (app, subproc) = cache.launchApplication(args=args, name='ipy', wait=config.LONG_DELAY)", "by: <NAME> <<EMAIL>> # Date: 08/06/2008 # Description: Application wrapper", "\"%s does not exist\" % exe args = [exe] (app,", "application you must provide the \"\\ \"full path or set", "the \"\\ \"full path or set the\\nUIAQA_HOME environment \"\\ \"variable.\"", "accessible, subproc=None): 'Get a reference to the scrollBar window' super(ScrollBar,", "= ScrollBar(app, subproc) cache.addApplication(scrollbar) scrollbar.scrollBarFrame.app = scrollbar return scrollbar #", "provide the \"\\ \"full path or set the\\nUIAQA_HOME environment \"\\", "08/06/2008 # Description: Application wrapper for scrollbar.py # Used by", "not os.path.exists(exe): raise IOError, \"%s does not exist\" % exe", "uiaqa_path if not os.path.exists(exe): raise IOError, \"%s does not exist\"", "############################################################################## # Written by: <NAME> <<EMAIL>> # Date: 08/06/2008 #", "cache.addApplication(scrollbar) scrollbar.scrollBarFrame.app = scrollbar return scrollbar # class to represent", "error and return None if something goes wrong' if exe", "'%s/samples/winforms/scrollbar.py' % uiaqa_path if not os.path.exists(exe): raise IOError, \"%s does", "uiaqa_path = harness_dir[:j] if uiaqa_path is None: raise IOError, \"When", "the application class ScrollBar(accessibles.Application): #checkShowing=False def __init__(self, accessible, subproc=None): 'Get", "and return a scrollbar object. Log an error and return", "IOError, \"%s does not exist\" % exe args = [exe]", "None: # make sure we can find the sample application", "wrapper for scrollbar.py # Used by the scrollbar-*.py tests ##############################################################################$", "scrollbar.scrollBarFrame.app = scrollbar return scrollbar # class to represent the", "* from os.path import exists from sys import path def", "= path[0] i = harness_dir.rfind(\"/\") j = harness_dir[:i].rfind(\"/\") uiaqa_path =", "you must provide the \"\\ \"full path or set the\\nUIAQA_HOME", "sys import path def launchScrollBar(exe=None): 'Launch ScrollBar with accessibility enabled" ]
[ "filepath = \"tweets.txt\" self.file = open(filepath,\"w\") #Slightly dangerous due to", "1 print(\"status count: {}\".format(self._current_count)) if self._current_count >= self._final_count: return False", "hashtag) session.add(hashtag_obj) hashtag_results.append(hashtag_obj) tweet = create_tweet_helper(data, user) for hashtag in", "u[\"followers_count\"], statuses_count = u[\"statuses_count\"], favourites_count = u[\"favourites_count\"], listed_count = u[\"listed_count\"],", "stream = Stream(auth, listener) languages = (\"en\",) try: stream.sample(languages =", "= t.get(\"lang\"), quoted_status_id = t.get(\"quoted_status_id\"), retweet_count = t[\"retweet_count\"], source =", "user=user, coordinates=coordinates, created_at = t[\"created_at\"], favorite_count = t[\"favorite_count\"], in_reply_to_screen_name =", "return user def create_tweet_helper(tweet_data, user): #alias for shorten calls t", "\"<KEY>\" auth = OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, acces_token_secret) def save_tweets(): directory", "favourites_count = u[\"favourites_count\"], listed_count = u[\"listed_count\"], geo_enabled = u[\"geo_enabled\"], lang", "favorite_count = t[\"favorite_count\"], in_reply_to_screen_name = t[\"in_reply_to_screen_name\"], in_reply_to_status_id = t[\"in_reply_to_status_id\"], in_reply_to_user_id", "if self._current_count >= self._final_count: return False def create_user_helper(user_data): #alias to", "self.on_status(data) def on_status(self, data): #this method is define in this", "= u[\"screen_name\"], created_at = u[\"created_at\"], description = u.get(\"description\"), followers_count =", "user def create_tweet_helper(tweet_data, user): #alias for shorten calls t =", "= u[\"listed_count\"], geo_enabled = u[\"geo_enabled\"], lang = u.get(\"lang\")) return user", "user_data user = user(uid = u[\"id_str\"], name = u[\"name\"], screen_name", "quoted_status_id = t.get(\"quoted_status_id\"), retweet_count = t[\"retweet_count\"], source = t[\"source\"], is_retweet", "= data[\"entities\"][\"hashtags\"] for hashtag in hashtags: hashtag = hashtag[\"text\"].lower() try:", "= open(filepath,\"w\") #Slightly dangerous due to circular references>> def __del__(self):", "= user_data user = user(uid = u[\"id_str\"], name = u[\"name\"],", "= user(uid = u[\"id_str\"], name = u[\"name\"], screen_name = u[\"screen_name\"],", "user): #alias for shorten calls t = tweet_data retweet =", "retweet) return tweet def save_to_database(data): try: user = session.query(User).filter_by(id=str(data[\"user\"][\"id\"])).one() except", "t.get(\"lang\"), quoted_status_id = t.get(\"quoted_status_id\"), retweet_count = t[\"retweet_count\"], source = t[\"source\"],", "from os import path from tweepy import OAuthHandler, Stream from", "stream.sample(languages = languages) except KeyboardInterrupt: listener.file.close() class DatabaseListener(StreamListener): def __init__(self,", "tweet = create_tweet_helper(data, user) for hashtag in hashtag_results: tweet.hashtags.append(hashtag) session.add(tweet)", "\"tweets.txt\" self.file = open(filepath,\"w\") #Slightly dangerous due to circular references>>", "save_to_database(data) self._current_count += 1 print(\"status count: {}\".format(self._current_count)) if self._current_count >=", "= session.query(User).filter_by(id=str(data[\"user\"][\"id\"])).one() except NoResultFound: user = create_user_helper(data[\"user\"]) session.add(user) hashtag_results =", "hashtag[\"text\"].lower() try: hashtag_obj=session.query(Hashtag).filer_by(text = hashtag).one() except NoResutlFound: user = create_", "= hashtag[\"text\"].lower() try: hashtag_obj=session.query(Hashtag).filer_by(text = hashtag).one() except NoResutlFound: user =", "data[\"entities\"][\"hashtags\"] for hashtag in hashtags: hashtag = hashtag[\"text\"].lower() try: hashtag_obj=session.query(Hashtag).filer_by(text", "t[\"text\"][:3] == \"RT \" else False coordinates = json.dumps(t[\"coordinates\"]) tweet", "= t[\"in_reply_to_user_id\"], lang = t.get(\"lang\"), quoted_status_id = t.get(\"quoted_status_id\"), retweet_count =", "filepath = None): self._final_count = number_tweets_to_save self._current_count = 0 if", "t = tweet_data retweet = True if t[\"text\"][:3] == \"RT", "Stream from tweepy.streaming import StreamListener from sqlalchemy.orm.exc import NoResultFound from", "directory = _get_dir_absolute_path() filepath = path.join(directory, \"tweets.json\") listener = DatabaseListener(number_tweets_to_save", "\"in_reply_to_status_id\" in data: return self.on_status(data) def on_status(self, data): #this method", "= DatabaseListener(number_tweets_to_save = 1000, filepath=filepath) stream = Stream(auth, listener) languages", "is define in this file save_to_database(data) self._current_count += 1 print(\"status", "if \"in_reply_to_status_id\" in data: return self.on_status(data) def on_status(self, data): #this", "open(filepath,\"w\") #Slightly dangerous due to circular references>> def __del__(self): self.file.close()", "else False coordinates = json.dumps(t[\"coordinates\"]) tweet = Tweet(tid=t[\"id_str\"], tweet=t[\"text\"], user=user,", "t[\"source\"], is_retweet = retweet) return tweet def save_to_database(data): try: user", "user = create_user_helper(data[\"user\"]) session.add(user) hashtag_results = [] hashtags = data[\"entities\"][\"hashtags\"]", "OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, acces_token_secret) def save_tweets(): directory = _get_dir_absolute_path() filepath", "json.dump(raw_data, self.file) self.file.write(\"\\n\") if \"in_reply_to_status_id\" in data: return self.on_status(data) def", "return tweet def save_to_database(data): try: user = session.query(User).filter_by(id=str(data[\"user\"][\"id\"])).one() except NoResultFound:", "created_at = u[\"created_at\"], description = u.get(\"description\"), followers_count = u[\"followers_count\"], statuses_count", "session, Tweet, Hashtag, User consumer_key = \"0qFf4T2xPWVIycLmAwk3rDQ55\" consumer_secret = \"<KEY>\"", "= _get_dir_absolute_path() filepath = path.join(directory, \"tweets.json\") listener = DatabaseListener(number_tweets_to_save =", "self._final_count = number_tweets_to_save self._current_count = 0 if filepath is None:", "OAuthHandler, Stream from tweepy.streaming import StreamListener from sqlalchemy.orm.exc import NoResultFound", "source = t[\"source\"], is_retweet = retweet) return tweet def save_to_database(data):", "DatabaseListener(StreamListener): def __init__(self, number_tweets_to_save, filepath = None): self._final_count = number_tweets_to_save", "Tweet(tid=t[\"id_str\"], tweet=t[\"text\"], user=user, coordinates=coordinates, created_at = t[\"created_at\"], favorite_count = t[\"favorite_count\"],", "create_tweet_helper(tweet_data, user): #alias for shorten calls t = tweet_data retweet", "_get_dir_absolute_path() filepath = path.join(directory, \"tweets.json\") listener = DatabaseListener(number_tweets_to_save = 1000,", "\"tweets.json\") listener = DatabaseListener(number_tweets_to_save = 1000, filepath=filepath) stream = Stream(auth,", "#alias for shorten calls t = tweet_data retweet = True", "def save_to_database(data): try: user = session.query(User).filter_by(id=str(data[\"user\"][\"id\"])).one() except NoResultFound: user =", "hashtag in hashtags: hashtag = hashtag[\"text\"].lower() try: hashtag_obj=session.query(Hashtag).filer_by(text = hashtag).one()", "in_reply_to_user_id = t[\"in_reply_to_user_id\"], lang = t.get(\"lang\"), quoted_status_id = t.get(\"quoted_status_id\"), retweet_count", "retweet_count = t[\"retweet_count\"], source = t[\"source\"], is_retweet = retweet) return", "Stream(auth, listener) languages = (\"en\",) try: stream.sample(languages = languages) except", "if filepath is None: filepath = \"tweets.txt\" self.file = open(filepath,\"w\")", "def on_status(self, data): #this method is define in this file", "= u[\"geo_enabled\"], lang = u.get(\"lang\")) return user def create_tweet_helper(tweet_data, user):", "= u[\"favourites_count\"], listed_count = u[\"listed_count\"], geo_enabled = u[\"geo_enabled\"], lang =", "except NoResultFound: user = create_user_helper(data[\"user\"]) session.add(user) hashtag_results = [] hashtags", "User consumer_key = \"0qFf4T2xPWVIycLmAwk3rDQ55\" consumer_secret = \"<KEY>\" access_token = \"<KEY>\"", "listed_count = u[\"listed_count\"], geo_enabled = u[\"geo_enabled\"], lang = u.get(\"lang\")) return", "database import session, Tweet, Hashtag, User consumer_key = \"0qFf4T2xPWVIycLmAwk3rDQ55\" consumer_secret", "None: filepath = \"tweets.txt\" self.file = open(filepath,\"w\") #Slightly dangerous due", "t[\"favorite_count\"], in_reply_to_screen_name = t[\"in_reply_to_screen_name\"], in_reply_to_status_id = t[\"in_reply_to_status_id\"], in_reply_to_user_id = t[\"in_reply_to_user_id\"],", "def create_user_helper(user_data): #alias to shorten calls u = user_data user", "access_token = \"<KEY>\" acces_token_secret = \"<KEY>\" auth = OAuthHandler(consumer_key, consumer_secret)", "1000, filepath=filepath) stream = Stream(auth, listener) languages = (\"en\",) try:", "define in this file save_to_database(data) self._current_count += 1 print(\"status count:", "statuses_count = u[\"statuses_count\"], favourites_count = u[\"favourites_count\"], listed_count = u[\"listed_count\"], geo_enabled", "t[\"retweet_count\"], source = t[\"source\"], is_retweet = retweet) return tweet def", "to circular references>> def __del__(self): self.file.close() def on_data(self, raw_data): data", "method is define in this file save_to_database(data) self._current_count += 1", "except KeyboardInterrupt: listener.file.close() class DatabaseListener(StreamListener): def __init__(self, number_tweets_to_save, filepath =", "import NoResultFound from database import session, Tweet, Hashtag, User consumer_key", "= number_tweets_to_save self._current_count = 0 if filepath is None: filepath", "to shorten calls u = user_data user = user(uid =", "on_data(self, raw_data): data = json.loads(raw_data) json.dump(raw_data, self.file) self.file.write(\"\\n\") if \"in_reply_to_status_id\"", "coordinates=coordinates, created_at = t[\"created_at\"], favorite_count = t[\"favorite_count\"], in_reply_to_screen_name = t[\"in_reply_to_screen_name\"],", "user = session.query(User).filter_by(id=str(data[\"user\"][\"id\"])).one() except NoResultFound: user = create_user_helper(data[\"user\"]) session.add(user) hashtag_results", "from database import session, Tweet, Hashtag, User consumer_key = \"0qFf4T2xPWVIycLmAwk3rDQ55\"", "self._current_count >= self._final_count: return False def create_user_helper(user_data): #alias to shorten", "= hashtag).one() except NoResutlFound: user = create_ hashtag_obj = Hashtag(text", "create_ hashtag_obj = Hashtag(text = hashtag) session.add(hashtag_obj) hashtag_results.append(hashtag_obj) tweet =", "this file save_to_database(data) self._current_count += 1 print(\"status count: {}\".format(self._current_count)) if", "hashtag_results = [] hashtags = data[\"entities\"][\"hashtags\"] for hashtag in hashtags:", "= t[\"source\"], is_retweet = retweet) return tweet def save_to_database(data): try:", "= t[\"created_at\"], favorite_count = t[\"favorite_count\"], in_reply_to_screen_name = t[\"in_reply_to_screen_name\"], in_reply_to_status_id =", "on_status(self, data): #this method is define in this file save_to_database(data)", "= t[\"in_reply_to_status_id\"], in_reply_to_user_id = t[\"in_reply_to_user_id\"], lang = t.get(\"lang\"), quoted_status_id =", "= t[\"favorite_count\"], in_reply_to_screen_name = t[\"in_reply_to_screen_name\"], in_reply_to_status_id = t[\"in_reply_to_status_id\"], in_reply_to_user_id =", "return self.on_status(data) def on_status(self, data): #this method is define in", "number_tweets_to_save, filepath = None): self._final_count = number_tweets_to_save self._current_count = 0", "tweet_data retweet = True if t[\"text\"][:3] == \"RT \" else", "acces_token_secret = \"<KEY>\" auth = OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, acces_token_secret) def", "shorten calls u = user_data user = user(uid = u[\"id_str\"],", "== \"RT \" else False coordinates = json.dumps(t[\"coordinates\"]) tweet =", "{}\".format(self._current_count)) if self._current_count >= self._final_count: return False def create_user_helper(user_data): #alias", "__del__(self): self.file.close() def on_data(self, raw_data): data = json.loads(raw_data) json.dump(raw_data, self.file)", "= u[\"statuses_count\"], favourites_count = u[\"favourites_count\"], listed_count = u[\"listed_count\"], geo_enabled =", "= OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, acces_token_secret) def save_tweets(): directory = _get_dir_absolute_path()", "= 1000, filepath=filepath) stream = Stream(auth, listener) languages = (\"en\",)", "is None: filepath = \"tweets.txt\" self.file = open(filepath,\"w\") #Slightly dangerous", "screen_name = u[\"screen_name\"], created_at = u[\"created_at\"], description = u.get(\"description\"), followers_count", "u[\"favourites_count\"], listed_count = u[\"listed_count\"], geo_enabled = u[\"geo_enabled\"], lang = u.get(\"lang\"))", "hashtag_results.append(hashtag_obj) tweet = create_tweet_helper(data, user) for hashtag in hashtag_results: tweet.hashtags.append(hashtag)", "consumer_secret) auth.set_access_token(access_token, acces_token_secret) def save_tweets(): directory = _get_dir_absolute_path() filepath =", "Tweet, Hashtag, User consumer_key = \"0qFf4T2xPWVIycLmAwk3rDQ55\" consumer_secret = \"<KEY>\" access_token", "acces_token_secret) def save_tweets(): directory = _get_dir_absolute_path() filepath = path.join(directory, \"tweets.json\")", "coordinates = json.dumps(t[\"coordinates\"]) tweet = Tweet(tid=t[\"id_str\"], tweet=t[\"text\"], user=user, coordinates=coordinates, created_at", "try: stream.sample(languages = languages) except KeyboardInterrupt: listener.file.close() class DatabaseListener(StreamListener): def", "auth.set_access_token(access_token, acces_token_secret) def save_tweets(): directory = _get_dir_absolute_path() filepath = path.join(directory,", "geo_enabled = u[\"geo_enabled\"], lang = u.get(\"lang\")) return user def create_tweet_helper(tweet_data,", "= create_ hashtag_obj = Hashtag(text = hashtag) session.add(hashtag_obj) hashtag_results.append(hashtag_obj) tweet", "def __del__(self): self.file.close() def on_data(self, raw_data): data = json.loads(raw_data) json.dump(raw_data,", "Hashtag(text = hashtag) session.add(hashtag_obj) hashtag_results.append(hashtag_obj) tweet = create_tweet_helper(data, user) for", "filepath = path.join(directory, \"tweets.json\") listener = DatabaseListener(number_tweets_to_save = 1000, filepath=filepath)", "class DatabaseListener(StreamListener): def __init__(self, number_tweets_to_save, filepath = None): self._final_count =", "data): #this method is define in this file save_to_database(data) self._current_count", "u[\"statuses_count\"], favourites_count = u[\"favourites_count\"], listed_count = u[\"listed_count\"], geo_enabled = u[\"geo_enabled\"],", "NoResultFound from database import session, Tweet, Hashtag, User consumer_key =", "u.get(\"lang\")) return user def create_tweet_helper(tweet_data, user): #alias for shorten calls", "for shorten calls t = tweet_data retweet = True if", "lang = u.get(\"lang\")) return user def create_tweet_helper(tweet_data, user): #alias for", "= path.join(directory, \"tweets.json\") listener = DatabaseListener(number_tweets_to_save = 1000, filepath=filepath) stream", "= \"<KEY>\" auth = OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, acces_token_secret) def save_tweets():", "for hashtag in hashtags: hashtag = hashtag[\"text\"].lower() try: hashtag_obj=session.query(Hashtag).filer_by(text =", "count: {}\".format(self._current_count)) if self._current_count >= self._final_count: return False def create_user_helper(user_data):", "path from tweepy import OAuthHandler, Stream from tweepy.streaming import StreamListener", "data = json.loads(raw_data) json.dump(raw_data, self.file) self.file.write(\"\\n\") if \"in_reply_to_status_id\" in data:", "def save_tweets(): directory = _get_dir_absolute_path() filepath = path.join(directory, \"tweets.json\") listener", "__init__(self, number_tweets_to_save, filepath = None): self._final_count = number_tweets_to_save self._current_count =", "tweet = Tweet(tid=t[\"id_str\"], tweet=t[\"text\"], user=user, coordinates=coordinates, created_at = t[\"created_at\"], favorite_count", "user = user(uid = u[\"id_str\"], name = u[\"name\"], screen_name =", "= retweet) return tweet def save_to_database(data): try: user = session.query(User).filter_by(id=str(data[\"user\"][\"id\"])).one()", "session.add(user) hashtag_results = [] hashtags = data[\"entities\"][\"hashtags\"] for hashtag in", ">= self._final_count: return False def create_user_helper(user_data): #alias to shorten calls", "= None): self._final_count = number_tweets_to_save self._current_count = 0 if filepath", "= json.dumps(t[\"coordinates\"]) tweet = Tweet(tid=t[\"id_str\"], tweet=t[\"text\"], user=user, coordinates=coordinates, created_at =", "= Stream(auth, listener) languages = (\"en\",) try: stream.sample(languages = languages)", "#Slightly dangerous due to circular references>> def __del__(self): self.file.close() def", "\"<KEY>\" access_token = \"<KEY>\" acces_token_secret = \"<KEY>\" auth = OAuthHandler(consumer_key,", "created_at = t[\"created_at\"], favorite_count = t[\"favorite_count\"], in_reply_to_screen_name = t[\"in_reply_to_screen_name\"], in_reply_to_status_id", "NoResultFound: user = create_user_helper(data[\"user\"]) session.add(user) hashtag_results = [] hashtags =", "hashtags: hashtag = hashtag[\"text\"].lower() try: hashtag_obj=session.query(Hashtag).filer_by(text = hashtag).one() except NoResutlFound:", "references>> def __del__(self): self.file.close() def on_data(self, raw_data): data = json.loads(raw_data)", "KeyboardInterrupt: listener.file.close() class DatabaseListener(StreamListener): def __init__(self, number_tweets_to_save, filepath = None):", "import path from tweepy import OAuthHandler, Stream from tweepy.streaming import", "create_user_helper(user_data): #alias to shorten calls u = user_data user =", "name = u[\"name\"], screen_name = u[\"screen_name\"], created_at = u[\"created_at\"], description", "False def create_user_helper(user_data): #alias to shorten calls u = user_data", "True if t[\"text\"][:3] == \"RT \" else False coordinates =", "self._final_count: return False def create_user_helper(user_data): #alias to shorten calls u", "u = user_data user = user(uid = u[\"id_str\"], name =", "\" else False coordinates = json.dumps(t[\"coordinates\"]) tweet = Tweet(tid=t[\"id_str\"], tweet=t[\"text\"],", "lang = t.get(\"lang\"), quoted_status_id = t.get(\"quoted_status_id\"), retweet_count = t[\"retweet_count\"], source", "= t.get(\"quoted_status_id\"), retweet_count = t[\"retweet_count\"], source = t[\"source\"], is_retweet =", "followers_count = u[\"followers_count\"], statuses_count = u[\"statuses_count\"], favourites_count = u[\"favourites_count\"], listed_count", "save_to_database(data): try: user = session.query(User).filter_by(id=str(data[\"user\"][\"id\"])).one() except NoResultFound: user = create_user_helper(data[\"user\"])", "from tweepy.streaming import StreamListener from sqlalchemy.orm.exc import NoResultFound from database", "description = u.get(\"description\"), followers_count = u[\"followers_count\"], statuses_count = u[\"statuses_count\"], favourites_count", "= u.get(\"description\"), followers_count = u[\"followers_count\"], statuses_count = u[\"statuses_count\"], favourites_count =", "= hashtag) session.add(hashtag_obj) hashtag_results.append(hashtag_obj) tweet = create_tweet_helper(data, user) for hashtag", "self.file.close() def on_data(self, raw_data): data = json.loads(raw_data) json.dump(raw_data, self.file) self.file.write(\"\\n\")", "u[\"screen_name\"], created_at = u[\"created_at\"], description = u.get(\"description\"), followers_count = u[\"followers_count\"],", "= u[\"name\"], screen_name = u[\"screen_name\"], created_at = u[\"created_at\"], description =", "consumer_secret = \"<KEY>\" access_token = \"<KEY>\" acces_token_secret = \"<KEY>\" auth", "retweet = True if t[\"text\"][:3] == \"RT \" else False", "t[\"in_reply_to_user_id\"], lang = t.get(\"lang\"), quoted_status_id = t.get(\"quoted_status_id\"), retweet_count = t[\"retweet_count\"],", "= u[\"id_str\"], name = u[\"name\"], screen_name = u[\"screen_name\"], created_at =", "import json from os import path from tweepy import OAuthHandler,", "calls t = tweet_data retweet = True if t[\"text\"][:3] ==", "self._current_count += 1 print(\"status count: {}\".format(self._current_count)) if self._current_count >= self._final_count:", "= Tweet(tid=t[\"id_str\"], tweet=t[\"text\"], user=user, coordinates=coordinates, created_at = t[\"created_at\"], favorite_count =", "= t[\"retweet_count\"], source = t[\"source\"], is_retweet = retweet) return tweet", "sqlalchemy.orm.exc import NoResultFound from database import session, Tweet, Hashtag, User", "due to circular references>> def __del__(self): self.file.close() def on_data(self, raw_data):", "StreamListener from sqlalchemy.orm.exc import NoResultFound from database import session, Tweet,", "user = create_ hashtag_obj = Hashtag(text = hashtag) session.add(hashtag_obj) hashtag_results.append(hashtag_obj)", "data: return self.on_status(data) def on_status(self, data): #this method is define", "try: hashtag_obj=session.query(Hashtag).filer_by(text = hashtag).one() except NoResutlFound: user = create_ hashtag_obj", "consumer_key = \"0qFf4T2xPWVIycLmAwk3rDQ55\" consumer_secret = \"<KEY>\" access_token = \"<KEY>\" acces_token_secret", "def __init__(self, number_tweets_to_save, filepath = None): self._final_count = number_tweets_to_save self._current_count", "hashtag).one() except NoResutlFound: user = create_ hashtag_obj = Hashtag(text =", "= Hashtag(text = hashtag) session.add(hashtag_obj) hashtag_results.append(hashtag_obj) tweet = create_tweet_helper(data, user)", "NoResutlFound: user = create_ hashtag_obj = Hashtag(text = hashtag) session.add(hashtag_obj)", "number_tweets_to_save self._current_count = 0 if filepath is None: filepath =", "session.add(hashtag_obj) hashtag_results.append(hashtag_obj) tweet = create_tweet_helper(data, user) for hashtag in hashtag_results:", "is_retweet = retweet) return tweet def save_to_database(data): try: user =", "u[\"id_str\"], name = u[\"name\"], screen_name = u[\"screen_name\"], created_at = u[\"created_at\"],", "= 0 if filepath is None: filepath = \"tweets.txt\" self.file", "DatabaseListener(number_tweets_to_save = 1000, filepath=filepath) stream = Stream(auth, listener) languages =", "shorten calls t = tweet_data retweet = True if t[\"text\"][:3]", "try: user = session.query(User).filter_by(id=str(data[\"user\"][\"id\"])).one() except NoResultFound: user = create_user_helper(data[\"user\"]) session.add(user)", "self.file.write(\"\\n\") if \"in_reply_to_status_id\" in data: return self.on_status(data) def on_status(self, data):", "\"<KEY>\" acces_token_secret = \"<KEY>\" auth = OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, acces_token_secret)", "t.get(\"quoted_status_id\"), retweet_count = t[\"retweet_count\"], source = t[\"source\"], is_retweet = retweet)", "= u[\"followers_count\"], statuses_count = u[\"statuses_count\"], favourites_count = u[\"favourites_count\"], listed_count =", "= tweet_data retweet = True if t[\"text\"][:3] == \"RT \"", "if t[\"text\"][:3] == \"RT \" else False coordinates = json.dumps(t[\"coordinates\"])", "= create_user_helper(data[\"user\"]) session.add(user) hashtag_results = [] hashtags = data[\"entities\"][\"hashtags\"] for", "def create_tweet_helper(tweet_data, user): #alias for shorten calls t = tweet_data", "import StreamListener from sqlalchemy.orm.exc import NoResultFound from database import session,", "import OAuthHandler, Stream from tweepy.streaming import StreamListener from sqlalchemy.orm.exc import", "= \"<KEY>\" acces_token_secret = \"<KEY>\" auth = OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token,", "u[\"created_at\"], description = u.get(\"description\"), followers_count = u[\"followers_count\"], statuses_count = u[\"statuses_count\"],", "u[\"name\"], screen_name = u[\"screen_name\"], created_at = u[\"created_at\"], description = u.get(\"description\"),", "= u.get(\"lang\")) return user def create_tweet_helper(tweet_data, user): #alias for shorten", "= t[\"in_reply_to_screen_name\"], in_reply_to_status_id = t[\"in_reply_to_status_id\"], in_reply_to_user_id = t[\"in_reply_to_user_id\"], lang =", "= \"<KEY>\" access_token = \"<KEY>\" acces_token_secret = \"<KEY>\" auth =", "in hashtags: hashtag = hashtag[\"text\"].lower() try: hashtag_obj=session.query(Hashtag).filer_by(text = hashtag).one() except", "create_user_helper(data[\"user\"]) session.add(user) hashtag_results = [] hashtags = data[\"entities\"][\"hashtags\"] for hashtag", "\"0qFf4T2xPWVIycLmAwk3rDQ55\" consumer_secret = \"<KEY>\" access_token = \"<KEY>\" acces_token_secret = \"<KEY>\"", "os import path from tweepy import OAuthHandler, Stream from tweepy.streaming", "languages) except KeyboardInterrupt: listener.file.close() class DatabaseListener(StreamListener): def __init__(self, number_tweets_to_save, filepath", "#this method is define in this file save_to_database(data) self._current_count +=", "tweet def save_to_database(data): try: user = session.query(User).filter_by(id=str(data[\"user\"][\"id\"])).one() except NoResultFound: user", "from tweepy import OAuthHandler, Stream from tweepy.streaming import StreamListener from", "save_tweets(): directory = _get_dir_absolute_path() filepath = path.join(directory, \"tweets.json\") listener =", "0 if filepath is None: filepath = \"tweets.txt\" self.file =", "tweet=t[\"text\"], user=user, coordinates=coordinates, created_at = t[\"created_at\"], favorite_count = t[\"favorite_count\"], in_reply_to_screen_name", "session.query(User).filter_by(id=str(data[\"user\"][\"id\"])).one() except NoResultFound: user = create_user_helper(data[\"user\"]) session.add(user) hashtag_results = []", "= \"0qFf4T2xPWVIycLmAwk3rDQ55\" consumer_secret = \"<KEY>\" access_token = \"<KEY>\" acces_token_secret =", "tweepy.streaming import StreamListener from sqlalchemy.orm.exc import NoResultFound from database import", "languages = (\"en\",) try: stream.sample(languages = languages) except KeyboardInterrupt: listener.file.close()", "u[\"listed_count\"], geo_enabled = u[\"geo_enabled\"], lang = u.get(\"lang\")) return user def", "in_reply_to_screen_name = t[\"in_reply_to_screen_name\"], in_reply_to_status_id = t[\"in_reply_to_status_id\"], in_reply_to_user_id = t[\"in_reply_to_user_id\"], lang", "= True if t[\"text\"][:3] == \"RT \" else False coordinates", "hashtags = data[\"entities\"][\"hashtags\"] for hashtag in hashtags: hashtag = hashtag[\"text\"].lower()", "print(\"status count: {}\".format(self._current_count)) if self._current_count >= self._final_count: return False def", "file save_to_database(data) self._current_count += 1 print(\"status count: {}\".format(self._current_count)) if self._current_count", "t[\"in_reply_to_screen_name\"], in_reply_to_status_id = t[\"in_reply_to_status_id\"], in_reply_to_user_id = t[\"in_reply_to_user_id\"], lang = t.get(\"lang\"),", "filepath=filepath) stream = Stream(auth, listener) languages = (\"en\",) try: stream.sample(languages", "listener) languages = (\"en\",) try: stream.sample(languages = languages) except KeyboardInterrupt:", "except NoResutlFound: user = create_ hashtag_obj = Hashtag(text = hashtag)", "tweepy import OAuthHandler, Stream from tweepy.streaming import StreamListener from sqlalchemy.orm.exc", "calls u = user_data user = user(uid = u[\"id_str\"], name", "auth = OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, acces_token_secret) def save_tweets(): directory =", "= \"tweets.txt\" self.file = open(filepath,\"w\") #Slightly dangerous due to circular", "self.file) self.file.write(\"\\n\") if \"in_reply_to_status_id\" in data: return self.on_status(data) def on_status(self,", "#alias to shorten calls u = user_data user = user(uid", "hashtag_obj = Hashtag(text = hashtag) session.add(hashtag_obj) hashtag_results.append(hashtag_obj) tweet = create_tweet_helper(data,", "u.get(\"description\"), followers_count = u[\"followers_count\"], statuses_count = u[\"statuses_count\"], favourites_count = u[\"favourites_count\"],", "in_reply_to_status_id = t[\"in_reply_to_status_id\"], in_reply_to_user_id = t[\"in_reply_to_user_id\"], lang = t.get(\"lang\"), quoted_status_id", "self.file = open(filepath,\"w\") #Slightly dangerous due to circular references>> def", "+= 1 print(\"status count: {}\".format(self._current_count)) if self._current_count >= self._final_count: return", "from sqlalchemy.orm.exc import NoResultFound from database import session, Tweet, Hashtag,", "import session, Tweet, Hashtag, User consumer_key = \"0qFf4T2xPWVIycLmAwk3rDQ55\" consumer_secret =", "t[\"in_reply_to_status_id\"], in_reply_to_user_id = t[\"in_reply_to_user_id\"], lang = t.get(\"lang\"), quoted_status_id = t.get(\"quoted_status_id\"),", "= json.loads(raw_data) json.dump(raw_data, self.file) self.file.write(\"\\n\") if \"in_reply_to_status_id\" in data: return", "dangerous due to circular references>> def __del__(self): self.file.close() def on_data(self,", "listener = DatabaseListener(number_tweets_to_save = 1000, filepath=filepath) stream = Stream(auth, listener)", "[] hashtags = data[\"entities\"][\"hashtags\"] for hashtag in hashtags: hashtag =", "json.dumps(t[\"coordinates\"]) tweet = Tweet(tid=t[\"id_str\"], tweet=t[\"text\"], user=user, coordinates=coordinates, created_at = t[\"created_at\"],", "= create_tweet_helper(data, user) for hashtag in hashtag_results: tweet.hashtags.append(hashtag) session.add(tweet) session.commit()", "Hashtag, User consumer_key = \"0qFf4T2xPWVIycLmAwk3rDQ55\" consumer_secret = \"<KEY>\" access_token =", "listener.file.close() class DatabaseListener(StreamListener): def __init__(self, number_tweets_to_save, filepath = None): self._final_count", "circular references>> def __del__(self): self.file.close() def on_data(self, raw_data): data =", "def on_data(self, raw_data): data = json.loads(raw_data) json.dump(raw_data, self.file) self.file.write(\"\\n\") if", "user(uid = u[\"id_str\"], name = u[\"name\"], screen_name = u[\"screen_name\"], created_at", "path.join(directory, \"tweets.json\") listener = DatabaseListener(number_tweets_to_save = 1000, filepath=filepath) stream =", "= languages) except KeyboardInterrupt: listener.file.close() class DatabaseListener(StreamListener): def __init__(self, number_tweets_to_save,", "\"RT \" else False coordinates = json.dumps(t[\"coordinates\"]) tweet = Tweet(tid=t[\"id_str\"],", "= [] hashtags = data[\"entities\"][\"hashtags\"] for hashtag in hashtags: hashtag", "self._current_count = 0 if filepath is None: filepath = \"tweets.txt\"", "u[\"geo_enabled\"], lang = u.get(\"lang\")) return user def create_tweet_helper(tweet_data, user): #alias", "= (\"en\",) try: stream.sample(languages = languages) except KeyboardInterrupt: listener.file.close() class", "return False def create_user_helper(user_data): #alias to shorten calls u =", "in data: return self.on_status(data) def on_status(self, data): #this method is", "json.loads(raw_data) json.dump(raw_data, self.file) self.file.write(\"\\n\") if \"in_reply_to_status_id\" in data: return self.on_status(data)", "raw_data): data = json.loads(raw_data) json.dump(raw_data, self.file) self.file.write(\"\\n\") if \"in_reply_to_status_id\" in", "in this file save_to_database(data) self._current_count += 1 print(\"status count: {}\".format(self._current_count))", "hashtag = hashtag[\"text\"].lower() try: hashtag_obj=session.query(Hashtag).filer_by(text = hashtag).one() except NoResutlFound: user", "filepath is None: filepath = \"tweets.txt\" self.file = open(filepath,\"w\") #Slightly", "= u[\"created_at\"], description = u.get(\"description\"), followers_count = u[\"followers_count\"], statuses_count =", "(\"en\",) try: stream.sample(languages = languages) except KeyboardInterrupt: listener.file.close() class DatabaseListener(StreamListener):", "json from os import path from tweepy import OAuthHandler, Stream", "t[\"created_at\"], favorite_count = t[\"favorite_count\"], in_reply_to_screen_name = t[\"in_reply_to_screen_name\"], in_reply_to_status_id = t[\"in_reply_to_status_id\"],", "hashtag_obj=session.query(Hashtag).filer_by(text = hashtag).one() except NoResutlFound: user = create_ hashtag_obj =", "None): self._final_count = number_tweets_to_save self._current_count = 0 if filepath is", "False coordinates = json.dumps(t[\"coordinates\"]) tweet = Tweet(tid=t[\"id_str\"], tweet=t[\"text\"], user=user, coordinates=coordinates," ]
[ "} # Flag goes here! # flags[\"alternate_homescreen\"] = False return", "# Flag goes here! # flags[\"alternate_homescreen\"] = False return render_template(", "flask import render_template, jsonify from app import app import random", "= False return render_template( 'index.html', **flags, title='Home' ) @app.route('/map') def", "here! # flags[\"alternate_homescreen\"] = False return render_template( 'index.html', **flags, title='Home'", "range(random.randint(2, 9))] return jsonify({'points': points}) @app.route('/contact') def contact(): return render_template('contact.html',", "flags init goes here! # # noinspection PyDictCreation flags =", "Feature flags init goes here! # # noinspection PyDictCreation flags", "from app import app import random @app.route('/') @app.route('/index') def index():", "# # noinspection PyDictCreation flags = { \"welcome_text\": \"welcome to", "title='Home' ) @app.route('/map') def map(): return render_template('map.html', title='Map') @app.route('/map/refresh', methods=['POST'])", "from flask import render_template, jsonify from app import app import", "# flags[\"alternate_homescreen\"] = False return render_template( 'index.html', **flags, title='Home' )", "points = [(random.uniform(48.8434100, 48.8634100), random.uniform(2.3388000, 2.3588000)) for _ in range(random.randint(2,", "@app.route('/') @app.route('/index') def index(): # Feature flags init goes here!", "import render_template, jsonify from app import app import random @app.route('/')", "render_template('map.html', title='Map') @app.route('/map/refresh', methods=['POST']) def map_refresh(): points = [(random.uniform(48.8434100, 48.8634100),", "import app import random @app.route('/') @app.route('/index') def index(): # Feature", "map(): return render_template('map.html', title='Map') @app.route('/map/refresh', methods=['POST']) def map_refresh(): points =", "2.3588000)) for _ in range(random.randint(2, 9))] return jsonify({'points': points}) @app.route('/contact')", "Flag goes here! # flags[\"alternate_homescreen\"] = False return render_template( 'index.html',", "@app.route('/map') def map(): return render_template('map.html', title='Map') @app.route('/map/refresh', methods=['POST']) def map_refresh():", "index(): # Feature flags init goes here! # # noinspection", "# noinspection PyDictCreation flags = { \"welcome_text\": \"welcome to my", "render_template, jsonify from app import app import random @app.route('/') @app.route('/index')", "# Feature flags init goes here! # # noinspection PyDictCreation", "init goes here! # # noinspection PyDictCreation flags = {", "app import app import random @app.route('/') @app.route('/index') def index(): #", "goes here! # # noinspection PyDictCreation flags = { \"welcome_text\":", "tutorial!\" } # Flag goes here! # flags[\"alternate_homescreen\"] = False", "for _ in range(random.randint(2, 9))] return jsonify({'points': points}) @app.route('/contact') def", "to my python FF tutorial!\" } # Flag goes here!", "'index.html', **flags, title='Home' ) @app.route('/map') def map(): return render_template('map.html', title='Map')", "def map_refresh(): points = [(random.uniform(48.8434100, 48.8634100), random.uniform(2.3388000, 2.3588000)) for _", "PyDictCreation flags = { \"welcome_text\": \"welcome to my python FF", "import random @app.route('/') @app.route('/index') def index(): # Feature flags init", "goes here! # flags[\"alternate_homescreen\"] = False return render_template( 'index.html', **flags,", "@app.route('/map/refresh', methods=['POST']) def map_refresh(): points = [(random.uniform(48.8434100, 48.8634100), random.uniform(2.3388000, 2.3588000))", "[(random.uniform(48.8434100, 48.8634100), random.uniform(2.3388000, 2.3588000)) for _ in range(random.randint(2, 9))] return", "\"welcome to my python FF tutorial!\" } # Flag goes", "9))] return jsonify({'points': points}) @app.route('/contact') def contact(): return render_template('contact.html', title='Contact')", "return render_template('map.html', title='Map') @app.route('/map/refresh', methods=['POST']) def map_refresh(): points = [(random.uniform(48.8434100,", "def map(): return render_template('map.html', title='Map') @app.route('/map/refresh', methods=['POST']) def map_refresh(): points", "in range(random.randint(2, 9))] return jsonify({'points': points}) @app.route('/contact') def contact(): return", "{ \"welcome_text\": \"welcome to my python FF tutorial!\" } #", "@app.route('/index') def index(): # Feature flags init goes here! #", "flags[\"alternate_homescreen\"] = False return render_template( 'index.html', **flags, title='Home' ) @app.route('/map')", "map_refresh(): points = [(random.uniform(48.8434100, 48.8634100), random.uniform(2.3388000, 2.3588000)) for _ in", "my python FF tutorial!\" } # Flag goes here! #", "\"welcome_text\": \"welcome to my python FF tutorial!\" } # Flag", "return render_template( 'index.html', **flags, title='Home' ) @app.route('/map') def map(): return", "48.8634100), random.uniform(2.3388000, 2.3588000)) for _ in range(random.randint(2, 9))] return jsonify({'points':", "_ in range(random.randint(2, 9))] return jsonify({'points': points}) @app.route('/contact') def contact():", "random @app.route('/') @app.route('/index') def index(): # Feature flags init goes", "title='Map') @app.route('/map/refresh', methods=['POST']) def map_refresh(): points = [(random.uniform(48.8434100, 48.8634100), random.uniform(2.3388000,", "render_template( 'index.html', **flags, title='Home' ) @app.route('/map') def map(): return render_template('map.html',", ") @app.route('/map') def map(): return render_template('map.html', title='Map') @app.route('/map/refresh', methods=['POST']) def", "methods=['POST']) def map_refresh(): points = [(random.uniform(48.8434100, 48.8634100), random.uniform(2.3388000, 2.3588000)) for", "False return render_template( 'index.html', **flags, title='Home' ) @app.route('/map') def map():", "= { \"welcome_text\": \"welcome to my python FF tutorial!\" }", "noinspection PyDictCreation flags = { \"welcome_text\": \"welcome to my python", "flags = { \"welcome_text\": \"welcome to my python FF tutorial!\"", "def index(): # Feature flags init goes here! # #", "python FF tutorial!\" } # Flag goes here! # flags[\"alternate_homescreen\"]", "FF tutorial!\" } # Flag goes here! # flags[\"alternate_homescreen\"] =", "random.uniform(2.3388000, 2.3588000)) for _ in range(random.randint(2, 9))] return jsonify({'points': points})", "app import random @app.route('/') @app.route('/index') def index(): # Feature flags", "= [(random.uniform(48.8434100, 48.8634100), random.uniform(2.3388000, 2.3588000)) for _ in range(random.randint(2, 9))]", "jsonify from app import app import random @app.route('/') @app.route('/index') def", "**flags, title='Home' ) @app.route('/map') def map(): return render_template('map.html', title='Map') @app.route('/map/refresh',", "here! # # noinspection PyDictCreation flags = { \"welcome_text\": \"welcome" ]
[ "''' import numpy as np a = np.arange(9).reshape(3,3) # 行", "= np.arange(9).reshape(3,3) # 行 a[1] a[[1,2]] a[np.array([1,2])] # 列 a[:,1]", "yangsen @license: @contact: @software: @file: numpy_mat.py @time: 18-8-25 下午9:56 @desc:", "@software: @file: numpy_mat.py @time: 18-8-25 下午9:56 @desc: ''' import numpy", "@time: 18-8-25 下午9:56 @desc: ''' import numpy as np a", "encoding: utf-8 ''' @author: yangsen @license: @contact: @software: @file: numpy_mat.py", "''' @author: yangsen @license: @contact: @software: @file: numpy_mat.py @time: 18-8-25", "@desc: ''' import numpy as np a = np.arange(9).reshape(3,3) #", "as np a = np.arange(9).reshape(3,3) # 行 a[1] a[[1,2]] a[np.array([1,2])]", "@contact: @software: @file: numpy_mat.py @time: 18-8-25 下午9:56 @desc: ''' import", "import numpy as np a = np.arange(9).reshape(3,3) # 行 a[1]", "np.arange(9).reshape(3,3) # 行 a[1] a[[1,2]] a[np.array([1,2])] # 列 a[:,1] a[:,[1,2]]", "utf-8 ''' @author: yangsen @license: @contact: @software: @file: numpy_mat.py @time:", "numpy_mat.py @time: 18-8-25 下午9:56 @desc: ''' import numpy as np", "@author: yangsen @license: @contact: @software: @file: numpy_mat.py @time: 18-8-25 下午9:56", "@license: @contact: @software: @file: numpy_mat.py @time: 18-8-25 下午9:56 @desc: '''", "numpy as np a = np.arange(9).reshape(3,3) # 行 a[1] a[[1,2]]", "# encoding: utf-8 ''' @author: yangsen @license: @contact: @software: @file:", "18-8-25 下午9:56 @desc: ''' import numpy as np a =", "np a = np.arange(9).reshape(3,3) # 行 a[1] a[[1,2]] a[np.array([1,2])] #", "@file: numpy_mat.py @time: 18-8-25 下午9:56 @desc: ''' import numpy as", "下午9:56 @desc: ''' import numpy as np a = np.arange(9).reshape(3,3)", "a = np.arange(9).reshape(3,3) # 行 a[1] a[[1,2]] a[np.array([1,2])] # 列", "# 行 a[1] a[[1,2]] a[np.array([1,2])] # 列 a[:,1] a[:,[1,2]] a[:,np.array([1,2])]" ]
[ "self.update_freq = int(self._register_param(kwargs, 'update_freq', 1)) self.batch_size = int(self._register_param(kwargs, 'batch_size', 80,", "describing the input. action_space (DataSpace): Dataspace describing the output. state_transform", "it's not exhaustive improvment but all changes are in relatively", "hidden layers in fully connected network. Default: (100, 100). lr", "hidden_layers (tuple of ints): Shape of the hidden layers in", "bucket_limits=self.z_atoms+self.z_delta, bucket_counts=dist, global_step=step ) # This method, `log_metrics`, isn't executed", "self.state_transform = state_transform if state_transform is not None else lambda", "gamma (float): Discount factor. Default: 0.99. tau (float): Soft-copy factor.", "(bool): Whether to use Double Q Learning network. Default: True.", "(self.batch_size, self.num_atoms) log_prob = self.net(states, log_prob=True) assert log_prob.shape == (self.batch_size,)", "-> None: \"\"\"Loads state from a file under provided path.", "(DeepMind team) https://arxiv.org/abs/1710.02298 \"\"\" model = \"Rainbow\" def __init__( self,", "same length. \"\"\" rewards = to_tensor(experiences['reward']).float().to(self.device) dones = to_tensor(experiences['done']).type(torch.int).to(self.device) states", "self.net, self.tau) def state_dict(self) -> Dict[str, dict]: \"\"\"Returns agent's state", "max=self.z_atoms[-1], num=len(self.z_atoms), sum=dist.sum(), sum_squares=dist.pow(2).sum(), bucket_limits=self.z_atoms+self.z_delta, bucket_counts=dist, global_step=step ) # This", "to_tensor(self.state_transform(obs)).float().unsqueeze(0).to(self.device) self.dist_probs = self.net.act(t_obs) q_values = (self.dist_probs * self.z_atoms).sum(-1) return", "eps: float = 0.) -> int: \"\"\" Returns actions for", "lambda x: x v_min = float(self._register_param(kwargs, \"v_min\", -10)) v_max =", "torch.arange(self.batch_size, device=self.device) self.n_steps = int(self._register_param(kwargs, \"n_steps\", 3)) self.n_buffer = NStepBuffer(n_steps=self.n_steps,", "discrete action (int)\" self.iteration += 1 t_obs = to_tensor(self.state_transform(obs)).float().to(\"cpu\") t_next_obs", "error.shape == (self.batch_size,) loss = error.mean() assert loss >= 0", "is not None: assert len(self.action_space.shape) == 1, \"Only 1D actions", "(int): Number of most recent samples to keep in memory", "value['loss'] self._loss = value def step(self, obs: ObsType, action: ActionType,", "Epsilon value in the epislon-greedy policy. \"\"\" # Epsilon-greedy action", "= RainbowNet(obs_space.shape, self.action_size, num_atoms=self.num_atoms, **kwargs) self.target_net = RainbowNet(obs_space.shape, self.action_size, num_atoms=self.num_atoms,", "assert loss >= 0 self.optimizer.zero_grad() loss.backward() nn.utils.clip_grad_norm_(self.net.parameters(), self.max_grad_norm) self.optimizer.step() self._loss", "starting any learning step. Default: 0. number_updates (int): How many", "\"num_atoms\", 21, drop=True)) self.z_atoms = torch.linspace(v_min, v_max, self.num_atoms, device=self.device) self.z_delta", "state=t_obs.numpy(), action=[int(action)], reward=[reward], done=[done], next_state=t_next_obs.numpy() ) if not self.n_buffer.available: return", "super().__eq__(o) \\ and isinstance(o, type(self)) \\ and self._config == o._config", "used in the value- and advantage-function in the dueling nets.", "def set_network(self, network_state: NetworkState) -> None: self.net.load_state_dict(network_state.net['net']) self.target_net.load_state_dict(network_state.net['target_net']) def set_buffer(self,", "DEVICE, update=True) self.obs_space = obs_space self.action_space = action_space self._config['obs_space'] =", "self._loss = value def step(self, obs: ObsType, action: ActionType, reward:", "path: String path indicating where the state is stored. \"\"\"", "self.n_buffer.add( state=t_obs.numpy(), action=[int(action)], reward=[reward], done=[done], next_state=t_next_obs.numpy() ) if not self.n_buffer.available:", "action took. done: (bool) Whether in terminal (end of episode)", "at state. next_obs (ObservationType): Observation in a state where the", "1 - dones, self.gamma ** self.n_steps, prob_next) assert m.shape ==", "with action_space.sample() once implemented assert len(self.action_space.shape) == 1, \"Only 1D", "the output. state_transform (optional func): reward_transform (optional func): Keyword parameters:", "= PERBuffer(**kwargs) self.__batch_indices = torch.arange(self.batch_size, device=self.device) self.n_steps = int(self._register_param(kwargs, \"n_steps\",", "value V. Default: -10. v_max (float): Upper bound for distributional", "into the buffer from provided file path. Parameters: path: String", "ints): Shape of the hidden layers in fully connected network.", "case we delay plotting weights. # It simply might be", "It simply might be quite costly. Thread wisely. if full_log:", "self.number_updates = int(self._register_param(kwargs, 'number_updates', 1)) self.max_grad_norm = float(self._register_param(kwargs, 'max_grad_norm', 10))", "file. Parameters: path: String path where to write the state.", "next_obs: ObsType, done: DoneType) -> None: \"\"\"Letting the agent to", "action_space self._config['obs_space'] = self.obs_space self._config['action_space'] = self.action_space self.action_size = action_space.to_feature()", "the logic is in the DQNAgent. Special treatment is required", "= log_prob[self.__batch_indices, actions.squeeze(), :] assert log_prob.shape == m.shape == (self.batch_size,", "= self.net(states, log_prob=True) assert log_prob.shape == (self.batch_size,) + self.action_size +", "return self._rng.randint(self.action_space.low, self.action_space.high) t_obs = to_tensor(self.state_transform(obs)).float().unsqueeze(0).to(self.device) self.dist_probs = self.net.act(t_obs) q_values", "is used in the value- and advantage-function in the dueling", "self.tau) def state_dict(self) -> Dict[str, dict]: \"\"\"Returns agent's state dictionary.", "takes input_shape and returns network): Used to preprocess state before", "-> bool: return super().__eq__(o) \\ and isinstance(o, type(self)) \\ and", "< eps: # TODO: Update with action_space.sample() once implemented assert", "contains a array and all arrays have to have the", "'number_updates', 1)) self.max_grad_norm = float(self._register_param(kwargs, 'max_grad_norm', 10)) self.iteration: int =", "actions currently supported\" action_size = self.action_size[0] for action_idx in range(action_size):", "def load_state(self, path: str) -> None: \"\"\"Loads state from a", "learning. Default: 10. using_double_q (bool): Whether to use Double Q", "obs_space: DataSpace, action_space: DataSpace, state_transform: Optional[Callable]=None, reward_transform: Optional[Callable]=None, **kwargs ):", "a file under provided path. Parameters: path: String path where", "with torch.no_grad(): prob_next = self.target_net.act(next_states) q_next = (prob_next * self.z_atoms).sum(-1)", "torch.argmax(q_next, dim=-1) prob_next = prob_next[self.__batch_indices, a_next, :] m = self.net.dist_projection(rewards,", "where the action took. done: (bool) Whether in terminal (end", "== 1, \"Only 1D is supported right now\" return self._rng.randint(self.action_space.low,", "ai_traineree.networks.heads import RainbowNet from ai_traineree.types import ActionType, AgentState, BufferState, DoneType,", "probability distributions. Each action is taken as the estimate from", "for distributional value V. Default: -10. v_max (float): Upper bound", "(int): Discrete action associated with observation. reward (float): Reward obtained", "layer.bias.cpu(), step) def get_state(self) -> AgentState: \"\"\"Provides agent's internal state.\"\"\"", "Default: True. n_steps (int): Number of lookahead steps when estimating", "state before it is used in the value- and advantage-function", "step. This is dependent on the `update_freq` value. Parameters: obs", "local & target soft_update(self.target_net, self.net, self.tau) def act(self, obs: ObsType,", "to keep in memory for learning. Default: 1e5. warm_up (int):", "log_prob, 1) assert error.shape == (self.batch_size,) loss = error.mean() assert", "data_logger.create_histogram(f\"advantage_net/layer_{idx}\", layer.weight.cpu(), step) if hasattr(layer, \"bias\") and layer.bias is not", "learning phase. Default: 1. max_grad_norm (float): Maximum norm of the", "(function that takes input_shape and returns network): Used to preprocess", "data_logger.create_histogram(f\"value_net/layer_weights_{idx}\", layer.weight.cpu(), step) if hasattr(layer, \"bias\") and layer.bias is not", "dump = self.buffer.dump_buffer(serialize=True) with open(path, 'w') as f: json.dump(dump, f)", "Priority Experience Replay * Multi-step * Double Q net *", "dictionary. Returns: State dicrionary for internal networks. \"\"\" return {\"net\":", "# Cross-entropy loss error and the loss is batch mean", "of most recent samples to keep in memory for learning.", "categorical nets which operate on probability distributions. Each action is", "self.z_atoms = torch.linspace(v_min, v_max, self.num_atoms, device=self.device) self.z_delta = self.z_atoms[1] -", "state.obs_space, 'action_space': state.action_space}) agent = RainbowAgent(**config) if state.network is not", "if len(self.buffer) >= self.batch_size and (self.iteration % self.update_freq) == 0:", "recent samples to keep in memory for learning. Default: 1e5.", "selection if self._rng.random() < eps: # TODO: Update with action_space.sample()", "buffer from provided file path. Parameters: path: String path indicating", "= None self._loss = float('nan') @property def loss(self): return {'loss':", "self.action_space self.action_size = action_space.to_feature() self.lr = float(self._register_param(kwargs, 'lr', 3e-4)) self.gamma", "hasattr(self.buffer, 'priority_update'): assert (~torch.isnan(error)).any() self.buffer.priority_update(experiences['index'], error.detach().cpu().numpy()) # Update networks -", "state_transform if state_transform is not None else lambda x: x", "actions.shape == (self.batch_size, 1) # Discrete domain with torch.no_grad(): prob_next", "func): Keyword parameters: pre_network_fn (function that takes input_shape and returns", "model=self.model, obs_space=self.obs_space, action_space=self.action_space, config=self._config, buffer=copy.deepcopy(self.buffer.get_state()), network=copy.deepcopy(self.get_network_state()), ) def get_network_state(self) ->", "account for n_steps (particularly the reward) self.n_buffer.add( state=t_obs.numpy(), action=[int(action)], reward=[reward],", "'batch_size', 80, update=True)) self.buffer_size = int(self._register_param(kwargs, 'buffer_size', int(1e5), update=True)) self.warm_up", "= value['loss'] self._loss = value def step(self, obs: ObsType, action:", "= reward_transform if reward_transform is not None else lambda x:", "to preprocess state before it is used in the value-", "dependent on the `update_freq` value. Parameters: obs (ObservationType): Observation. action", "from the memory buffer. Five keys are expected, i.e. `state`,", "action: ActionType, reward: RewardType, next_obs: ObsType, done: DoneType) -> None:", "def from_state(state: AgentState) -> AgentBase: config = copy.copy(state.config) config.update({'obs_space': state.obs_space,", "update=True)) self.warm_up = int(self._register_param(kwargs, 'warm_up', 0)) self.number_updates = int(self._register_param(kwargs, 'number_updates',", "Parameters: path: String path where to write the state. \"\"\"", "'update_freq', 1)) self.batch_size = int(self._register_param(kwargs, 'batch_size', 80, update=True)) self.buffer_size =", "lr (default: 1e-3): Learning rate value. gamma (float): Discount factor.", "Parameters: experiences: Contains all experiences for the agent. Typically sampled", "from a file under provided path. Parameters: path: String path", "torch.no_grad(): prob_next = self.target_net.act(next_states) q_next = (prob_next * self.z_atoms).sum(-1) *", "- dones, self.gamma ** self.n_steps, prob_next) assert m.shape == (self.batch_size,", "use learning step in the learning phase. Default: 1. max_grad_norm", "self.gamma ** self.n_steps, prob_next) assert m.shape == (self.batch_size, self.num_atoms) log_prob", "in enumerate(self.net.advantage_net.layers): if hasattr(layer, \"weight\"): data_logger.create_histogram(f\"advantage_net/layer_{idx}\", layer.weight.cpu(), step) if hasattr(layer,", "Consider this class as a particular version of the DQN", "the reward) self.n_buffer.add( state=t_obs.numpy(), action=[int(action)], reward=[reward], done=[done], next_state=t_next_obs.numpy() ) if", "if self.using_double_q: duel_prob_next = self.net.act(next_states) a_next = torch.argmax((duel_prob_next * self.z_atoms).sum(-1),", "-> None: \"\"\"Loads data into the buffer from provided file", "actions for given state as per current policy. Parameters: state:", "int(self._register_param(kwargs, \"n_steps\", 3)) self.n_buffer = NStepBuffer(n_steps=self.n_steps, gamma=self.gamma) # Note that", "self.target_net = RainbowNet(obs_space.shape, self.action_size, num_atoms=self.num_atoms, **kwargs) self.optimizer = optim.Adam(self.net.parameters(), lr=self.lr)", "= float(self._register_param(kwargs, 'tau', 0.002)) self.update_freq = int(self._register_param(kwargs, 'update_freq', 1)) self.batch_size", "path: str) -> None: \"\"\"Saves agent's state into a file.", "some improvments that were suggested before 2017. As mentioned by", "Number of steps between each learning step. Default 1. batch_size", "delay plotting weights. # It simply might be quite costly.", "'max_grad_norm', 10)) self.iteration: int = 0 self.using_double_q = bool(self._register_param(kwargs, \"using_double_q\",", "path) def load_state(self, path: str) -> None: \"\"\"Loads state from", "Shape of the hidden layers in fully connected network. Default:", "state_dict(self) -> Dict[str, dict]: \"\"\"Returns agent's state dictionary. Returns: State", "= self.net.act(t_obs) q_values = (self.dist_probs * self.z_atoms).sum(-1) return int(q_values.argmax(-1)) #", "layer in enumerate(self.net.advantage_net.layers): if hasattr(layer, \"weight\"): data_logger.create_histogram(f\"advantage_net/layer_{idx}\", layer.weight.cpu(), step) if", "List, Optional import torch import torch.nn as nn import torch.optim", "Multi-step * Double Q net * Dueling nets * NoisyNet", "as a particular version of the DQN agent. [1] \"Rainbow:", "(100, 100). lr (default: 1e-3): Learning rate value. gamma (float):", "buffer_size (int): Number of most recent samples to keep in", "update=True) self.obs_space = obs_space self.action_space = action_space self._config['obs_space'] = self.obs_space", "% self.update_freq) == 0: for _ in range(self.number_updates): self.learn(self.buffer.sample()) #", "= float('nan') @property def loss(self): return {'loss': self._loss} @loss.setter def", "Returns: State dicrionary for internal networks. \"\"\" return {\"net\": self.net.state_dict(),", "action_size = self.action_size[0] for action_idx in range(action_size): dist = self.dist_probs[0,", "in range(action_size): dist = self.dist_probs[0, action_idx] data_logger.log_value(f'dist/expected_{action_idx}', (dist*self.z_atoms).sum().item(), step) data_logger.add_histogram(", "self._config['obs_space'] = self.obs_space self._config['action_space'] = self.action_space self.action_size = action_space.to_feature() self.lr", "BufferFactory.from_state(buffer_state) def save_state(self, path: str) -> None: \"\"\"Saves agent's state", "only once - sync local & target soft_update(self.target_net, self.net, self.tau)", "range(action_size): dist = self.dist_probs[0, action_idx] data_logger.log_value(f'dist/expected_{action_idx}', (dist*self.z_atoms).sum().item(), step) data_logger.add_histogram( f'dist/Q_{action_idx}',", "in the dueling nets. hidden_layers (tuple of ints): Shape of", "reward = self.reward_transform(reward) # Delay adding to buffer to account", "This is dependent on the `update_freq` value. Parameters: obs (ObservationType):", "sampled from the memory buffer. Five keys are expected, i.e.", "preprocess state before it is used in the value- and", "* self.z_delta if self.using_double_q: duel_prob_next = self.net.act(next_states) a_next = torch.argmax((duel_prob_next", "phase. Default: 1. max_grad_norm (float): Maximum norm of the gradient", "int(self._register_param(kwargs, 'batch_size', 80, update=True)) self.buffer_size = int(self._register_param(kwargs, 'buffer_size', int(1e5), update=True))", "Lower bound for distributional value V. Default: -10. v_max (float):", "as optim from ai_traineree import DEVICE from ai_traineree.agents import AgentBase", "uses categorical nets which operate on probability distributions. Each action", "are expected, i.e. `state`, `action`, `reward`, `next_state`, `done`. Each key", "once - sync local & target soft_update(self.target_net, self.net, self.tau) def", "DoneType, NetworkState, ObsType, RewardType from ai_traineree.types.dataspace import DataSpace from ai_traineree.utils", "agent uses categorical nets which operate on probability distributions. Each", "Parameters: path: String path indicating where the state is stored.", "learning step. Default 1. batch_size (int): Number of samples to", "ObsType, done: DoneType) -> None: \"\"\"Letting the agent to take", "Number of lookahead steps when estimating reward. See :ref:`NStepBuffer`. Default:", "states) in the value V distribution. Default: 21. \"\"\" super().__init__(**kwargs)", "update_freq (int): Number of steps between each learning step. Default", "log_prob[self.__batch_indices, actions.squeeze(), :] assert log_prob.shape == m.shape == (self.batch_size, self.num_atoms)", "As mentioned by the authors it's not exhaustive improvment but", "self._loss} @loss.setter def loss(self, value): if isinstance(value, dict): value =", "t_next_obs = to_tensor(self.state_transform(next_obs)).float().to(\"cpu\") reward = self.reward_transform(reward) # Delay adding to", "suggested before 2017. As mentioned by the authors it's not", "for learning. Default: 1e5. warm_up (int): Number of samples to", "nets which operate on probability distributions. Each action is taken", "value V. Default: 10. num_atoms (int): Number of atoms (discrete", "10)) self.iteration: int = 0 self.using_double_q = bool(self._register_param(kwargs, \"using_double_q\", True))", "it should be explicitly passed in kwargs kwargs[\"hidden_layers\"] = to_numbers_seq(self._register_param(kwargs,", "currently supported\" action_size = self.action_size[0] for action_idx in range(action_size): dist", "improvements are: * Priority Experience Replay * Multi-step * Double", "provided path. Parameters: path: String path where to write the", "nn import torch.optim as optim from ai_traineree import DEVICE from", "= to_tensor(experiences['done']).type(torch.int).to(self.device) states = to_tensor(experiences['state']).float().to(self.device) next_states = to_tensor(experiences['next_state']).float().to(self.device) actions =", "if hasattr(layer, \"weight\"): data_logger.create_histogram(f\"advantage_net/layer_{idx}\", layer.weight.cpu(), step) if hasattr(layer, \"bias\") and", "passed in kwargs kwargs[\"hidden_layers\"] = to_numbers_seq(self._register_param(kwargs, \"hidden_layers\", (100, 100))) self.net", "distributions. Each action is taken as the estimate from such", "self.net.dist_projection(rewards, 1 - dones, self.gamma ** self.n_steps, prob_next) assert m.shape", "(particularly the reward) self.n_buffer.add( state=t_obs.numpy(), action=[int(action)], reward=[reward], done=[done], next_state=t_next_obs.numpy() )", "of episode) state. \"\"\" assert isinstance(action, int), \"Rainbow expects discrete", "log_prob=True) assert log_prob.shape == (self.batch_size,) + self.action_size + (self.num_atoms,) log_prob", "self.net = RainbowNet(obs_space.shape, self.action_size, num_atoms=self.num_atoms, **kwargs) self.target_net = RainbowNet(obs_space.shape, self.action_size,", "before starting any learning step. Default: 0. number_updates (int): How", "'priority_update'): assert (~torch.isnan(error)).any() self.buffer.priority_update(experiences['index'], error.detach().cpu().numpy()) # Update networks - sync", "NetworkState) -> None: self.net.load_state_dict(network_state.net['net']) self.target_net.load_state_dict(network_state.net['target_net']) def set_buffer(self, buffer_state: BufferState) ->", "Reward obtained for taking action at state. next_obs (ObservationType): Observation", "network. Default: (100, 100). lr (default: 1e-3): Learning rate value.", "DoneType) -> None: \"\"\"Letting the agent to take a step.", "None: \"\"\"Loads data into the buffer from provided file path.", "and (self.iteration % self.update_freq) == 0: for _ in range(self.number_updates):", "0.002. update_freq (int): Number of steps between each learning step.", "the agent to take a step. On some steps the", "reward_transform (optional func): Keyword parameters: pre_network_fn (function that takes input_shape", "== dones.shape == (self.batch_size, 1) assert states.shape == next_states.shape ==", "values, # it should be explicitly passed in kwargs kwargs[\"hidden_layers\"]", "tau (float): Soft-copy factor. Default: 0.002. update_freq (int): Number of", "def get_network_state(self) -> NetworkState: return NetworkState(net=dict(net=self.net.state_dict(), target_net=self.target_net.state_dict())) @staticmethod def from_state(state:", "@property def loss(self): return {'loss': self._loss} @loss.setter def loss(self, value):", "is not None: data_logger.create_histogram(f\"advantage_net/layer_bias_{idx}\", layer.bias.cpu(), step) def get_state(self) -> AgentState:", "\"weight\"): data_logger.create_histogram(f\"advantage_net/layer_{idx}\", layer.weight.cpu(), step) if hasattr(layer, \"bias\") and layer.bias is", "-> Dict[str, dict]: \"\"\"Returns agent's state dictionary. Returns: State dicrionary", "None: \"\"\"Saves data from the buffer into a file under", "int, full_log: bool=False): data_logger.log_value(\"loss/agent\", self._loss, step) if full_log and self.dist_probs", "obs: ObsType, eps: float = 0.) -> int: \"\"\" Returns", "0.002)) self.update_freq = int(self._register_param(kwargs, 'update_freq', 1)) self.batch_size = int(self._register_param(kwargs, 'batch_size',", "ai_traineree import DEVICE from ai_traineree.agents import AgentBase from ai_traineree.agents.agent_utils import", "Typically sampled from the memory buffer. Five keys are expected,", "states.shape == next_states.shape == (self.batch_size,) + self.obs_space.shape assert actions.shape ==", "that extracts pixels values, # it should be explicitly passed", "`reward`, `next_state`, `done`. Each key contains a array and all", "+= 1 t_obs = to_tensor(self.state_transform(obs)).float().to(\"cpu\") t_next_obs = to_tensor(self.state_transform(next_obs)).float().to(\"cpu\") reward =", "DQN agent. [1] \"Rainbow: Combining Improvements in Deep Reinforcement Learning\"", "path: String path where to write the buffer. \"\"\" import", "where the state is stored. \"\"\" agent_state = torch.load(path) self._config", "import torch import torch.nn as nn import torch.optim as optim", "pixels values, # it should be explicitly passed in kwargs", "(self.batch_size,) + self.obs_space.shape assert actions.shape == (self.batch_size, 1) # Discrete", "learn(self, experiences: Dict[str, List]) -> None: \"\"\" Parameters: experiences: Contains", "< self.warm_up: return if len(self.buffer) >= self.batch_size and (self.iteration %", "torch.argmax((duel_prob_next * self.z_atoms).sum(-1), dim=-1) else: a_next = torch.argmax(q_next, dim=-1) prob_next", "network. Default: True. n_steps (int): Number of lookahead steps when", "loss(self): return {'loss': self._loss} @loss.setter def loss(self, value): if isinstance(value,", "torch.optim as optim from ai_traineree import DEVICE from ai_traineree.agents import", "authors it's not exhaustive improvment but all changes are in", "# Delay adding to buffer to account for n_steps (particularly", "1 t_obs = to_tensor(self.state_transform(obs)).float().to(\"cpu\") t_next_obs = to_tensor(self.state_transform(next_obs)).float().to(\"cpu\") reward = self.reward_transform(reward)", "agent.set_buffer(state.buffer) return agent def set_network(self, network_state: NetworkState) -> None: self.net.load_state_dict(network_state.net['net'])", "m = self.net.dist_projection(rewards, 1 - dones, self.gamma ** self.n_steps, prob_next)", "o: object) -> bool: return super().__eq__(o) \\ and isinstance(o, type(self))", "0 self.optimizer.zero_grad() loss.backward() nn.utils.clip_grad_norm_(self.net.parameters(), self.max_grad_norm) self.optimizer.step() self._loss = float(loss.item()) if", "enumerate(self.net.value_net.layers): if hasattr(layer, \"weight\"): data_logger.create_histogram(f\"value_net/layer_weights_{idx}\", layer.weight.cpu(), step) if hasattr(layer, \"bias\")", "== (self.batch_size, self.num_atoms) log_prob = self.net(states, log_prob=True) assert log_prob.shape ==", "is required because the Rainbow agent uses categorical nets which", "a_next, :] m = self.net.dist_projection(rewards, 1 - dones, self.gamma **", "0 self.using_double_q = bool(self._register_param(kwargs, \"using_double_q\", True)) self.state_transform = state_transform if", "assert log_prob.shape == (self.batch_size,) + self.action_size + (self.num_atoms,) log_prob =", "(DataSpace): Dataspace describing the output. state_transform (optional func): reward_transform (optional", "Dict, List, Optional import torch import torch.nn as nn import", "Optional import torch import torch.nn as nn import torch.optim as", "state_transform: Optional[Callable]=None, reward_transform: Optional[Callable]=None, **kwargs ): \"\"\" A wrapper over", "extracts pixels values, # it should be explicitly passed in", "sense. These improvements are: * Priority Experience Replay * Multi-step", "Q estimate Consider this class as a particular version of", "model = \"Rainbow\" def __init__( self, obs_space: DataSpace, action_space: DataSpace,", "should be explicitly passed in kwargs kwargs[\"hidden_layers\"] = to_numbers_seq(self._register_param(kwargs, \"hidden_layers\",", "dones.shape == (self.batch_size, 1) assert states.shape == next_states.shape == (self.batch_size,)", "rewards = to_tensor(experiences['reward']).float().to(self.device) dones = to_tensor(experiences['done']).type(torch.int).to(self.device) states = to_tensor(experiences['state']).float().to(self.device) next_states", "from ai_traineree.buffers import NStepBuffer, PERBuffer from ai_traineree.buffers.buffer_factory import BufferFactory from", "of steps between each learning step. Default 1. batch_size (int):", "'warm_up', 0)) self.number_updates = int(self._register_param(kwargs, 'number_updates', 1)) self.max_grad_norm = float(self._register_param(kwargs,", "done: DoneType) -> None: \"\"\"Letting the agent to take a", "(int): Number of lookahead steps when estimating reward. See :ref:`NStepBuffer`.", "target soft_update(self.target_net, self.net, self.tau) def state_dict(self) -> Dict[str, dict]: \"\"\"Returns", "= float(loss.item()) if hasattr(self.buffer, 'priority_update'): assert (~torch.isnan(error)).any() self.buffer.priority_update(experiences['index'], error.detach().cpu().numpy()) #", "data_logger: DataLogger, step: int, full_log: bool=False): data_logger.log_value(\"loss/agent\", self._loss, step) if", "func): reward_transform (optional func): Keyword parameters: pre_network_fn (function that takes", "value): if isinstance(value, dict): value = value['loss'] self._loss = value", "sum_squares=dist.pow(2).sum(), bucket_limits=self.z_atoms+self.z_delta, bucket_counts=dist, global_step=step ) # This method, `log_metrics`, isn't", "PERBuffer(**kwargs) self.__batch_indices = torch.arange(self.batch_size, device=self.device) self.n_steps = int(self._register_param(kwargs, \"n_steps\", 3))", "AgentState: \"\"\"Provides agent's internal state.\"\"\" return AgentState( model=self.model, obs_space=self.obs_space, action_space=self.action_space,", "agent_state = self.get_state() torch.save(agent_state, path) def load_state(self, path: str) ->", "not None: agent.set_buffer(state.buffer) return agent def set_network(self, network_state: NetworkState) ->", "the agent. Typically sampled from the memory buffer. Five keys", "self.buffer.add(**self.n_buffer.get().get_dict()) if self.iteration < self.warm_up: return if len(self.buffer) >= self.batch_size", "data_logger.create_histogram(f\"value_net/layer_bias_{idx}\", layer.bias.cpu(), step) for idx, layer in enumerate(self.net.advantage_net.layers): if hasattr(layer,", "t_obs = to_tensor(self.state_transform(obs)).float().to(\"cpu\") t_next_obs = to_tensor(self.state_transform(next_obs)).float().to(\"cpu\") reward = self.reward_transform(reward) #", "is provided, e.g. a shared net that extracts pixels values,", "self.reward_transform(reward) # Delay adding to buffer to account for n_steps", "= agent_state.get('config', {}) self.__dict__.update(**self._config) self.net.load_state_dict(agent_state['net']) self.target_net.load_state_dict(agent_state['target_net']) def save_buffer(self, path: str)", "'r') as f: buffer_dump = json.load(f) self.buffer.load_buffer(buffer_dump) def __eq__(self, o:", "expects discrete action (int)\" self.iteration += 1 t_obs = to_tensor(self.state_transform(obs)).float().to(\"cpu\")", "# Note that in case a pre_network is provided, e.g.", "Default: 10. using_double_q (bool): Whether to use Double Q Learning", "prob_next) assert m.shape == (self.batch_size, self.num_atoms) log_prob = self.net(states, log_prob=True)", "with some improvments that were suggested before 2017. As mentioned", "int(self._register_param(kwargs, 'warm_up', 0)) self.number_updates = int(self._register_param(kwargs, 'number_updates', 1)) self.max_grad_norm =", "else lambda x: x v_min = float(self._register_param(kwargs, \"v_min\", -10)) v_max", "agent def set_network(self, network_state: NetworkState) -> None: self.net.load_state_dict(network_state.net['net']) self.target_net.load_state_dict(network_state.net['target_net']) def", "config = copy.copy(state.config) config.update({'obs_space': state.obs_space, 'action_space': state.action_space}) agent = RainbowAgent(**config)", "\"\"\"Loads data into the buffer from provided file path. Parameters:", "= self.dist_probs[0, action_idx] data_logger.log_value(f'dist/expected_{action_idx}', (dist*self.z_atoms).sum().item(), step) data_logger.add_histogram( f'dist/Q_{action_idx}', min=self.z_atoms[0], max=self.z_atoms[-1],", "self.dist_probs is not None: assert len(self.action_space.shape) == 1, \"Only 1D", "self.action_size, num_atoms=self.num_atoms, **kwargs) self.optimizer = optim.Adam(self.net.parameters(), lr=self.lr) self.dist_probs = None", "Number of samples to use at each learning step. Default:", "String path where to write the state. \"\"\" agent_state =", "state from the environment. epislon: Epsilon value in the epislon-greedy", "nn.utils.clip_grad_norm_(self.net.parameters(), self.max_grad_norm) self.optimizer.step() self._loss = float(loss.item()) if hasattr(self.buffer, 'priority_update'): assert", "state is stored. \"\"\" agent_state = torch.load(path) self._config = agent_state.get('config',", "input. action_space (DataSpace): Dataspace describing the output. state_transform (optional func):", "and advantage-function in the dueling nets. hidden_layers (tuple of ints):", "learning step in the learning phase. Default: 1. max_grad_norm (float):", "(~torch.isnan(error)).any() self.buffer.priority_update(experiences['index'], error.detach().cpu().numpy()) # Update networks - sync local &", "CategoricalNet for Q estimate Consider this class as a particular", "\"\"\" model = \"Rainbow\" def __init__( self, obs_space: DataSpace, action_space:", "self.dist_probs[0, action_idx] data_logger.log_value(f'dist/expected_{action_idx}', (dist*self.z_atoms).sum().item(), step) data_logger.add_histogram( f'dist/Q_{action_idx}', min=self.z_atoms[0], max=self.z_atoms[-1], num=len(self.z_atoms),", "= to_tensor(self.state_transform(next_obs)).float().to(\"cpu\") reward = self.reward_transform(reward) # Delay adding to buffer", "Soft-copy factor. Default: 0.002. update_freq (int): Number of steps between", "agent will initiate learning step. This is dependent on the", "in the value- and advantage-function in the dueling nets. hidden_layers", "PERBuffer from ai_traineree.buffers.buffer_factory import BufferFactory from ai_traineree.loggers import DataLogger from", "error.detach().cpu().numpy()) # Update networks - sync local & target soft_update(self.target_net,", "# TODO: Update with action_space.sample() once implemented assert len(self.action_space.shape) ==", "self._register_param(kwargs, \"device\", DEVICE, update=True) self.obs_space = obs_space self.action_space = action_space", "RainbowAgent(**config) if state.network is not None: agent.set_network(state.network) if state.buffer is", "0.99. tau (float): Soft-copy factor. Default: 0.002. update_freq (int): Number", "if state.buffer is not None: agent.set_buffer(state.buffer) return agent def set_network(self,", "Whether to use Double Q Learning network. Default: True. n_steps", "the same length. \"\"\" rewards = to_tensor(experiences['reward']).float().to(self.device) dones = to_tensor(experiences['done']).type(torch.int).to(self.device)", "\"v_max\", 10)) self.num_atoms = int(self._register_param(kwargs, \"num_atoms\", 21, drop=True)) self.z_atoms =", "might be quite costly. Thread wisely. if full_log: for idx,", "input_shape and returns network): Used to preprocess state before it", "the value- and advantage-function in the dueling nets. hidden_layers (tuple", "def step(self, obs: ObsType, action: ActionType, reward: RewardType, next_obs: ObsType,", "a state where the action took. done: (bool) Whether in", "AgentState( model=self.model, obs_space=self.obs_space, action_space=self.action_space, config=self._config, buffer=copy.deepcopy(self.buffer.get_state()), network=copy.deepcopy(self.get_network_state()), ) def get_network_state(self)", "= state_transform if state_transform is not None else lambda x:", "DataSpace, action_space: DataSpace, state_transform: Optional[Callable]=None, reward_transform: Optional[Callable]=None, **kwargs ): \"\"\"", "x: x self.reward_transform = reward_transform if reward_transform is not None", "where the buffer is stored. \"\"\" import json with open(path,", "layer.bias is not None: data_logger.create_histogram(f\"value_net/layer_bias_{idx}\", layer.bias.cpu(), step) for idx, layer", "self.obs_space.shape assert actions.shape == (self.batch_size, 1) # Discrete domain with", "described in [1]. Rainbow is a DQN agent with some", "distribution. Default: 21. \"\"\" super().__init__(**kwargs) self.device = self._register_param(kwargs, \"device\", DEVICE,", "self.iteration < self.warm_up: return if len(self.buffer) >= self.batch_size and (self.iteration", "buffer_state: BufferState) -> None: self.buffer = BufferFactory.from_state(buffer_state) def save_state(self, path:", "assert isinstance(action, int), \"Rainbow expects discrete action (int)\" self.iteration +=", "-torch.sum(m * log_prob, 1) assert error.shape == (self.batch_size,) loss =", "def state_dict(self) -> Dict[str, dict]: \"\"\"Returns agent's state dictionary. Returns:", "policy. \"\"\" # Epsilon-greedy action selection if self._rng.random() < eps:", "= to_tensor(experiences['reward']).float().to(self.device) dones = to_tensor(experiences['done']).type(torch.int).to(self.device) states = to_tensor(experiences['state']).float().to(self.device) next_states =", "\"\"\" return {\"net\": self.net.state_dict(), \"target_net\": self.target_net.state_dict()} def log_metrics(self, data_logger: DataLogger,", "supported right now\" return self._rng.randint(self.action_space.low, self.action_space.high) t_obs = to_tensor(self.state_transform(obs)).float().unsqueeze(0).to(self.device) self.dist_probs", "= int(self._register_param(kwargs, 'buffer_size', int(1e5), update=True)) self.warm_up = int(self._register_param(kwargs, 'warm_up', 0))", "bound for distributional value V. Default: 10. num_atoms (int): Number", "String path indicating where the state is stored. \"\"\" agent_state", "of the DQN agent. [1] \"Rainbow: Combining Improvements in Deep", "\"\"\" super().__init__(**kwargs) self.device = self._register_param(kwargs, \"device\", DEVICE, update=True) self.obs_space =", "self.gamma = float(self._register_param(kwargs, 'gamma', 0.99)) self.tau = float(self._register_param(kwargs, 'tau', 0.002))", "loss(self, value): if isinstance(value, dict): value = value['loss'] self._loss =", "Default 1. batch_size (int): Number of samples to use at", "): \"\"\" A wrapper over the DQN thus majority of", "into a file under provided path. Parameters: path: String path", "value Q(s, a) def learn(self, experiences: Dict[str, List]) -> None:", "taking action at state. next_obs (ObservationType): Observation in a state", "'buffer_size', int(1e5), update=True)) self.warm_up = int(self._register_param(kwargs, 'warm_up', 0)) self.number_updates =", "self._config == o._config \\ and self.buffer == o.buffer \\ and", "now\" return self._rng.randint(self.action_space.low, self.action_space.high) t_obs = to_tensor(self.state_transform(obs)).float().unsqueeze(0).to(self.device) self.dist_probs = self.net.act(t_obs)", "not None else lambda x: x v_min = float(self._register_param(kwargs, \"v_min\",", "idx, layer in enumerate(self.net.advantage_net.layers): if hasattr(layer, \"weight\"): data_logger.create_histogram(f\"advantage_net/layer_{idx}\", layer.weight.cpu(), step)", "is not None: agent.set_buffer(state.buffer) return agent def set_network(self, network_state: NetworkState)", "(float): Reward obtained for taking action at state. next_obs (ObservationType):", "state: Current available state from the environment. epislon: Epsilon value", "data_logger.add_histogram( f'dist/Q_{action_idx}', min=self.z_atoms[0], max=self.z_atoms[-1], num=len(self.z_atoms), sum=dist.sum(), sum_squares=dist.pow(2).sum(), bucket_limits=self.z_atoms+self.z_delta, bucket_counts=dist, global_step=step", "path. Parameters: path: String path indicating where the buffer is", "\"Rainbow\" def __init__( self, obs_space: DataSpace, action_space: DataSpace, state_transform: Optional[Callable]=None,", "@loss.setter def loss(self, value): if isinstance(value, dict): value = value['loss']", "the buffer into a file under provided path. Parameters: path:", "idx, layer in enumerate(self.net.value_net.layers): if hasattr(layer, \"weight\"): data_logger.create_histogram(f\"value_net/layer_weights_{idx}\", layer.weight.cpu(), step)", "(float): Lower bound for distributional value V. Default: -10. v_max", "DataLogger from ai_traineree.networks.heads import RainbowNet from ai_traineree.types import ActionType, AgentState,", "ai_traineree.loggers import DataLogger from ai_traineree.networks.heads import RainbowNet from ai_traineree.types import", "when estimating reward. See :ref:`NStepBuffer`. Default: 3. v_min (float): Lower", "path indicating where the buffer is stored. \"\"\" import json", "memory for learning. Default: 1e5. warm_up (int): Number of samples", "quite costly. Thread wisely. if full_log: for idx, layer in", "import AgentBase from ai_traineree.agents.agent_utils import soft_update from ai_traineree.buffers import NStepBuffer,", "the hidden layers in fully connected network. Default: (100, 100).", "= int(self._register_param(kwargs, \"num_atoms\", 21, drop=True)) self.z_atoms = torch.linspace(v_min, v_max, self.num_atoms,", "state.network is not None: agent.set_network(state.network) if state.buffer is not None:", ">= self.batch_size and (self.iteration % self.update_freq) == 0: for _", "self.__batch_indices = torch.arange(self.batch_size, device=self.device) self.n_steps = int(self._register_param(kwargs, \"n_steps\", 3)) self.n_buffer", "to use at each learning step. Default: 80. buffer_size (int):", "def load_buffer(self, path: str) -> None: \"\"\"Loads data into the", "soft_update from ai_traineree.buffers import NStepBuffer, PERBuffer from ai_traineree.buffers.buffer_factory import BufferFactory", "self.optimizer.zero_grad() loss.backward() nn.utils.clip_grad_norm_(self.net.parameters(), self.max_grad_norm) self.optimizer.step() self._loss = float(loss.item()) if hasattr(self.buffer,", "return super().__eq__(o) \\ and isinstance(o, type(self)) \\ and self._config ==", "is supported right now\" return self._rng.randint(self.action_space.low, self.action_space.high) t_obs = to_tensor(self.state_transform(obs)).float().unsqueeze(0).to(self.device)", "copy from typing import Callable, Dict, List, Optional import torch", "self.learn(self.buffer.sample()) # Update networks only once - sync local &", "# it should be explicitly passed in kwargs kwargs[\"hidden_layers\"] =", "bool(self._register_param(kwargs, \"using_double_q\", True)) self.state_transform = state_transform if state_transform is not", "def save_buffer(self, path: str) -> None: \"\"\"Saves data from the", "makes sense. These improvements are: * Priority Experience Replay *", "batch mean error = -torch.sum(m * log_prob, 1) assert error.shape", "obs: ObsType, action: ActionType, reward: RewardType, next_obs: ObsType, done: DoneType)", "ai_traineree.types.dataspace import DataSpace from ai_traineree.utils import to_numbers_seq, to_tensor class RainbowAgent(AgentBase):", "== o._config \\ and self.buffer == o.buffer \\ and self.get_network_state()", "-> None: \"\"\" Parameters: experiences: Contains all experiences for the", "internal networks. \"\"\" return {\"net\": self.net.state_dict(), \"target_net\": self.target_net.state_dict()} def log_metrics(self,", "self.target_net.act(next_states) q_next = (prob_next * self.z_atoms).sum(-1) * self.z_delta if self.using_double_q:", "self.z_atoms).sum(-1) return int(q_values.argmax(-1)) # Action maximizes state-action value Q(s, a)", "in the learning phase. Default: 1. max_grad_norm (float): Maximum norm", "Parameters: state: Current available state from the environment. epislon: Epsilon", "= \"Rainbow\" def __init__( self, obs_space: DataSpace, action_space: DataSpace, state_transform:", "\"\"\" Returns actions for given state as per current policy.", "(ObservationType): Observation in a state where the action took. done:", "isinstance(o, type(self)) \\ and self._config == o._config \\ and self.buffer", "from ai_traineree.utils import to_numbers_seq, to_tensor class RainbowAgent(AgentBase): \"\"\"Rainbow agent as", "fully connected network. Default: (100, 100). lr (default: 1e-3): Learning", "steps the agent will initiate learning step. This is dependent", "How many times to use learning step in the learning", "net * Dueling nets * NoisyNet * CategoricalNet for Q", "List]) -> None: \"\"\" Parameters: experiences: Contains all experiences for", "_ in range(self.number_updates): self.learn(self.buffer.sample()) # Update networks only once -", "self.__dict__.update(**self._config) self.net.load_state_dict(agent_state['net']) self.target_net.load_state_dict(agent_state['target_net']) def save_buffer(self, path: str) -> None: \"\"\"Saves", "reward_transform: Optional[Callable]=None, **kwargs ): \"\"\" A wrapper over the DQN", "kwargs[\"hidden_layers\"] = to_numbers_seq(self._register_param(kwargs, \"hidden_layers\", (100, 100))) self.net = RainbowNet(obs_space.shape, self.action_size,", "a DQN agent with some improvments that were suggested before", "write the buffer. \"\"\" import json dump = self.buffer.dump_buffer(serialize=True) with", "atoms (discrete states) in the value V distribution. Default: 21.", "0. number_updates (int): How many times to use learning step", "agent's state into a file. Parameters: path: String path where", "[1] \"Rainbow: Combining Improvements in Deep Reinforcement Learning\" by Hessel", "Update networks only once - sync local & target soft_update(self.target_net,", "DQN thus majority of the logic is in the DQNAgent.", "save_state(self, path: str) -> None: \"\"\"Saves agent's state into a", "per current policy. Parameters: state: Current available state from the", "self.n_buffer.available: return self.buffer.add(**self.n_buffer.get().get_dict()) if self.iteration < self.warm_up: return if len(self.buffer)", "1. max_grad_norm (float): Maximum norm of the gradient used in", "dict): value = value['loss'] self._loss = value def step(self, obs:", "* Multi-step * Double Q net * Dueling nets *", "int(self._register_param(kwargs, 'update_freq', 1)) self.batch_size = int(self._register_param(kwargs, 'batch_size', 80, update=True)) self.buffer_size", "assert rewards.shape == dones.shape == (self.batch_size, 1) assert states.shape ==", "Observation. action (int): Discrete action associated with observation. reward (float):", "length. \"\"\" rewards = to_tensor(experiences['reward']).float().to(self.device) dones = to_tensor(experiences['done']).type(torch.int).to(self.device) states =", "None: data_logger.create_histogram(f\"advantage_net/layer_bias_{idx}\", layer.bias.cpu(), step) def get_state(self) -> AgentState: \"\"\"Provides agent's", "in a state where the action took. done: (bool) Whether", "all arrays have to have the same length. \"\"\" rewards", "target soft_update(self.target_net, self.net, self.tau) def act(self, obs: ObsType, eps: float", "copy.copy(state.config) config.update({'obs_space': state.obs_space, 'action_space': state.action_space}) agent = RainbowAgent(**config) if state.network", "= bool(self._register_param(kwargs, \"using_double_q\", True)) self.state_transform = state_transform if state_transform is", "a step. On some steps the agent will initiate learning", "Update with action_space.sample() once implemented assert len(self.action_space.shape) == 1, \"Only", "self.dist_probs = self.net.act(t_obs) q_values = (self.dist_probs * self.z_atoms).sum(-1) return int(q_values.argmax(-1))", "import copy from typing import Callable, Dict, List, Optional import", "batch_size (int): Number of samples to use at each learning", "agent. [1] \"Rainbow: Combining Improvements in Deep Reinforcement Learning\" by", "supported\" action_size = self.action_size[0] for action_idx in range(action_size): dist =", "* self.z_atoms).sum(-1), dim=-1) else: a_next = torch.argmax(q_next, dim=-1) prob_next =", "reward. See :ref:`NStepBuffer`. Default: 3. v_min (float): Lower bound for", "- self.z_atoms[0] self.buffer = PERBuffer(**kwargs) self.__batch_indices = torch.arange(self.batch_size, device=self.device) self.n_steps", "len(self.buffer) >= self.batch_size and (self.iteration % self.update_freq) == 0: for", "device=self.device) self.z_delta = self.z_atoms[1] - self.z_atoms[0] self.buffer = PERBuffer(**kwargs) self.__batch_indices", "agent_state.get('config', {}) self.__dict__.update(**self._config) self.net.load_state_dict(agent_state['net']) self.target_net.load_state_dict(agent_state['target_net']) def save_buffer(self, path: str) ->", "21. \"\"\" super().__init__(**kwargs) self.device = self._register_param(kwargs, \"device\", DEVICE, update=True) self.obs_space", "samples to use at each learning step. Default: 80. buffer_size", "ai_traineree.agents.agent_utils import soft_update from ai_traineree.buffers import NStepBuffer, PERBuffer from ai_traineree.buffers.buffer_factory", "factor. Default: 0.002. update_freq (int): Number of steps between each", "V. Default: -10. v_max (float): Upper bound for distributional value", "* log_prob, 1) assert error.shape == (self.batch_size,) loss = error.mean()", "import Callable, Dict, List, Optional import torch import torch.nn as", "**kwargs) self.optimizer = optim.Adam(self.net.parameters(), lr=self.lr) self.dist_probs = None self._loss =", "(self.iteration % self.update_freq) == 0: for _ in range(self.number_updates): self.learn(self.buffer.sample())", "from such distributions. Parameters: obs_space (DataSpace): Dataspace describing the input.", "if hasattr(layer, \"bias\") and layer.bias is not None: data_logger.create_histogram(f\"advantage_net/layer_bias_{idx}\", layer.bias.cpu(),", "== (self.batch_size, 1) assert states.shape == next_states.shape == (self.batch_size,) +", "action associated with observation. reward (float): Reward obtained for taking", "optim from ai_traineree import DEVICE from ai_traineree.agents import AgentBase from", "True. n_steps (int): Number of lookahead steps when estimating reward.", "dim=-1) prob_next = prob_next[self.__batch_indices, a_next, :] m = self.net.dist_projection(rewards, 1", "RewardType from ai_traineree.types.dataspace import DataSpace from ai_traineree.utils import to_numbers_seq, to_tensor", "num_atoms=self.num_atoms, **kwargs) self.optimizer = optim.Adam(self.net.parameters(), lr=self.lr) self.dist_probs = None self._loss", "as f: buffer_dump = json.load(f) self.buffer.load_buffer(buffer_dump) def __eq__(self, o: object)", "open(path, 'w') as f: json.dump(dump, f) def load_buffer(self, path: str)", "treatment is required because the Rainbow agent uses categorical nets", "reward (float): Reward obtained for taking action at state. next_obs", "take a step. On some steps the agent will initiate", "80, update=True)) self.buffer_size = int(self._register_param(kwargs, 'buffer_size', int(1e5), update=True)) self.warm_up =", "Discount factor. Default: 0.99. tau (float): Soft-copy factor. Default: 0.002.", "assert len(self.action_space.shape) == 1, \"Only 1D actions currently supported\" action_size", "case a pre_network is provided, e.g. a shared net that", "= -torch.sum(m * log_prob, 1) assert error.shape == (self.batch_size,) loss", "ObsType, eps: float = 0.) -> int: \"\"\" Returns actions", "Dict[str, dict]: \"\"\"Returns agent's state dictionary. Returns: State dicrionary for", "Five keys are expected, i.e. `state`, `action`, `reward`, `next_state`, `done`.", "bool: return super().__eq__(o) \\ and isinstance(o, type(self)) \\ and self._config", "layer.bias.cpu(), step) for idx, layer in enumerate(self.net.advantage_net.layers): if hasattr(layer, \"weight\"):", "if hasattr(self.buffer, 'priority_update'): assert (~torch.isnan(error)).any() self.buffer.priority_update(experiences['index'], error.detach().cpu().numpy()) # Update networks", "\\ and self._config == o._config \\ and self.buffer == o.buffer", "agent as described in [1]. Rainbow is a DQN agent", "assert states.shape == next_states.shape == (self.batch_size,) + self.obs_space.shape assert actions.shape", "to write the buffer. \"\"\" import json dump = self.buffer.dump_buffer(serialize=True)", "required because the Rainbow agent uses categorical nets which operate", "Callable, Dict, List, Optional import torch import torch.nn as nn", "self.net.load_state_dict(network_state.net['net']) self.target_net.load_state_dict(network_state.net['target_net']) def set_buffer(self, buffer_state: BufferState) -> None: self.buffer =", "self.using_double_q: duel_prob_next = self.net.act(next_states) a_next = torch.argmax((duel_prob_next * self.z_atoms).sum(-1), dim=-1)", "str) -> None: \"\"\"Loads state from a file under provided", "the buffer. \"\"\" import json dump = self.buffer.dump_buffer(serialize=True) with open(path,", "= self.obs_space self._config['action_space'] = self.action_space self.action_size = action_space.to_feature() self.lr =", "layer.weight.cpu(), step) if hasattr(layer, \"bias\") and layer.bias is not None:", "path: str) -> None: \"\"\"Loads state from a file under", "= value def step(self, obs: ObsType, action: ActionType, reward: RewardType,", "and all arrays have to have the same length. \"\"\"", "observation. reward (float): Reward obtained for taking action at state.", "loss error and the loss is batch mean error =", "assert error.shape == (self.batch_size,) loss = error.mean() assert loss >=", "from ai_traineree.agents import AgentBase from ai_traineree.agents.agent_utils import soft_update from ai_traineree.buffers", "import json with open(path, 'r') as f: buffer_dump = json.load(f)", "# Epsilon-greedy action selection if self._rng.random() < eps: # TODO:", "config=self._config, buffer=copy.deepcopy(self.buffer.get_state()), network=copy.deepcopy(self.get_network_state()), ) def get_network_state(self) -> NetworkState: return NetworkState(net=dict(net=self.net.state_dict(),", "\"hidden_layers\", (100, 100))) self.net = RainbowNet(obs_space.shape, self.action_size, num_atoms=self.num_atoms, **kwargs) self.target_net", "Number of samples to observe before starting any learning step.", "self.net.act(next_states) a_next = torch.argmax((duel_prob_next * self.z_atoms).sum(-1), dim=-1) else: a_next =", "self.net.act(t_obs) q_values = (self.dist_probs * self.z_atoms).sum(-1) return int(q_values.argmax(-1)) # Action", "type(self)) \\ and self._config == o._config \\ and self.buffer ==", "= int(self._register_param(kwargs, 'number_updates', 1)) self.max_grad_norm = float(self._register_param(kwargs, 'max_grad_norm', 10)) self.iteration:", "layers in fully connected network. Default: (100, 100). lr (default:", "* Double Q net * Dueling nets * NoisyNet *", "torch import torch.nn as nn import torch.optim as optim from", "\"target_net\": self.target_net.state_dict()} def log_metrics(self, data_logger: DataLogger, step: int, full_log: bool=False):", "a) def learn(self, experiences: Dict[str, List]) -> None: \"\"\" Parameters:", "data_logger.log_value(\"loss/agent\", self._loss, step) if full_log and self.dist_probs is not None:", "reward_transform if reward_transform is not None else lambda x: x", "the estimate from such distributions. Parameters: obs_space (DataSpace): Dataspace describing", "their connection makes sense. These improvements are: * Priority Experience", "self.warm_up = int(self._register_param(kwargs, 'warm_up', 0)) self.number_updates = int(self._register_param(kwargs, 'number_updates', 1))", "(int): Number of steps between each learning step. Default 1.", "to use Double Q Learning network. Default: True. n_steps (int):", "= RainbowNet(obs_space.shape, self.action_size, num_atoms=self.num_atoms, **kwargs) self.optimizer = optim.Adam(self.net.parameters(), lr=self.lr) self.dist_probs", "None: self.buffer = BufferFactory.from_state(buffer_state) def save_state(self, path: str) -> None:", "Default: 0. number_updates (int): How many times to use learning", "log_prob.shape == m.shape == (self.batch_size, self.num_atoms) # Cross-entropy loss error", "float(self._register_param(kwargs, 'lr', 3e-4)) self.gamma = float(self._register_param(kwargs, 'gamma', 0.99)) self.tau =", "Default: 21. \"\"\" super().__init__(**kwargs) self.device = self._register_param(kwargs, \"device\", DEVICE, update=True)", "return {\"net\": self.net.state_dict(), \"target_net\": self.target_net.state_dict()} def log_metrics(self, data_logger: DataLogger, step:", "self.buffer = PERBuffer(**kwargs) self.__batch_indices = torch.arange(self.batch_size, device=self.device) self.n_steps = int(self._register_param(kwargs,", "= action_space.to_feature() self.lr = float(self._register_param(kwargs, 'lr', 3e-4)) self.gamma = float(self._register_param(kwargs,", "if full_log: for idx, layer in enumerate(self.net.value_net.layers): if hasattr(layer, \"weight\"):", "improvment but all changes are in relatively separate areas so", "load_state(self, path: str) -> None: \"\"\"Loads state from a file", "import ActionType, AgentState, BufferState, DoneType, NetworkState, ObsType, RewardType from ai_traineree.types.dataspace", "as nn import torch.optim as optim from ai_traineree import DEVICE", "-> None: \"\"\"Saves agent's state into a file. Parameters: path:", "Experience Replay * Multi-step * Double Q net * Dueling", "number_updates (int): How many times to use learning step in", "policy. Parameters: state: Current available state from the environment. epislon:", "costly. Thread wisely. if full_log: for idx, layer in enumerate(self.net.value_net.layers):", "state-action value Q(s, a) def learn(self, experiences: Dict[str, List]) ->", "assert (~torch.isnan(error)).any() self.buffer.priority_update(experiences['index'], error.detach().cpu().numpy()) # Update networks - sync local", "10. num_atoms (int): Number of atoms (discrete states) in the", "State dicrionary for internal networks. \"\"\" return {\"net\": self.net.state_dict(), \"target_net\":", "value V distribution. Default: 21. \"\"\" super().__init__(**kwargs) self.device = self._register_param(kwargs,", "None: \"\"\"Loads state from a file under provided path. Parameters:", "et al. (DeepMind team) https://arxiv.org/abs/1710.02298 \"\"\" model = \"Rainbow\" def", "= optim.Adam(self.net.parameters(), lr=self.lr) self.dist_probs = None self._loss = float('nan') @property", "be quite costly. Thread wisely. if full_log: for idx, layer", "step) if hasattr(layer, \"bias\") and layer.bias is not None: data_logger.create_histogram(f\"value_net/layer_bias_{idx}\",", "self.iteration: int = 0 self.using_double_q = bool(self._register_param(kwargs, \"using_double_q\", True)) self.state_transform", "-> None: \"\"\"Letting the agent to take a step. On", ") if not self.n_buffer.available: return self.buffer.add(**self.n_buffer.get().get_dict()) if self.iteration < self.warm_up:", "reward_transform is not None else lambda x: x v_min =", "action_idx] data_logger.log_value(f'dist/expected_{action_idx}', (dist*self.z_atoms).sum().item(), step) data_logger.add_histogram( f'dist/Q_{action_idx}', min=self.z_atoms[0], max=self.z_atoms[-1], num=len(self.z_atoms), sum=dist.sum(),", "int(1e5), update=True)) self.warm_up = int(self._register_param(kwargs, 'warm_up', 0)) self.number_updates = int(self._register_param(kwargs,", "json dump = self.buffer.dump_buffer(serialize=True) with open(path, 'w') as f: json.dump(dump,", "current policy. Parameters: state: Current available state from the environment.", "all experiences for the agent. Typically sampled from the memory", "== (self.batch_size,) loss = error.mean() assert loss >= 0 self.optimizer.zero_grad()", "explicitly passed in kwargs kwargs[\"hidden_layers\"] = to_numbers_seq(self._register_param(kwargs, \"hidden_layers\", (100, 100)))", "path where to write the buffer. \"\"\" import json dump", "Action maximizes state-action value Q(s, a) def learn(self, experiences: Dict[str,", "= 0.) -> int: \"\"\" Returns actions for given state", "* self.z_atoms).sum(-1) * self.z_delta if self.using_double_q: duel_prob_next = self.net.act(next_states) a_next", "\"n_steps\", 3)) self.n_buffer = NStepBuffer(n_steps=self.n_steps, gamma=self.gamma) # Note that in", "-> NetworkState: return NetworkState(net=dict(net=self.net.state_dict(), target_net=self.target_net.state_dict())) @staticmethod def from_state(state: AgentState) ->", "self.action_size, num_atoms=self.num_atoms, **kwargs) self.target_net = RainbowNet(obs_space.shape, self.action_size, num_atoms=self.num_atoms, **kwargs) self.optimizer", "get_network_state(self) -> NetworkState: return NetworkState(net=dict(net=self.net.state_dict(), target_net=self.target_net.state_dict())) @staticmethod def from_state(state: AgentState)", "(DataSpace): Dataspace describing the input. action_space (DataSpace): Dataspace describing the", "it is used in the value- and advantage-function in the", "NetworkState(net=dict(net=self.net.state_dict(), target_net=self.target_net.state_dict())) @staticmethod def from_state(state: AgentState) -> AgentBase: config =", "from ai_traineree import DEVICE from ai_traineree.agents import AgentBase from ai_traineree.agents.agent_utils", "obs_space (DataSpace): Dataspace describing the input. action_space (DataSpace): Dataspace describing", "buffer. Five keys are expected, i.e. `state`, `action`, `reward`, `next_state`,", "Update networks - sync local & target soft_update(self.target_net, self.net, self.tau)", "AgentState) -> AgentBase: config = copy.copy(state.config) config.update({'obs_space': state.obs_space, 'action_space': state.action_space})", "Learning\" by Hessel et al. (DeepMind team) https://arxiv.org/abs/1710.02298 \"\"\" model", "warm_up (int): Number of samples to observe before starting any", "(self.batch_size,) + self.action_size + (self.num_atoms,) log_prob = log_prob[self.__batch_indices, actions.squeeze(), :]", "set_network(self, network_state: NetworkState) -> None: self.net.load_state_dict(network_state.net['net']) self.target_net.load_state_dict(network_state.net['target_net']) def set_buffer(self, buffer_state:", "log_prob = log_prob[self.__batch_indices, actions.squeeze(), :] assert log_prob.shape == m.shape ==", "def learn(self, experiences: Dict[str, List]) -> None: \"\"\" Parameters: experiences:", "to use learning step in the learning phase. Default: 1.", "= self.net.act(next_states) a_next = torch.argmax((duel_prob_next * self.z_atoms).sum(-1), dim=-1) else: a_next", "duel_prob_next = self.net.act(next_states) a_next = torch.argmax((duel_prob_next * self.z_atoms).sum(-1), dim=-1) else:", "epislon: Epsilon value in the epislon-greedy policy. \"\"\" # Epsilon-greedy", "act(self, obs: ObsType, eps: float = 0.) -> int: \"\"\"", "{}) self.__dict__.update(**self._config) self.net.load_state_dict(agent_state['net']) self.target_net.load_state_dict(agent_state['target_net']) def save_buffer(self, path: str) -> None:", "BufferState, DoneType, NetworkState, ObsType, RewardType from ai_traineree.types.dataspace import DataSpace from", "next_obs (ObservationType): Observation in a state where the action took.", "the action took. done: (bool) Whether in terminal (end of", "ActionType, reward: RewardType, next_obs: ObsType, done: DoneType) -> None: \"\"\"Letting", "factor. Default: 0.99. tau (float): Soft-copy factor. Default: 0.002. update_freq", "__init__( self, obs_space: DataSpace, action_space: DataSpace, state_transform: Optional[Callable]=None, reward_transform: Optional[Callable]=None,", "(prob_next * self.z_atoms).sum(-1) * self.z_delta if self.using_double_q: duel_prob_next = self.net.act(next_states)", "that in case a pre_network is provided, e.g. a shared", "+ (self.num_atoms,) log_prob = log_prob[self.__batch_indices, actions.squeeze(), :] assert log_prob.shape ==", "action_space (DataSpace): Dataspace describing the output. state_transform (optional func): reward_transform", "the buffer from provided file path. Parameters: path: String path", "= prob_next[self.__batch_indices, a_next, :] m = self.net.dist_projection(rewards, 1 - dones,", "action at state. next_obs (ObservationType): Observation in a state where", "available state from the environment. epislon: Epsilon value in the", "action_space.sample() once implemented assert len(self.action_space.shape) == 1, \"Only 1D is", "data_logger.log_value(f'dist/expected_{action_idx}', (dist*self.z_atoms).sum().item(), step) data_logger.add_histogram( f'dist/Q_{action_idx}', min=self.z_atoms[0], max=self.z_atoms[-1], num=len(self.z_atoms), sum=dist.sum(), sum_squares=dist.pow(2).sum(),", "self.num_atoms) log_prob = self.net(states, log_prob=True) assert log_prob.shape == (self.batch_size,) +", "ObsType, RewardType from ai_traineree.types.dataspace import DataSpace from ai_traineree.utils import to_numbers_seq,", "but all changes are in relatively separate areas so their", "import soft_update from ai_traineree.buffers import NStepBuffer, PERBuffer from ai_traineree.buffers.buffer_factory import", "samples to observe before starting any learning step. Default: 0.", "the agent will initiate learning step. This is dependent on", "connected network. Default: (100, 100). lr (default: 1e-3): Learning rate", "'tau', 0.002)) self.update_freq = int(self._register_param(kwargs, 'update_freq', 1)) self.batch_size = int(self._register_param(kwargs,", "path. Parameters: path: String path indicating where the state is", "so their connection makes sense. These improvements are: * Priority", "buffer_dump = json.load(f) self.buffer.load_buffer(buffer_dump) def __eq__(self, o: object) -> bool:", "of the hidden layers in fully connected network. Default: (100,", "1. batch_size (int): Number of samples to use at each", "and layer.bias is not None: data_logger.create_histogram(f\"value_net/layer_bias_{idx}\", layer.bias.cpu(), step) for idx,", "ai_traineree.buffers import NStepBuffer, PERBuffer from ai_traineree.buffers.buffer_factory import BufferFactory from ai_traineree.loggers", "norm of the gradient used in learning. Default: 10. using_double_q", "state as per current policy. Parameters: state: Current available state", "is not None: data_logger.create_histogram(f\"value_net/layer_bias_{idx}\", layer.bias.cpu(), step) for idx, layer in", "in the DQNAgent. Special treatment is required because the Rainbow", "self._config = agent_state.get('config', {}) self.__dict__.update(**self._config) self.net.load_state_dict(agent_state['net']) self.target_net.load_state_dict(agent_state['target_net']) def save_buffer(self, path:", "Maximum norm of the gradient used in learning. Default: 10.", "* Priority Experience Replay * Multi-step * Double Q net", "DQN agent with some improvments that were suggested before 2017.", "path. Parameters: path: String path where to write the buffer.", "path: str) -> None: \"\"\"Saves data from the buffer into", "self.buffer.dump_buffer(serialize=True) with open(path, 'w') as f: json.dump(dump, f) def load_buffer(self,", "3e-4)) self.gamma = float(self._register_param(kwargs, 'gamma', 0.99)) self.tau = float(self._register_param(kwargs, 'tau',", "and self._config == o._config \\ and self.buffer == o.buffer \\", "Current available state from the environment. epislon: Epsilon value in", "import NStepBuffer, PERBuffer from ai_traineree.buffers.buffer_factory import BufferFactory from ai_traineree.loggers import", "V distribution. Default: 21. \"\"\" super().__init__(**kwargs) self.device = self._register_param(kwargs, \"device\",", "the DQNAgent. Special treatment is required because the Rainbow agent", "float = 0.) -> int: \"\"\" Returns actions for given", "float(self._register_param(kwargs, 'max_grad_norm', 10)) self.iteration: int = 0 self.using_double_q = bool(self._register_param(kwargs,", "= (prob_next * self.z_atoms).sum(-1) * self.z_delta if self.using_double_q: duel_prob_next =", "\"Only 1D actions currently supported\" action_size = self.action_size[0] for action_idx", "in enumerate(self.net.value_net.layers): if hasattr(layer, \"weight\"): data_logger.create_histogram(f\"value_net/layer_weights_{idx}\", layer.weight.cpu(), step) if hasattr(layer,", "optim.Adam(self.net.parameters(), lr=self.lr) self.dist_probs = None self._loss = float('nan') @property def", "experiences for the agent. Typically sampled from the memory buffer.", "typing import Callable, Dict, List, Optional import torch import torch.nn", "provided, e.g. a shared net that extracts pixels values, #", "and the loss is batch mean error = -torch.sum(m *", "V. Default: 10. num_atoms (int): Number of atoms (discrete states)", "(dist*self.z_atoms).sum().item(), step) data_logger.add_histogram( f'dist/Q_{action_idx}', min=self.z_atoms[0], max=self.z_atoms[-1], num=len(self.z_atoms), sum=dist.sum(), sum_squares=dist.pow(2).sum(), bucket_limits=self.z_atoms+self.z_delta,", "self.z_atoms[1] - self.z_atoms[0] self.buffer = PERBuffer(**kwargs) self.__batch_indices = torch.arange(self.batch_size, device=self.device)", "1) assert states.shape == next_states.shape == (self.batch_size,) + self.obs_space.shape assert", "every iteration but just in case we delay plotting weights.", "import json dump = self.buffer.dump_buffer(serialize=True) with open(path, 'w') as f:", "Epsilon-greedy action selection if self._rng.random() < eps: # TODO: Update", "String path indicating where the buffer is stored. \"\"\" import", "a_next = torch.argmax(q_next, dim=-1) prob_next = prob_next[self.__batch_indices, a_next, :] m", "= torch.load(path) self._config = agent_state.get('config', {}) self.__dict__.update(**self._config) self.net.load_state_dict(agent_state['net']) self.target_net.load_state_dict(agent_state['target_net']) def", "path: String path indicating where the buffer is stored. \"\"\"", "else: a_next = torch.argmax(q_next, dim=-1) prob_next = prob_next[self.__batch_indices, a_next, :]", "\"bias\") and layer.bias is not None: data_logger.create_histogram(f\"advantage_net/layer_bias_{idx}\", layer.bias.cpu(), step) def", "-> None: self.net.load_state_dict(network_state.net['net']) self.target_net.load_state_dict(network_state.net['target_net']) def set_buffer(self, buffer_state: BufferState) -> None:", "[1]. Rainbow is a DQN agent with some improvments that", "# Update networks - sync local & target soft_update(self.target_net, self.net,", ":] assert log_prob.shape == m.shape == (self.batch_size, self.num_atoms) # Cross-entropy", "rewards.shape == dones.shape == (self.batch_size, 1) assert states.shape == next_states.shape", "in the value V distribution. Default: 21. \"\"\" super().__init__(**kwargs) self.device", "(optional func): reward_transform (optional func): Keyword parameters: pre_network_fn (function that", "mean error = -torch.sum(m * log_prob, 1) assert error.shape ==", ":ref:`NStepBuffer`. Default: 3. v_min (float): Lower bound for distributional value", "file under provided path. Parameters: path: String path indicating where", "indicating where the buffer is stored. \"\"\" import json with", "on the `update_freq` value. Parameters: obs (ObservationType): Observation. action (int):", "self.z_delta if self.using_double_q: duel_prob_next = self.net.act(next_states) a_next = torch.argmax((duel_prob_next *", "self.optimizer = optim.Adam(self.net.parameters(), lr=self.lr) self.dist_probs = None self._loss = float('nan')", "def __init__( self, obs_space: DataSpace, action_space: DataSpace, state_transform: Optional[Callable]=None, reward_transform:", "of ints): Shape of the hidden layers in fully connected", "use at each learning step. Default: 80. buffer_size (int): Number", "# This method, `log_metrics`, isn't executed on every iteration but", "kwargs kwargs[\"hidden_layers\"] = to_numbers_seq(self._register_param(kwargs, \"hidden_layers\", (100, 100))) self.net = RainbowNet(obs_space.shape,", "`log_metrics`, isn't executed on every iteration but just in case", "assert m.shape == (self.batch_size, self.num_atoms) log_prob = self.net(states, log_prob=True) assert", "return {'loss': self._loss} @loss.setter def loss(self, value): if isinstance(value, dict):", "\"\"\" assert isinstance(action, int), \"Rainbow expects discrete action (int)\" self.iteration", "simply might be quite costly. Thread wisely. if full_log: for", "Discrete domain with torch.no_grad(): prob_next = self.target_net.act(next_states) q_next = (prob_next", "n_steps (particularly the reward) self.n_buffer.add( state=t_obs.numpy(), action=[int(action)], reward=[reward], done=[done], next_state=t_next_obs.numpy()", "(100, 100))) self.net = RainbowNet(obs_space.shape, self.action_size, num_atoms=self.num_atoms, **kwargs) self.target_net =", "action selection if self._rng.random() < eps: # TODO: Update with", "\"\"\"Provides agent's internal state.\"\"\" return AgentState( model=self.model, obs_space=self.obs_space, action_space=self.action_space, config=self._config,", "float(loss.item()) if hasattr(self.buffer, 'priority_update'): assert (~torch.isnan(error)).any() self.buffer.priority_update(experiences['index'], error.detach().cpu().numpy()) # Update", "path: String path where to write the state. \"\"\" agent_state", "hasattr(layer, \"bias\") and layer.bias is not None: data_logger.create_histogram(f\"value_net/layer_bias_{idx}\", layer.bias.cpu(), step)", "by Hessel et al. (DeepMind team) https://arxiv.org/abs/1710.02298 \"\"\" model =", "networks. \"\"\" return {\"net\": self.net.state_dict(), \"target_net\": self.target_net.state_dict()} def log_metrics(self, data_logger:", "step) data_logger.add_histogram( f'dist/Q_{action_idx}', min=self.z_atoms[0], max=self.z_atoms[-1], num=len(self.z_atoms), sum=dist.sum(), sum_squares=dist.pow(2).sum(), bucket_limits=self.z_atoms+self.z_delta, bucket_counts=dist,", "import torch.optim as optim from ai_traineree import DEVICE from ai_traineree.agents", "for idx, layer in enumerate(self.net.value_net.layers): if hasattr(layer, \"weight\"): data_logger.create_histogram(f\"value_net/layer_weights_{idx}\", layer.weight.cpu(),", "log_prob = self.net(states, log_prob=True) assert log_prob.shape == (self.batch_size,) + self.action_size", "network): Used to preprocess state before it is used in", "self.num_atoms, device=self.device) self.z_delta = self.z_atoms[1] - self.z_atoms[0] self.buffer = PERBuffer(**kwargs)", "int: \"\"\" Returns actions for given state as per current", "by the authors it's not exhaustive improvment but all changes", "assert actions.shape == (self.batch_size, 1) # Discrete domain with torch.no_grad():", "None: \"\"\"Saves agent's state into a file. Parameters: path: String", "next_states.shape == (self.batch_size,) + self.obs_space.shape assert actions.shape == (self.batch_size, 1)", "and isinstance(o, type(self)) \\ and self._config == o._config \\ and", "\"\"\"Letting the agent to take a step. On some steps", "expected, i.e. `state`, `action`, `reward`, `next_state`, `done`. Each key contains", "= self.net.dist_projection(rewards, 1 - dones, self.gamma ** self.n_steps, prob_next) assert", "on every iteration but just in case we delay plotting", "dicrionary for internal networks. \"\"\" return {\"net\": self.net.state_dict(), \"target_net\": self.target_net.state_dict()}", "relatively separate areas so their connection makes sense. These improvements", "wisely. if full_log: for idx, layer in enumerate(self.net.value_net.layers): if hasattr(layer,", "actions.squeeze(), :] assert log_prob.shape == m.shape == (self.batch_size, self.num_atoms) #", "for _ in range(self.number_updates): self.learn(self.buffer.sample()) # Update networks only once", "21, drop=True)) self.z_atoms = torch.linspace(v_min, v_max, self.num_atoms, device=self.device) self.z_delta =", "(self.num_atoms,) log_prob = log_prob[self.__batch_indices, actions.squeeze(), :] assert log_prob.shape == m.shape", "None: data_logger.create_histogram(f\"value_net/layer_bias_{idx}\", layer.bias.cpu(), step) for idx, layer in enumerate(self.net.advantage_net.layers): if", "m.shape == (self.batch_size, self.num_atoms) # Cross-entropy loss error and the", "state.buffer is not None: agent.set_buffer(state.buffer) return agent def set_network(self, network_state:", "'action_space': state.action_space}) agent = RainbowAgent(**config) if state.network is not None:", "e.g. a shared net that extracts pixels values, # it", "state. \"\"\" assert isinstance(action, int), \"Rainbow expects discrete action (int)\"", "= to_tensor(experiences['next_state']).float().to(self.device) actions = to_tensor(experiences['action']).type(torch.long).to(self.device) assert rewards.shape == dones.shape ==", "assert len(self.action_space.shape) == 1, \"Only 1D is supported right now\"", "1) assert error.shape == (self.batch_size,) loss = error.mean() assert loss", "= int(self._register_param(kwargs, \"n_steps\", 3)) self.n_buffer = NStepBuffer(n_steps=self.n_steps, gamma=self.gamma) # Note", "= torch.argmax((duel_prob_next * self.z_atoms).sum(-1), dim=-1) else: a_next = torch.argmax(q_next, dim=-1)", "obs (ObservationType): Observation. action (int): Discrete action associated with observation.", "method, `log_metrics`, isn't executed on every iteration but just in", "enumerate(self.net.advantage_net.layers): if hasattr(layer, \"weight\"): data_logger.create_histogram(f\"advantage_net/layer_{idx}\", layer.weight.cpu(), step) if hasattr(layer, \"bias\")", "\"weight\"): data_logger.create_histogram(f\"value_net/layer_weights_{idx}\", layer.weight.cpu(), step) if hasattr(layer, \"bias\") and layer.bias is", "changes are in relatively separate areas so their connection makes", "t_obs = to_tensor(self.state_transform(obs)).float().unsqueeze(0).to(self.device) self.dist_probs = self.net.act(t_obs) q_values = (self.dist_probs *", "= self.action_size[0] for action_idx in range(action_size): dist = self.dist_probs[0, action_idx]", "= action_space self._config['obs_space'] = self.obs_space self._config['action_space'] = self.action_space self.action_size =", "\"\"\"Rainbow agent as described in [1]. Rainbow is a DQN", "step. On some steps the agent will initiate learning step.", "step: int, full_log: bool=False): data_logger.log_value(\"loss/agent\", self._loss, step) if full_log and", "Discrete action associated with observation. reward (float): Reward obtained for", "return self.buffer.add(**self.n_buffer.get().get_dict()) if self.iteration < self.warm_up: return if len(self.buffer) >=", "ai_traineree.types import ActionType, AgentState, BufferState, DoneType, NetworkState, ObsType, RewardType from", "the DQN thus majority of the logic is in the", "None else lambda x: x self.reward_transform = reward_transform if reward_transform", "if reward_transform is not None else lambda x: x v_min", "def __eq__(self, o: object) -> bool: return super().__eq__(o) \\ and", "obs_space=self.obs_space, action_space=self.action_space, config=self._config, buffer=copy.deepcopy(self.buffer.get_state()), network=copy.deepcopy(self.get_network_state()), ) def get_network_state(self) -> NetworkState:", "in [1]. Rainbow is a DQN agent with some improvments", "Parameters: obs (ObservationType): Observation. action (int): Discrete action associated with", "- sync local & target soft_update(self.target_net, self.net, self.tau) def state_dict(self)", "the `update_freq` value. Parameters: obs (ObservationType): Observation. action (int): Discrete", "NStepBuffer, PERBuffer from ai_traineree.buffers.buffer_factory import BufferFactory from ai_traineree.loggers import DataLogger", "= self.target_net.act(next_states) q_next = (prob_next * self.z_atoms).sum(-1) * self.z_delta if", "where to write the state. \"\"\" agent_state = self.get_state() torch.save(agent_state,", "soft_update(self.target_net, self.net, self.tau) def state_dict(self) -> Dict[str, dict]: \"\"\"Returns agent's", "None: \"\"\" Parameters: experiences: Contains all experiences for the agent.", "`action`, `reward`, `next_state`, `done`. Each key contains a array and", "hasattr(layer, \"weight\"): data_logger.create_histogram(f\"advantage_net/layer_{idx}\", layer.weight.cpu(), step) if hasattr(layer, \"bias\") and layer.bias", "1e-3): Learning rate value. gamma (float): Discount factor. Default: 0.99.", "Special treatment is required because the Rainbow agent uses categorical", "rate value. gamma (float): Discount factor. Default: 0.99. tau (float):", "not None else lambda x: x self.reward_transform = reward_transform if", "self.net.load_state_dict(agent_state['net']) self.target_net.load_state_dict(agent_state['target_net']) def save_buffer(self, path: str) -> None: \"\"\"Saves data", "# Discrete domain with torch.no_grad(): prob_next = self.target_net.act(next_states) q_next =", "path: str) -> None: \"\"\"Loads data into the buffer from", "experiences: Dict[str, List]) -> None: \"\"\" Parameters: experiences: Contains all", "the DQN agent. [1] \"Rainbow: Combining Improvements in Deep Reinforcement", "this class as a particular version of the DQN agent.", "al. (DeepMind team) https://arxiv.org/abs/1710.02298 \"\"\" model = \"Rainbow\" def __init__(", "= float(self._register_param(kwargs, \"v_max\", 10)) self.num_atoms = int(self._register_param(kwargs, \"num_atoms\", 21, drop=True))", "prob_next = self.target_net.act(next_states) q_next = (prob_next * self.z_atoms).sum(-1) * self.z_delta", "\"Only 1D is supported right now\" return self._rng.randint(self.action_space.low, self.action_space.high) t_obs", "were suggested before 2017. As mentioned by the authors it's", "int(self._register_param(kwargs, \"num_atoms\", 21, drop=True)) self.z_atoms = torch.linspace(v_min, v_max, self.num_atoms, device=self.device)", "network_state: NetworkState) -> None: self.net.load_state_dict(network_state.net['net']) self.target_net.load_state_dict(network_state.net['target_net']) def set_buffer(self, buffer_state: BufferState)", "from ai_traineree.loggers import DataLogger from ai_traineree.networks.heads import RainbowNet from ai_traineree.types", "the memory buffer. Five keys are expected, i.e. `state`, `action`,", "we delay plotting weights. # It simply might be quite", "self._loss, step) if full_log and self.dist_probs is not None: assert", "epislon-greedy policy. \"\"\" # Epsilon-greedy action selection if self._rng.random() <", "Default: 1e5. warm_up (int): Number of samples to observe before", "states = to_tensor(experiences['state']).float().to(self.device) next_states = to_tensor(experiences['next_state']).float().to(self.device) actions = to_tensor(experiences['action']).type(torch.long).to(self.device) assert", "data into the buffer from provided file path. Parameters: path:", "self.net, self.tau) def act(self, obs: ObsType, eps: float = 0.)", "json.dump(dump, f) def load_buffer(self, path: str) -> None: \"\"\"Loads data", "torch.linspace(v_min, v_max, self.num_atoms, device=self.device) self.z_delta = self.z_atoms[1] - self.z_atoms[0] self.buffer", "nets. hidden_layers (tuple of ints): Shape of the hidden layers", "= float(self._register_param(kwargs, 'gamma', 0.99)) self.tau = float(self._register_param(kwargs, 'tau', 0.002)) self.update_freq", "Observation in a state where the action took. done: (bool)", "as described in [1]. Rainbow is a DQN agent with", "from ai_traineree.types import ActionType, AgentState, BufferState, DoneType, NetworkState, ObsType, RewardType", "Note that in case a pre_network is provided, e.g. a", "Optional[Callable]=None, **kwargs ): \"\"\" A wrapper over the DQN thus", "Used to preprocess state before it is used in the", "of samples to observe before starting any learning step. Default:", "\"\"\" agent_state = torch.load(path) self._config = agent_state.get('config', {}) self.__dict__.update(**self._config) self.net.load_state_dict(agent_state['net'])", "is dependent on the `update_freq` value. Parameters: obs (ObservationType): Observation.", "= to_tensor(experiences['state']).float().to(self.device) next_states = to_tensor(experiences['next_state']).float().to(self.device) actions = to_tensor(experiences['action']).type(torch.long).to(self.device) assert rewards.shape", ":] m = self.net.dist_projection(rewards, 1 - dones, self.gamma ** self.n_steps,", "DEVICE from ai_traineree.agents import AgentBase from ai_traineree.agents.agent_utils import soft_update from", "where to write the buffer. \"\"\" import json dump =", "if self._rng.random() < eps: # TODO: Update with action_space.sample() once", "**kwargs ): \"\"\" A wrapper over the DQN thus majority", "NetworkState: return NetworkState(net=dict(net=self.net.state_dict(), target_net=self.target_net.state_dict())) @staticmethod def from_state(state: AgentState) -> AgentBase:", "0: for _ in range(self.number_updates): self.learn(self.buffer.sample()) # Update networks only", "1)) self.max_grad_norm = float(self._register_param(kwargs, 'max_grad_norm', 10)) self.iteration: int = 0", "a file under provided path. Parameters: path: String path indicating", "to_tensor class RainbowAgent(AgentBase): \"\"\"Rainbow agent as described in [1]. Rainbow", "state.action_space}) agent = RainbowAgent(**config) if state.network is not None: agent.set_network(state.network)", "from ai_traineree.buffers.buffer_factory import BufferFactory from ai_traineree.loggers import DataLogger from ai_traineree.networks.heads", "dones, self.gamma ** self.n_steps, prob_next) assert m.shape == (self.batch_size, self.num_atoms)", "- sync local & target soft_update(self.target_net, self.net, self.tau) def act(self,", "array and all arrays have to have the same length.", "isinstance(value, dict): value = value['loss'] self._loss = value def step(self,", "path where to write the state. \"\"\" agent_state = self.get_state()", "= int(self._register_param(kwargs, 'update_freq', 1)) self.batch_size = int(self._register_param(kwargs, 'batch_size', 80, update=True))", "\"Rainbow: Combining Improvements in Deep Reinforcement Learning\" by Hessel et", "(self.batch_size, 1) assert states.shape == next_states.shape == (self.batch_size,) + self.obs_space.shape", "the state is stored. \"\"\" agent_state = torch.load(path) self._config =", "Parameters: path: String path indicating where the buffer is stored.", "parameters: pre_network_fn (function that takes input_shape and returns network): Used", "TODO: Update with action_space.sample() once implemented assert len(self.action_space.shape) == 1,", "__eq__(self, o: object) -> bool: return super().__eq__(o) \\ and isinstance(o,", "steps between each learning step. Default 1. batch_size (int): Number", "action (int)\" self.iteration += 1 t_obs = to_tensor(self.state_transform(obs)).float().to(\"cpu\") t_next_obs =", "update=True)) self.buffer_size = int(self._register_param(kwargs, 'buffer_size', int(1e5), update=True)) self.warm_up = int(self._register_param(kwargs,", "= self._register_param(kwargs, \"device\", DEVICE, update=True) self.obs_space = obs_space self.action_space =", "step. Default 1. batch_size (int): Number of samples to use", "self.max_grad_norm) self.optimizer.step() self._loss = float(loss.item()) if hasattr(self.buffer, 'priority_update'): assert (~torch.isnan(error)).any()", "\"bias\") and layer.bias is not None: data_logger.create_histogram(f\"value_net/layer_bias_{idx}\", layer.bias.cpu(), step) for", "Default: 0.002. update_freq (int): Number of steps between each learning", "value. Parameters: obs (ObservationType): Observation. action (int): Discrete action associated", "soft_update(self.target_net, self.net, self.tau) def act(self, obs: ObsType, eps: float =", "0)) self.number_updates = int(self._register_param(kwargs, 'number_updates', 1)) self.max_grad_norm = float(self._register_param(kwargs, 'max_grad_norm',", "assert log_prob.shape == m.shape == (self.batch_size, self.num_atoms) # Cross-entropy loss", "{'loss': self._loss} @loss.setter def loss(self, value): if isinstance(value, dict): value", "str) -> None: \"\"\"Saves data from the buffer into a", "as f: json.dump(dump, f) def load_buffer(self, path: str) -> None:", "self.optimizer.step() self._loss = float(loss.item()) if hasattr(self.buffer, 'priority_update'): assert (~torch.isnan(error)).any() self.buffer.priority_update(experiences['index'],", "Default: 80. buffer_size (int): Number of most recent samples to", "pre_network is provided, e.g. a shared net that extracts pixels", "operate on probability distributions. Each action is taken as the", "in learning. Default: 10. using_double_q (bool): Whether to use Double", "int(self._register_param(kwargs, 'buffer_size', int(1e5), update=True)) self.warm_up = int(self._register_param(kwargs, 'warm_up', 0)) self.number_updates", "= error.mean() assert loss >= 0 self.optimizer.zero_grad() loss.backward() nn.utils.clip_grad_norm_(self.net.parameters(), self.max_grad_norm)", "self.net.state_dict(), \"target_net\": self.target_net.state_dict()} def log_metrics(self, data_logger: DataLogger, step: int, full_log:", "else lambda x: x self.reward_transform = reward_transform if reward_transform is", "to_tensor(self.state_transform(obs)).float().to(\"cpu\") t_next_obs = to_tensor(self.state_transform(next_obs)).float().to(\"cpu\") reward = self.reward_transform(reward) # Delay adding", "1e5. warm_up (int): Number of samples to observe before starting", "buffer to account for n_steps (particularly the reward) self.n_buffer.add( state=t_obs.numpy(),", "# Action maximizes state-action value Q(s, a) def learn(self, experiences:", "a_next = torch.argmax((duel_prob_next * self.z_atoms).sum(-1), dim=-1) else: a_next = torch.argmax(q_next,", "Delay adding to buffer to account for n_steps (particularly the", "Optional[Callable]=None, reward_transform: Optional[Callable]=None, **kwargs ): \"\"\" A wrapper over the", "buffer=copy.deepcopy(self.buffer.get_state()), network=copy.deepcopy(self.get_network_state()), ) def get_network_state(self) -> NetworkState: return NetworkState(net=dict(net=self.net.state_dict(), target_net=self.target_net.state_dict()))", "* Dueling nets * NoisyNet * CategoricalNet for Q estimate", "is not None else lambda x: x self.reward_transform = reward_transform", "self.tau) def act(self, obs: ObsType, eps: float = 0.) ->", "* self.z_atoms).sum(-1) return int(q_values.argmax(-1)) # Action maximizes state-action value Q(s,", "Number of atoms (discrete states) in the value V distribution.", "distributional value V. Default: 10. num_atoms (int): Number of atoms", "advantage-function in the dueling nets. hidden_layers (tuple of ints): Shape", "\\ and isinstance(o, type(self)) \\ and self._config == o._config \\", "= torch.arange(self.batch_size, device=self.device) self.n_steps = int(self._register_param(kwargs, \"n_steps\", 3)) self.n_buffer =", "file under provided path. Parameters: path: String path where to", "if self.iteration < self.warm_up: return if len(self.buffer) >= self.batch_size and", "Number of most recent samples to keep in memory for", "lookahead steps when estimating reward. See :ref:`NStepBuffer`. Default: 3. v_min", "some steps the agent will initiate learning step. This is", "if hasattr(layer, \"bias\") and layer.bias is not None: data_logger.create_histogram(f\"value_net/layer_bias_{idx}\", layer.bias.cpu(),", "return NetworkState(net=dict(net=self.net.state_dict(), target_net=self.target_net.state_dict())) @staticmethod def from_state(state: AgentState) -> AgentBase: config", "use Double Q Learning network. Default: True. n_steps (int): Number", "distributional value V. Default: -10. v_max (float): Upper bound for", "These improvements are: * Priority Experience Replay * Multi-step *", "self.device = self._register_param(kwargs, \"device\", DEVICE, update=True) self.obs_space = obs_space self.action_space", "num_atoms=self.num_atoms, **kwargs) self.target_net = RainbowNet(obs_space.shape, self.action_size, num_atoms=self.num_atoms, **kwargs) self.optimizer =", "import BufferFactory from ai_traineree.loggers import DataLogger from ai_traineree.networks.heads import RainbowNet", "Dataspace describing the output. state_transform (optional func): reward_transform (optional func):", "step) if hasattr(layer, \"bias\") and layer.bias is not None: data_logger.create_histogram(f\"advantage_net/layer_bias_{idx}\",", "On some steps the agent will initiate learning step. This", "Returns actions for given state as per current policy. Parameters:", "in case a pre_network is provided, e.g. a shared net", "for idx, layer in enumerate(self.net.advantage_net.layers): if hasattr(layer, \"weight\"): data_logger.create_histogram(f\"advantage_net/layer_{idx}\", layer.weight.cpu(),", "\"\"\" agent_state = self.get_state() torch.save(agent_state, path) def load_state(self, path: str)", "json with open(path, 'r') as f: buffer_dump = json.load(f) self.buffer.load_buffer(buffer_dump)", "dict]: \"\"\"Returns agent's state dictionary. Returns: State dicrionary for internal", "len(self.action_space.shape) == 1, \"Only 1D actions currently supported\" action_size =", "used in learning. Default: 10. using_double_q (bool): Whether to use", "learning step. This is dependent on the `update_freq` value. Parameters:", "-10. v_max (float): Upper bound for distributional value V. Default:", "q_values = (self.dist_probs * self.z_atoms).sum(-1) return int(q_values.argmax(-1)) # Action maximizes", "self.reward_transform = reward_transform if reward_transform is not None else lambda", "= torch.argmax(q_next, dim=-1) prob_next = prob_next[self.__batch_indices, a_next, :] m =", "True)) self.state_transform = state_transform if state_transform is not None else", "self.update_freq) == 0: for _ in range(self.number_updates): self.learn(self.buffer.sample()) # Update", "action_space.to_feature() self.lr = float(self._register_param(kwargs, 'lr', 3e-4)) self.gamma = float(self._register_param(kwargs, 'gamma',", "mentioned by the authors it's not exhaustive improvment but all", "x: x v_min = float(self._register_param(kwargs, \"v_min\", -10)) v_max = float(self._register_param(kwargs,", "the gradient used in learning. Default: 10. using_double_q (bool): Whether", "returns network): Used to preprocess state before it is used", "learning. Default: 1e5. warm_up (int): Number of samples to observe", "Each key contains a array and all arrays have to", "for the agent. Typically sampled from the memory buffer. Five", "that were suggested before 2017. As mentioned by the authors", "self.num_atoms = int(self._register_param(kwargs, \"num_atoms\", 21, drop=True)) self.z_atoms = torch.linspace(v_min, v_max,", "to account for n_steps (particularly the reward) self.n_buffer.add( state=t_obs.numpy(), action=[int(action)],", "Dueling nets * NoisyNet * CategoricalNet for Q estimate Consider", "Hessel et al. (DeepMind team) https://arxiv.org/abs/1710.02298 \"\"\" model = \"Rainbow\"", "right now\" return self._rng.randint(self.action_space.low, self.action_space.high) t_obs = to_tensor(self.state_transform(obs)).float().unsqueeze(0).to(self.device) self.dist_probs =", "-> None: \"\"\"Saves data from the buffer into a file", "(float): Discount factor. Default: 0.99. tau (float): Soft-copy factor. Default:", "stored. \"\"\" import json with open(path, 'r') as f: buffer_dump", "initiate learning step. This is dependent on the `update_freq` value.", "to_tensor(experiences['action']).type(torch.long).to(self.device) assert rewards.shape == dones.shape == (self.batch_size, 1) assert states.shape", "int = 0 self.using_double_q = bool(self._register_param(kwargs, \"using_double_q\", True)) self.state_transform =", "keep in memory for learning. Default: 1e5. warm_up (int): Number", "be explicitly passed in kwargs kwargs[\"hidden_layers\"] = to_numbers_seq(self._register_param(kwargs, \"hidden_layers\", (100,", "of atoms (discrete states) in the value V distribution. Default:", "Replay * Multi-step * Double Q net * Dueling nets", "100). lr (default: 1e-3): Learning rate value. gamma (float): Discount", "Keyword parameters: pre_network_fn (function that takes input_shape and returns network):", "log_metrics(self, data_logger: DataLogger, step: int, full_log: bool=False): data_logger.log_value(\"loss/agent\", self._loss, step)", "int(self._register_param(kwargs, 'number_updates', 1)) self.max_grad_norm = float(self._register_param(kwargs, 'max_grad_norm', 10)) self.iteration: int", "full_log and self.dist_probs is not None: assert len(self.action_space.shape) == 1,", "in case we delay plotting weights. # It simply might", "distributions. Parameters: obs_space (DataSpace): Dataspace describing the input. action_space (DataSpace):", "to buffer to account for n_steps (particularly the reward) self.n_buffer.add(", "import RainbowNet from ai_traineree.types import ActionType, AgentState, BufferState, DoneType, NetworkState,", "= 0 self.using_double_q = bool(self._register_param(kwargs, \"using_double_q\", True)) self.state_transform = state_transform", "if isinstance(value, dict): value = value['loss'] self._loss = value def", "json.load(f) self.buffer.load_buffer(buffer_dump) def __eq__(self, o: object) -> bool: return super().__eq__(o)", "describing the output. state_transform (optional func): reward_transform (optional func): Keyword", "self._rng.random() < eps: # TODO: Update with action_space.sample() once implemented", "reward) self.n_buffer.add( state=t_obs.numpy(), action=[int(action)], reward=[reward], done=[done], next_state=t_next_obs.numpy() ) if not", "self._loss = float(loss.item()) if hasattr(self.buffer, 'priority_update'): assert (~torch.isnan(error)).any() self.buffer.priority_update(experiences['index'], error.detach().cpu().numpy())", "self.batch_size and (self.iteration % self.update_freq) == 0: for _ in", "\"\"\" A wrapper over the DQN thus majority of the", "shared net that extracts pixels values, # it should be", "(int): Number of atoms (discrete states) in the value V", "the dueling nets. hidden_layers (tuple of ints): Shape of the", "sync local & target soft_update(self.target_net, self.net, self.tau) def act(self, obs:", "Cross-entropy loss error and the loss is batch mean error", "isn't executed on every iteration but just in case we", "networks only once - sync local & target soft_update(self.target_net, self.net,", "error = -torch.sum(m * log_prob, 1) assert error.shape == (self.batch_size,)", "self, obs_space: DataSpace, action_space: DataSpace, state_transform: Optional[Callable]=None, reward_transform: Optional[Callable]=None, **kwargs", "str) -> None: \"\"\"Saves agent's state into a file. Parameters:", "self.n_steps = int(self._register_param(kwargs, \"n_steps\", 3)) self.n_buffer = NStepBuffer(n_steps=self.n_steps, gamma=self.gamma) #", "once implemented assert len(self.action_space.shape) == 1, \"Only 1D is supported", "state into a file. Parameters: path: String path where to", "Default: 3. v_min (float): Lower bound for distributional value V.", "all changes are in relatively separate areas so their connection", "See :ref:`NStepBuffer`. Default: 3. v_min (float): Lower bound for distributional", "from provided file path. Parameters: path: String path indicating where", "internal state.\"\"\" return AgentState( model=self.model, obs_space=self.obs_space, action_space=self.action_space, config=self._config, buffer=copy.deepcopy(self.buffer.get_state()), network=copy.deepcopy(self.get_network_state()),", "that takes input_shape and returns network): Used to preprocess state", "= to_numbers_seq(self._register_param(kwargs, \"hidden_layers\", (100, 100))) self.net = RainbowNet(obs_space.shape, self.action_size, num_atoms=self.num_atoms,", "(optional func): Keyword parameters: pre_network_fn (function that takes input_shape and", "is not None else lambda x: x v_min = float(self._register_param(kwargs,", "sum=dist.sum(), sum_squares=dist.pow(2).sum(), bucket_limits=self.z_atoms+self.z_delta, bucket_counts=dist, global_step=step ) # This method, `log_metrics`,", "None: assert len(self.action_space.shape) == 1, \"Only 1D actions currently supported\"", "for given state as per current policy. Parameters: state: Current", "\"device\", DEVICE, update=True) self.obs_space = obs_space self.action_space = action_space self._config['obs_space']", "if hasattr(layer, \"weight\"): data_logger.create_histogram(f\"value_net/layer_weights_{idx}\", layer.weight.cpu(), step) if hasattr(layer, \"bias\") and", "get_state(self) -> AgentState: \"\"\"Provides agent's internal state.\"\"\" return AgentState( model=self.model,", "particular version of the DQN agent. [1] \"Rainbow: Combining Improvements", "self.num_atoms) # Cross-entropy loss error and the loss is batch", "1D actions currently supported\" action_size = self.action_size[0] for action_idx in", "will initiate learning step. This is dependent on the `update_freq`", "is not None: agent.set_network(state.network) if state.buffer is not None: agent.set_buffer(state.buffer)", "* CategoricalNet for Q estimate Consider this class as a", "* NoisyNet * CategoricalNet for Q estimate Consider this class", "https://arxiv.org/abs/1710.02298 \"\"\" model = \"Rainbow\" def __init__( self, obs_space: DataSpace,", "state.\"\"\" return AgentState( model=self.model, obs_space=self.obs_space, action_space=self.action_space, config=self._config, buffer=copy.deepcopy(self.buffer.get_state()), network=copy.deepcopy(self.get_network_state()), )", "Learning rate value. gamma (float): Discount factor. Default: 0.99. tau", "(discrete states) in the value V distribution. Default: 21. \"\"\"", "\"using_double_q\", True)) self.state_transform = state_transform if state_transform is not None", "RainbowNet(obs_space.shape, self.action_size, num_atoms=self.num_atoms, **kwargs) self.target_net = RainbowNet(obs_space.shape, self.action_size, num_atoms=self.num_atoms, **kwargs)", "and layer.bias is not None: data_logger.create_histogram(f\"advantage_net/layer_bias_{idx}\", layer.bias.cpu(), step) def get_state(self)", "error and the loss is batch mean error = -torch.sum(m", "just in case we delay plotting weights. # It simply", "improvments that were suggested before 2017. As mentioned by the", "implemented assert len(self.action_space.shape) == 1, \"Only 1D is supported right", "= torch.linspace(v_min, v_max, self.num_atoms, device=self.device) self.z_delta = self.z_atoms[1] - self.z_atoms[0]", "Reinforcement Learning\" by Hessel et al. (DeepMind team) https://arxiv.org/abs/1710.02298 \"\"\"", "the Rainbow agent uses categorical nets which operate on probability", "torch.load(path) self._config = agent_state.get('config', {}) self.__dict__.update(**self._config) self.net.load_state_dict(agent_state['net']) self.target_net.load_state_dict(agent_state['target_net']) def save_buffer(self,", "self.iteration += 1 t_obs = to_tensor(self.state_transform(obs)).float().to(\"cpu\") t_next_obs = to_tensor(self.state_transform(next_obs)).float().to(\"cpu\") reward", "\"\"\" Parameters: experiences: Contains all experiences for the agent. Typically", "not None: agent.set_network(state.network) if state.buffer is not None: agent.set_buffer(state.buffer) return", "Rainbow agent uses categorical nets which operate on probability distributions.", "(int): Number of samples to observe before starting any learning", "Upper bound for distributional value V. Default: 10. num_atoms (int):", "if state_transform is not None else lambda x: x self.reward_transform", "RewardType, next_obs: ObsType, done: DoneType) -> None: \"\"\"Letting the agent", "= to_tensor(experiences['action']).type(torch.long).to(self.device) assert rewards.shape == dones.shape == (self.batch_size, 1) assert", "0.) -> int: \"\"\" Returns actions for given state as", "object) -> bool: return super().__eq__(o) \\ and isinstance(o, type(self)) \\", "\"\"\" # Epsilon-greedy action selection if self._rng.random() < eps: #", "self.buffer.load_buffer(buffer_dump) def __eq__(self, o: object) -> bool: return super().__eq__(o) \\", "Parameters: path: String path where to write the buffer. \"\"\"", "a particular version of the DQN agent. [1] \"Rainbow: Combining", "(self.dist_probs * self.z_atoms).sum(-1) return int(q_values.argmax(-1)) # Action maximizes state-action value", "from ai_traineree.networks.heads import RainbowNet from ai_traineree.types import ActionType, AgentState, BufferState,", "(float): Soft-copy factor. Default: 0.002. update_freq (int): Number of steps", "estimating reward. See :ref:`NStepBuffer`. Default: 3. v_min (float): Lower bound", "o._config \\ and self.buffer == o.buffer \\ and self.get_network_state() ==", "self.n_buffer = NStepBuffer(n_steps=self.n_steps, gamma=self.gamma) # Note that in case a", "self.action_space.high) t_obs = to_tensor(self.state_transform(obs)).float().unsqueeze(0).to(self.device) self.dist_probs = self.net.act(t_obs) q_values = (self.dist_probs", "next_states = to_tensor(experiences['next_state']).float().to(self.device) actions = to_tensor(experiences['action']).type(torch.long).to(self.device) assert rewards.shape == dones.shape", "2017. As mentioned by the authors it's not exhaustive improvment", "with open(path, 'r') as f: buffer_dump = json.load(f) self.buffer.load_buffer(buffer_dump) def", "AgentBase: config = copy.copy(state.config) config.update({'obs_space': state.obs_space, 'action_space': state.action_space}) agent =", "the learning phase. Default: 1. max_grad_norm (float): Maximum norm of", "thus majority of the logic is in the DQNAgent. Special", "and self.dist_probs is not None: assert len(self.action_space.shape) == 1, \"Only", "samples to keep in memory for learning. Default: 1e5. warm_up", "Deep Reinforcement Learning\" by Hessel et al. (DeepMind team) https://arxiv.org/abs/1710.02298", "= self.z_atoms[1] - self.z_atoms[0] self.buffer = PERBuffer(**kwargs) self.__batch_indices = torch.arange(self.batch_size,", "self.buffer = BufferFactory.from_state(buffer_state) def save_state(self, path: str) -> None: \"\"\"Saves", "(end of episode) state. \"\"\" assert isinstance(action, int), \"Rainbow expects", "self.lr = float(self._register_param(kwargs, 'lr', 3e-4)) self.gamma = float(self._register_param(kwargs, 'gamma', 0.99))", "'gamma', 0.99)) self.tau = float(self._register_param(kwargs, 'tau', 0.002)) self.update_freq = int(self._register_param(kwargs,", "n_steps (int): Number of lookahead steps when estimating reward. See", "associated with observation. reward (float): Reward obtained for taking action", "(default: 1e-3): Learning rate value. gamma (float): Discount factor. Default:", "def act(self, obs: ObsType, eps: float = 0.) -> int:", "m.shape == (self.batch_size, self.num_atoms) log_prob = self.net(states, log_prob=True) assert log_prob.shape", "self.net(states, log_prob=True) assert log_prob.shape == (self.batch_size,) + self.action_size + (self.num_atoms,)", "are: * Priority Experience Replay * Multi-step * Double Q", "state_transform (optional func): reward_transform (optional func): Keyword parameters: pre_network_fn (function", "= obs_space self.action_space = action_space self._config['obs_space'] = self.obs_space self._config['action_space'] =", "hasattr(layer, \"weight\"): data_logger.create_histogram(f\"value_net/layer_weights_{idx}\", layer.weight.cpu(), step) if hasattr(layer, \"bias\") and layer.bias", "the state. \"\"\" agent_state = self.get_state() torch.save(agent_state, path) def load_state(self,", "Default: (100, 100). lr (default: 1e-3): Learning rate value. gamma", "agent's internal state.\"\"\" return AgentState( model=self.model, obs_space=self.obs_space, action_space=self.action_space, config=self._config, buffer=copy.deepcopy(self.buffer.get_state()),", "agent = RainbowAgent(**config) if state.network is not None: agent.set_network(state.network) if", "as the estimate from such distributions. Parameters: obs_space (DataSpace): Dataspace", "self.action_size + (self.num_atoms,) log_prob = log_prob[self.__batch_indices, actions.squeeze(), :] assert log_prob.shape", "def log_metrics(self, data_logger: DataLogger, step: int, full_log: bool=False): data_logger.log_value(\"loss/agent\", self._loss,", "because the Rainbow agent uses categorical nets which operate on", "(int): How many times to use learning step in the", "is stored. \"\"\" import json with open(path, 'r') as f:", "(float): Upper bound for distributional value V. Default: 10. num_atoms", "under provided path. Parameters: path: String path where to write", "the loss is batch mean error = -torch.sum(m * log_prob,", "None else lambda x: x v_min = float(self._register_param(kwargs, \"v_min\", -10))", "and returns network): Used to preprocess state before it is", "return int(q_values.argmax(-1)) # Action maximizes state-action value Q(s, a) def", "\"\"\"Saves agent's state into a file. Parameters: path: String path", "= NStepBuffer(n_steps=self.n_steps, gamma=self.gamma) # Note that in case a pre_network", "for distributional value V. Default: 10. num_atoms (int): Number of", "stored. \"\"\" agent_state = torch.load(path) self._config = agent_state.get('config', {}) self.__dict__.update(**self._config)", "range(self.number_updates): self.learn(self.buffer.sample()) # Update networks only once - sync local", "self.using_double_q = bool(self._register_param(kwargs, \"using_double_q\", True)) self.state_transform = state_transform if state_transform", "of the gradient used in learning. Default: 10. using_double_q (bool):", "if state.network is not None: agent.set_network(state.network) if state.buffer is not", "wrapper over the DQN thus majority of the logic is", "maximizes state-action value Q(s, a) def learn(self, experiences: Dict[str, List])", "load_buffer(self, path: str) -> None: \"\"\"Loads data into the buffer", "for internal networks. \"\"\" return {\"net\": self.net.state_dict(), \"target_net\": self.target_net.state_dict()} def", "of lookahead steps when estimating reward. See :ref:`NStepBuffer`. Default: 3.", "Each action is taken as the estimate from such distributions.", "layer in enumerate(self.net.value_net.layers): if hasattr(layer, \"weight\"): data_logger.create_histogram(f\"value_net/layer_weights_{idx}\", layer.weight.cpu(), step) if", "given state as per current policy. Parameters: state: Current available", "(self.batch_size, self.num_atoms) # Cross-entropy loss error and the loss is", "as per current policy. Parameters: state: Current available state from", "in kwargs kwargs[\"hidden_layers\"] = to_numbers_seq(self._register_param(kwargs, \"hidden_layers\", (100, 100))) self.net =", "provided path. Parameters: path: String path indicating where the state", "in relatively separate areas so their connection makes sense. These", "error.mean() assert loss >= 0 self.optimizer.zero_grad() loss.backward() nn.utils.clip_grad_norm_(self.net.parameters(), self.max_grad_norm) self.optimizer.step()", "Combining Improvements in Deep Reinforcement Learning\" by Hessel et al.", "obtained for taking action at state. next_obs (ObservationType): Observation in", "self.get_state() torch.save(agent_state, path) def load_state(self, path: str) -> None: \"\"\"Loads", "obs_space self.action_space = action_space self._config['obs_space'] = self.obs_space self._config['action_space'] = self.action_space", "in Deep Reinforcement Learning\" by Hessel et al. (DeepMind team)", "observe before starting any learning step. Default: 0. number_updates (int):", "arrays have to have the same length. \"\"\" rewards =", ">= 0 self.optimizer.zero_grad() loss.backward() nn.utils.clip_grad_norm_(self.net.parameters(), self.max_grad_norm) self.optimizer.step() self._loss = float(loss.item())", "provided file path. Parameters: path: String path indicating where the", "# Update networks only once - sync local & target", "= (self.dist_probs * self.z_atoms).sum(-1) return int(q_values.argmax(-1)) # Action maximizes state-action", "domain with torch.no_grad(): prob_next = self.target_net.act(next_states) q_next = (prob_next *", "\"v_min\", -10)) v_max = float(self._register_param(kwargs, \"v_max\", 10)) self.num_atoms = int(self._register_param(kwargs,", "lambda x: x self.reward_transform = reward_transform if reward_transform is not", "action_idx in range(action_size): dist = self.dist_probs[0, action_idx] data_logger.log_value(f'dist/expected_{action_idx}', (dist*self.z_atoms).sum().item(), step)", "\"Rainbow expects discrete action (int)\" self.iteration += 1 t_obs =", "None: agent.set_buffer(state.buffer) return agent def set_network(self, network_state: NetworkState) -> None:", "& target soft_update(self.target_net, self.net, self.tau) def act(self, obs: ObsType, eps:", "self.obs_space = obs_space self.action_space = action_space self._config['obs_space'] = self.obs_space self._config['action_space']", "= to_tensor(self.state_transform(obs)).float().to(\"cpu\") t_next_obs = to_tensor(self.state_transform(next_obs)).float().to(\"cpu\") reward = self.reward_transform(reward) # Delay", "to_tensor(self.state_transform(next_obs)).float().to(\"cpu\") reward = self.reward_transform(reward) # Delay adding to buffer to", "10)) self.num_atoms = int(self._register_param(kwargs, \"num_atoms\", 21, drop=True)) self.z_atoms = torch.linspace(v_min,", "NoisyNet * CategoricalNet for Q estimate Consider this class as", "gamma=self.gamma) # Note that in case a pre_network is provided,", "self.target_net.load_state_dict(agent_state['target_net']) def save_buffer(self, path: str) -> None: \"\"\"Saves data from", "connection makes sense. These improvements are: * Priority Experience Replay", "class as a particular version of the DQN agent. [1]", "== (self.batch_size,) + self.obs_space.shape assert actions.shape == (self.batch_size, 1) #", "if not self.n_buffer.available: return self.buffer.add(**self.n_buffer.get().get_dict()) if self.iteration < self.warm_up: return", "float(self._register_param(kwargs, 'tau', 0.002)) self.update_freq = int(self._register_param(kwargs, 'update_freq', 1)) self.batch_size =", "self.buffer.priority_update(experiences['index'], error.detach().cpu().numpy()) # Update networks - sync local & target", "-> None: self.buffer = BufferFactory.from_state(buffer_state) def save_state(self, path: str) ->", "taken as the estimate from such distributions. Parameters: obs_space (DataSpace):", "super().__init__(**kwargs) self.device = self._register_param(kwargs, \"device\", DEVICE, update=True) self.obs_space = obs_space", "write the state. \"\"\" agent_state = self.get_state() torch.save(agent_state, path) def", "(self.batch_size, 1) # Discrete domain with torch.no_grad(): prob_next = self.target_net.act(next_states)", "loss >= 0 self.optimizer.zero_grad() loss.backward() nn.utils.clip_grad_norm_(self.net.parameters(), self.max_grad_norm) self.optimizer.step() self._loss =", "f'dist/Q_{action_idx}', min=self.z_atoms[0], max=self.z_atoms[-1], num=len(self.z_atoms), sum=dist.sum(), sum_squares=dist.pow(2).sum(), bucket_limits=self.z_atoms+self.z_delta, bucket_counts=dist, global_step=step )", "file path. Parameters: path: String path indicating where the buffer", "{\"net\": self.net.state_dict(), \"target_net\": self.target_net.state_dict()} def log_metrics(self, data_logger: DataLogger, step: int,", "= float(self._register_param(kwargs, 'lr', 3e-4)) self.gamma = float(self._register_param(kwargs, 'gamma', 0.99)) self.tau", "-> AgentBase: config = copy.copy(state.config) config.update({'obs_space': state.obs_space, 'action_space': state.action_space}) agent", "None: agent.set_network(state.network) if state.buffer is not None: agent.set_buffer(state.buffer) return agent", "state from a file under provided path. Parameters: path: String", "agent with some improvments that were suggested before 2017. As", "majority of the logic is in the DQNAgent. Special treatment", "step) def get_state(self) -> AgentState: \"\"\"Provides agent's internal state.\"\"\" return", "is in the DQNAgent. Special treatment is required because the", "reward: RewardType, next_obs: ObsType, done: DoneType) -> None: \"\"\"Letting the", "== (self.batch_size, 1) # Discrete domain with torch.no_grad(): prob_next =", "from typing import Callable, Dict, List, Optional import torch import", "estimate from such distributions. Parameters: obs_space (DataSpace): Dataspace describing the", "int), \"Rainbow expects discrete action (int)\" self.iteration += 1 t_obs", "into a file. Parameters: path: String path where to write", "prob_next = prob_next[self.__batch_indices, a_next, :] m = self.net.dist_projection(rewards, 1 -", "step) for idx, layer in enumerate(self.net.advantage_net.layers): if hasattr(layer, \"weight\"): data_logger.create_histogram(f\"advantage_net/layer_{idx}\",", "exhaustive improvment but all changes are in relatively separate areas", "Parameters: obs_space (DataSpace): Dataspace describing the input. action_space (DataSpace): Dataspace", "of the logic is in the DQNAgent. Special treatment is", "prob_next[self.__batch_indices, a_next, :] m = self.net.dist_projection(rewards, 1 - dones, self.gamma", "100))) self.net = RainbowNet(obs_space.shape, self.action_size, num_atoms=self.num_atoms, **kwargs) self.target_net = RainbowNet(obs_space.shape,", "in terminal (end of episode) state. \"\"\" assert isinstance(action, int),", "= self.reward_transform(reward) # Delay adding to buffer to account for", "NetworkState, ObsType, RewardType from ai_traineree.types.dataspace import DataSpace from ai_traineree.utils import", "RainbowNet from ai_traineree.types import ActionType, AgentState, BufferState, DoneType, NetworkState, ObsType,", "to_numbers_seq, to_tensor class RainbowAgent(AgentBase): \"\"\"Rainbow agent as described in [1].", "plotting weights. # It simply might be quite costly. Thread", "from the environment. epislon: Epsilon value in the epislon-greedy policy.", "took. done: (bool) Whether in terminal (end of episode) state.", "each learning step. Default 1. batch_size (int): Number of samples", "self.action_size = action_space.to_feature() self.lr = float(self._register_param(kwargs, 'lr', 3e-4)) self.gamma =", "to have the same length. \"\"\" rewards = to_tensor(experiences['reward']).float().to(self.device) dones", "value def step(self, obs: ObsType, action: ActionType, reward: RewardType, next_obs:", "experiences: Contains all experiences for the agent. Typically sampled from", "== (self.batch_size,) + self.action_size + (self.num_atoms,) log_prob = log_prob[self.__batch_indices, actions.squeeze(),", "num_atoms (int): Number of atoms (discrete states) in the value", "None: self.net.load_state_dict(network_state.net['net']) self.target_net.load_state_dict(network_state.net['target_net']) def set_buffer(self, buffer_state: BufferState) -> None: self.buffer", "= json.load(f) self.buffer.load_buffer(buffer_dump) def __eq__(self, o: object) -> bool: return", "data from the buffer into a file under provided path.", "'lr', 3e-4)) self.gamma = float(self._register_param(kwargs, 'gamma', 0.99)) self.tau = float(self._register_param(kwargs,", "Improvements in Deep Reinforcement Learning\" by Hessel et al. (DeepMind", "bucket_counts=dist, global_step=step ) # This method, `log_metrics`, isn't executed on", "== m.shape == (self.batch_size, self.num_atoms) # Cross-entropy loss error and", "len(self.action_space.shape) == 1, \"Only 1D is supported right now\" return", "to observe before starting any learning step. Default: 0. number_updates", "gradient used in learning. Default: 10. using_double_q (bool): Whether to", "(ObservationType): Observation. action (int): Discrete action associated with observation. reward", "int(q_values.argmax(-1)) # Action maximizes state-action value Q(s, a) def learn(self,", "= self.action_space self.action_size = action_space.to_feature() self.lr = float(self._register_param(kwargs, 'lr', 3e-4))", "nets * NoisyNet * CategoricalNet for Q estimate Consider this", "done: (bool) Whether in terminal (end of episode) state. \"\"\"", "== 0: for _ in range(self.number_updates): self.learn(self.buffer.sample()) # Update networks", "import torch.nn as nn import torch.optim as optim from ai_traineree", "to_numbers_seq(self._register_param(kwargs, \"hidden_layers\", (100, 100))) self.net = RainbowNet(obs_space.shape, self.action_size, num_atoms=self.num_atoms, **kwargs)", "+ self.action_size + (self.num_atoms,) log_prob = log_prob[self.__batch_indices, actions.squeeze(), :] assert", "self.target_net.state_dict()} def log_metrics(self, data_logger: DataLogger, step: int, full_log: bool=False): data_logger.log_value(\"loss/agent\",", "at each learning step. Default: 80. buffer_size (int): Number of", "x self.reward_transform = reward_transform if reward_transform is not None else", "before 2017. As mentioned by the authors it's not exhaustive", "x v_min = float(self._register_param(kwargs, \"v_min\", -10)) v_max = float(self._register_param(kwargs, \"v_max\",", "import DataLogger from ai_traineree.networks.heads import RainbowNet from ai_traineree.types import ActionType,", "on probability distributions. Each action is taken as the estimate", "hasattr(layer, \"bias\") and layer.bias is not None: data_logger.create_histogram(f\"advantage_net/layer_bias_{idx}\", layer.bias.cpu(), step)", "\"\"\" import json dump = self.buffer.dump_buffer(serialize=True) with open(path, 'w') as", "agent_state = torch.load(path) self._config = agent_state.get('config', {}) self.__dict__.update(**self._config) self.net.load_state_dict(agent_state['net']) self.target_net.load_state_dict(agent_state['target_net'])", "not None: assert len(self.action_space.shape) == 1, \"Only 1D actions currently", "in fully connected network. Default: (100, 100). lr (default: 1e-3):", "dones = to_tensor(experiences['done']).type(torch.int).to(self.device) states = to_tensor(experiences['state']).float().to(self.device) next_states = to_tensor(experiences['next_state']).float().to(self.device) actions", "A wrapper over the DQN thus majority of the logic", "is a DQN agent with some improvments that were suggested", "1, \"Only 1D actions currently supported\" action_size = self.action_size[0] for", "# It simply might be quite costly. Thread wisely. if", "keys are expected, i.e. `state`, `action`, `reward`, `next_state`, `done`. Each", "lr=self.lr) self.dist_probs = None self._loss = float('nan') @property def loss(self):", "bound for distributional value V. Default: -10. v_max (float): Upper", "DataLogger, step: int, full_log: bool=False): data_logger.log_value(\"loss/agent\", self._loss, step) if full_log", "is taken as the estimate from such distributions. Parameters: obs_space", "\"\"\" rewards = to_tensor(experiences['reward']).float().to(self.device) dones = to_tensor(experiences['done']).type(torch.int).to(self.device) states = to_tensor(experiences['state']).float().to(self.device)", "action_space: DataSpace, state_transform: Optional[Callable]=None, reward_transform: Optional[Callable]=None, **kwargs ): \"\"\" A", "Thread wisely. if full_log: for idx, layer in enumerate(self.net.value_net.layers): if", "eps: # TODO: Update with action_space.sample() once implemented assert len(self.action_space.shape)", "dist = self.dist_probs[0, action_idx] data_logger.log_value(f'dist/expected_{action_idx}', (dist*self.z_atoms).sum().item(), step) data_logger.add_histogram( f'dist/Q_{action_idx}', min=self.z_atoms[0],", "= int(self._register_param(kwargs, 'warm_up', 0)) self.number_updates = int(self._register_param(kwargs, 'number_updates', 1)) self.max_grad_norm", "= self.get_state() torch.save(agent_state, path) def load_state(self, path: str) -> None:", "self._config['action_space'] = self.action_space self.action_size = action_space.to_feature() self.lr = float(self._register_param(kwargs, 'lr',", "the environment. epislon: Epsilon value in the epislon-greedy policy. \"\"\"", "times to use learning step in the learning phase. Default:", "such distributions. Parameters: obs_space (DataSpace): Dataspace describing the input. action_space", "agent. Typically sampled from the memory buffer. Five keys are", "buffer is stored. \"\"\" import json with open(path, 'r') as", "v_max, self.num_atoms, device=self.device) self.z_delta = self.z_atoms[1] - self.z_atoms[0] self.buffer =", "(int)\" self.iteration += 1 t_obs = to_tensor(self.state_transform(obs)).float().to(\"cpu\") t_next_obs = to_tensor(self.state_transform(next_obs)).float().to(\"cpu\")", "loss = error.mean() assert loss >= 0 self.optimizer.zero_grad() loss.backward() nn.utils.clip_grad_norm_(self.net.parameters(),", "self.z_atoms).sum(-1), dim=-1) else: a_next = torch.argmax(q_next, dim=-1) prob_next = prob_next[self.__batch_indices,", "output. state_transform (optional func): reward_transform (optional func): Keyword parameters: pre_network_fn", "Q net * Dueling nets * NoisyNet * CategoricalNet for", "is stored. \"\"\" agent_state = torch.load(path) self._config = agent_state.get('config', {})", "net that extracts pixels values, # it should be explicitly", "Learning network. Default: True. n_steps (int): Number of lookahead steps", "self.buffer_size = int(self._register_param(kwargs, 'buffer_size', int(1e5), update=True)) self.warm_up = int(self._register_param(kwargs, 'warm_up',", "ai_traineree.agents import AgentBase from ai_traineree.agents.agent_utils import soft_update from ai_traineree.buffers import", "a array and all arrays have to have the same", "areas so their connection makes sense. These improvements are: *", "AgentBase from ai_traineree.agents.agent_utils import soft_update from ai_traineree.buffers import NStepBuffer, PERBuffer", "\"\"\"Saves data from the buffer into a file under provided", "set_buffer(self, buffer_state: BufferState) -> None: self.buffer = BufferFactory.from_state(buffer_state) def save_state(self,", "data_logger.create_histogram(f\"advantage_net/layer_bias_{idx}\", layer.bias.cpu(), step) def get_state(self) -> AgentState: \"\"\"Provides agent's internal", "many times to use learning step in the learning phase.", "buffer into a file under provided path. Parameters: path: String", "done=[done], next_state=t_next_obs.numpy() ) if not self.n_buffer.available: return self.buffer.add(**self.n_buffer.get().get_dict()) if self.iteration", "= float(self._register_param(kwargs, 'max_grad_norm', 10)) self.iteration: int = 0 self.using_double_q =", "-> int: \"\"\" Returns actions for given state as per", "learning step. Default: 0. number_updates (int): How many times to", "action (int): Discrete action associated with observation. reward (float): Reward", "== next_states.shape == (self.batch_size,) + self.obs_space.shape assert actions.shape == (self.batch_size,", "dim=-1) else: a_next = torch.argmax(q_next, dim=-1) prob_next = prob_next[self.__batch_indices, a_next,", "state. \"\"\" agent_state = self.get_state() torch.save(agent_state, path) def load_state(self, path:", "self.dist_probs = None self._loss = float('nan') @property def loss(self): return", "local & target soft_update(self.target_net, self.net, self.tau) def state_dict(self) -> Dict[str,", "of samples to use at each learning step. Default: 80.", "v_max = float(self._register_param(kwargs, \"v_max\", 10)) self.num_atoms = int(self._register_param(kwargs, \"num_atoms\", 21,", "any learning step. Default: 0. number_updates (int): How many times", "actions = to_tensor(experiences['action']).type(torch.long).to(self.device) assert rewards.shape == dones.shape == (self.batch_size, 1)", "but just in case we delay plotting weights. # It", "value in the epislon-greedy policy. \"\"\" # Epsilon-greedy action selection", "1) # Discrete domain with torch.no_grad(): prob_next = self.target_net.act(next_states) q_next", "** self.n_steps, prob_next) assert m.shape == (self.batch_size, self.num_atoms) log_prob =", "iteration but just in case we delay plotting weights. #", "DataSpace, state_transform: Optional[Callable]=None, reward_transform: Optional[Callable]=None, **kwargs ): \"\"\" A wrapper", "loss is batch mean error = -torch.sum(m * log_prob, 1)", "estimate Consider this class as a particular version of the", "agent's state dictionary. Returns: State dicrionary for internal networks. \"\"\"", "== 1, \"Only 1D actions currently supported\" action_size = self.action_size[0]", "q_next = (prob_next * self.z_atoms).sum(-1) * self.z_delta if self.using_double_q: duel_prob_next", "self.batch_size = int(self._register_param(kwargs, 'batch_size', 80, update=True)) self.buffer_size = int(self._register_param(kwargs, 'buffer_size',", "num=len(self.z_atoms), sum=dist.sum(), sum_squares=dist.pow(2).sum(), bucket_limits=self.z_atoms+self.z_delta, bucket_counts=dist, global_step=step ) # This method,", "AgentState, BufferState, DoneType, NetworkState, ObsType, RewardType from ai_traineree.types.dataspace import DataSpace", "self.action_space = action_space self._config['obs_space'] = self.obs_space self._config['action_space'] = self.action_space self.action_size", "(float): Maximum norm of the gradient used in learning. Default:", "to_tensor(experiences['reward']).float().to(self.device) dones = to_tensor(experiences['done']).type(torch.int).to(self.device) states = to_tensor(experiences['state']).float().to(self.device) next_states = to_tensor(experiences['next_state']).float().to(self.device)", ") def get_network_state(self) -> NetworkState: return NetworkState(net=dict(net=self.net.state_dict(), target_net=self.target_net.state_dict())) @staticmethod def", "Whether in terminal (end of episode) state. \"\"\" assert isinstance(action,", "to_tensor(experiences['done']).type(torch.int).to(self.device) states = to_tensor(experiences['state']).float().to(self.device) next_states = to_tensor(experiences['next_state']).float().to(self.device) actions = to_tensor(experiences['action']).type(torch.long).to(self.device)", "self.tau = float(self._register_param(kwargs, 'tau', 0.002)) self.update_freq = int(self._register_param(kwargs, 'update_freq', 1))", "def get_state(self) -> AgentState: \"\"\"Provides agent's internal state.\"\"\" return AgentState(", "str) -> None: \"\"\"Loads data into the buffer from provided", "float(self._register_param(kwargs, \"v_max\", 10)) self.num_atoms = int(self._register_param(kwargs, \"num_atoms\", 21, drop=True)) self.z_atoms", "-> AgentState: \"\"\"Provides agent's internal state.\"\"\" return AgentState( model=self.model, obs_space=self.obs_space,", "f: buffer_dump = json.load(f) self.buffer.load_buffer(buffer_dump) def __eq__(self, o: object) ->", "self.obs_space self._config['action_space'] = self.action_space self.action_size = action_space.to_feature() self.lr = float(self._register_param(kwargs,", "def set_buffer(self, buffer_state: BufferState) -> None: self.buffer = BufferFactory.from_state(buffer_state) def", "from ai_traineree.types.dataspace import DataSpace from ai_traineree.utils import to_numbers_seq, to_tensor class", "global_step=step ) # This method, `log_metrics`, isn't executed on every", "float(self._register_param(kwargs, \"v_min\", -10)) v_max = float(self._register_param(kwargs, \"v_max\", 10)) self.num_atoms =", "self.z_atoms).sum(-1) * self.z_delta if self.using_double_q: duel_prob_next = self.net.act(next_states) a_next =", "Default: -10. v_max (float): Upper bound for distributional value V.", "Default: 0.99. tau (float): Soft-copy factor. Default: 0.002. update_freq (int):", "self.z_atoms[0] self.buffer = PERBuffer(**kwargs) self.__batch_indices = torch.arange(self.batch_size, device=self.device) self.n_steps =", "max_grad_norm (float): Maximum norm of the gradient used in learning.", "drop=True)) self.z_atoms = torch.linspace(v_min, v_max, self.num_atoms, device=self.device) self.z_delta = self.z_atoms[1]", "steps when estimating reward. See :ref:`NStepBuffer`. Default: 3. v_min (float):", "v_min = float(self._register_param(kwargs, \"v_min\", -10)) v_max = float(self._register_param(kwargs, \"v_max\", 10))", "torch.nn as nn import torch.optim as optim from ai_traineree import", "80. buffer_size (int): Number of most recent samples to keep", "to write the state. \"\"\" agent_state = self.get_state() torch.save(agent_state, path)", "environment. epislon: Epsilon value in the epislon-greedy policy. \"\"\" #", "\"\"\" import json with open(path, 'r') as f: buffer_dump =", "def loss(self, value): if isinstance(value, dict): value = value['loss'] self._loss", "def save_state(self, path: str) -> None: \"\"\"Saves agent's state into", "`done`. Each key contains a array and all arrays have", "1, \"Only 1D is supported right now\" return self._rng.randint(self.action_space.low, self.action_space.high)", "logic is in the DQNAgent. Special treatment is required because", "-10)) v_max = float(self._register_param(kwargs, \"v_max\", 10)) self.num_atoms = int(self._register_param(kwargs, \"num_atoms\",", "in memory for learning. Default: 1e5. warm_up (int): Number of", "the epislon-greedy policy. \"\"\" # Epsilon-greedy action selection if self._rng.random()", "pre_network_fn (function that takes input_shape and returns network): Used to", "buffer. \"\"\" import json dump = self.buffer.dump_buffer(serialize=True) with open(path, 'w')", "min=self.z_atoms[0], max=self.z_atoms[-1], num=len(self.z_atoms), sum=dist.sum(), sum_squares=dist.pow(2).sum(), bucket_limits=self.z_atoms+self.z_delta, bucket_counts=dist, global_step=step ) #", "ObsType, action: ActionType, reward: RewardType, next_obs: ObsType, done: DoneType) ->", "agent.set_network(state.network) if state.buffer is not None: agent.set_buffer(state.buffer) return agent def", "a file. Parameters: path: String path where to write the", "for Q estimate Consider this class as a particular version", "DQNAgent. Special treatment is required because the Rainbow agent uses", "Dict[str, List]) -> None: \"\"\" Parameters: experiences: Contains all experiences", "terminal (end of episode) state. \"\"\" assert isinstance(action, int), \"Rainbow", "separate areas so their connection makes sense. These improvements are:", "= float(self._register_param(kwargs, \"v_min\", -10)) v_max = float(self._register_param(kwargs, \"v_max\", 10)) self.num_atoms", "with open(path, 'w') as f: json.dump(dump, f) def load_buffer(self, path:", "**kwargs) self.target_net = RainbowNet(obs_space.shape, self.action_size, num_atoms=self.num_atoms, **kwargs) self.optimizer = optim.Adam(self.net.parameters(),", "Contains all experiences for the agent. Typically sampled from the", "f: json.dump(dump, f) def load_buffer(self, path: str) -> None: \"\"\"Loads", "using_double_q (bool): Whether to use Double Q Learning network. Default:", "\\ and self.buffer == o.buffer \\ and self.get_network_state() == o.get_network_state()", "i.e. `state`, `action`, `reward`, `next_state`, `done`. Each key contains a", "self.warm_up: return if len(self.buffer) >= self.batch_size and (self.iteration % self.update_freq)", "(int): Number of samples to use at each learning step.", "over the DQN thus majority of the logic is in", "self.action_size[0] for action_idx in range(action_size): dist = self.dist_probs[0, action_idx] data_logger.log_value(f'dist/expected_{action_idx}',", "RainbowNet(obs_space.shape, self.action_size, num_atoms=self.num_atoms, **kwargs) self.optimizer = optim.Adam(self.net.parameters(), lr=self.lr) self.dist_probs =", "import DataSpace from ai_traineree.utils import to_numbers_seq, to_tensor class RainbowAgent(AgentBase): \"\"\"Rainbow", "target_net=self.target_net.state_dict())) @staticmethod def from_state(state: AgentState) -> AgentBase: config = copy.copy(state.config)", "1D is supported right now\" return self._rng.randint(self.action_space.low, self.action_space.high) t_obs =", "+ self.obs_space.shape assert actions.shape == (self.batch_size, 1) # Discrete domain", "\"\"\"Loads state from a file under provided path. Parameters: path:", "ai_traineree.utils import to_numbers_seq, to_tensor class RainbowAgent(AgentBase): \"\"\"Rainbow agent as described", "None self._loss = float('nan') @property def loss(self): return {'loss': self._loss}", "state. next_obs (ObservationType): Observation in a state where the action", "3. v_min (float): Lower bound for distributional value V. Default:", "have the same length. \"\"\" rewards = to_tensor(experiences['reward']).float().to(self.device) dones =", "full_log: for idx, layer in enumerate(self.net.value_net.layers): if hasattr(layer, \"weight\"): data_logger.create_histogram(f\"value_net/layer_weights_{idx}\",", "state where the action took. done: (bool) Whether in terminal", "Double Q Learning network. Default: True. n_steps (int): Number of", "Double Q net * Dueling nets * NoisyNet * CategoricalNet", "with observation. reward (float): Reward obtained for taking action at", "Q Learning network. Default: True. n_steps (int): Number of lookahead", "float('nan') @property def loss(self): return {'loss': self._loss} @loss.setter def loss(self,", "in the epislon-greedy policy. \"\"\" # Epsilon-greedy action selection if", "not exhaustive improvment but all changes are in relatively separate", "action=[int(action)], reward=[reward], done=[done], next_state=t_next_obs.numpy() ) if not self.n_buffer.available: return self.buffer.add(**self.n_buffer.get().get_dict())", "step(self, obs: ObsType, action: ActionType, reward: RewardType, next_obs: ObsType, done:", "device=self.device) self.n_steps = int(self._register_param(kwargs, \"n_steps\", 3)) self.n_buffer = NStepBuffer(n_steps=self.n_steps, gamma=self.gamma)", "= copy.copy(state.config) config.update({'obs_space': state.obs_space, 'action_space': state.action_space}) agent = RainbowAgent(**config) if", "state_transform is not None else lambda x: x self.reward_transform =", "self.max_grad_norm = float(self._register_param(kwargs, 'max_grad_norm', 10)) self.iteration: int = 0 self.using_double_q", "NStepBuffer(n_steps=self.n_steps, gamma=self.gamma) # Note that in case a pre_network is", "not None: data_logger.create_histogram(f\"value_net/layer_bias_{idx}\", layer.bias.cpu(), step) for idx, layer in enumerate(self.net.advantage_net.layers):", "a pre_network is provided, e.g. a shared net that extracts", "config.update({'obs_space': state.obs_space, 'action_space': state.action_space}) agent = RainbowAgent(**config) if state.network is", "import to_numbers_seq, to_tensor class RainbowAgent(AgentBase): \"\"\"Rainbow agent as described in", "each learning step. Default: 80. buffer_size (int): Number of most", "memory buffer. Five keys are expected, i.e. `state`, `action`, `reward`,", "DataSpace from ai_traineree.utils import to_numbers_seq, to_tensor class RainbowAgent(AgentBase): \"\"\"Rainbow agent", "agent to take a step. On some steps the agent", "`state`, `action`, `reward`, `next_state`, `done`. Each key contains a array", "next_state=t_next_obs.numpy() ) if not self.n_buffer.available: return self.buffer.add(**self.n_buffer.get().get_dict()) if self.iteration <", "Rainbow is a DQN agent with some improvments that were", "if full_log and self.dist_probs is not None: assert len(self.action_space.shape) ==", "from ai_traineree.agents.agent_utils import soft_update from ai_traineree.buffers import NStepBuffer, PERBuffer from", "BufferFactory from ai_traineree.loggers import DataLogger from ai_traineree.networks.heads import RainbowNet from", "ActionType, AgentState, BufferState, DoneType, NetworkState, ObsType, RewardType from ai_traineree.types.dataspace import", "is batch mean error = -torch.sum(m * log_prob, 1) assert", "for taking action at state. next_obs (ObservationType): Observation in a", "open(path, 'r') as f: buffer_dump = json.load(f) self.buffer.load_buffer(buffer_dump) def __eq__(self,", "not self.n_buffer.available: return self.buffer.add(**self.n_buffer.get().get_dict()) if self.iteration < self.warm_up: return if", "bool=False): data_logger.log_value(\"loss/agent\", self._loss, step) if full_log and self.dist_probs is not", "to_tensor(experiences['state']).float().to(self.device) next_states = to_tensor(experiences['next_state']).float().to(self.device) actions = to_tensor(experiences['action']).type(torch.long).to(self.device) assert rewards.shape ==", "@staticmethod def from_state(state: AgentState) -> AgentBase: config = copy.copy(state.config) config.update({'obs_space':", "Dataspace describing the input. action_space (DataSpace): Dataspace describing the output.", "full_log: bool=False): data_logger.log_value(\"loss/agent\", self._loss, step) if full_log and self.dist_probs is", "= int(self._register_param(kwargs, 'batch_size', 80, update=True)) self.buffer_size = int(self._register_param(kwargs, 'buffer_size', int(1e5),", "dueling nets. hidden_layers (tuple of ints): Shape of the hidden", "under provided path. Parameters: path: String path indicating where the", "indicating where the state is stored. \"\"\" agent_state = torch.load(path)", "'w') as f: json.dump(dump, f) def load_buffer(self, path: str) ->", "Default: 1. max_grad_norm (float): Maximum norm of the gradient used", "networks - sync local & target soft_update(self.target_net, self.net, self.tau) def", "learning step. Default: 80. buffer_size (int): Number of most recent", "(self.batch_size,) loss = error.mean() assert loss >= 0 self.optimizer.zero_grad() loss.backward()", "self._loss = float('nan') @property def loss(self): return {'loss': self._loss} @loss.setter", "torch.save(agent_state, path) def load_state(self, path: str) -> None: \"\"\"Loads state", "network=copy.deepcopy(self.get_network_state()), ) def get_network_state(self) -> NetworkState: return NetworkState(net=dict(net=self.net.state_dict(), target_net=self.target_net.state_dict())) @staticmethod", "from_state(state: AgentState) -> AgentBase: config = copy.copy(state.config) config.update({'obs_space': state.obs_space, 'action_space':", "team) https://arxiv.org/abs/1710.02298 \"\"\" model = \"Rainbow\" def __init__( self, obs_space:", "None: \"\"\"Letting the agent to take a step. On some", "& target soft_update(self.target_net, self.net, self.tau) def state_dict(self) -> Dict[str, dict]:", "step. Default: 80. buffer_size (int): Number of most recent samples", "float(self._register_param(kwargs, 'gamma', 0.99)) self.tau = float(self._register_param(kwargs, 'tau', 0.002)) self.update_freq =", "ai_traineree.buffers.buffer_factory import BufferFactory from ai_traineree.loggers import DataLogger from ai_traineree.networks.heads import", "to_tensor(experiences['next_state']).float().to(self.device) actions = to_tensor(experiences['action']).type(torch.long).to(self.device) assert rewards.shape == dones.shape == (self.batch_size,", "(bool) Whether in terminal (end of episode) state. \"\"\" assert", "This method, `log_metrics`, isn't executed on every iteration but just", "self._rng.randint(self.action_space.low, self.action_space.high) t_obs = to_tensor(self.state_transform(obs)).float().unsqueeze(0).to(self.device) self.dist_probs = self.net.act(t_obs) q_values =", "0.99)) self.tau = float(self._register_param(kwargs, 'tau', 0.002)) self.update_freq = int(self._register_param(kwargs, 'update_freq',", "reward=[reward], done=[done], next_state=t_next_obs.numpy() ) if not self.n_buffer.available: return self.buffer.add(**self.n_buffer.get().get_dict()) if", "= RainbowAgent(**config) if state.network is not None: agent.set_network(state.network) if state.buffer", "value- and advantage-function in the dueling nets. hidden_layers (tuple of", "before it is used in the value- and advantage-function in", "f) def load_buffer(self, path: str) -> None: \"\"\"Loads data into", "not None: data_logger.create_histogram(f\"advantage_net/layer_bias_{idx}\", layer.bias.cpu(), step) def get_state(self) -> AgentState: \"\"\"Provides", "self.z_delta = self.z_atoms[1] - self.z_atoms[0] self.buffer = PERBuffer(**kwargs) self.__batch_indices =", "1)) self.batch_size = int(self._register_param(kwargs, 'batch_size', 80, update=True)) self.buffer_size = int(self._register_param(kwargs,", "sync local & target soft_update(self.target_net, self.net, self.tau) def state_dict(self) ->", ") # This method, `log_metrics`, isn't executed on every iteration", "from the buffer into a file under provided path. Parameters:", "the input. action_space (DataSpace): Dataspace describing the output. state_transform (optional", "most recent samples to keep in memory for learning. Default:", "`next_state`, `done`. Each key contains a array and all arrays", "BufferState) -> None: self.buffer = BufferFactory.from_state(buffer_state) def save_state(self, path: str)", "key contains a array and all arrays have to have", "def loss(self): return {'loss': self._loss} @loss.setter def loss(self, value): if", "v_min (float): Lower bound for distributional value V. Default: -10.", "RainbowAgent(AgentBase): \"\"\"Rainbow agent as described in [1]. Rainbow is a", "to take a step. On some steps the agent will", "for action_idx in range(action_size): dist = self.dist_probs[0, action_idx] data_logger.log_value(f'dist/expected_{action_idx}', (dist*self.z_atoms).sum().item(),", "value = value['loss'] self._loss = value def step(self, obs: ObsType,", "return agent def set_network(self, network_state: NetworkState) -> None: self.net.load_state_dict(network_state.net['net']) self.target_net.load_state_dict(network_state.net['target_net'])", "for n_steps (particularly the reward) self.n_buffer.add( state=t_obs.numpy(), action=[int(action)], reward=[reward], done=[done],", "isinstance(action, int), \"Rainbow expects discrete action (int)\" self.iteration += 1", "self.n_steps, prob_next) assert m.shape == (self.batch_size, self.num_atoms) log_prob = self.net(states,", "== (self.batch_size, self.num_atoms) # Cross-entropy loss error and the loss", "class RainbowAgent(AgentBase): \"\"\"Rainbow agent as described in [1]. Rainbow is", "10. using_double_q (bool): Whether to use Double Q Learning network.", "= self.buffer.dump_buffer(serialize=True) with open(path, 'w') as f: json.dump(dump, f) def", "import DEVICE from ai_traineree.agents import AgentBase from ai_traineree.agents.agent_utils import soft_update", "\"\"\"Returns agent's state dictionary. Returns: State dicrionary for internal networks.", "return AgentState( model=self.model, obs_space=self.obs_space, action_space=self.action_space, config=self._config, buffer=copy.deepcopy(self.buffer.get_state()), network=copy.deepcopy(self.get_network_state()), ) def", "value. gamma (float): Discount factor. Default: 0.99. tau (float): Soft-copy", "path indicating where the state is stored. \"\"\" agent_state =", "state dictionary. Returns: State dicrionary for internal networks. \"\"\" return", "3)) self.n_buffer = NStepBuffer(n_steps=self.n_steps, gamma=self.gamma) # Note that in case", "Default: 10. num_atoms (int): Number of atoms (discrete states) in", "action_space=self.action_space, config=self._config, buffer=copy.deepcopy(self.buffer.get_state()), network=copy.deepcopy(self.get_network_state()), ) def get_network_state(self) -> NetworkState: return", "= to_tensor(self.state_transform(obs)).float().unsqueeze(0).to(self.device) self.dist_probs = self.net.act(t_obs) q_values = (self.dist_probs * self.z_atoms).sum(-1)", "= BufferFactory.from_state(buffer_state) def save_state(self, path: str) -> None: \"\"\"Saves agent's", "which operate on probability distributions. Each action is taken as", "log_prob.shape == (self.batch_size,) + self.action_size + (self.num_atoms,) log_prob = log_prob[self.__batch_indices,", "return if len(self.buffer) >= self.batch_size and (self.iteration % self.update_freq) ==", "action is taken as the estimate from such distributions. Parameters:", "are in relatively separate areas so their connection makes sense.", "a shared net that extracts pixels values, # it should", "executed on every iteration but just in case we delay", "loss.backward() nn.utils.clip_grad_norm_(self.net.parameters(), self.max_grad_norm) self.optimizer.step() self._loss = float(loss.item()) if hasattr(self.buffer, 'priority_update'):", "version of the DQN agent. [1] \"Rainbow: Combining Improvements in", "v_max (float): Upper bound for distributional value V. Default: 10.", "step) if full_log and self.dist_probs is not None: assert len(self.action_space.shape)", "Q(s, a) def learn(self, experiences: Dict[str, List]) -> None: \"\"\"", "the value V distribution. Default: 21. \"\"\" super().__init__(**kwargs) self.device =", "layer.bias is not None: data_logger.create_histogram(f\"advantage_net/layer_bias_{idx}\", layer.bias.cpu(), step) def get_state(self) ->", "the buffer is stored. \"\"\" import json with open(path, 'r')", "step in the learning phase. Default: 1. max_grad_norm (float): Maximum", "weights. # It simply might be quite costly. Thread wisely.", "adding to buffer to account for n_steps (particularly the reward)", "step. Default: 0. number_updates (int): How many times to use", "between each learning step. Default 1. batch_size (int): Number of", "have to have the same length. \"\"\" rewards = to_tensor(experiences['reward']).float().to(self.device)", "`update_freq` value. Parameters: obs (ObservationType): Observation. action (int): Discrete action", "in range(self.number_updates): self.learn(self.buffer.sample()) # Update networks only once - sync", "save_buffer(self, path: str) -> None: \"\"\"Saves data from the buffer", "String path where to write the buffer. \"\"\" import json", "self.target_net.load_state_dict(network_state.net['target_net']) def set_buffer(self, buffer_state: BufferState) -> None: self.buffer = BufferFactory.from_state(buffer_state)", "the authors it's not exhaustive improvment but all changes are", "(tuple of ints): Shape of the hidden layers in fully", "episode) state. \"\"\" assert isinstance(action, int), \"Rainbow expects discrete action" ]
[ "for single-precision floating-point square root) 1 (default, use IEEE round-to-nearest", "FMA contraction) 1 (default, enable FMA contraction) -g (enable generation", "instead of None in searched_arch.get when indicating failure to prevent", "return version() def get_ir_version(self): return ir_version() def add_module(self, buff, name", "# #value: libdevice source # libdevice = {} # #key:given", "add_module_to_program, compile_program, create_program, destroy_program, get_compiled_result, get_compiled_result_size, get_program_log, get_program_log_size, lazy_add_module_to_program, verify_program)", "def get_libdevice(self, arch = 20): return get_libdevice(arch) # libdevice =", "1) prec_div = options.get(\"prec_div\", 1) fma = options.get(\"fma\", 0) opts", "= create_program() handle = create_program() weakref.finalize(self, destroy_program, handle) super().__init__(handle, arch)", "line number information) \"\"\" opt = options.get(\"opt\", 3) arch =", "= options.get(\"fma\", 0) opts = [f\"-opt={opt}\", f\"-arch=compute_{arch}\", f\"-ftz={ftz}\", f\"-prec-sqrt={prec_sqrt}\", f\"-prec-div={prec_div}\",", "lazy_add_module_to_program, verify_program) import os import sys from ctypes import c_char_p", "no \"compute_\" is stored under None key) # libdevice =", "operations) 1 (flush denormal values to zero, when performing single-precision", "return ptx def verify_program(self, options = {}): pass # verify_program(self.handle,", "zero, when performing single-precision floating-point operations) -prec-sqrt= 0 (use a", "to ptx return ptx def verify_program(self, options = {}): pass", "opt == 0: opts.append(\"-g\") else: #raise warning (g is only", "if libdevice is None: # #note: use False instead of", "-arch= compute_35 compute_37 compute_50 compute_52 (default) compute_53 compute_60 compute_61 compute_62", "# self.searched_arch[arch] = found_arch # self.libdevice[arch] = libdevice # return", "floating-point division and reciprocals) 1 (default, use IEEE round-to-nearest mode", "{} # #key:given arch # #value: closest available arch found", "warning (g is only valid when -opt=0) pass if options.get(\"generate-line-info\",", "(g is only valid when -opt=0) pass if options.get(\"generate-line-info\", True):", "None: # #note: use False instead of None in searched_arch.get", "if isinstance(name, str): name = name.encode('utf8') size = len(buff) add_module_to_program(self.handle,", "from pycu.nvvm import (get_libdevice, ir_version, version, add_module_to_program, compile_program, create_program, destroy_program,", "only with -opt=0) -generate-line-info (generate line number information) -opt= 0", "libdevice is not arch specific) # #value: libdevice source #", "# #key:given arch # #value: closest available arch found #", "approximation for single-precision floating-point division and reciprocals) 1 (default, use", "-opt=0) -generate-line-info (generate line number information) \"\"\" opt = options.get(\"opt\",", "* len(opts))(*[c_char_p(opt.encode('utf8')) for opt in opts]) compile_program(self.handle, options) ptx =", "None key from libdevice (libdevice with no \"compute_\" is stored", "self.get_libdevice(arch) self.handle = handle def get_libdevice(self, arch = 20): return", "0 (use a faster approximation for single-precision floating-point division and", "libdevice is None: # found_arch, libdevice = next(iter(get_libdevice(arch).items())) # self.searched_arch[arch]", "= self.libdevice.get(self.searched_arch.get(arch, False), None) # if libdevice is None: #", "performing single-precision floating-point operations) -prec-sqrt= 0 (use a faster approximation", "compute_61 compute_62 compute_70 compute_72 compute_75 compute_80 -ftz= 0 (default, preserve", "compute_75 compute_80 -ftz= 0 (default, preserve denormal values, when performing", "ptx = get_compiled_result(self.handle) #TO DO #Apply Numba's debug patch to", "reciprocals) 1 (default, use IEEE round-to-nearest mode for single-precision floating-point", "if opt == 0: opts.append(\"-g\") else: #raise warning (g is", "single-precision floating-point division and reciprocals) -fma= 0 (disable FMA contraction)", "found_arch, libdevice = next(iter(get_libdevice(arch).items())) # self.searched_arch[arch] = found_arch # self.libdevice[arch]", "in opts]) compile_program(self.handle, options) ptx = get_compiled_result(self.handle) #TO DO #Apply", "= \"<unnamed>\"): if isinstance(buff, str): buff = buff.encode('utf8') if isinstance(name,", "optimizations) -arch= compute_35 compute_37 compute_50 compute_52 (default) compute_53 compute_60 compute_61", "f\"-arch=compute_{arch}\", f\"-ftz={ftz}\", f\"-prec-sqrt={prec_sqrt}\", f\"-prec-div={prec_div}\", f\"-fma={fma}\",] if options.get(\"g\", False) and opt", "import sys from ctypes import c_char_p import weakref class NVVMPtr:", "a faster approximation for single-precision floating-point division and reciprocals) 1", "options.get(\"g\", False) and opt == 0: if opt == 0:", "# #key: arch associated with libdevice (None indicates libdevice is", "use IEEE round-to-nearest mode for single-precision floating-point division and reciprocals)", "DO #Apply Numba's debug patch to ptx return ptx def", "ftz = options.get(\"ftz\", 0) prec_sqrt = options.get(\"prec_sqrt\", 1) prec_div =", "{} def __init__(self, handle, arch = 20): self.get_libdevice(arch) self.handle =", "libdevice def get_version(self): return version() def get_ir_version(self): return ir_version() def", "square root) -prec-div= 0 (use a faster approximation for single-precision", "patch to ptx return ptx def verify_program(self, options = {}):", "get_libdevice(self, arch = 20): return get_libdevice(arch) # libdevice = self.libdevice.get(arch,", "self.handle = handle def get_libdevice(self, arch = 20): return get_libdevice(arch)", "# found_arch, libdevice = next(iter(get_libdevice(arch).items())) # self.searched_arch[arch] = found_arch #", "single-precision floating-point operations) 1 (flush denormal values to zero, when", "and opt == 0: if opt == 0: opts.append(\"-g\") else:", "single-precision floating-point square root) 1 (default, use IEEE round-to-nearest mode", "sys from ctypes import c_char_p import weakref class NVVMPtr: #", "compute_50 compute_52 (default) compute_53 compute_60 compute_61 compute_62 compute_70 compute_72 compute_75", "only with -opt=0) -generate-line-info (generate line number information) \"\"\" opt", "libdevice = {} # #key:given arch # #value: closest available", "3) arch = options.get(\"arch\", 52) ftz = options.get(\"ftz\", 0) prec_sqrt", "fma = options.get(\"fma\", 0) opts = [f\"-opt={opt}\", f\"-arch=compute_{arch}\", f\"-ftz={ftz}\", f\"-prec-sqrt={prec_sqrt}\",", "when performing single-precision floating-point operations) 1 (flush denormal values to", "1 (default, use IEEE round-to-nearest mode for single-precision floating-point square", "f\"-ftz={ftz}\", f\"-prec-sqrt={prec_sqrt}\", f\"-prec-div={prec_div}\", f\"-fma={fma}\",] if options.get(\"g\", False) and opt ==", "values to zero, when performing single-precision floating-point operations) -prec-sqrt= 0", "3 (default, enable optimizations) -arch= compute_35 compute_37 compute_50 compute_52 (default)", "-prec-sqrt= 0 (use a faster approximation for single-precision floating-point square", "handle, arch = 20): self.get_libdevice(arch) self.handle = handle def get_libdevice(self,", "f\"-fma={fma}\",] if options.get(\"g\", False) and opt == 0: if opt", "get_program_log_size, lazy_add_module_to_program, verify_program) import os import sys from ctypes import", "str): buff = buff.encode('utf8') if isinstance(name, str): name = name.encode('utf8')", "add_module(self, buff, name = \"<unnamed>\"): if isinstance(buff, str): buff =", "key from libdevice (libdevice with no \"compute_\" is stored under", "for opt in opts]) compile_program(self.handle, options) ptx = get_compiled_result(self.handle) #TO", "valid when -opt=0) pass if options.get(\"generate-line-info\", True): opts.append(\"-generate-line-info\") options =", "arch found # searched_arch = {} def __init__(self, handle, arch", "#note: use False instead of None in searched_arch.get when indicating", "buff = buff.encode('utf8') if isinstance(name, str): name = name.encode('utf8') size", "information, valid only with -opt=0) -generate-line-info (generate line number information)", "= options.get(\"arch\", 52) ftz = options.get(\"ftz\", 0) prec_sqrt = options.get(\"prec_sqrt\",", "import c_char_p import weakref class NVVMPtr: # #key: arch associated", "contraction) -g (enable generation of debugging information, valid only with", "(use a faster approximation for single-precision floating-point division and reciprocals)", "version() def get_ir_version(self): return ir_version() def add_module(self, buff, name =", "to zero, when performing single-precision floating-point operations) -prec-sqrt= 0 (use", "-opt=0) -generate-line-info (generate line number information) -opt= 0 (disable optimizations)", "compute_70 compute_72 compute_75 compute_80 -ftz= 0 (default, preserve denormal values,", "== 0: opts.append(\"-g\") else: #raise warning (g is only valid", "ir_version() def add_module(self, buff, name = \"<unnamed>\"): if isinstance(buff, str):", "compile_program(self.handle, options) ptx = get_compiled_result(self.handle) #TO DO #Apply Numba's debug", "IEEE round-to-nearest mode for single-precision floating-point division and reciprocals) -fma=", "compute_35 compute_37 compute_50 compute_52 (default) compute_53 compute_60 compute_61 compute_62 compute_70", "optimizations) 3 (default, enable optimizations) -arch= compute_35 compute_37 compute_50 compute_52", "from libdevice (libdevice with no \"compute_\" is stored under None", "class NVVM(NVVMPtr): def __init__(self, arch = 20): # self.handle =", "None) # if libdevice is None: # found_arch, libdevice =", "libdevice = next(iter(get_libdevice(arch).items())) # self.searched_arch[arch] = found_arch # self.libdevice[arch] =", "searched_arch = {} def __init__(self, handle, arch = 20): self.get_libdevice(arch)", "name = name.encode('utf8') size = len(buff) add_module_to_program(self.handle, buff, size, name)", "options.get(\"arch\", 52) ftz = options.get(\"ftz\", 0) prec_sqrt = options.get(\"prec_sqrt\", 1)", "None key) # libdevice = self.libdevice.get(self.searched_arch.get(arch, False), None) # if", "return libdevice def get_version(self): return version() def get_ir_version(self): return ir_version()", "NVVMPtr: # #key: arch associated with libdevice (None indicates libdevice", "options.get(\"generate-line-info\", True): opts.append(\"-generate-line-info\") options = (c_char_p * len(opts))(*[c_char_p(opt.encode('utf8')) for opt", "compute_53 compute_60 compute_61 compute_62 compute_70 compute_72 compute_75 compute_80 -ftz= 0", "compute_62 compute_70 compute_72 compute_75 compute_80 -ftz= 0 (default, preserve denormal", "# if libdevice is None: # found_arch, libdevice = next(iter(get_libdevice(arch).items()))", "faster approximation for single-precision floating-point square root) 1 (default, use", "if options.get(\"g\", False) and opt == 0: if opt ==", "self.libdevice.get(self.searched_arch.get(arch, False), None) # if libdevice is None: # found_arch,", "information) -opt= 0 (disable optimizations) 3 (default, enable optimizations) -arch=", "return ir_version() def add_module(self, buff, name = \"<unnamed>\"): if isinstance(buff,", "{}): \"\"\" https://docs.nvidia.com/cuda/libnvvm-api/group__compilation.html#group__compilation_1g76ac1e23f5d0e2240e78be0e63450346 Valid compiler options are -g (enable generation", "= [f\"-opt={opt}\", f\"-arch=compute_{arch}\", f\"-ftz={ftz}\", f\"-prec-sqrt={prec_sqrt}\", f\"-prec-div={prec_div}\", f\"-fma={fma}\",] if options.get(\"g\", False)", "IEEE round-to-nearest mode for single-precision floating-point square root) -prec-div= 0", "create_program, destroy_program, get_compiled_result, get_compiled_result_size, get_program_log, get_program_log_size, lazy_add_module_to_program, verify_program) import os", "when indicating failure to prevent getting None key from libdevice", "0: if opt == 0: opts.append(\"-g\") else: #raise warning (g", "0) prec_sqrt = options.get(\"prec_sqrt\", 1) prec_div = options.get(\"prec_div\", 1) fma", "import os import sys from ctypes import c_char_p import weakref", "valid only with -opt=0) -generate-line-info (generate line number information) \"\"\"", "prec_div = options.get(\"prec_div\", 1) fma = options.get(\"fma\", 0) opts =", "= 20): return get_libdevice(arch) # libdevice = self.libdevice.get(arch, None) #", "# #value: closest available arch found # searched_arch = {}", "= found_arch # self.libdevice[arch] = libdevice # return libdevice def", "1 (flush denormal values to zero, when performing single-precision floating-point", "specific) # #value: libdevice source # libdevice = {} #", "(disable FMA contraction) 1 (default, enable FMA contraction) -g (enable", "-generate-line-info (generate line number information) \"\"\" opt = options.get(\"opt\", 3)", "and reciprocals) 1 (default, use IEEE round-to-nearest mode for single-precision", "information) \"\"\" opt = options.get(\"opt\", 3) arch = options.get(\"arch\", 52)", "use IEEE round-to-nearest mode for single-precision floating-point square root) -prec-div=", "opt == 0: if opt == 0: opts.append(\"-g\") else: #raise", "verify_program(self, options = {}): pass # verify_program(self.handle, ) class NVVM(NVVMPtr):", "floating-point square root) -prec-div= 0 (use a faster approximation for", "root) 1 (default, use IEEE round-to-nearest mode for single-precision floating-point", "size = len(buff) add_module_to_program(self.handle, buff, size, name) def compile(self, options", "#value: libdevice source # libdevice = {} # #key:given arch", "-ftz= 0 (default, preserve denormal values, when performing single-precision floating-point", "for single-precision floating-point square root) -prec-div= 0 (use a faster", "1 (default, use IEEE round-to-nearest mode for single-precision floating-point division", "= self.libdevice.get(arch, None) # if libdevice is None: # #note:", "of None in searched_arch.get when indicating failure to prevent getting", "= 20): # self.handle = handle = create_program() handle =", "if libdevice is None: # found_arch, libdevice = next(iter(get_libdevice(arch).items())) #", "False), None) # if libdevice is None: # found_arch, libdevice", "-prec-div= 0 (use a faster approximation for single-precision floating-point division", "True): opts.append(\"-generate-line-info\") options = (c_char_p * len(opts))(*[c_char_p(opt.encode('utf8')) for opt in", "buff, size, name) def compile(self, options = {}): \"\"\" https://docs.nvidia.com/cuda/libnvvm-api/group__compilation.html#group__compilation_1g76ac1e23f5d0e2240e78be0e63450346", "is stored under None key) # libdevice = self.libdevice.get(self.searched_arch.get(arch, False),", "= len(buff) add_module_to_program(self.handle, buff, size, name) def compile(self, options =", "-opt=0) pass if options.get(\"generate-line-info\", True): opts.append(\"-generate-line-info\") options = (c_char_p *", "floating-point operations) 1 (flush denormal values to zero, when performing", "with -opt=0) -generate-line-info (generate line number information) -opt= 0 (disable", "#Apply Numba's debug patch to ptx return ptx def verify_program(self,", "\"\"\" https://docs.nvidia.com/cuda/libnvvm-api/group__compilation.html#group__compilation_1g76ac1e23f5d0e2240e78be0e63450346 Valid compiler options are -g (enable generation of", ") class NVVM(NVVMPtr): def __init__(self, arch = 20): # self.handle", "opts.append(\"-generate-line-info\") options = (c_char_p * len(opts))(*[c_char_p(opt.encode('utf8')) for opt in opts])", "single-precision floating-point operations) -prec-sqrt= 0 (use a faster approximation for", "floating-point square root) 1 (default, use IEEE round-to-nearest mode for", "indicates libdevice is not arch specific) # #value: libdevice source", "debug patch to ptx return ptx def verify_program(self, options =", "False instead of None in searched_arch.get when indicating failure to", "opt = options.get(\"opt\", 3) arch = options.get(\"arch\", 52) ftz =", "handle def get_libdevice(self, arch = 20): return get_libdevice(arch) # libdevice", "libdevice = self.libdevice.get(arch, None) # if libdevice is None: #", "preserve denormal values, when performing single-precision floating-point operations) 1 (flush", "(libdevice with no \"compute_\" is stored under None key) #", "self.handle = handle = create_program() handle = create_program() weakref.finalize(self, destroy_program,", "(default, use IEEE round-to-nearest mode for single-precision floating-point square root)", "version, add_module_to_program, compile_program, create_program, destroy_program, get_compiled_result, get_compiled_result_size, get_program_log, get_program_log_size, lazy_add_module_to_program,", "root) -prec-div= 0 (use a faster approximation for single-precision floating-point", "found # searched_arch = {} def __init__(self, handle, arch =", "= {}): pass # verify_program(self.handle, ) class NVVM(NVVMPtr): def __init__(self,", "failure to prevent getting None key from libdevice (libdevice with", "from ctypes import c_char_p import weakref class NVVMPtr: # #key:", "is None: # #note: use False instead of None in", "return get_libdevice(arch) # libdevice = self.libdevice.get(arch, None) # if libdevice", "pass if options.get(\"generate-line-info\", True): opts.append(\"-generate-line-info\") options = (c_char_p * len(opts))(*[c_char_p(opt.encode('utf8'))", "# verify_program(self.handle, ) class NVVM(NVVMPtr): def __init__(self, arch = 20):", "libdevice # return libdevice def get_version(self): return version() def get_ir_version(self):", "next(iter(get_libdevice(arch).items())) # self.searched_arch[arch] = found_arch # self.libdevice[arch] = libdevice #", "None) # if libdevice is None: # #note: use False", "in searched_arch.get when indicating failure to prevent getting None key", "stored under None key) # libdevice = self.libdevice.get(self.searched_arch.get(arch, False), None)", "denormal values, when performing single-precision floating-point operations) 1 (flush denormal", "division and reciprocals) 1 (default, use IEEE round-to-nearest mode for", "(generate line number information) -opt= 0 (disable optimizations) 3 (default,", "options) ptx = get_compiled_result(self.handle) #TO DO #Apply Numba's debug patch", "available arch found # searched_arch = {} def __init__(self, handle,", "def __init__(self, arch = 20): # self.handle = handle =", "20): self.get_libdevice(arch) self.handle = handle def get_libdevice(self, arch = 20):", "if options.get(\"generate-line-info\", True): opts.append(\"-generate-line-info\") options = (c_char_p * len(opts))(*[c_char_p(opt.encode('utf8')) for", "options are -g (enable generation of debugging information, valid only", "else: #raise warning (g is only valid when -opt=0) pass", "NVVM(NVVMPtr): def __init__(self, arch = 20): # self.handle = handle", "# return libdevice def get_version(self): return version() def get_ir_version(self): return", "to prevent getting None key from libdevice (libdevice with no", "generation of debugging information, valid only with -opt=0) -generate-line-info (generate", "str): name = name.encode('utf8') size = len(buff) add_module_to_program(self.handle, buff, size,", "f\"-prec-div={prec_div}\", f\"-fma={fma}\",] if options.get(\"g\", False) and opt == 0: if", "round-to-nearest mode for single-precision floating-point square root) -prec-div= 0 (use", "if isinstance(buff, str): buff = buff.encode('utf8') if isinstance(name, str): name", "single-precision floating-point division and reciprocals) 1 (default, use IEEE round-to-nearest", "arch associated with libdevice (None indicates libdevice is not arch", "number information) \"\"\" opt = options.get(\"opt\", 3) arch = options.get(\"arch\",", "(get_libdevice, ir_version, version, add_module_to_program, compile_program, create_program, destroy_program, get_compiled_result, get_compiled_result_size, get_program_log,", "arch = options.get(\"arch\", 52) ftz = options.get(\"ftz\", 0) prec_sqrt =", "self.searched_arch[arch] = found_arch # self.libdevice[arch] = libdevice # return libdevice", "-opt= 0 (disable optimizations) 3 (default, enable optimizations) -arch= compute_35", "enable FMA contraction) -g (enable generation of debugging information, valid", "round-to-nearest mode for single-precision floating-point division and reciprocals) -fma= 0", "(default) compute_53 compute_60 compute_61 compute_62 compute_70 compute_72 compute_75 compute_80 -ftz=", "# if libdevice is None: # #note: use False instead", "prevent getting None key from libdevice (libdevice with no \"compute_\"", "compute_72 compute_75 compute_80 -ftz= 0 (default, preserve denormal values, when", "compute_80 -ftz= 0 (default, preserve denormal values, when performing single-precision", "= get_compiled_result(self.handle) #TO DO #Apply Numba's debug patch to ptx", "= 20): self.get_libdevice(arch) self.handle = handle def get_libdevice(self, arch =", "libdevice is None: # #note: use False instead of None", "1 (default, enable FMA contraction) -g (enable generation of debugging", "closest available arch found # searched_arch = {} def __init__(self,", "get_compiled_result, get_compiled_result_size, get_program_log, get_program_log_size, lazy_add_module_to_program, verify_program) import os import sys", "0 (disable FMA contraction) 1 (default, enable FMA contraction) -g", "key) # libdevice = self.libdevice.get(self.searched_arch.get(arch, False), None) # if libdevice", "opts.append(\"-g\") else: #raise warning (g is only valid when -opt=0)", "#key: arch associated with libdevice (None indicates libdevice is not", "FMA contraction) -g (enable generation of debugging information, valid only", "-fma= 0 (disable FMA contraction) 1 (default, enable FMA contraction)", "size, name) def compile(self, options = {}): \"\"\" https://docs.nvidia.com/cuda/libnvvm-api/group__compilation.html#group__compilation_1g76ac1e23f5d0e2240e78be0e63450346 Valid", "# #note: use False instead of None in searched_arch.get when", "pass # verify_program(self.handle, ) class NVVM(NVVMPtr): def __init__(self, arch =", "getting None key from libdevice (libdevice with no \"compute_\" is", "a faster approximation for single-precision floating-point square root) 1 (default,", "import (get_libdevice, ir_version, version, add_module_to_program, compile_program, create_program, destroy_program, get_compiled_result, get_compiled_result_size,", "get_version(self): return version() def get_ir_version(self): return ir_version() def add_module(self, buff,", "(use a faster approximation for single-precision floating-point square root) 1", "compute_37 compute_50 compute_52 (default) compute_53 compute_60 compute_61 compute_62 compute_70 compute_72", "(enable generation of debugging information, valid only with -opt=0) -generate-line-info", "#key:given arch # #value: closest available arch found # searched_arch", "(flush denormal values to zero, when performing single-precision floating-point operations)", "def compile(self, options = {}): \"\"\" https://docs.nvidia.com/cuda/libnvvm-api/group__compilation.html#group__compilation_1g76ac1e23f5d0e2240e78be0e63450346 Valid compiler options", "use False instead of None in searched_arch.get when indicating failure", "add_module_to_program(self.handle, buff, size, name) def compile(self, options = {}): \"\"\"", "opt in opts]) compile_program(self.handle, options) ptx = get_compiled_result(self.handle) #TO DO", "20): return get_libdevice(arch) # libdevice = self.libdevice.get(arch, None) # if", "options.get(\"opt\", 3) arch = options.get(\"arch\", 52) ftz = options.get(\"ftz\", 0)", "with libdevice (None indicates libdevice is not arch specific) #", "(c_char_p * len(opts))(*[c_char_p(opt.encode('utf8')) for opt in opts]) compile_program(self.handle, options) ptx", "def __init__(self, handle, arch = 20): self.get_libdevice(arch) self.handle = handle", "0) opts = [f\"-opt={opt}\", f\"-arch=compute_{arch}\", f\"-ftz={ftz}\", f\"-prec-sqrt={prec_sqrt}\", f\"-prec-div={prec_div}\", f\"-fma={fma}\",] if", "approximation for single-precision floating-point square root) 1 (default, use IEEE", "self.libdevice[arch] = libdevice # return libdevice def get_version(self): return version()", "contraction) 1 (default, enable FMA contraction) -g (enable generation of", "buff.encode('utf8') if isinstance(name, str): name = name.encode('utf8') size = len(buff)", "get_libdevice(arch) # libdevice = self.libdevice.get(arch, None) # if libdevice is", "floating-point division and reciprocals) -fma= 0 (disable FMA contraction) 1", "__init__(self, arch = 20): # self.handle = handle = create_program()", "= handle = create_program() handle = create_program() weakref.finalize(self, destroy_program, handle)", "(disable optimizations) 3 (default, enable optimizations) -arch= compute_35 compute_37 compute_50", "destroy_program, get_compiled_result, get_compiled_result_size, get_program_log, get_program_log_size, lazy_add_module_to_program, verify_program) import os import", "compiler options are -g (enable generation of debugging information, valid", "isinstance(buff, str): buff = buff.encode('utf8') if isinstance(name, str): name =", "#raise warning (g is only valid when -opt=0) pass if", "os import sys from ctypes import c_char_p import weakref class", "Numba's debug patch to ptx return ptx def verify_program(self, options", "of debugging information, valid only with -opt=0) -generate-line-info (generate line", "division and reciprocals) -fma= 0 (disable FMA contraction) 1 (default,", "found_arch # self.libdevice[arch] = libdevice # return libdevice def get_version(self):", "handle = create_program() handle = create_program() weakref.finalize(self, destroy_program, handle) super().__init__(handle,", "with -opt=0) -generate-line-info (generate line number information) \"\"\" opt =", "= options.get(\"ftz\", 0) prec_sqrt = options.get(\"prec_sqrt\", 1) prec_div = options.get(\"prec_div\",", "#TO DO #Apply Numba's debug patch to ptx return ptx", "= {} # #key:given arch # #value: closest available arch", "prec_sqrt = options.get(\"prec_sqrt\", 1) prec_div = options.get(\"prec_div\", 1) fma =", "options = (c_char_p * len(opts))(*[c_char_p(opt.encode('utf8')) for opt in opts]) compile_program(self.handle,", "arch = 20): return get_libdevice(arch) # libdevice = self.libdevice.get(arch, None)", "ir_version, version, add_module_to_program, compile_program, create_program, destroy_program, get_compiled_result, get_compiled_result_size, get_program_log, get_program_log_size,", "arch # #value: closest available arch found # searched_arch =", "None in searched_arch.get when indicating failure to prevent getting None", "with no \"compute_\" is stored under None key) # libdevice", "mode for single-precision floating-point square root) -prec-div= 0 (use a", "under None key) # libdevice = self.libdevice.get(self.searched_arch.get(arch, False), None) #", "square root) 1 (default, use IEEE round-to-nearest mode for single-precision", "source # libdevice = {} # #key:given arch # #value:", "options.get(\"fma\", 0) opts = [f\"-opt={opt}\", f\"-arch=compute_{arch}\", f\"-ftz={ftz}\", f\"-prec-sqrt={prec_sqrt}\", f\"-prec-div={prec_div}\", f\"-fma={fma}\",]", "get_ir_version(self): return ir_version() def add_module(self, buff, name = \"<unnamed>\"): if", "mode for single-precision floating-point division and reciprocals) -fma= 0 (disable", "(default, enable FMA contraction) -g (enable generation of debugging information,", "20): # self.handle = handle = create_program() handle = create_program()", "values, when performing single-precision floating-point operations) 1 (flush denormal values", "options.get(\"prec_sqrt\", 1) prec_div = options.get(\"prec_div\", 1) fma = options.get(\"fma\", 0)", "#value: closest available arch found # searched_arch = {} def", "ctypes import c_char_p import weakref class NVVMPtr: # #key: arch", "enable optimizations) -arch= compute_35 compute_37 compute_50 compute_52 (default) compute_53 compute_60", "arch = 20): self.get_libdevice(arch) self.handle = handle def get_libdevice(self, arch", "\"<unnamed>\"): if isinstance(buff, str): buff = buff.encode('utf8') if isinstance(name, str):", "def get_version(self): return version() def get_ir_version(self): return ir_version() def add_module(self,", "valid only with -opt=0) -generate-line-info (generate line number information) -opt=", "weakref class NVVMPtr: # #key: arch associated with libdevice (None", "name = \"<unnamed>\"): if isinstance(buff, str): buff = buff.encode('utf8') if", "== 0: if opt == 0: opts.append(\"-g\") else: #raise warning", "compute_60 compute_61 compute_62 compute_70 compute_72 compute_75 compute_80 -ftz= 0 (default,", "indicating failure to prevent getting None key from libdevice (libdevice", "get_compiled_result_size, get_program_log, get_program_log_size, lazy_add_module_to_program, verify_program) import os import sys from", "# libdevice = {} # #key:given arch # #value: closest", "= libdevice # return libdevice def get_version(self): return version() def", "performing single-precision floating-point operations) 1 (flush denormal values to zero,", "f\"-prec-sqrt={prec_sqrt}\", f\"-prec-div={prec_div}\", f\"-fma={fma}\",] if options.get(\"g\", False) and opt == 0:", "self.libdevice.get(arch, None) # if libdevice is None: # #note: use", "buff, name = \"<unnamed>\"): if isinstance(buff, str): buff = buff.encode('utf8')", "# libdevice = self.libdevice.get(self.searched_arch.get(arch, False), None) # if libdevice is", "def add_module(self, buff, name = \"<unnamed>\"): if isinstance(buff, str): buff", "False) and opt == 0: if opt == 0: opts.append(\"-g\")", "0: opts.append(\"-g\") else: #raise warning (g is only valid when", "are -g (enable generation of debugging information, valid only with", "libdevice (libdevice with no \"compute_\" is stored under None key)", "# self.handle = handle = create_program() handle = create_program() weakref.finalize(self,", "opts]) compile_program(self.handle, options) ptx = get_compiled_result(self.handle) #TO DO #Apply Numba's", "c_char_p import weakref class NVVMPtr: # #key: arch associated with", "= {}): \"\"\" https://docs.nvidia.com/cuda/libnvvm-api/group__compilation.html#group__compilation_1g76ac1e23f5d0e2240e78be0e63450346 Valid compiler options are -g (enable", "= next(iter(get_libdevice(arch).items())) # self.searched_arch[arch] = found_arch # self.libdevice[arch] = libdevice", "name.encode('utf8') size = len(buff) add_module_to_program(self.handle, buff, size, name) def compile(self,", "# libdevice = self.libdevice.get(arch, None) # if libdevice is None:", "compile(self, options = {}): \"\"\" https://docs.nvidia.com/cuda/libnvvm-api/group__compilation.html#group__compilation_1g76ac1e23f5d0e2240e78be0e63450346 Valid compiler options are", "arch = 20): # self.handle = handle = create_program() handle", "floating-point operations) -prec-sqrt= 0 (use a faster approximation for single-precision", "debugging information, valid only with -opt=0) -generate-line-info (generate line number", "ptx return ptx def verify_program(self, options = {}): pass #", "__init__(self, handle, arch = 20): self.get_libdevice(arch) self.handle = handle def", "\"compute_\" is stored under None key) # libdevice = self.libdevice.get(self.searched_arch.get(arch,", "libdevice source # libdevice = {} # #key:given arch #", "when performing single-precision floating-point operations) -prec-sqrt= 0 (use a faster", "faster approximation for single-precision floating-point division and reciprocals) 1 (default,", "# searched_arch = {} def __init__(self, handle, arch = 20):", "number information) -opt= 0 (disable optimizations) 3 (default, enable optimizations)", "-generate-line-info (generate line number information) -opt= 0 (disable optimizations) 3", "get_program_log, get_program_log_size, lazy_add_module_to_program, verify_program) import os import sys from ctypes", "-g (enable generation of debugging information, valid only with -opt=0)", "options.get(\"ftz\", 0) prec_sqrt = options.get(\"prec_sqrt\", 1) prec_div = options.get(\"prec_div\", 1)", "options = {}): pass # verify_program(self.handle, ) class NVVM(NVVMPtr): def", "len(buff) add_module_to_program(self.handle, buff, size, name) def compile(self, options = {}):", "(generate line number information) \"\"\" opt = options.get(\"opt\", 3) arch", "Valid compiler options are -g (enable generation of debugging information,", "{}): pass # verify_program(self.handle, ) class NVVM(NVVMPtr): def __init__(self, arch", "is not arch specific) # #value: libdevice source # libdevice", "single-precision floating-point square root) -prec-div= 0 (use a faster approximation", "(default, use IEEE round-to-nearest mode for single-precision floating-point division and", "get_compiled_result(self.handle) #TO DO #Apply Numba's debug patch to ptx return", "class NVVMPtr: # #key: arch associated with libdevice (None indicates", "verify_program(self.handle, ) class NVVM(NVVMPtr): def __init__(self, arch = 20): #", "for single-precision floating-point division and reciprocals) 1 (default, use IEEE", "= (c_char_p * len(opts))(*[c_char_p(opt.encode('utf8')) for opt in opts]) compile_program(self.handle, options)", "= buff.encode('utf8') if isinstance(name, str): name = name.encode('utf8') size =", "ptx def verify_program(self, options = {}): pass # verify_program(self.handle, )", "1) fma = options.get(\"fma\", 0) opts = [f\"-opt={opt}\", f\"-arch=compute_{arch}\", f\"-ftz={ftz}\",", "= options.get(\"opt\", 3) arch = options.get(\"arch\", 52) ftz = options.get(\"ftz\",", "options = {}): \"\"\" https://docs.nvidia.com/cuda/libnvvm-api/group__compilation.html#group__compilation_1g76ac1e23f5d0e2240e78be0e63450346 Valid compiler options are -g", "reciprocals) -fma= 0 (disable FMA contraction) 1 (default, enable FMA", "libdevice (None indicates libdevice is not arch specific) # #value:", "denormal values to zero, when performing single-precision floating-point operations) -prec-sqrt=", "def verify_program(self, options = {}): pass # verify_program(self.handle, ) class", "def get_ir_version(self): return ir_version() def add_module(self, buff, name = \"<unnamed>\"):", "pycu.nvvm import (get_libdevice, ir_version, version, add_module_to_program, compile_program, create_program, destroy_program, get_compiled_result,", "and reciprocals) -fma= 0 (disable FMA contraction) 1 (default, enable", "not arch specific) # #value: libdevice source # libdevice =", "<filename>nvvm/core/nvvm.py from pycu.nvvm import (get_libdevice, ir_version, version, add_module_to_program, compile_program, create_program,", "only valid when -opt=0) pass if options.get(\"generate-line-info\", True): opts.append(\"-generate-line-info\") options", "for single-precision floating-point division and reciprocals) -fma= 0 (disable FMA", "searched_arch.get when indicating failure to prevent getting None key from", "operations) -prec-sqrt= 0 (use a faster approximation for single-precision floating-point", "len(opts))(*[c_char_p(opt.encode('utf8')) for opt in opts]) compile_program(self.handle, options) ptx = get_compiled_result(self.handle)", "compute_52 (default) compute_53 compute_60 compute_61 compute_62 compute_70 compute_72 compute_75 compute_80", "associated with libdevice (None indicates libdevice is not arch specific)", "[f\"-opt={opt}\", f\"-arch=compute_{arch}\", f\"-ftz={ftz}\", f\"-prec-sqrt={prec_sqrt}\", f\"-prec-div={prec_div}\", f\"-fma={fma}\",] if options.get(\"g\", False) and", "# self.libdevice[arch] = libdevice # return libdevice def get_version(self): return", "0 (default, preserve denormal values, when performing single-precision floating-point operations)", "arch specific) # #value: libdevice source # libdevice = {}", "is only valid when -opt=0) pass if options.get(\"generate-line-info\", True): opts.append(\"-generate-line-info\")", "None: # found_arch, libdevice = next(iter(get_libdevice(arch).items())) # self.searched_arch[arch] = found_arch", "options.get(\"prec_div\", 1) fma = options.get(\"fma\", 0) opts = [f\"-opt={opt}\", f\"-arch=compute_{arch}\",", "(None indicates libdevice is not arch specific) # #value: libdevice", "= name.encode('utf8') size = len(buff) add_module_to_program(self.handle, buff, size, name) def", "0 (disable optimizations) 3 (default, enable optimizations) -arch= compute_35 compute_37", "(default, preserve denormal values, when performing single-precision floating-point operations) 1", "name) def compile(self, options = {}): \"\"\" https://docs.nvidia.com/cuda/libnvvm-api/group__compilation.html#group__compilation_1g76ac1e23f5d0e2240e78be0e63450346 Valid compiler", "52) ftz = options.get(\"ftz\", 0) prec_sqrt = options.get(\"prec_sqrt\", 1) prec_div", "import weakref class NVVMPtr: # #key: arch associated with libdevice", "verify_program) import os import sys from ctypes import c_char_p import", "= options.get(\"prec_div\", 1) fma = options.get(\"fma\", 0) opts = [f\"-opt={opt}\",", "= {} def __init__(self, handle, arch = 20): self.get_libdevice(arch) self.handle", "is None: # found_arch, libdevice = next(iter(get_libdevice(arch).items())) # self.searched_arch[arch] =", "0 (use a faster approximation for single-precision floating-point square root)", "compile_program, create_program, destroy_program, get_compiled_result, get_compiled_result_size, get_program_log, get_program_log_size, lazy_add_module_to_program, verify_program) import", "= options.get(\"prec_sqrt\", 1) prec_div = options.get(\"prec_div\", 1) fma = options.get(\"fma\",", "when -opt=0) pass if options.get(\"generate-line-info\", True): opts.append(\"-generate-line-info\") options = (c_char_p", "= handle def get_libdevice(self, arch = 20): return get_libdevice(arch) #", "(default, enable optimizations) -arch= compute_35 compute_37 compute_50 compute_52 (default) compute_53", "isinstance(name, str): name = name.encode('utf8') size = len(buff) add_module_to_program(self.handle, buff,", "https://docs.nvidia.com/cuda/libnvvm-api/group__compilation.html#group__compilation_1g76ac1e23f5d0e2240e78be0e63450346 Valid compiler options are -g (enable generation of debugging", "libdevice = self.libdevice.get(self.searched_arch.get(arch, False), None) # if libdevice is None:", "\"\"\" opt = options.get(\"opt\", 3) arch = options.get(\"arch\", 52) ftz", "line number information) -opt= 0 (disable optimizations) 3 (default, enable", "opts = [f\"-opt={opt}\", f\"-arch=compute_{arch}\", f\"-ftz={ftz}\", f\"-prec-sqrt={prec_sqrt}\", f\"-prec-div={prec_div}\", f\"-fma={fma}\",] if options.get(\"g\"," ]
[ "Copyright (c) 2022, itsdve GmbH and Contributors # See license.txt", "itsdve GmbH and Contributors # See license.txt # import frappe", "and Contributors # See license.txt # import frappe import unittest", "See license.txt # import frappe import unittest class TestFieldserviceSettings(unittest.TestCase): pass", "# Copyright (c) 2022, itsdve GmbH and Contributors # See", "<gh_stars>0 # Copyright (c) 2022, itsdve GmbH and Contributors #", "(c) 2022, itsdve GmbH and Contributors # See license.txt #", "2022, itsdve GmbH and Contributors # See license.txt # import", "GmbH and Contributors # See license.txt # import frappe import", "Contributors # See license.txt # import frappe import unittest class", "# See license.txt # import frappe import unittest class TestFieldserviceSettings(unittest.TestCase):" ]
[ "SP500members 3.remove anomalies 4.normalized data 5.fill NaN with 0 '''", "path of different factor 2.path2:file path of SP500members 3.remove anomalies", "else: columns.append(i) data.columns = columns return data def Seasonal_data_fill(path): data", "for date in factor: mean=factor[date].mean() std=factor[date].std() factor[date]=(factor[date]-mean)/std # fill NAN", "factor: median=factor[date].quantile(0.5) factor.fillna(median,inplace=True) #read SP500 member datas member=pd.read_excel(path2,index_col=0) #merge industry", "order = 2 for j in data: if '20' in", "with 0 ''' #read factor.xlsx factor=pd.read_excel(path1,index_col=0) #remove anomalies which is", "Nov 21 14:51:01 2021 @author: 75638 \"\"\" import pandas as", "different factor 2.path2:file path of SP500members 3.remove anomalies 4.normalized data", "np pd.set_option('display.max_columns', None) pd.set_option('display.width', 10000) def process_data(path1,path2): ''' 1.path1: file", "5.fill NaN with 0 ''' #read factor.xlsx factor=pd.read_excel(path1,index_col=0) #remove anomalies", "columns.append(i[:7]) else: columns.append(i) data.columns = columns return data def Seasonal_data_fill(path):", "less than median-s*std for date in factor: median=factor[date].quantile(0.5) std=factor[date].std() min=median-5*std", "factor.fillna(median,inplace=True) #read SP500 member datas member=pd.read_excel(path2,index_col=0) #merge industry data factor=pd.merge(member,factor,left_index=True,right_index=True)", "for date in factor: median=factor[date].quantile(0.5) std=factor[date].std() min=median-5*std max=median+5*std factor[date]=factor[date].clip(min,max) #normalize", "std=factor[date].std() factor[date]=(factor[date]-mean)/std # fill NAN for date in factor: median=factor[date].quantile(0.5)", "remove_dates(data): columns = [] for i in data: if '20'", "'20' in i: columns.append(i[:7]) else: columns.append(i) data.columns = columns return", "columns return data def Seasonal_data_fill(path): data = pd.read_csv('{}'.format(path)) order =", "+str(month+2) data.insert(order+1, '{}'.format(time_1), np.nan) data.insert(order+2, '{}'.format(time_2), np.nan) order += 3", "temp = data.iloc[:,:2] data = data.iloc[:,2:] data = data.ffill(axis =", "data = pd.read_csv('{}'.format(path)) order = 2 for j in data:", "# save processed data factor.to_csv('C:\\\\Users\\\\75638\\\\OneDrive - UW\\\\Desktop\\\\703project\\\\data\\\\volatility.csv') return factor def", "14:51:01 2021 @author: 75638 \"\"\" import pandas as pd import", "factor=pd.merge(member,factor,left_index=True,right_index=True) # save processed data factor.to_csv('C:\\\\Users\\\\75638\\\\OneDrive - UW\\\\Desktop\\\\703project\\\\data\\\\volatility.csv') return factor", "path of SP500members 3.remove anomalies 4.normalized data 5.fill NaN with", "in factor: median=factor[date].quantile(0.5) std=factor[date].std() min=median-5*std max=median+5*std factor[date]=factor[date].clip(min,max) #normalize data for", "year + '-' +str(month+1) time_2 = year + '-' +str(month+2)", "i in data: if '20' in i: columns.append(i[:7]) else: columns.append(i)", "data.iloc[:,2:] data = data.ffill(axis = 1) data = pd.concat([temp, data],", "data 5.fill NaN with 0 ''' #read factor.xlsx factor=pd.read_excel(path1,index_col=0) #remove", "=(int)(month) time_1 = year + '-' +str(month+1) time_2 = year", "factor 2.path2:file path of SP500members 3.remove anomalies 4.normalized data 5.fill", "pandas as pd import numpy as np pd.set_option('display.max_columns', None) pd.set_option('display.width',", "@author: 75638 \"\"\" import pandas as pd import numpy as", "= remove_dates(pd.read_csv('PE.csv')).columns data = data.set_index(data.columns[0]) return data.to_csv('New {}'.format(path)) if __name__", "def remove_dates(data): columns = [] for i in data: if", "numpy as np pd.set_option('display.max_columns', None) pd.set_option('display.width', 10000) def process_data(path1,path2): '''", "Sun Nov 21 14:51:01 2021 @author: 75638 \"\"\" import pandas", "industry data factor=pd.merge(member,factor,left_index=True,right_index=True) # save processed data factor.to_csv('C:\\\\Users\\\\75638\\\\OneDrive - UW\\\\Desktop\\\\703project\\\\data\\\\volatility.csv')", "if __name__ == '__main__': path1='C:\\\\Users\\\\75638\\\\OneDrive - UW\\\\Desktop\\\\703project\\\\original_data\\\\volatility.xlsx' path2='C:\\\\Users\\\\75638\\\\OneDrive - UW\\\\Desktop\\\\703project\\\\SP500\\\\SP500members.xlsx'", "pd.concat([temp, data], axis = 1) data.columns = remove_dates(pd.read_csv('PE.csv')).columns data =", "data = data.set_index(data.columns[0]) return data.to_csv('New {}'.format(path)) if __name__ == '__main__':", "= columns return data def Seasonal_data_fill(path): data = pd.read_csv('{}'.format(path)) order", "is greater than median+5*std or less than median-s*std for date", "{}'.format(path)) if __name__ == '__main__': path1='C:\\\\Users\\\\75638\\\\OneDrive - UW\\\\Desktop\\\\703project\\\\original_data\\\\volatility.xlsx' path2='C:\\\\Users\\\\75638\\\\OneDrive -", "mean=factor[date].mean() std=factor[date].std() factor[date]=(factor[date]-mean)/std # fill NAN for date in factor:", "= 2 for j in data: if '20' in j:", "None) pd.set_option('display.width', 10000) def process_data(path1,path2): ''' 1.path1: file path of", "month = j.split('/')[0] month =(int)(month) time_1 = year + '-'", "member=pd.read_excel(path2,index_col=0) #merge industry data factor=pd.merge(member,factor,left_index=True,right_index=True) # save processed data factor.to_csv('C:\\\\Users\\\\75638\\\\OneDrive", "as np pd.set_option('display.max_columns', None) pd.set_option('display.width', 10000) def process_data(path1,path2): ''' 1.path1:", "= year + '-' +str(month+2) data.insert(order+1, '{}'.format(time_1), np.nan) data.insert(order+2, '{}'.format(time_2),", "save processed data factor.to_csv('C:\\\\Users\\\\75638\\\\OneDrive - UW\\\\Desktop\\\\703project\\\\data\\\\volatility.csv') return factor def remove_dates(data):", "return data.to_csv('New {}'.format(path)) if __name__ == '__main__': path1='C:\\\\Users\\\\75638\\\\OneDrive - UW\\\\Desktop\\\\703project\\\\original_data\\\\volatility.xlsx'", "= j.split('/')[0] month =(int)(month) time_1 = year + '-' +str(month+1)", "= year + '-' +str(month+1) time_2 = year + '-'", "processed data factor.to_csv('C:\\\\Users\\\\75638\\\\OneDrive - UW\\\\Desktop\\\\703project\\\\data\\\\volatility.csv') return factor def remove_dates(data): columns", "month =(int)(month) time_1 = year + '-' +str(month+1) time_2 =", "'-' +str(month+1) time_2 = year + '-' +str(month+2) data.insert(order+1, '{}'.format(time_1),", "factor[date]=(factor[date]-mean)/std # fill NAN for date in factor: median=factor[date].quantile(0.5) factor.fillna(median,inplace=True)", "in i: columns.append(i[:7]) else: columns.append(i) data.columns = columns return data", "data = pd.concat([temp, data], axis = 1) data.columns = remove_dates(pd.read_csv('PE.csv')).columns", "as pd import numpy as np pd.set_option('display.max_columns', None) pd.set_option('display.width', 10000)", "- UW\\\\Desktop\\\\703project\\\\data\\\\volatility.csv') return factor def remove_dates(data): columns = [] for", "'-' +str(month+2) data.insert(order+1, '{}'.format(time_1), np.nan) data.insert(order+2, '{}'.format(time_2), np.nan) order +=", "data.ffill(axis = 1) data = pd.concat([temp, data], axis = 1)", "for j in data: if '20' in j: year =", "fill NAN for date in factor: median=factor[date].quantile(0.5) factor.fillna(median,inplace=True) #read SP500", "#remove anomalies which is greater than median+5*std or less than", "#normalize data for date in factor: mean=factor[date].mean() std=factor[date].std() factor[date]=(factor[date]-mean)/std #", "datas member=pd.read_excel(path2,index_col=0) #merge industry data factor=pd.merge(member,factor,left_index=True,right_index=True) # save processed data", "= data.set_index(data.columns[0]) return data.to_csv('New {}'.format(path)) if __name__ == '__main__': path1='C:\\\\Users\\\\75638\\\\OneDrive", "factor def remove_dates(data): columns = [] for i in data:", "i: columns.append(i[:7]) else: columns.append(i) data.columns = columns return data def", "-*- coding: utf-8 -*- \"\"\" Created on Sun Nov 21", "3 temp = data.iloc[:,:2] data = data.iloc[:,2:] data = data.ffill(axis", "year = j.split('/')[2] month = j.split('/')[0] month =(int)(month) time_1 =", "= data.iloc[:,:2] data = data.iloc[:,2:] data = data.ffill(axis = 1)", "or less than median-s*std for date in factor: median=factor[date].quantile(0.5) std=factor[date].std()", "__name__ == '__main__': path1='C:\\\\Users\\\\75638\\\\OneDrive - UW\\\\Desktop\\\\703project\\\\original_data\\\\volatility.xlsx' path2='C:\\\\Users\\\\75638\\\\OneDrive - UW\\\\Desktop\\\\703project\\\\SP500\\\\SP500members.xlsx' data=process_data(path1,path2)", "factor.to_csv('C:\\\\Users\\\\75638\\\\OneDrive - UW\\\\Desktop\\\\703project\\\\data\\\\volatility.csv') return factor def remove_dates(data): columns = []", "import numpy as np pd.set_option('display.max_columns', None) pd.set_option('display.width', 10000) def process_data(path1,path2):", "+str(month+1) time_2 = year + '-' +str(month+2) data.insert(order+1, '{}'.format(time_1), np.nan)", "time_2 = year + '-' +str(month+2) data.insert(order+1, '{}'.format(time_1), np.nan) data.insert(order+2,", "greater than median+5*std or less than median-s*std for date in", "for date in factor: median=factor[date].quantile(0.5) factor.fillna(median,inplace=True) #read SP500 member datas", "Seasonal_data_fill(path): data = pd.read_csv('{}'.format(path)) order = 2 for j in", "def process_data(path1,path2): ''' 1.path1: file path of different factor 2.path2:file", "j in data: if '20' in j: year = j.split('/')[2]", "= 1) data = pd.concat([temp, data], axis = 1) data.columns", "of different factor 2.path2:file path of SP500members 3.remove anomalies 4.normalized", "factor[date]=factor[date].clip(min,max) #normalize data for date in factor: mean=factor[date].mean() std=factor[date].std() factor[date]=(factor[date]-mean)/std", "in j: year = j.split('/')[2] month = j.split('/')[0] month =(int)(month)", "data], axis = 1) data.columns = remove_dates(pd.read_csv('PE.csv')).columns data = data.set_index(data.columns[0])", "std=factor[date].std() min=median-5*std max=median+5*std factor[date]=factor[date].clip(min,max) #normalize data for date in factor:", "pd import numpy as np pd.set_option('display.max_columns', None) pd.set_option('display.width', 10000) def", "Created on Sun Nov 21 14:51:01 2021 @author: 75638 \"\"\"", "SP500 member datas member=pd.read_excel(path2,index_col=0) #merge industry data factor=pd.merge(member,factor,left_index=True,right_index=True) # save", "= j.split('/')[2] month = j.split('/')[0] month =(int)(month) time_1 = year", "year + '-' +str(month+2) data.insert(order+1, '{}'.format(time_1), np.nan) data.insert(order+2, '{}'.format(time_2), np.nan)", "return data def Seasonal_data_fill(path): data = pd.read_csv('{}'.format(path)) order = 2", "member datas member=pd.read_excel(path2,index_col=0) #merge industry data factor=pd.merge(member,factor,left_index=True,right_index=True) # save processed", "data.set_index(data.columns[0]) return data.to_csv('New {}'.format(path)) if __name__ == '__main__': path1='C:\\\\Users\\\\75638\\\\OneDrive -", "NaN with 0 ''' #read factor.xlsx factor=pd.read_excel(path1,index_col=0) #remove anomalies which", "data.insert(order+1, '{}'.format(time_1), np.nan) data.insert(order+2, '{}'.format(time_2), np.nan) order += 3 temp", "date in factor: median=factor[date].quantile(0.5) factor.fillna(median,inplace=True) #read SP500 member datas member=pd.read_excel(path2,index_col=0)", "= [] for i in data: if '20' in i:", "j.split('/')[2] month = j.split('/')[0] month =(int)(month) time_1 = year +", "data = data.iloc[:,2:] data = data.ffill(axis = 1) data =", "data: if '20' in j: year = j.split('/')[2] month =", "j: year = j.split('/')[2] month = j.split('/')[0] month =(int)(month) time_1", "if '20' in j: year = j.split('/')[2] month = j.split('/')[0]", "process_data(path1,path2): ''' 1.path1: file path of different factor 2.path2:file path", "pd.set_option('display.max_columns', None) pd.set_option('display.width', 10000) def process_data(path1,path2): ''' 1.path1: file path", "data: if '20' in i: columns.append(i[:7]) else: columns.append(i) data.columns =", "data.to_csv('New {}'.format(path)) if __name__ == '__main__': path1='C:\\\\Users\\\\75638\\\\OneDrive - UW\\\\Desktop\\\\703project\\\\original_data\\\\volatility.xlsx' path2='C:\\\\Users\\\\75638\\\\OneDrive", "\"\"\" import pandas as pd import numpy as np pd.set_option('display.max_columns',", "for i in data: if '20' in i: columns.append(i[:7]) else:", "+= 3 temp = data.iloc[:,:2] data = data.iloc[:,2:] data =", "time_1 = year + '-' +str(month+1) time_2 = year +", "date in factor: median=factor[date].quantile(0.5) std=factor[date].std() min=median-5*std max=median+5*std factor[date]=factor[date].clip(min,max) #normalize data", "'{}'.format(time_2), np.nan) order += 3 temp = data.iloc[:,:2] data =", "order += 3 temp = data.iloc[:,:2] data = data.iloc[:,2:] data", "21 14:51:01 2021 @author: 75638 \"\"\" import pandas as pd", "of SP500members 3.remove anomalies 4.normalized data 5.fill NaN with 0", "2 for j in data: if '20' in j: year", "which is greater than median+5*std or less than median-s*std for", "data factor=pd.merge(member,factor,left_index=True,right_index=True) # save processed data factor.to_csv('C:\\\\Users\\\\75638\\\\OneDrive - UW\\\\Desktop\\\\703project\\\\data\\\\volatility.csv') return", "median=factor[date].quantile(0.5) std=factor[date].std() min=median-5*std max=median+5*std factor[date]=factor[date].clip(min,max) #normalize data for date in", "than median-s*std for date in factor: median=factor[date].quantile(0.5) std=factor[date].std() min=median-5*std max=median+5*std", "<reponame>BrickerP/Investment- # -*- coding: utf-8 -*- \"\"\" Created on Sun", "= 1) data.columns = remove_dates(pd.read_csv('PE.csv')).columns data = data.set_index(data.columns[0]) return data.to_csv('New", "median=factor[date].quantile(0.5) factor.fillna(median,inplace=True) #read SP500 member datas member=pd.read_excel(path2,index_col=0) #merge industry data", "3.remove anomalies 4.normalized data 5.fill NaN with 0 ''' #read", "data for date in factor: mean=factor[date].mean() std=factor[date].std() factor[date]=(factor[date]-mean)/std # fill", "in factor: mean=factor[date].mean() std=factor[date].std() factor[date]=(factor[date]-mean)/std # fill NAN for date", "data.insert(order+2, '{}'.format(time_2), np.nan) order += 3 temp = data.iloc[:,:2] data", "data = data.ffill(axis = 1) data = pd.concat([temp, data], axis", "in factor: median=factor[date].quantile(0.5) factor.fillna(median,inplace=True) #read SP500 member datas member=pd.read_excel(path2,index_col=0) #merge", "def Seasonal_data_fill(path): data = pd.read_csv('{}'.format(path)) order = 2 for j", "in data: if '20' in j: year = j.split('/')[2] month", "axis = 1) data.columns = remove_dates(pd.read_csv('PE.csv')).columns data = data.set_index(data.columns[0]) return", "columns = [] for i in data: if '20' in", "median+5*std or less than median-s*std for date in factor: median=factor[date].quantile(0.5)", "factor.xlsx factor=pd.read_excel(path1,index_col=0) #remove anomalies which is greater than median+5*std or", "# -*- coding: utf-8 -*- \"\"\" Created on Sun Nov", "2.path2:file path of SP500members 3.remove anomalies 4.normalized data 5.fill NaN", "if '20' in i: columns.append(i[:7]) else: columns.append(i) data.columns = columns", "= pd.read_csv('{}'.format(path)) order = 2 for j in data: if", "j.split('/')[0] month =(int)(month) time_1 = year + '-' +str(month+1) time_2", "1) data = pd.concat([temp, data], axis = 1) data.columns =", "in data: if '20' in i: columns.append(i[:7]) else: columns.append(i) data.columns", "+ '-' +str(month+1) time_2 = year + '-' +str(month+2) data.insert(order+1,", "min=median-5*std max=median+5*std factor[date]=factor[date].clip(min,max) #normalize data for date in factor: mean=factor[date].mean()", "2021 @author: 75638 \"\"\" import pandas as pd import numpy", "np.nan) data.insert(order+2, '{}'.format(time_2), np.nan) order += 3 temp = data.iloc[:,:2]", "4.normalized data 5.fill NaN with 0 ''' #read factor.xlsx factor=pd.read_excel(path1,index_col=0)", "columns.append(i) data.columns = columns return data def Seasonal_data_fill(path): data =", "= data.ffill(axis = 1) data = pd.concat([temp, data], axis =", "= pd.concat([temp, data], axis = 1) data.columns = remove_dates(pd.read_csv('PE.csv')).columns data", "median-s*std for date in factor: median=factor[date].quantile(0.5) std=factor[date].std() min=median-5*std max=median+5*std factor[date]=factor[date].clip(min,max)", "[] for i in data: if '20' in i: columns.append(i[:7])", "np.nan) order += 3 temp = data.iloc[:,:2] data = data.iloc[:,2:]", "= data.iloc[:,2:] data = data.ffill(axis = 1) data = pd.concat([temp,", "1.path1: file path of different factor 2.path2:file path of SP500members", "''' #read factor.xlsx factor=pd.read_excel(path1,index_col=0) #remove anomalies which is greater than", "file path of different factor 2.path2:file path of SP500members 3.remove", "1) data.columns = remove_dates(pd.read_csv('PE.csv')).columns data = data.set_index(data.columns[0]) return data.to_csv('New {}'.format(path))", "\"\"\" Created on Sun Nov 21 14:51:01 2021 @author: 75638", "10000) def process_data(path1,path2): ''' 1.path1: file path of different factor", "UW\\\\Desktop\\\\703project\\\\data\\\\volatility.csv') return factor def remove_dates(data): columns = [] for i", "anomalies which is greater than median+5*std or less than median-s*std", "than median+5*std or less than median-s*std for date in factor:", "pd.read_csv('{}'.format(path)) order = 2 for j in data: if '20'", "+ '-' +str(month+2) data.insert(order+1, '{}'.format(time_1), np.nan) data.insert(order+2, '{}'.format(time_2), np.nan) order", "data.columns = columns return data def Seasonal_data_fill(path): data = pd.read_csv('{}'.format(path))", "# fill NAN for date in factor: median=factor[date].quantile(0.5) factor.fillna(median,inplace=True) #read", "max=median+5*std factor[date]=factor[date].clip(min,max) #normalize data for date in factor: mean=factor[date].mean() std=factor[date].std()", "''' 1.path1: file path of different factor 2.path2:file path of", "remove_dates(pd.read_csv('PE.csv')).columns data = data.set_index(data.columns[0]) return data.to_csv('New {}'.format(path)) if __name__ ==", "return factor def remove_dates(data): columns = [] for i in", "NAN for date in factor: median=factor[date].quantile(0.5) factor.fillna(median,inplace=True) #read SP500 member", "#read factor.xlsx factor=pd.read_excel(path1,index_col=0) #remove anomalies which is greater than median+5*std", "date in factor: mean=factor[date].mean() std=factor[date].std() factor[date]=(factor[date]-mean)/std # fill NAN for", "utf-8 -*- \"\"\" Created on Sun Nov 21 14:51:01 2021", "75638 \"\"\" import pandas as pd import numpy as np", "factor: mean=factor[date].mean() std=factor[date].std() factor[date]=(factor[date]-mean)/std # fill NAN for date in", "#merge industry data factor=pd.merge(member,factor,left_index=True,right_index=True) # save processed data factor.to_csv('C:\\\\Users\\\\75638\\\\OneDrive -", "data factor.to_csv('C:\\\\Users\\\\75638\\\\OneDrive - UW\\\\Desktop\\\\703project\\\\data\\\\volatility.csv') return factor def remove_dates(data): columns =", "anomalies 4.normalized data 5.fill NaN with 0 ''' #read factor.xlsx", "data def Seasonal_data_fill(path): data = pd.read_csv('{}'.format(path)) order = 2 for", "'{}'.format(time_1), np.nan) data.insert(order+2, '{}'.format(time_2), np.nan) order += 3 temp =", "'20' in j: year = j.split('/')[2] month = j.split('/')[0] month", "factor=pd.read_excel(path1,index_col=0) #remove anomalies which is greater than median+5*std or less", "on Sun Nov 21 14:51:01 2021 @author: 75638 \"\"\" import", "factor: median=factor[date].quantile(0.5) std=factor[date].std() min=median-5*std max=median+5*std factor[date]=factor[date].clip(min,max) #normalize data for date", "-*- \"\"\" Created on Sun Nov 21 14:51:01 2021 @author:", "0 ''' #read factor.xlsx factor=pd.read_excel(path1,index_col=0) #remove anomalies which is greater", "#read SP500 member datas member=pd.read_excel(path2,index_col=0) #merge industry data factor=pd.merge(member,factor,left_index=True,right_index=True) #", "import pandas as pd import numpy as np pd.set_option('display.max_columns', None)", "data.iloc[:,:2] data = data.iloc[:,2:] data = data.ffill(axis = 1) data", "coding: utf-8 -*- \"\"\" Created on Sun Nov 21 14:51:01", "pd.set_option('display.width', 10000) def process_data(path1,path2): ''' 1.path1: file path of different", "data.columns = remove_dates(pd.read_csv('PE.csv')).columns data = data.set_index(data.columns[0]) return data.to_csv('New {}'.format(path)) if" ]
[ "import pytest from pathlib import Path from blendtorch import btt", "info = env.step(0.6) assert done obs = env.reset() assert obs", "obs == pytest.approx(0.6) assert reward == 1. assert not done", "env.step(0.6) assert done obs = env.reset() assert obs == 0.", "MyEnv(background=background) obs = env.reset() assert obs == 0. obs, reward,", "pytest from pathlib import Path from blendtorch import btt BLENDDIR", "done, info = env.step(0.6) assert done obs = env.reset() assert", "1. assert not done assert info['count'] == 3 for _", "env.reset() assert obs == 0. obs, reward, done, info =", "env.step(0.6) assert obs == pytest.approx(0.6) assert reward == 1. assert", "# 1 is already set by reset() obs, reward, done,", "blendtorch import btt BLENDDIR = Path(__file__).parent/'blender' class MyEnv(btt.env.OpenAIRemoteEnv): def __init__(self,", "happens. def _run_remote_env(background): env = MyEnv(background=background) obs = env.reset() assert", "env.step(0.1) assert obs == pytest.approx(0.1) assert reward == 0. assert", "already set by reset() obs, reward, done, info = env.step(0.6)", "done assert info['count'] == 2 env.close() @pytest.mark.background def test_remote_env(): _run_remote_env(background=True)", "reward, done, info = env.step(0.6) assert obs == pytest.approx(0.6) assert", "fail since # _env_post_step() is not called. Its unclear currently", "range(8): obs, reward, done, info = env.step(0.6) assert done obs", "Path(__file__).parent/'blender' class MyEnv(btt.env.OpenAIRemoteEnv): def __init__(self, background=True, **kwargs): super().__init__(version='1.0.0') self.launch(scene=BLENDDIR/'env.blend', script=BLENDDIR", "done assert info['count'] == 3 for _ in range(8): obs,", "self.launch(scene=BLENDDIR/'env.blend', script=BLENDDIR / 'env.blend.py', background=background, **kwargs) # For Blender 2.9", "obs == 0. obs, reward, done, info = env.step(0.1) assert", "= env.step(0.6) assert obs == pytest.approx(0.6) assert reward == 1.", "reset() obs, reward, done, info = env.step(0.6) assert obs ==", "set by reset() obs, reward, done, info = env.step(0.6) assert", "class MyEnv(btt.env.OpenAIRemoteEnv): def __init__(self, background=True, **kwargs): super().__init__(version='1.0.0') self.launch(scene=BLENDDIR/'env.blend', script=BLENDDIR /", "3 for _ in range(8): obs, reward, done, info =", "_run_remote_env(background): env = MyEnv(background=background) obs = env.reset() assert obs ==", "the tests below fail since # _env_post_step() is not called.", "background=background, **kwargs) # For Blender 2.9 if we pass scene='',", "done assert info['count'] == 2 # 1 is already set", "# For Blender 2.9 if we pass scene='', the tests", "import Path from blendtorch import btt BLENDDIR = Path(__file__).parent/'blender' class", "done obs = env.reset() assert obs == 0. obs, reward,", "pytest.approx(0.1) assert reward == 0. assert not done assert info['count']", "/ 'env.blend.py', background=background, **kwargs) # For Blender 2.9 if we", "by reset() obs, reward, done, info = env.step(0.6) assert obs", "assert reward == 0. assert not done assert info['count'] ==", "Blender 2.9 if we pass scene='', the tests below fail", "not done assert info['count'] == 3 for _ in range(8):", "1 is already set by reset() obs, reward, done, info", "assert obs == pytest.approx(0.1) assert reward == 0. assert not", "info['count'] == 2 # 1 is already set by reset()", "== pytest.approx(0.1) assert reward == 0. assert not done assert", "assert info['count'] == 2 # 1 is already set by", "this happens. def _run_remote_env(background): env = MyEnv(background=background) obs = env.reset()", "== 2 env.close() @pytest.mark.background def test_remote_env(): _run_remote_env(background=True) def test_remote_env_ui(): _run_remote_env(background=False)", "For Blender 2.9 if we pass scene='', the tests below", "script=BLENDDIR / 'env.blend.py', background=background, **kwargs) # For Blender 2.9 if", "assert not done assert info['count'] == 2 # 1 is", "assert obs == pytest.approx(0.6) assert reward == 1. assert not", "super().__init__(version='1.0.0') self.launch(scene=BLENDDIR/'env.blend', script=BLENDDIR / 'env.blend.py', background=background, **kwargs) # For Blender", "if we pass scene='', the tests below fail since #", "done, info = env.step(0.1) assert obs == pytest.approx(0.1) assert reward", "not done assert info['count'] == 2 # 1 is already", "import btt BLENDDIR = Path(__file__).parent/'blender' class MyEnv(btt.env.OpenAIRemoteEnv): def __init__(self, background=True,", "from pathlib import Path from blendtorch import btt BLENDDIR =", "= env.step(0.6) assert done obs = env.reset() assert obs ==", "obs, reward, done, info = env.step(0.6) assert obs == pytest.approx(0.6)", "obs == pytest.approx(0.1) assert reward == 0. assert not done", "reward == 1. assert not done assert info['count'] == 3", "= Path(__file__).parent/'blender' class MyEnv(btt.env.OpenAIRemoteEnv): def __init__(self, background=True, **kwargs): super().__init__(version='1.0.0') self.launch(scene=BLENDDIR/'env.blend',", "== pytest.approx(0.6) assert reward == 1. assert not done assert", "info['count'] == 3 for _ in range(8): obs, reward, done,", "unclear currently why this happens. def _run_remote_env(background): env = MyEnv(background=background)", "obs = env.reset() assert obs == 0. obs, reward, done,", "not done assert info['count'] == 2 env.close() @pytest.mark.background def test_remote_env():", "assert not done assert info['count'] == 2 env.close() @pytest.mark.background def", "Path from blendtorch import btt BLENDDIR = Path(__file__).parent/'blender' class MyEnv(btt.env.OpenAIRemoteEnv):", "reward, done, info = env.step(0.6) assert done obs = env.reset()", "obs, reward, done, info = env.step(0.6) assert done obs =", "info = env.step(0.1) assert obs == pytest.approx(0.1) assert reward ==", "env = MyEnv(background=background) obs = env.reset() assert obs == 0.", "== 0. assert not done assert info['count'] == 2 env.close()", "is already set by reset() obs, reward, done, info =", "2 # 1 is already set by reset() obs, reward,", "called. Its unclear currently why this happens. def _run_remote_env(background): env", "def _run_remote_env(background): env = MyEnv(background=background) obs = env.reset() assert obs", "pathlib import Path from blendtorch import btt BLENDDIR = Path(__file__).parent/'blender'", "**kwargs) # For Blender 2.9 if we pass scene='', the", "== 3 for _ in range(8): obs, reward, done, info", "BLENDDIR = Path(__file__).parent/'blender' class MyEnv(btt.env.OpenAIRemoteEnv): def __init__(self, background=True, **kwargs): super().__init__(version='1.0.0')", "currently why this happens. def _run_remote_env(background): env = MyEnv(background=background) obs", "== 1. assert not done assert info['count'] == 3 for", "in range(8): obs, reward, done, info = env.step(0.6) assert done", "== 0. obs, reward, done, info = env.step(0.1) assert obs", "below fail since # _env_post_step() is not called. Its unclear", "== 2 # 1 is already set by reset() obs,", "for _ in range(8): obs, reward, done, info = env.step(0.6)", "background=True, **kwargs): super().__init__(version='1.0.0') self.launch(scene=BLENDDIR/'env.blend', script=BLENDDIR / 'env.blend.py', background=background, **kwargs) #", "# _env_post_step() is not called. Its unclear currently why this", "== 0. assert not done assert info['count'] == 2 #", "__init__(self, background=True, **kwargs): super().__init__(version='1.0.0') self.launch(scene=BLENDDIR/'env.blend', script=BLENDDIR / 'env.blend.py', background=background, **kwargs)", "def __init__(self, background=True, **kwargs): super().__init__(version='1.0.0') self.launch(scene=BLENDDIR/'env.blend', script=BLENDDIR / 'env.blend.py', background=background,", "= MyEnv(background=background) obs = env.reset() assert obs == 0. obs,", "pytest.approx(0.6) assert reward == 1. assert not done assert info['count']", "0. obs, reward, done, info = env.step(0.1) assert obs ==", "reward, done, info = env.step(0.1) assert obs == pytest.approx(0.1) assert", "0. assert not done assert info['count'] == 2 env.close() @pytest.mark.background", "2.9 if we pass scene='', the tests below fail since", "obs, reward, done, info = env.step(0.1) assert obs == pytest.approx(0.1)", "info['count'] == 2 env.close() @pytest.mark.background def test_remote_env(): _run_remote_env(background=True) def test_remote_env_ui():", "tests below fail since # _env_post_step() is not called. Its", "btt BLENDDIR = Path(__file__).parent/'blender' class MyEnv(btt.env.OpenAIRemoteEnv): def __init__(self, background=True, **kwargs):", "pass scene='', the tests below fail since # _env_post_step() is", "is not called. Its unclear currently why this happens. def", "why this happens. def _run_remote_env(background): env = MyEnv(background=background) obs =", "info = env.step(0.6) assert obs == pytest.approx(0.6) assert reward ==", "since # _env_post_step() is not called. Its unclear currently why", "reward == 0. assert not done assert info['count'] == 2", "0. assert not done assert info['count'] == 2 # 1", "from blendtorch import btt BLENDDIR = Path(__file__).parent/'blender' class MyEnv(btt.env.OpenAIRemoteEnv): def", "MyEnv(btt.env.OpenAIRemoteEnv): def __init__(self, background=True, **kwargs): super().__init__(version='1.0.0') self.launch(scene=BLENDDIR/'env.blend', script=BLENDDIR / 'env.blend.py',", "_ in range(8): obs, reward, done, info = env.step(0.6) assert", "assert info['count'] == 3 for _ in range(8): obs, reward,", "Its unclear currently why this happens. def _run_remote_env(background): env =", "'env.blend.py', background=background, **kwargs) # For Blender 2.9 if we pass", "= env.step(0.1) assert obs == pytest.approx(0.1) assert reward == 0.", "assert obs == 0. obs, reward, done, info = env.step(0.1)", "done, info = env.step(0.6) assert obs == pytest.approx(0.6) assert reward", "not called. Its unclear currently why this happens. def _run_remote_env(background):", "scene='', the tests below fail since # _env_post_step() is not", "we pass scene='', the tests below fail since # _env_post_step()", "_env_post_step() is not called. Its unclear currently why this happens.", "= env.reset() assert obs == 0. obs, reward, done, info", "assert info['count'] == 2 env.close() @pytest.mark.background def test_remote_env(): _run_remote_env(background=True) def", "**kwargs): super().__init__(version='1.0.0') self.launch(scene=BLENDDIR/'env.blend', script=BLENDDIR / 'env.blend.py', background=background, **kwargs) # For", "assert reward == 1. assert not done assert info['count'] ==", "assert not done assert info['count'] == 3 for _ in", "assert done obs = env.reset() assert obs == 0. obs," ]
[]
[ "makes the code more readable. # pylint: disable=g-backslash-continuation VEGA_URL =", "subset of one task. Returns: The same dataframe subset with", "num examples:Q', title='Number of examples'), color=alt.condition(brush, 'Task:N', alt.value('lightgray')), tooltip=['Task', 'Runtime", "mid = round(num_rows / 2) return individual_region_bars(df.iloc[0:20], 'Top runtime regions')", "that causes bundling by task to avoid showing multiple overlapping", "candidates', 'num examples'] CSS_STYLES = \"\"\" <style> body { font-family:", "output def calculate_totals(df: pd.DataFrame) -> pd.DataFrame: \"\"\"Calculates total runtime, formats", "report with all the charts. write_to_html_report( charts=charts, title=title, subtitle=subtitle, html_output=html_output)", "'total runtime') top_5000 = df.nlargest(5000, 'total runtime') # Sample the", "'selected_longest_and_median_regions', 'chart': selected_longest_and_median_regions(df) }, { 'id': 'zero_examples', 'chart': top_regions_producing_zero_examples(df) }]", "report. columns_used = [ 'task cumsum order', 'task cumsum fraction',", "A dataframe subset of one task. Returns: The same dataframe", "= [ 'task cumsum order', 'task cumsum fraction', 'tooltip', 'Task',", "Brushing on the task_scatter plot highlights the same tasks in", "typing import Dict, Sequence, List, Tuple, Text, Any, Union from", "in binary form must reproduce the above copyright # notice,", "-> str: \"\"\"Creates a nice format string from a potentially", "without specific prior written permission. # # THIS SOFTWARE IS", "this # software without specific prior written permission. # #", "= 'https://storage.googleapis.com/deepvariant/lib/vega' FLAGS = flags.FLAGS flags.DEFINE_string( 'input', None, 'TSV file", "'downloadFileName': download_filename} html_output.write('vegaEmbed(\"#vis_{}\", spec_{}, {})\\n'.format( chart['id'], chart['id'], embed_options)) html_output.write('</script>\\n') #", "the report. html_output: Writable file object where output will be", "# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF", "Altair uses a lot of method chaining, such as #", "written. \"\"\" # Load data into pandas dataframes and add", "regions account for Y% of the total runtime.\" There is", "f\"the runtime in task {row['Task']}\") def calculate_pareto_metrics(df_subset: pd.DataFrame) -> pd.DataFrame:", "Args: df: A dataframe of all regions. Returns: An altair", "[path_string] list_of_dataframes = [] for i, path in enumerate(paths): if", "y=alt.Y( 'task cumsum fraction', title='Account for Y% of the total", "the html report. columns_used = [ 'task cumsum order', 'task", "'chart': stage_histogram( top_100, title='Runtime by stage for regions in the", "title='Trends for regions in the bottom 99%') }]) return charts", "= calculate_totals(df) by_task = summarize_by_task(df) return df, by_task def make_all_charts(", "runtimes, either by region or by task. title: A title", "+ RUNTIME_COLUMNS, row=COUNT_COLUMNS, ).properties(title=title) def totals_by_stage(d: pd.DataFrame) -> alt.Chart: \"\"\"Plots", "EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE", "affect the other. Using max(task) for 'text' is a #", "tooltip='region' ).properties(width=100, height=100) \\ .repeat( column=['total runtime'] + RUNTIME_COLUMNS, row=COUNT_COLUMNS,", "either by region or by task. title: A title for", "method chaining, such as # chart.mark_bar().encode(...).properties(...), so using backslash #", "plot of task runtimes. Tracing each curve shows to what", "title='Trends for all regions') }]) else: # With too many", "list of conditions and the following disclaimer. # # 2.", "matching the TSV file(s) but with added Task column. \"\"\"", "use the same dataframe as the first chart to enable", "object. Returns: None. Writes into the html_output file object. \"\"\"", "' f'across {len(by_task)} task{\"(s)\" if len(by_task) > 1 else \"\"}')", "pd.DataFrame, by_task: pd.DataFrame) -> List[Dict[Text, Union[str, alt.Chart]]]: \"\"\"Creates charts and", "the HTML document. html_output.write('<!DOCTYPE html>\\n<html>\\n<head>') # Add dependencies vega and", "example, 2h3m5.012s. \"\"\" minutes, seconds = divmod(raw_seconds, 60) hours, minutes", "if len(argv) > 1: raise app.UsageError( 'Command line parsing failure:", "by regions. title: A title for the plot. Returns: An", "Google LLC. # # Redistribution and use in source and", "regions') def top_regions_producing_zero_examples(df: pd.DataFrame) -> alt.Chart: \"\"\"Creates a chart of", "updated to 0.24+, pd.read_csv will work for gs:// # without", "'runtime_by_stage']) \\ .mark_bar(opacity=0.3) \\ .encode( x=alt.X('runtime_by_stage:Q', bin=alt.Bin(maxbins=100), title='Runtime (seconds)'), y=alt.Y('count()',", "'task num examples', 'Runtime for task' ] df = df[columns_used]", "y=alt.Y('runtime_by_stage:Q', scale=alt.Scale(type='linear'), title='Runtime (seconds)'), fill=alt.Fill('Stage:N', sort=None), tooltip='Runtime:N' ).properties(title=title) def selected_longest_and_median_regions(df:", "report. subtitle: The subtitle to show just below the title", "list(map(lambda x: x / n, range(0, n))) df_subset['tooltip'] = df_subset.apply(pareto_by_task_tooltip,", "top_100 = df.nlargest(100, 'total runtime') top_5000 = df.nlargest(5000, 'total runtime')", "= list(map(lambda x: x / n, range(0, n))) df_subset['tooltip'] =", "task. title: A title for the plot. Returns: An altair", "outliers that obscure general trends. bottom_99_percent = df.nsmallest(int(len(df) * .99),", "'total runtime') if len(bottom_99_percent) > 5000: bottom_99_percent = bottom_99_percent.sample(5000) charts.extend([{", "the text look funky. task_scatter = alt.Chart(df).mark_point(size=10).encode( x=alt.X('max(task total runtime)',", "with some additional summary columns. \"\"\" # 'total runtime' is", "and binary forms, with or without # modification, are permitted", "title=title, subtitle=subtitle, html_output=html_output) def main(argv: Sequence[str]): if len(argv) > 1:", "names of its # contributors may be used to endorse", ".99), 'total runtime') if len(bottom_99_percent) > 5000: bottom_99_percent = bottom_99_percent.sample(5000)", "pareto_and_runtimes_by_task(df: pd.DataFrame) -> alt.Chart: \"\"\"Creates an interactive Pareto curve and", "runtime, formats it nicely, and sorts by it. Args: df:", "type=\"text/javascript\" src=\"{}/vega@5\"></script>' '\\n'.format(VEGA_URL)) html_output.write( '<script type=\"text/javascript\" src=\"{}/vega-lite@4.8.1\"></script>' '\\n'.format(VEGA_URL)) html_output.write( '<script", "-> alt.Chart: \"\"\"Creates a chart of the top regions that", "for chart in charts: html_output.write('var spec_{} = {};\\n'.format(chart['id'], chart['chart'].to_json())) download_filename", "df.nlargest(100, 'total runtime') top_5000 = df.nlargest(5000, 'total runtime') # Sample", "= FLAGS.output else: output_filename = f'{FLAGS.output}.html' # Start HTML document.", "examples:Q', title='Number of examples'), color=alt.condition(brush, 'Task:N', alt.value('lightgray')), tooltip=['Task', 'Runtime for", "of source code must retain the above copyright notice, #", "stage for regions in the bottom 99%') }, { 'id':", "regions, each of which will be shown as a bar.", "len(df_subset) df_subset['task cumsum order'] = list(map(lambda x: x / n,", "-> None: \"\"\"Makes the html report with all the charts", "columns to greatly reduce the size of the html report.", "written permission. # # THIS SOFTWARE IS PROVIDED BY THE", "or promote products derived from this # software without specific", "with some top-level stats. subtitle = (f'Runtime profiling for make_examples", "GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR", "WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF", "software without specific prior written permission. # # THIS SOFTWARE", "written to:', output_filename) if __name__ == '__main__': flags.mark_flags_as_required(['input', 'title']) app.run(main)", "\"\"\" minutes, seconds = divmod(raw_seconds, 60) hours, minutes = divmod(minutes,", "'histogram_bottom_99_percent', 'chart': stage_histogram( bottom_99_percent, title='Runtime by stage for regions in", "BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,", "fraction'] * 100:.2f}% of \" f\"the runtime in task {row['Task']}\")", "runtime', axis=alt.Axis(format='%')), tooltip='tooltip', color=alt.condition(brush, 'Task:N', alt.value('lightgray'))).properties( title='Pareto curve for each", "html_output.write('<script>\\n') for chart in charts: html_output.write('var spec_{} = {};\\n'.format(chart['id'], chart['chart'].to_json()))", "THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS", "make_examples ' 'with --runtime_by_region. Can be sharded, e.g. /path/runtime@64.tsv.') flags.DEFINE_string(", "= '{}_{}'.format(title.replace(' ', '_'), chart['id']) embed_options = {'mode': 'vega-lite', 'downloadFileName':", "# brushing on one to affect the other. Using max(task)", "on the report. html_output: a writable file object. Returns: None.", "# trick that causes bundling by task to avoid showing", "> 0: output += f'{int(hours)}h' if minutes > 0: output", "TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR", "pd.DataFrame, title: str = '') -> alt.Chart: \"\"\"Plots a histogram", "order', title='The longest-runtime X% of regions', axis=alt.Axis(format='%')), y=alt.Y( 'task cumsum", "below the title on the report. html_output: a writable file", "(f\"{row['task cumsum order'] * 100:.2f}% of regions \" f\"account for", "from a single or sharded path into a pandas dataframe.", "does not accept ' 'positional arguments, but found these extra", "longest regions are shown. if len(df) > 5000: x =", "for the plot. If a dict, it should contain 'title'", "subtitle = ( f'Spent {runtime_of_zeros:.2f} hours processing the ' f'{len(regions_with_zero_examples)}", "some additional summary columns. \"\"\" # 'total runtime' is a", "Task column. \"\"\" if sharded_file_utils.is_sharded_file_spec(path_string): paths = sharded_file_utils.generate_sharded_filenames(path_string) else: paths", "The subtitle to show just below the title on the", "task, for the scatter plot: df_subset['task total runtime'] = df_subset['total", "the charts. write_to_html_report( charts=charts, title=title, subtitle=subtitle, html_output=html_output) def main(argv: Sequence[str]):", "regions in the bottom 99%') }]) return charts def make_report(input_path:", "Redistributions of source code must retain the above copyright notice,", "d: A dataframe of runtimes, either by region or by", "With too many points, make different subsets to show trends", "versus covariates. Args: d: A pandas dataframe of runtime by", "html_output=html_output) def main(argv: Sequence[str]): if len(argv) > 1: raise app.UsageError(", "following conditions # are met: # # 1. Redistributions of", "pandas is updated to 0.24+, pd.read_csv will work for gs://", "HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN", "# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT", "the following disclaimer in the # documentation and/or other materials", "runtime'].sum() df_subset['Runtime for task'] = df_subset['task total runtime'].apply( format_runtime_string) df_subset['task", "containing a chart and a descriptive ID. \"\"\" charts =", "sort=None), y=alt.Y('runtime_by_stage:Q', scale=alt.Scale(type='linear'), title='Runtime (seconds)'), fill=alt.Fill('Stage:N', sort=None), tooltip='Runtime:N' ).properties(title=title) def", "dataframe. Args: path_string: The path to the input file, which", "into an HTML report. Args: input_path: Path of the input", "HTML document. html_output.write('<!DOCTYPE html>\\n<html>\\n<head>') # Add dependencies vega and vega-lite,", "df: A dataframe with one row per region. by_task: A", "= tf.io.gfile.GFile(output_filename, 'w') make_report( input_path=FLAGS.input, title=FLAGS.title, html_output=html_output) html_output.close() # Abstracted", "extra arguments: \"{}\".' ''.format(str(argv[1:]))) # Add html to the output", ") \\ .properties(title='Total runtime for each task (drag to highlight)')", "VEGA_URL = 'https://storage.googleapis.com/deepvariant/lib/vega' FLAGS = flags.FLAGS flags.DEFINE_string( 'input', None, 'TSV", "A dataframe with one row per region. by_task: A dataframe", "= len(df_subset) df_subset['task cumsum order'] = list(map(lambda x: x /", "FLAGS.output else: output_filename = f'{FLAGS.output}.html' # Start HTML document. Using", "chart to enable the # brushing on one to affect", "bar charts of the top 20 and median 20 regions.", "binary form must reproduce the above copyright # notice, this", "html_output.write('<!DOCTYPE html>\\n<html>\\n<head>') # Add dependencies vega and vega-lite, which render", "html_output.write('<script type=\"text/javascript\" src=\"{}/vega@5\"></script>' '\\n'.format(VEGA_URL)) html_output.write( '<script type=\"text/javascript\" src=\"{}/vega-lite@4.8.1\"></script>' '\\n'.format(VEGA_URL)) html_output.write(", "region or by task. title: A title for the plot.", "html_output: Writable file object where output will be written. \"\"\"", "nor the names of its # contributors may be used", "dataframe matching the TSV file(s) but with added Task column.", "chart['id'], chart['id'], embed_options)) html_output.write('</script>\\n') # Close HTML document. html_output.write('</body></html>') def", "OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE", "DAMAGE. r\"\"\"Create a visual report of make_examples runtime by region.", "d: A pandas dataframe of runtime by regions. title: A", "stage_totals_series, columns=['Runtime (seconds)']) stage_totals.reset_index(inplace=True) stage_totals = stage_totals.rename(columns={'index': 'Stage'}) stage_totals['Runtime'] =", "above copyright # notice, this list of conditions and the", "RUNTIME_COLUMNS, as_=['Stage', 'runtime_by_stage']) \\ .mark_bar(opacity=0.3) \\ .encode( x=alt.X('runtime_by_stage:Q', bin=alt.Bin(maxbins=100), title='Runtime", "def stage_histogram(d: pd.DataFrame, title: str = '') -> alt.Chart: \"\"\"Plots", "Args: d: A dataframe of runtimes. Returns: An altair chart.", "# Limit columns to greatly reduce the size of the", "of which will be shown as a bar. title: A", "The dataframe grouped by task. \"\"\" by_task = df.groupby(by=['Task']).sum() return", "row per task. \"\"\" df = read_sharded_runtime_tsvs(input_path) df = calculate_totals(df)", "df['total runtime'].apply(format_runtime_string) # Sort by descending total region runtime. df.sort_values(by='total", "vega specs and hook them up to the divs with", "divmod(raw_seconds, 60) hours, minutes = divmod(minutes, 60) seconds = round(seconds,", "long-running regions contribute disproportionately to the overall runtime. That is,", "of altair chart objects. title: The title to show at", "nicely, and sorts by it. Args: df: A dataframe of", "'get reads', 'find candidates', 'make pileup images', 'write outputs' ]", "Build all the charts. charts = make_all_charts(df, by_task) # Write", "region. by_task: A dataframe with one row per task. Returns:", "write_to_html_report( charts=charts, title=title, subtitle=subtitle, html_output=html_output) def main(argv: Sequence[str]): if len(argv)", "chart \"\"\" columns_used = ['region', 'total runtime'] + RUNTIME_COLUMNS +", "be an html file.') RUNTIME_COLUMNS = [ 'get reads', 'find", "TSV file (or sharded files). title: Title to put at", "\"\"\"Plots a histogram of runtimes stacked by stage. Args: d:", "df = df[columns_used] # Brushing on the task_scatter plot highlights", "def individual_region_bars(small_df: pd.DataFrame, title: Union[str, Dict[str, str]] = '') ->", "of the total runtime', axis=alt.Axis(format='%')), tooltip='tooltip', color=alt.condition(brush, 'Task:N', alt.value('lightgray'))).properties( title='Pareto", "for regions in the top 5000') }, { 'id': 'scatter_grid_bottom_99_percent',", "'subtitle': subtitle }) def write_to_html_report(charts: List[Dict[Text, alt.Chart]], title: str, subtitle:", "# 1. Redistributions of source code must retain the above", "3600 subtitle = ( f'Spent {runtime_of_zeros:.2f} hours processing the '", "'total runtime') # Sample the bottom 99% to avoid outliers", "\"\"\"Calculates total runtime, formats it nicely, and sorts by it.", "is a simple sum of the runtime columns. df['total runtime']", "as alt import pandas as pd import tensorflow as tf", "the # documentation and/or other materials provided with the distribution.", "# Add dependencies vega and vega-lite, which render the altair", "at the top of the report. subtitle: The subtitle to", "of the input TSV file (or sharded files). title: Title", "EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,", "OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY", "runtime'] + RUNTIME_COLUMNS + COUNT_COLUMNS d = d[columns_used] return alt.Chart(d).mark_circle(opacity=0.1).encode(", "\"\"\" df = read_sharded_runtime_tsvs(input_path) df = calculate_totals(df) by_task = summarize_by_task(df)", "of regions, each of which will be shown as a", "\\ .repeat( column=['total runtime'] + RUNTIME_COLUMNS, row=COUNT_COLUMNS, ).properties(title=title) def totals_by_stage(d:", "code must retain the above copyright notice, # this list", "Args: small_df: A dataframe of regions, each of which will", "row per region. by_task: A dataframe with one row per", "> 1 else \"\"}') # Write the HTML report with", "# contributors may be used to endorse or promote products", "visualize the runtime-by-region data generated by running make_examples with --runtime_by_region.", "src=\"{}/vega-embed@6\"></script>' '\\n'.format(VEGA_URL)) # Add styles (CSS). html_output.write(CSS_STYLES) html_output.write('</head>\\n<body>') html_output.write('<h1>{}</h1>\\n'.format(title)) html_output.write('<h2>{}</h2>\\n'.format(subtitle))", "A dataframe with one row per task. Returns: list of", "the longest regions are shown. if len(df) > 5000: x", "runtimes of stages versus covariates. Args: d: A pandas dataframe", "is a # trick that causes bundling by task to", "None: \"\"\"Reads data, creates charts, and composes the charts into", "input_path: str) -> Tuple[pd.DataFrame, pd.DataFrame]: \"\"\"Loads data from a file", "of a dataframe containing some specific cumulative sum columns. Returns:", "task'] = df_subset['task total runtime'].apply( format_runtime_string) df_subset['task num examples'] =", "X% of regions account for Y% of the total runtime.\"", "'https://storage.googleapis.com/deepvariant/lib/vega' FLAGS = flags.FLAGS flags.DEFINE_string( 'input', None, 'TSV file that", "- x)]) # Limit columns to greatly reduce the size", "multiple overlapping # points which otherwise make the text look", "chart with runtime of each stage for individual regions. Args:", "examples'] = df_subset['num examples'].sum() # These are cumulative sums for", "a dataframe. Args: df_subset: A dataframe subset of one task.", "runtime'].apply(format_runtime_string) # Sort by descending total region runtime. df.sort_values(by='total runtime',", "into separate lines makes the code more readable. # pylint:", "pd.DataFrame: \"\"\"Groups regions to get the total runtime for each", "account for Y% of the total runtime.\" There is a", "reads', 'find candidates', 'make pileup images', 'write outputs' ] COUNT_COLUMNS", "each stage for individual regions. Args: small_df: A dataframe of", "subtitle = (f'Runtime profiling for make_examples on {len(df)} regions '", "chart. \"\"\" columns_used = RUNTIME_COLUMNS d = d[columns_used] return alt.Chart(d).transform_fold(", "a tooltip description. Args: row: A Pandas Series, one row", "# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR", "/ total_runtime * 100:.2f}% of the total ' f'runtime of", "the output path if that is not already the suffix.", "correlation_scatter_charts( top_5000, title='Trends for regions in the top 5000') },", "{len(by_task)} task{\"(s)\" if len(by_task) > 1 else \"\"}') # Write", "charts.extend([{ 'id': 'histogram_bottom_99_percent', 'chart': stage_histogram( bottom_99_percent, title='Runtime by stage for", "\"\"\"Makes a stacked bar chart with runtime of each stage", "other materials provided with the distribution. # # 3. Neither", "Tuple[pd.DataFrame, pd.DataFrame]: \"\"\"Loads data from a file into one dataframe", "99% to avoid outliers that obscure general trends. bottom_99_percent =", "WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES", "on the task_scatter plot highlights the same tasks in the", "to show at the top of the report. subtitle: The", "'') -> alt.Chart: \"\"\"Produces a grid of scatter plots of", "range(0, n))) df_subset['tooltip'] = df_subset.apply(pareto_by_task_tooltip, axis=1) return df_subset def pareto_and_runtimes_by_task(df:", "{ 'id': 'histogram_top_100', 'chart': stage_histogram( top_100, title='Runtime by stage for", "RUNTIME_COLUMNS + COUNT_COLUMNS d = d[columns_used] return alt.Chart(d).mark_circle(opacity=0.1).encode( x=alt.X(alt.repeat('column'), type='quantitative',", "alt.Chart(d).transform_fold( RUNTIME_COLUMNS, as_=['Stage', 'runtime_by_stage']) \\ .mark_bar().encode( x=alt.X('region:N', sort=None), y=alt.Y('runtime_by_stage:Q', scale=alt.Scale(type='linear'),", "VegaEmbed. html_output.write('<script>\\n') for chart in charts: html_output.write('var spec_{} = {};\\n'.format(chart['id'],", "df.groupby(df['Task'], sort=False) df = grouped.apply(calculate_pareto_metrics) # Sample along the Pareto", "f'Spent {runtime_of_zeros:.2f} hours processing the ' f'{len(regions_with_zero_examples)} regions that produced", "99%') }]) return charts def make_report(input_path: str, title: str, html_output:", "'The longest-running regions that produced no examples', 'subtitle': subtitle })", "columns=['Runtime (seconds)']) stage_totals.reset_index(inplace=True) stage_totals = stage_totals.rename(columns={'index': 'Stage'}) stage_totals['Runtime'] = stage_totals['Runtime", "enables writing to GCS too. html_output = tf.io.gfile.GFile(output_filename, 'w') make_report(", "each curve shows to what extent a small proportion of", "of each stage for individual regions. Args: small_df: A dataframe", "for downloaded image files.') flags.DEFINE_string('output', 'runtime_by_region_report.html', 'Path for the output", "\"\"\"Imports data from a single or sharded path into a", "altair chart \"\"\" columns_used = ['region', 'total runtime'] + RUNTIME_COLUMNS", "df_subset['Runtime for task'] = df_subset['task total runtime'].apply( format_runtime_string) df_subset['task num", "html_output=html_output) html_output.close() # Abstracted out the file open/close to enable", "# are met: # # 1. Redistributions of source code", "= d[columns_used] return alt.Chart(d).transform_fold( RUNTIME_COLUMNS, as_=['Stage', 'runtime_by_stage']) \\ .mark_bar(opacity=0.3) \\", "Add html to the output path if that is not", "Returns: An altair chart. \"\"\" regions_with_zero_examples = df[df['num examples'] ==", "X% of regions', axis=alt.Axis(format='%')), y=alt.Y( 'task cumsum fraction', title='Account for", "by stage. Args: d: A dataframe of runtimes, either by", "column=['total runtime'] + RUNTIME_COLUMNS, row=COUNT_COLUMNS, ).properties(title=title) def totals_by_stage(d: pd.DataFrame) ->", "subtitle to show just below the title on the report.", "/ 2) return individual_region_bars(df.iloc[0:20], 'Top runtime regions') \\ | individual_region_bars(df.iloc[mid-10:mid+11],", "pd.DataFrame, title: Union[str, Dict[str, str]] = '') -> alt.Chart: \"\"\"Makes", "= df_subset['task total runtime'].apply( format_runtime_string) df_subset['task num examples'] = df_subset['num", "a max of 5000 data points. if len(df) <= 5000:", "sum of the runtime columns. df['total runtime'] = df[RUNTIME_COLUMNS].sum(axis=1) #", "copyright holder nor the names of its # contributors may", "divmod(minutes, 60) seconds = round(seconds, 3) output = '' if", "str]] = '') -> alt.Chart: \"\"\"Makes a stacked bar chart", "data generated by running make_examples with --runtime_by_region. \"\"\" from typing", "# chart.mark_bar().encode(...).properties(...), so using backslash # continuation to break this", "for the output report, which will be an html file.')", "def make_all_charts( df: pd.DataFrame, by_task: pd.DataFrame) -> List[Dict[Text, Union[str, alt.Chart]]]:", "bottom_99_percent, title='Runtime by stage for regions in the bottom 99%')", "sort=None), tooltip='Runtime:N' ).properties(title=title) def selected_longest_and_median_regions(df: pd.DataFrame) -> alt.Chart: \"\"\"Creates a", "that produced zero examples. Args: df: A dataframe of all", "pareto_by_task | task_scatter def individual_region_bars(small_df: pd.DataFrame, title: Union[str, Dict[str, str]]", "PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT", "report with all the charts inserted. Args: charts: A list", "\"\"\" columns_used = RUNTIME_COLUMNS d = d[columns_used] return alt.Chart(d).transform_fold( RUNTIME_COLUMNS,", "'Task', 'task total runtime', 'task num examples', 'Runtime for task'", "GCS too. html_output = tf.io.gfile.GFile(output_filename, 'w') make_report( input_path=FLAGS.input, title=FLAGS.title, html_output=html_output)", "TSV file (may be sharded). Returns: df: A dataframe with", "A Pandas Series, one row of a dataframe containing some", "as_=['Stage', 'runtime_by_stage']) \\ .mark_bar().encode( x=alt.X('region:N', sort=None), y=alt.Y('runtime_by_stage:Q', scale=alt.Scale(type='linear'), title='Runtime (seconds)'),", "runtime'].sum() / 3600 subtitle = ( f'Spent {runtime_of_zeros:.2f} hours processing", "pileup images', 'write outputs' ] COUNT_COLUMNS = ['num reads', 'num", "copyright # notice, this list of conditions and the following", "30px; } </style> \"\"\" def read_sharded_runtime_tsvs(path_string: str) -> pd.DataFrame: \"\"\"Imports", "if len(df) <= 5000: # With up to 5000 points,", "the total ' f'runtime of {total_runtime:.2f} hours.') return individual_region_bars( regions_with_zero_examples.nlargest(50,", "specific prior written permission. # # THIS SOFTWARE IS PROVIDED", "num_rows = len(df) mid = round(num_rows / 2) return individual_region_bars(df.iloc[0:20],", "charts def make_report(input_path: str, title: str, html_output: tf.io.gfile.GFile) -> None:", "Returns: A string to show as the tooltip for a", "= '') -> alt.Chart: \"\"\"Plots a histogram of runtimes stacked", "profiling for make_examples on {len(df)} regions ' f'across {len(by_task)} task{\"(s)\"", "curve for each task').interactive() # This chart needs to use", "title: A title for the plot. If a dict, it", "runtimes. Tracing each curve shows to what extent a small", "should contain 'title' and/or 'subtitle'. Returns: An altair chart. \"\"\"", "= len(df) mid = round(num_rows / 2) return individual_region_bars(df.iloc[0:20], 'Top", "axis=alt.Axis(format='%')), tooltip='tooltip', color=alt.condition(brush, 'Task:N', alt.value('lightgray'))).properties( title='Pareto curve for each task').interactive()", "= small_df[columns_used] return alt.Chart(d).transform_fold( RUNTIME_COLUMNS, as_=['Stage', 'runtime_by_stage']) \\ .mark_bar().encode( x=alt.X('region:N',", "contribute disproportionately to the overall runtime. That is, \"The longest-running", "task. Args: df: A dataframe of runtime profiling numbers. Returns:", "chart. \"\"\" stage_totals_series = d.sum()[RUNTIME_COLUMNS] stage_totals = pd.DataFrame( stage_totals_series, columns=['Runtime", "html_output: a writable file object. Returns: None. Writes into the", "axis=1) return df_subset def pareto_and_runtimes_by_task(df: pd.DataFrame) -> alt.Chart: \"\"\"Creates an", "charts inserted. Args: charts: A list of altair chart objects.", "\"The longest-running X% of regions account for Y% of the", "list_of_dataframes.append(d) return pd.concat(list_of_dataframes, axis=0, ignore_index=True) def format_runtime_string(raw_seconds: float) -> str:", "LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS", "chart needs to use the same dataframe as the first", "# Sort by descending total region runtime. df.sort_values(by='total runtime', inplace=True,", "runtime') if len(bottom_99_percent) > 5000: bottom_99_percent = bottom_99_percent.sample(5000) charts.extend([{ 'id':", "html_output.close() # Abstracted out the file open/close to enable testing.", "to enable the # brushing on one to affect the", "'chart': stage_histogram( bottom_99_percent, title='Runtime by stage for regions in the", "obscure general trends. bottom_99_percent = df.nsmallest(int(len(df) * .99), 'total runtime')", "their ID names. Args: df: A dataframe with one row", "no examples', 'subtitle': subtitle }) def write_to_html_report(charts: List[Dict[Text, alt.Chart]], title:", ").properties(title=title) def selected_longest_and_median_regions(df: pd.DataFrame) -> alt.Chart: \"\"\"Creates a stacked bar", "df.nlargest(5000, 'total runtime') # Sample the bottom 99% to avoid", "+= f'{int(hours)}h' if minutes > 0: output += f'{int(minutes)}m' if", "i, path in enumerate(paths): if path.startswith('gs://'): # Once pandas is", "conditions and the following disclaimer. # # 2. Redistributions in", "# curve. brush = alt.selection_interval() pareto_by_task = alt.Chart(df).mark_line(size=2).encode( x=alt.X( 'task", "open/close to enable testing. print('Output written to:', output_filename) if __name__", "all regions. Returns: An altair chart. \"\"\" num_rows = len(df)", "title='Runtime (seconds)'), y=alt.Y('count()', title='Count of regions', stack=None), color=alt.Color('Stage:N', sort=None) ).properties(title=title)", "plot. Returns: An altair chart \"\"\" columns_used = ['region', 'total", "'runtime_by_stage']) \\ .mark_bar().encode( x=alt.X('region:N', sort=None), y=alt.Y('runtime_by_stage:Q', scale=alt.Scale(type='linear'), title='Runtime (seconds)'), fill=alt.Fill('Stage:N',", "altair chart objects. title: The title to show at the", ".mark_bar().encode( x=alt.X('region:N', sort=None), y=alt.Y('runtime_by_stage:Q', scale=alt.Scale(type='linear'), title='Runtime (seconds)'), fill=alt.Fill('Stage:N', sort=None), tooltip='Runtime:N'", "alt.Chart: \"\"\"Makes a stacked bar chart with runtime of each", "5000: # With up to 5000 points, just show them", "format_runtime_string) return alt.Chart(stage_totals).mark_bar().encode( x='Runtime (seconds)', y=alt.Y('Stage', sort=None), tooltip=['Runtime'], fill=alt.Fill('Stage', sort=None)).properties(title='Overall", "cumulative sums for the pareto curves: df_subset['task cumsum fraction'] =", "more readable. # pylint: disable=g-backslash-continuation VEGA_URL = 'https://storage.googleapis.com/deepvariant/lib/vega' FLAGS =", "of one task. Returns: The same dataframe subset with some", "DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING,", "with the distribution. # # 3. Neither the name of", "sharded, e.g. /path/runtime@64.tsv.') flags.DEFINE_string( 'title', None, 'Title will be shown", "OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT", "'title' and/or 'subtitle'. Returns: An altair chart. \"\"\" columns_used =", "render the altair charts. html_output.write('<script type=\"text/javascript\" src=\"{}/vega@5\"></script>' '\\n'.format(VEGA_URL)) html_output.write( '<script", "''.format(str(argv[1:]))) # Add html to the output path if that", "disable=g-backslash-continuation VEGA_URL = 'https://storage.googleapis.com/deepvariant/lib/vega' FLAGS = flags.FLAGS flags.DEFINE_string( 'input', None,", "}, { 'id': 'histogram_top_100', 'chart': stage_histogram( top_100, title='Runtime by stage", "Sequence, List, Tuple, Text, Any, Union from absl import app", "zero examples. Args: df: A dataframe of all regions. Returns:", "' 'be used as a prefix for downloaded image files.')", "the bottom 99%') }]) return charts def make_report(input_path: str, title:", "# Write the HTML report with all the charts. write_to_html_report(", "{ 'id': 'selected_longest_and_median_regions', 'chart': selected_longest_and_median_regions(df) }, { 'id': 'zero_examples', 'chart':", "lot of method chaining, such as # chart.mark_bar().encode(...).properties(...), so using", "descriptive ID. \"\"\" charts = [{ 'id': 'total_by_stage', 'chart': totals_by_stage(by_task)", "title: str, html_output: tf.io.gfile.GFile) -> None: \"\"\"Reads data, creates charts,", "df_subset['task total runtime'] = df_subset['total runtime'].sum() df_subset['Runtime for task'] =", "\"\"\" columns_used = ['region', 'total runtime'] + RUNTIME_COLUMNS + COUNT_COLUMNS", "summary columns. \"\"\" # 'total runtime' is a simple sum", "def calculate_pareto_metrics(df_subset: pd.DataFrame) -> pd.DataFrame: \"\"\"Calculates cumulative sums for a", "= df['total runtime'].sum() / 3600 subtitle = ( f'Spent {runtime_of_zeros:.2f}", "the scatter plot: df_subset['task total runtime'] = df_subset['total runtime'].sum() df_subset['Runtime", "y=alt.Y('count()', title='Count of regions', stack=None), color=alt.Color('Stage:N', sort=None) ).properties(title=title) def correlation_scatter_charts(d:", "runtime', inplace=True, ascending=False) return df def summarize_by_task(df: pd.DataFrame) -> pd.DataFrame:", "Abstracted out the file open/close to enable testing. print('Output written", "a nice format string from a potentially large number of", "description. Args: row: A Pandas Series, one row of a", "'task cumsum order', title='The longest-runtime X% of regions', axis=alt.Axis(format='%')), y=alt.Y(", "Write the HTML report with all the charts. write_to_html_report( charts=charts,", "df[df['num examples'] == 0] runtime_of_zeros = regions_with_zero_examples['total runtime'].sum() / 3600", "(seconds)'), fill=alt.Fill('Stage:N', sort=None), tooltip='Runtime:N' ).properties(title=title) def selected_longest_and_median_regions(df: pd.DataFrame) -> alt.Chart:", "output_filename = f'{FLAGS.output}.html' # Start HTML document. Using GFile enables", "Create a formatted runtime string for tooltips. df['Runtime'] = df['total", "OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE", "title: The title to show at the top of the", "INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF", "ID names. Args: df: A dataframe with one row per", "regions_with_zero_examples['total runtime'].sum() / 3600 total_runtime = df['total runtime'].sum() / 3600", "Tuple, Text, Any, Union from absl import app from absl", "+= f'{seconds}s' return output def calculate_totals(df: pd.DataFrame) -> pd.DataFrame: \"\"\"Calculates", "A dataframe of runtime profiling numbers. Returns: The dataframe grouped", "fraction'] = df_subset['total runtime'].cumsum( ) / df_subset['total runtime'].sum() n =", "Dict[str, str]] = '') -> alt.Chart: \"\"\"Makes a stacked bar", "into one dataframe as-is and one by task. Args: input_path:", "to show trends better. top_100 = df.nlargest(100, 'total runtime') top_5000", "charts.extend([{ 'id': 'histogram', 'chart': stage_histogram(df, title='Runtime by stage for all", "HTML document. Using GFile enables writing to GCS too. html_output", "num examples'] = df_subset['num examples'].sum() # These are cumulative sums", "d = d[columns_used] return alt.Chart(d).mark_circle(opacity=0.1).encode( x=alt.X(alt.repeat('column'), type='quantitative', axis=alt.Axis(labelExpr=\"datum.value + 's'\")),", "pareto_by_task_tooltip(row: pd.Series) -> str: \"\"\"For one row of a dataframe,", "len(by_task) > 1 else \"\"}') # Write the HTML report", "str, title: str, html_output: tf.io.gfile.GFile) -> None: \"\"\"Reads data, creates", "sharded. Returns: A dataframe matching the TSV file(s) but with", "all regions') }]) else: # With too many points, make", "OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER", "return individual_region_bars( regions_with_zero_examples.nlargest(50, 'total runtime'), title={ 'text': 'The longest-running regions", "creates charts, and composes the charts into an HTML report.", "regions. Returns: An altair chart. \"\"\" regions_with_zero_examples = df[df['num examples']", "general trends. bottom_99_percent = df.nsmallest(int(len(df) * .99), 'total runtime') if", "df[RUNTIME_COLUMNS].sum(axis=1) # Create a formatted runtime string for tooltips. df['Runtime']", "\"\"\" if sharded_file_utils.is_sharded_file_spec(path_string): paths = sharded_file_utils.generate_sharded_filenames(path_string) else: paths = [path_string]", "from third_party.nucleus.io import sharded_file_utils # Altair uses a lot of", "dataframe grouped by task. \"\"\" by_task = df.groupby(by=['Task']).sum() return by_task.reset_index()", "profiling numbers. Returns: The same dataframe with some additional summary", "df_subset['task cumsum fraction'] = df_subset['total runtime'].cumsum( ) / df_subset['total runtime'].sum()", "a curve for each task. Args: df: A dataframe of", "df.sort_values(by='total runtime', inplace=True, ascending=False) return df def summarize_by_task(df: pd.DataFrame) ->", "# notice, this list of conditions and the following disclaimer", "used as a prefix for downloaded image files.') flags.DEFINE_string('output', 'runtime_by_region_report.html',", "That is, \"The longest-running X% of regions account for Y%", "{ 'id': 'zero_examples', 'chart': top_regions_producing_zero_examples(df) }] # Altair shows a", "(drag to highlight)') \\ .add_selection(brush) return pareto_by_task | task_scatter def", "dataframe with one row per task. \"\"\" df = read_sharded_runtime_tsvs(input_path)", "html_output.write('var spec_{} = {};\\n'.format(chart['id'], chart['chart'].to_json())) download_filename = '{}_{}'.format(title.replace(' ', '_'),", "# Altair shows a max of 5000 data points. if", "in charts: html_output.write('var spec_{} = {};\\n'.format(chart['id'], chart['chart'].to_json())) download_filename = '{}_{}'.format(title.replace('", "* 100:.2f}% of regions \" f\"account for {row['task cumsum fraction']", "too. html_output = tf.io.gfile.GFile(output_filename, 'w') make_report( input_path=FLAGS.input, title=FLAGS.title, html_output=html_output) html_output.close()", "html_output.write( '<script type=\"text/javascript\" src=\"{}/vega-lite@4.8.1\"></script>' '\\n'.format(VEGA_URL)) html_output.write( '<script type=\"text/javascript\" src=\"{}/vega-embed@6\"></script>' '\\n'.format(VEGA_URL))", "out the file open/close to enable testing. print('Output written to:',", "subtitle=subtitle, html_output=html_output) def main(argv: Sequence[str]): if len(argv) > 1: raise", "AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN", "cumulative sums for a subset of a dataframe. Args: df_subset:", "and will ' 'be used as a prefix for downloaded", "and one by task. Args: input_path: str, path of the", "1 else \"\"}') # Write the HTML report with all", "None: \"\"\"Makes the html report with all the charts inserted.", "-> alt.Chart: \"\"\"Produces a grid of scatter plots of runtimes", "ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY,", "bottom 99% to avoid outliers that obscure general trends. bottom_99_percent", "tooltip=['Task', 'Runtime for task'] ) \\ .properties(title='Total runtime for each", "type=\"text/javascript\" src=\"{}/vega-embed@6\"></script>' '\\n'.format(VEGA_URL)) # Add styles (CSS). html_output.write(CSS_STYLES) html_output.write('</head>\\n<body>') html_output.write('<h1>{}</h1>\\n'.format(title))", "the title on the report. html_output: a writable file object.", "sharded_file_utils # Altair uses a lot of method chaining, such", "ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT", "of dicts, each containing a chart and a descriptive ID.", "disproportionately to the overall runtime. That is, \"The longest-running X%", "num examples', 'Runtime for task' ] df = df[columns_used] #", "0 or not output: output += f'{seconds}s' return output def", "\" f\"account for {row['task cumsum fraction'] * 100:.2f}% of \"", "covariates. Args: d: A pandas dataframe of runtime by regions.", "document. html_output.write('</body></html>') def read_data_and_make_dataframes( input_path: str) -> Tuple[pd.DataFrame, pd.DataFrame]: \"\"\"Loads", "of a dataframe. Args: df_subset: A dataframe subset of one", "df = grouped.apply(calculate_pareto_metrics) # Sample along the Pareto curve, ensuring", "str: \"\"\"Creates a nice format string from a potentially large", "data, creates charts, and composes the charts into an HTML", "'make pileup images', 'write outputs' ] COUNT_COLUMNS = ['num reads',", "stage') def pareto_by_task_tooltip(row: pd.Series) -> str: \"\"\"For one row of", "enable testing. print('Output written to:', output_filename) if __name__ == '__main__':", "as f: d = pd.read_csv(f, sep='\\t') else: d = pd.read_csv(path,", "IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"", "the runtime-by-region data generated by running make_examples with --runtime_by_region. \"\"\"", "stats. subtitle = (f'Runtime profiling for make_examples on {len(df)} regions", "endorse or promote products derived from this # software without", "regions ' f'across {len(by_task)} task{\"(s)\" if len(by_task) > 1 else", "Returns: An altair chart. \"\"\" columns_used = RUNTIME_COLUMNS d =", "running make_examples with --runtime_by_region. \"\"\" from typing import Dict, Sequence,", "tensorflow as tf from third_party.nucleus.io import sharded_file_utils # Altair uses", "the input file, which may be sharded. Returns: A dataframe", "by task. \"\"\" by_task = df.groupby(by=['Task']).sum() return by_task.reset_index() def stage_histogram(d:", "cumsum fraction'] * 100:.2f}% of \" f\"the runtime in task", "len(df) > 5000: x = 1000 df = pd.concat([df.nlargest(x, 'total", "Returns: An altair chart. \"\"\" stage_totals_series = d.sum()[RUNTIME_COLUMNS] stage_totals =", "= 1000 df = pd.concat([df.nlargest(x, 'total runtime'), df.sample(5000 - x)])", "spec_{}, {})\\n'.format( chart['id'], chart['id'], embed_options)) html_output.write('</script>\\n') # Close HTML document.", "def totals_by_stage(d: pd.DataFrame) -> alt.Chart: \"\"\"Plots total runtimes for each", "A dataframe of runtimes. Returns: An altair chart. \"\"\" stage_totals_series", "html_output.write('vegaEmbed(\"#vis_{}\", spec_{}, {})\\n'.format( chart['id'], chart['id'], embed_options)) html_output.write('</script>\\n') # Close HTML", "an html file.') RUNTIME_COLUMNS = [ 'get reads', 'find candidates',", "of examples'), color=alt.condition(brush, 'Task:N', alt.value('lightgray')), tooltip=['Task', 'Runtime for task'] )", "BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY", "its # contributors may be used to endorse or promote", "for gs:// # without this workaround. with tf.io.gfile.GFile(path) as f:", "'') -> alt.Chart: \"\"\"Plots a histogram of runtimes stacked by", "= d.sum()[RUNTIME_COLUMNS] stage_totals = pd.DataFrame( stage_totals_series, columns=['Runtime (seconds)']) stage_totals.reset_index(inplace=True) stage_totals", "html_output: tf.io.gfile.GFile) -> None: \"\"\"Reads data, creates charts, and composes", "0: output += f'{int(minutes)}m' if seconds > 0 or not", "SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS", "into the html_output file object. \"\"\" # Start the HTML", "-> pd.DataFrame: \"\"\"Calculates cumulative sums for a subset of a", "(INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT", "of its # contributors may be used to endorse or", "def correlation_scatter_charts(d: pd.DataFrame, title: str = '') -> alt.Chart: \"\"\"Produces", "df def summarize_by_task(df: pd.DataFrame) -> pd.DataFrame: \"\"\"Groups regions to get", "each task. Args: df: A dataframe of runtime profiling numbers.", "that produced no examples, ' f'which is {runtime_of_zeros / total_runtime", ".add_selection(brush) return pareto_by_task | task_scatter def individual_region_bars(small_df: pd.DataFrame, title: Union[str,", "}) def write_to_html_report(charts: List[Dict[Text, alt.Chart]], title: str, subtitle: str, html_output:", "sort=False) df = grouped.apply(calculate_pareto_metrics) # Sample along the Pareto curve,", "THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A", "curve, ensuring the longest regions are shown. if len(df) >", "hook them up to the divs with VegaEmbed. html_output.write('<script>\\n') for", "# Create a formatted runtime string for tooltips. df['Runtime'] =", "CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF #", "OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON", "for each stage. Args: d: A dataframe of runtimes. Returns:", "title: str = '') -> alt.Chart: \"\"\"Produces a grid of", "with one row per task. Returns: list of dicts, each", "format_runtime_string(raw_seconds: float) -> str: \"\"\"Creates a nice format string from", "\"\"\"Creates charts and puts them in a list with their", "must retain the above copyright notice, # this list of", "title for the plot. Returns: An altair chart. \"\"\" columns_used", "pd.DataFrame: \"\"\"Calculates total runtime, formats it nicely, and sorts by", "title='Runtime (seconds)'), y=alt.Y('task num examples:Q', title='Number of examples'), color=alt.condition(brush, 'Task:N',", "\"\"\" # 'total runtime' is a simple sum of the", "files). title: Title to put at the top of the", "row=COUNT_COLUMNS, ).properties(title=title) def totals_by_stage(d: pd.DataFrame) -> alt.Chart: \"\"\"Plots total runtimes", "writing to GCS too. html_output = tf.io.gfile.GFile(output_filename, 'w') make_report( input_path=FLAGS.input,", "pd.DataFrame) -> alt.Chart: \"\"\"Creates a stacked bar charts of the", "# POSSIBILITY OF SUCH DAMAGE. r\"\"\"Create a visual report of", "to affect the other. Using max(task) for 'text' is a", "region runtime. df.sort_values(by='total runtime', inplace=True, ascending=False) return df def summarize_by_task(df:", "arguments, but found these extra arguments: \"{}\".' ''.format(str(argv[1:]))) # Add", "individual_region_bars( regions_with_zero_examples.nlargest(50, 'total runtime'), title={ 'text': 'The longest-running regions that", "data from a single or sharded path into a pandas", "not accept ' 'positional arguments, but found these extra arguments:", "import sharded_file_utils # Altair uses a lot of method chaining,", "same dataframe subset with some additional columns. \"\"\" # These", "provided with the distribution. # # 3. Neither the name", "pd.DataFrame) -> alt.Chart: \"\"\"Creates a chart of the top regions", ".properties(title='Total runtime for each task (drag to highlight)') \\ .add_selection(brush)", "data from a file into one dataframe as-is and one", "calculate_pareto_metrics(df_subset: pd.DataFrame) -> pd.DataFrame: \"\"\"Calculates cumulative sums for a subset", "and a descriptive ID. \"\"\" charts = [{ 'id': 'total_by_stage',", "0] runtime_of_zeros = regions_with_zero_examples['total runtime'].sum() / 3600 total_runtime = df['total", "html_output.write('</div>') # Add JSON vega specs and hook them up", "# Write a subtitle with some top-level stats. subtitle =", "fraction', title='Account for Y% of the total runtime', axis=alt.Axis(format='%')), tooltip='tooltip',", "if seconds > 0 or not output: output += f'{seconds}s'", "total region runtime. df.sort_values(by='total runtime', inplace=True, ascending=False) return df def", "= divmod(raw_seconds, 60) hours, minutes = divmod(minutes, 60) seconds =", "df_subset['task total runtime'].apply( format_runtime_string) df_subset['task num examples'] = df_subset['num examples'].sum()", "longest-runtime X% of regions', axis=alt.Axis(format='%')), y=alt.Y( 'task cumsum fraction', title='Account", "examples, ' f'which is {runtime_of_zeros / total_runtime * 100:.2f}% of", "object where output will be written. \"\"\" # Load data", "Args: path_string: The path to the input file, which may", "up to 5000 points, just show them all. charts.extend([{ 'id':", "list with their ID names. Args: df: A dataframe with", "remaining seconds, formatted nicely. For example, 2h3m5.012s. \"\"\" minutes, seconds", "stage_totals = pd.DataFrame( stage_totals_series, columns=['Runtime (seconds)']) stage_totals.reset_index(inplace=True) stage_totals = stage_totals.rename(columns={'index':", "containing all the charts. html_output.write('<div>') for chart in charts: html_output.write(", "x=alt.X('max(task total runtime)', title='Runtime (seconds)'), y=alt.Y('task num examples:Q', title='Number of", "lines makes the code more readable. # pylint: disable=g-backslash-continuation VEGA_URL", "plot highlights the same tasks in the Pareto # curve.", "runtime profiling numbers. Returns: The same dataframe with some additional", "minutes > 0: output += f'{int(minutes)}m' if seconds > 0", "n, range(0, n))) df_subset['tooltip'] = df_subset.apply(pareto_by_task_tooltip, axis=1) return df_subset def", "file open/close to enable testing. print('Output written to:', output_filename) if", "to get the total runtime for each task. Args: df:", "runtime'), df.sample(5000 - x)]) # Limit columns to greatly reduce", "a div containing all the charts. html_output.write('<div>') for chart in", "(or sharded files). title: Title to put at the top", "regions that produced no examples', 'subtitle': subtitle }) def write_to_html_report(charts:", "Make a div containing all the charts. html_output.write('<div>') for chart", "outputs' ] COUNT_COLUMNS = ['num reads', 'num candidates', 'num examples']", "in task {row['Task']}\") def calculate_pareto_metrics(df_subset: pd.DataFrame) -> pd.DataFrame: \"\"\"Calculates cumulative", "'Top runtime regions') \\ | individual_region_bars(df.iloc[mid-10:mid+11], 'Median runtime regions') def", "not already the suffix. if FLAGS.output.endswith('html'): output_filename = FLAGS.output else:", "' 'with --runtime_by_region. Can be sharded, e.g. /path/runtime@64.tsv.') flags.DEFINE_string( 'title',", "COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT,", "'s'\")), y=alt.Y(alt.repeat('row'), type='quantitative'), tooltip='region' ).properties(width=100, height=100) \\ .repeat( column=['total runtime']", "on one to affect the other. Using max(task) for 'text'", "of runtimes stacked by stage. Args: d: A dataframe of", "if len(bottom_99_percent) > 5000: bottom_99_percent = bottom_99_percent.sample(5000) charts.extend([{ 'id': 'histogram_bottom_99_percent',", "pd.Series) -> str: \"\"\"For one row of a dataframe, computes", "individual regions. Args: small_df: A dataframe of regions, each of", "def make_report(input_path: str, title: str, html_output: tf.io.gfile.GFile) -> None: \"\"\"Reads", "it nicely, and sorts by it. Args: df: A dataframe", "third_party.nucleus.io import sharded_file_utils # Altair uses a lot of method", "in the bottom 99%') }]) return charts def make_report(input_path: str,", "title=FLAGS.title, html_output=html_output) html_output.close() # Abstracted out the file open/close to", "the same tasks in the Pareto # curve. brush =", "input_path: str, path of the input TSV file (may be", "row: A Pandas Series, one row of a dataframe containing", "list_of_dataframes = [] for i, path in enumerate(paths): if path.startswith('gs://'):", "AND CONTRIBUTORS \"AS IS\" # AND ANY EXPRESS OR IMPLIED", "the input TSV file (or sharded files). title: Title to", "= ['region', 'total runtime'] + RUNTIME_COLUMNS + COUNT_COLUMNS d =", "form must reproduce the above copyright # notice, this list", "# continuation to break this into separate lines makes the", "i list_of_dataframes.append(d) return pd.concat(list_of_dataframes, axis=0, ignore_index=True) def format_runtime_string(raw_seconds: float) ->", "return df def summarize_by_task(df: pd.DataFrame) -> pd.DataFrame: \"\"\"Groups regions to", "html_output.write('</head>\\n<body>') html_output.write('<h1>{}</h1>\\n'.format(title)) html_output.write('<h2>{}</h2>\\n'.format(subtitle)) # Make a div containing all the", "Add styles (CSS). html_output.write(CSS_STYLES) html_output.write('</head>\\n<body>') html_output.write('<h1>{}</h1>\\n'.format(title)) html_output.write('<h2>{}</h2>\\n'.format(subtitle)) # Make a", "# points which otherwise make the text look funky. task_scatter", "if hours > 0: output += f'{int(hours)}h' if minutes >", "df.groupby(by=['Task']).sum() return by_task.reset_index() def stage_histogram(d: pd.DataFrame, title: str = '')", "def summarize_by_task(df: pd.DataFrame) -> pd.DataFrame: \"\"\"Groups regions to get the", "'id': 'histogram_bottom_99_percent', 'chart': stage_histogram( bottom_99_percent, title='Runtime by stage for regions", "by task. title: A title for the plot. Returns: An", "it should contain 'title' and/or 'subtitle'. Returns: An altair chart.", "title on the report. html_output: a writable file object. Returns:", "Args: input_path: str, path of the input TSV file (may", "for regions in the bottom 99%') }]) return charts def", "from absl import flags import altair as alt import pandas", "height=100) \\ .repeat( column=['total runtime'] + RUNTIME_COLUMNS, row=COUNT_COLUMNS, ).properties(title=title) def", "app from absl import flags import altair as alt import", "to what extent a small proportion of long-running regions contribute", "to show just below the title on the report. html_output:", "show just below the title on the report. html_output: a", "grid of scatter plots of runtimes of stages versus covariates.", "input file, which may be sharded. Returns: A dataframe matching", "embed_options)) html_output.write('</script>\\n') # Close HTML document. html_output.write('</body></html>') def read_data_and_make_dataframes( input_path:", "'id': 'scatter_grid_bottom_99_percent', 'chart': correlation_scatter_charts( bottom_99_percent, title='Trends for regions in the", "grouped.apply(calculate_pareto_metrics) # Sample along the Pareto curve, ensuring the longest", "-> alt.Chart: \"\"\"Creates an interactive Pareto curve and scatter plot", "seconds = round(seconds, 3) output = '' if hours >", "into a pandas dataframe. Args: path_string: The path to the", "\\ .properties(title='Total runtime for each task (drag to highlight)') \\", "seconds = divmod(raw_seconds, 60) hours, minutes = divmod(minutes, 60) seconds", "file object where output will be written. \"\"\" # Load", "one row of a dataframe, computes a tooltip description. Args:", "each containing a chart and a descriptive ID. \"\"\" charts", "\"AS IS\" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,", "at the top of the report and will ' 'be", "chart. \"\"\" grouped = df.groupby(df['Task'], sort=False) df = grouped.apply(calculate_pareto_metrics) #", "bundling by task to avoid showing multiple overlapping # points", "of scatter plots of runtimes of stages versus covariates. Args:", "the pareto curves: df_subset['task cumsum fraction'] = df_subset['total runtime'].cumsum( )", "sharded_file_utils.is_sharded_file_spec(path_string): paths = sharded_file_utils.generate_sharded_filenames(path_string) else: paths = [path_string] list_of_dataframes =", "one to affect the other. Using max(task) for 'text' is", "tooltip=['Runtime'], fill=alt.Fill('Stage', sort=None)).properties(title='Overall runtime by stage') def pareto_by_task_tooltip(row: pd.Series) ->", "of the report. html_output: Writable file object where output will", "promote products derived from this # software without specific prior", "return individual_region_bars(df.iloc[0:20], 'Top runtime regions') \\ | individual_region_bars(df.iloc[mid-10:mid+11], 'Median runtime", "CONTRIBUTORS \"AS IS\" # AND ANY EXPRESS OR IMPLIED WARRANTIES,", "needs to use the same dataframe as the first chart", "# With up to 5000 points, just show them all.", "Limit columns to greatly reduce the size of the html", "of the total ' f'runtime of {total_runtime:.2f} hours.') return individual_region_bars(", "task. Returns: list of dicts, each containing a chart and", "suffix. if FLAGS.output.endswith('html'): output_filename = FLAGS.output else: output_filename = f'{FLAGS.output}.html'", "absl import app from absl import flags import altair as", "f'{FLAGS.output}.html' # Start HTML document. Using GFile enables writing to", "print('Output written to:', output_filename) if __name__ == '__main__': flags.mark_flags_as_required(['input', 'title'])", "prefix for downloaded image files.') flags.DEFINE_string('output', 'runtime_by_region_report.html', 'Path for the", "FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL", "[ 'get reads', 'find candidates', 'make pileup images', 'write outputs'", "Series, one row of a dataframe containing some specific cumulative", "= df[columns_used] # Brushing on the task_scatter plot highlights the", "# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR", "\" f\"the runtime in task {row['Task']}\") def calculate_pareto_metrics(df_subset: pd.DataFrame) ->", "df_subset['total runtime'].sum() df_subset['Runtime for task'] = df_subset['task total runtime'].apply( format_runtime_string)", "all regions') }, { 'id': 'scatter_grid', 'chart': correlation_scatter_charts(df, title='Trends for", "are cumulative sums for the pareto curves: df_subset['task cumsum fraction']", "# Load data into pandas dataframes and add summary columns.", "# With too many points, make different subsets to show", "input TSV file (or sharded files). title: Title to put", "df = read_sharded_runtime_tsvs(input_path) df = calculate_totals(df) by_task = summarize_by_task(df) return", "the top 5000') }, { 'id': 'scatter_grid_bottom_99_percent', 'chart': correlation_scatter_charts( bottom_99_percent,", "0: output += f'{int(hours)}h' if minutes > 0: output +=", "The same dataframe subset with some additional columns. \"\"\" #", "A number of seconds. Returns: The seconds divided into hours,", "of stages versus covariates. Args: d: A pandas dataframe of", "df, by_task def make_all_charts( df: pd.DataFrame, by_task: pd.DataFrame) -> List[Dict[Text,", "d[columns_used] return alt.Chart(d).mark_circle(opacity=0.1).encode( x=alt.X(alt.repeat('column'), type='quantitative', axis=alt.Axis(labelExpr=\"datum.value + 's'\")), y=alt.Y(alt.repeat('row'), type='quantitative'),", "vega-lite, which render the altair charts. html_output.write('<script type=\"text/javascript\" src=\"{}/vega@5\"></script>' '\\n'.format(VEGA_URL))", "subsets to show trends better. top_100 = df.nlargest(100, 'total runtime')", "x='Runtime (seconds)', y=alt.Y('Stage', sort=None), tooltip=['Runtime'], fill=alt.Fill('Stage', sort=None)).properties(title='Overall runtime by stage')", "html_output.write( '<script type=\"text/javascript\" src=\"{}/vega-embed@6\"></script>' '\\n'.format(VEGA_URL)) # Add styles (CSS). html_output.write(CSS_STYLES)", "= RUNTIME_COLUMNS d = d[columns_used] return alt.Chart(d).transform_fold( RUNTIME_COLUMNS, as_=['Stage', 'runtime_by_stage'])", "df = calculate_totals(df) by_task = summarize_by_task(df) return df, by_task def", "IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE", "or without # modification, are permitted provided that the following", "runtime columns. df['total runtime'] = df[RUNTIME_COLUMNS].sum(axis=1) # Create a formatted", "altair chart. \"\"\" stage_totals_series = d.sum()[RUNTIME_COLUMNS] stage_totals = pd.DataFrame( stage_totals_series,", "Args: df: A dataframe of runtime profiling numbers. Returns: The", "totals_by_stage(by_task) }, { 'id': 'pareto_and_runtimes_by_task', 'chart': pareto_and_runtimes_by_task(df) }, { 'id':", "dataframe of all regions. Returns: An altair chart. \"\"\" grouped", "SUCH DAMAGE. r\"\"\"Create a visual report of make_examples runtime by", "= {};\\n'.format(chart['id'], chart['chart'].to_json())) download_filename = '{}_{}'.format(title.replace(' ', '_'), chart['id']) embed_options", "for a subset of a dataframe. Args: df_subset: A dataframe", "d: A dataframe of runtimes. Returns: An altair chart. \"\"\"", "runtime'].cumsum( ) / df_subset['total runtime'].sum() n = len(df_subset) df_subset['task cumsum", "examples. Args: df: A dataframe of all regions. Returns: An", "stage_totals.reset_index(inplace=True) stage_totals = stage_totals.rename(columns={'index': 'Stage'}) stage_totals['Runtime'] = stage_totals['Runtime (seconds)'].apply( format_runtime_string)", "USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED", "per task. Returns: list of dicts, each containing a chart", "to the input file, which may be sharded. Returns: A", "class=\"chart-container\" id=\"vis_{}\"></div>\\n'.format(chart['id'])) html_output.write('</div>') # Add JSON vega specs and hook", "RUNTIME_COLUMNS d = small_df[columns_used] return alt.Chart(d).transform_fold( RUNTIME_COLUMNS, as_=['Stage', 'runtime_by_stage']) \\", "proportion of long-running regions contribute disproportionately to the overall runtime.", "dataframe of runtime profiling numbers. Returns: The same dataframe with", "{};\\n'.format(chart['id'], chart['chart'].to_json())) download_filename = '{}_{}'.format(title.replace(' ', '_'), chart['id']) embed_options =", "runtime') top_5000 = df.nlargest(5000, 'total runtime') # Sample the bottom", "will be an html file.') RUNTIME_COLUMNS = [ 'get reads',", "regions in the top 5000') }, { 'id': 'scatter_grid_bottom_99_percent', 'chart':", "dataframes and add summary columns. df, by_task = read_data_and_make_dataframes(input_path) #", "5000: x = 1000 df = pd.concat([df.nlargest(x, 'total runtime'), df.sample(5000", "as # chart.mark_bar().encode(...).properties(...), so using backslash # continuation to break", "bottom_99_percent = df.nsmallest(int(len(df) * .99), 'total runtime') if len(bottom_99_percent) >", "# Copyright 2020 Google LLC. # # Redistribution and use", "max of 5000 data points. if len(df) <= 5000: #", "line parsing failure: this script does not accept ' 'positional", "make_report( input_path=FLAGS.input, title=FLAGS.title, html_output=html_output) html_output.close() # Abstracted out the file", "all the charts. html_output.write('<div>') for chart in charts: html_output.write( '<div", "each task. Args: df: A dataframe of all regions. Returns:", "of seconds. Returns: The seconds divided into hours, minutes, and", "A list of altair chart objects. title: The title to", "3. Neither the name of the copyright holder nor the", "THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE", "raise app.UsageError( 'Command line parsing failure: this script does not", "as the first chart to enable the # brushing on", "Returns: An altair chart. \"\"\" grouped = df.groupby(df['Task'], sort=False) df", "summary columns. df, by_task = read_data_and_make_dataframes(input_path) # Build all the", "pd.DataFrame, title: str = '') -> alt.Chart: \"\"\"Produces a grid", "one row of a dataframe containing some specific cumulative sum", "for each task').interactive() # This chart needs to use the", "-> alt.Chart: \"\"\"Plots total runtimes for each stage. Args: d:", "testing. print('Output written to:', output_filename) if __name__ == '__main__': flags.mark_flags_as_required(['input',", "top_100, title='Runtime by stage for regions in the top 100')", "Union from absl import app from absl import flags import", "produced zero examples. Args: df: A dataframe of all regions.", "top of the report. html_output: Writable file object where output", "(CSS). html_output.write(CSS_STYLES) html_output.write('</head>\\n<body>') html_output.write('<h1>{}</h1>\\n'.format(title)) html_output.write('<h2>{}</h2>\\n'.format(subtitle)) # Make a div containing", "formatted runtime string for tooltips. df['Runtime'] = df['total runtime'].apply(format_runtime_string) #", "report and will ' 'be used as a prefix for", "Args: input_path: Path of the input TSV file (or sharded", "from this # software without specific prior written permission. #", "runtimes for each stage. Args: d: A dataframe of runtimes.", "'TSV file that was produced when running make_examples ' 'with", "else: d = pd.read_csv(path, sep='\\t') d['Task'] = i list_of_dataframes.append(d) return", "use in source and binary forms, with or without #", "task{\"(s)\" if len(by_task) > 1 else \"\"}') # Write the", "per task. \"\"\" df = read_sharded_runtime_tsvs(input_path) df = calculate_totals(df) by_task", "5000 points, just show them all. charts.extend([{ 'id': 'histogram', 'chart':", "= grouped.apply(calculate_pareto_metrics) # Sample along the Pareto curve, ensuring the", "if len(by_task) > 1 else \"\"}') # Write the HTML", "x=alt.X('runtime_by_stage:Q', bin=alt.Bin(maxbins=100), title='Runtime (seconds)'), y=alt.Y('count()', title='Count of regions', stack=None), color=alt.Color('Stage:N',", "top_regions_producing_zero_examples(df) }] # Altair shows a max of 5000 data", "STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING", "(seconds)']) stage_totals.reset_index(inplace=True) stage_totals = stage_totals.rename(columns={'index': 'Stage'}) stage_totals['Runtime'] = stage_totals['Runtime (seconds)'].apply(", "if minutes > 0: output += f'{int(minutes)}m' if seconds >", "to 5000 points, just show them all. charts.extend([{ 'id': 'histogram',", "totals_by_stage(d: pd.DataFrame) -> alt.Chart: \"\"\"Plots total runtimes for each stage.", "chaining, such as # chart.mark_bar().encode(...).properties(...), so using backslash # continuation", "html_output: Any) -> None: \"\"\"Makes the html report with all", "report, which will be an html file.') RUNTIME_COLUMNS = [", "COUNT_COLUMNS = ['num reads', 'num candidates', 'num examples'] CSS_STYLES =", "single or sharded path into a pandas dataframe. Args: path_string:", "def calculate_totals(df: pd.DataFrame) -> pd.DataFrame: \"\"\"Calculates total runtime, formats it", "dataframe with some additional summary columns. \"\"\" # 'total runtime'", "charts. write_to_html_report( charts=charts, title=title, subtitle=subtitle, html_output=html_output) def main(argv: Sequence[str]): if", "data points. if len(df) <= 5000: # With up to", "<filename>deepvariant/runtime_by_region_vis.py # Copyright 2020 Google LLC. # # Redistribution and", "ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES", "\"\"\" # Load data into pandas dataframes and add summary", "None, 'TSV file that was produced when running make_examples '", "\"\"\"Creates a nice format string from a potentially large number", "'scatter_grid_top_5000', 'chart': correlation_scatter_charts( top_5000, title='Trends for regions in the top", "FLAGS.output.endswith('html'): output_filename = FLAGS.output else: output_filename = f'{FLAGS.output}.html' # Start", "stacked bar charts of the top 20 and median 20", "raw_seconds: A number of seconds. Returns: The seconds divided into", "already the suffix. if FLAGS.output.endswith('html'): output_filename = FLAGS.output else: output_filename", "with some additional columns. \"\"\" # These are the same", "total runtimes for each stage. Args: d: A dataframe of", "shown at the top of the report and will '", "Y% of the total runtime', axis=alt.Axis(format='%')), tooltip='tooltip', color=alt.condition(brush, 'Task:N', alt.value('lightgray'))).properties(", "df_subset['total runtime'].sum() n = len(df_subset) df_subset['task cumsum order'] = list(map(lambda", "this into separate lines makes the code more readable. #", "\"\"\" # These are the same for all regions in", "OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,", "alt.Chart(df).mark_line(size=2).encode( x=alt.X( 'task cumsum order', title='The longest-runtime X% of regions',", "otherwise make the text look funky. task_scatter = alt.Chart(df).mark_point(size=10).encode( x=alt.X('max(task", "top 5000') }, { 'id': 'scatter_grid_bottom_99_percent', 'chart': correlation_scatter_charts( bottom_99_percent, title='Trends", "chart['chart'].to_json())) download_filename = '{}_{}'.format(title.replace(' ', '_'), chart['id']) embed_options = {'mode':", "pd.DataFrame) -> alt.Chart: \"\"\"Plots total runtimes for each stage. Args:", "make_report(input_path: str, title: str, html_output: tf.io.gfile.GFile) -> None: \"\"\"Reads data,", "formats it nicely, and sorts by it. Args: df: A", "some additional columns. \"\"\" # These are the same for", "pd.concat([df.nlargest(x, 'total runtime'), df.sample(5000 - x)]) # Limit columns to", "sum columns. Returns: A string to show as the tooltip", "regions \" f\"account for {row['task cumsum fraction'] * 100:.2f}% of", "with runtime of each stage for individual regions. Args: small_df:", "the plot. Returns: An altair chart. \"\"\" columns_used = RUNTIME_COLUMNS", "}] # Altair shows a max of 5000 data points.", "sort=None), tooltip=['Runtime'], fill=alt.Fill('Stage', sort=None)).properties(title='Overall runtime by stage') def pareto_by_task_tooltip(row: pd.Series)", "files.') flags.DEFINE_string('output', 'runtime_by_region_report.html', 'Path for the output report, which will", "are shown. if len(df) > 5000: x = 1000 df", "what extent a small proportion of long-running regions contribute disproportionately", "Returns: The seconds divided into hours, minutes, and remaining seconds,", "An altair chart. \"\"\" columns_used = RUNTIME_COLUMNS d = d[columns_used]", "-> alt.Chart: \"\"\"Plots a histogram of runtimes stacked by stage.", "chart and a descriptive ID. \"\"\" charts = [{ 'id':", "total_runtime * 100:.2f}% of the total ' f'runtime of {total_runtime:.2f}", "<style> body { font-family: sans-serif; } .chart-container { padding: 30px;", "to avoid outliers that obscure general trends. bottom_99_percent = df.nsmallest(int(len(df)", "html to the output path if that is not already", "points which otherwise make the text look funky. task_scatter =", "DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND", "prior written permission. # # THIS SOFTWARE IS PROVIDED BY", "be used to endorse or promote products derived from this", "df_subset['tooltip'] = df_subset.apply(pareto_by_task_tooltip, axis=1) return df_subset def pareto_and_runtimes_by_task(df: pd.DataFrame) ->", "correlation_scatter_charts(d: pd.DataFrame, title: str = '') -> alt.Chart: \"\"\"Produces a", "str = '') -> alt.Chart: \"\"\"Plots a histogram of runtimes", "import Dict, Sequence, List, Tuple, Text, Any, Union from absl", "subtitle }) def write_to_html_report(charts: List[Dict[Text, alt.Chart]], title: str, subtitle: str,", "HOLDERS AND CONTRIBUTORS \"AS IS\" # AND ANY EXPRESS OR", "with one row per task. \"\"\" df = read_sharded_runtime_tsvs(input_path) df", "this workaround. with tf.io.gfile.GFile(path) as f: d = pd.read_csv(f, sep='\\t')", "other. Using max(task) for 'text' is a # trick that", "for the pareto curves: df_subset['task cumsum fraction'] = df_subset['total runtime'].cumsum(", "all the charts. write_to_html_report( charts=charts, title=title, subtitle=subtitle, html_output=html_output) def main(argv:", "altair chart. \"\"\" columns_used = ['region', 'Runtime'] + RUNTIME_COLUMNS d", "dicts, each containing a chart and a descriptive ID. \"\"\"", "A dataframe of regions, each of which will be shown", "the copyright holder nor the names of its # contributors", "runtime. That is, \"The longest-running X% of regions account for", "= alt.selection_interval() pareto_by_task = alt.Chart(df).mark_line(size=2).encode( x=alt.X( 'task cumsum order', title='The", "of runtime profiling numbers. Returns: The same dataframe with some", "without this workaround. with tf.io.gfile.GFile(path) as f: d = pd.read_csv(f,", "= df.nsmallest(int(len(df) * .99), 'total runtime') if len(bottom_99_percent) > 5000:", "\"\"\" def read_sharded_runtime_tsvs(path_string: str) -> pd.DataFrame: \"\"\"Imports data from a", "a prefix for downloaded image files.') flags.DEFINE_string('output', 'runtime_by_region_report.html', 'Path for", "by task to avoid showing multiple overlapping # points which", "runtimes. Returns: An altair chart. \"\"\" stage_totals_series = d.sum()[RUNTIME_COLUMNS] stage_totals", "output += f'{seconds}s' return output def calculate_totals(df: pd.DataFrame) -> pd.DataFrame:", "runtime string for tooltips. df['Runtime'] = df['total runtime'].apply(format_runtime_string) # Sort", "}]) return charts def make_report(input_path: str, title: str, html_output: tf.io.gfile.GFile)", "# 3. Neither the name of the copyright holder nor", "total runtime', 'task num examples', 'Runtime for task' ] df", "regions') }, { 'id': 'scatter_grid', 'chart': correlation_scatter_charts(df, title='Trends for all", "\"\"\"Plots total runtimes for each stage. Args: d: A dataframe", "= ['num reads', 'num candidates', 'num examples'] CSS_STYLES = \"\"\"", "x: x / n, range(0, n))) df_subset['tooltip'] = df_subset.apply(pareto_by_task_tooltip, axis=1)", "chart['id']) embed_options = {'mode': 'vega-lite', 'downloadFileName': download_filename} html_output.write('vegaEmbed(\"#vis_{}\", spec_{}, {})\\n'.format(", "title='Count of regions', stack=None), color=alt.Color('Stage:N', sort=None) ).properties(title=title) def correlation_scatter_charts(d: pd.DataFrame,", "] COUNT_COLUMNS = ['num reads', 'num candidates', 'num examples'] CSS_STYLES", "scatter plots of runtimes of stages versus covariates. Args: d:", "as pd import tensorflow as tf from third_party.nucleus.io import sharded_file_utils", "a subtitle with some top-level stats. subtitle = (f'Runtime profiling", "stage for individual regions. Args: small_df: A dataframe of regions,", "# These are the same for all regions in the", "the total runtime.\" There is a curve for each task.", "'chart': stage_histogram(by_task, title='Stage runtimes for each task') }, { 'id':", ") / df_subset['total runtime'].sum() n = len(df_subset) df_subset['task cumsum order']", "plot: df_subset['task total runtime'] = df_subset['total runtime'].sum() df_subset['Runtime for task']", "readable. # pylint: disable=g-backslash-continuation VEGA_URL = 'https://storage.googleapis.com/deepvariant/lib/vega' FLAGS = flags.FLAGS", "a file into one dataframe as-is and one by task.", "ensuring the longest regions are shown. if len(df) > 5000:", "html report. columns_used = [ 'task cumsum order', 'task cumsum", "examples', 'Runtime for task' ] df = df[columns_used] # Brushing", "d.sum()[RUNTIME_COLUMNS] stage_totals = pd.DataFrame( stage_totals_series, columns=['Runtime (seconds)']) stage_totals.reset_index(inplace=True) stage_totals =", "accept ' 'positional arguments, but found these extra arguments: \"{}\".'", "len(df) <= 5000: # With up to 5000 points, just", "df_subset['task num examples'] = df_subset['num examples'].sum() # These are cumulative", "SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR", "if path.startswith('gs://'): # Once pandas is updated to 0.24+, pd.read_csv", "Returns: None. Writes into the html_output file object. \"\"\" #", "= bottom_99_percent.sample(5000) charts.extend([{ 'id': 'histogram_bottom_99_percent', 'chart': stage_histogram( bottom_99_percent, title='Runtime by", "path in enumerate(paths): if path.startswith('gs://'): # Once pandas is updated", "charts = [{ 'id': 'total_by_stage', 'chart': totals_by_stage(by_task) }, { 'id':", "shows a max of 5000 data points. if len(df) <=", "src=\"{}/vega-lite@4.8.1\"></script>' '\\n'.format(VEGA_URL)) html_output.write( '<script type=\"text/javascript\" src=\"{}/vega-embed@6\"></script>' '\\n'.format(VEGA_URL)) # Add styles", "{row['Task']}\") def calculate_pareto_metrics(df_subset: pd.DataFrame) -> pd.DataFrame: \"\"\"Calculates cumulative sums for", "download_filename = '{}_{}'.format(title.replace(' ', '_'), chart['id']) embed_options = {'mode': 'vega-lite',", "x / n, range(0, n))) df_subset['tooltip'] = df_subset.apply(pareto_by_task_tooltip, axis=1) return", "charts = make_all_charts(df, by_task) # Write a subtitle with some", "A title for the plot. If a dict, it should", "</style> \"\"\" def read_sharded_runtime_tsvs(path_string: str) -> pd.DataFrame: \"\"\"Imports data from", "3) output = '' if hours > 0: output +=", "# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)", "report. html_output: a writable file object. Returns: None. Writes into", "the top 100') }, { 'id': 'scatter_grid_top_5000', 'chart': correlation_scatter_charts( top_5000,", "points, just show them all. charts.extend([{ 'id': 'histogram', 'chart': stage_histogram(df,", "of the top regions that produced zero examples. Args: df:", "top_regions_producing_zero_examples(df: pd.DataFrame) -> alt.Chart: \"\"\"Creates a chart of the top", "for each task. Args: df: A dataframe of all regions.", "these extra arguments: \"{}\".' ''.format(str(argv[1:]))) # Add html to the", "are the same for all regions in the same task,", "ARISING IN ANY WAY OUT OF THE USE OF THIS", "and the following disclaimer. # # 2. Redistributions in binary", "but found these extra arguments: \"{}\".' ''.format(str(argv[1:]))) # Add html", "For example, 2h3m5.012s. \"\"\" minutes, seconds = divmod(raw_seconds, 60) hours,", "cumsum order'] = list(map(lambda x: x / n, range(0, n)))", "List[Dict[Text, alt.Chart]], title: str, subtitle: str, html_output: Any) -> None:", "ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN", "' f'{len(regions_with_zero_examples)} regions that produced no examples, ' f'which is", "{ 'id': 'histogram_by_task', 'chart': stage_histogram(by_task, title='Stage runtimes for each task')", "file (or sharded files). title: Title to put at the", "= [{ 'id': 'total_by_stage', 'chart': totals_by_stage(by_task) }, { 'id': 'pareto_and_runtimes_by_task',", "alt.Chart(stage_totals).mark_bar().encode( x='Runtime (seconds)', y=alt.Y('Stage', sort=None), tooltip=['Runtime'], fill=alt.Fill('Stage', sort=None)).properties(title='Overall runtime by", "f'{int(hours)}h' if minutes > 0: output += f'{int(minutes)}m' if seconds", "# These are cumulative sums for the pareto curves: df_subset['task", "small proportion of long-running regions contribute disproportionately to the overall", "divs with VegaEmbed. html_output.write('<script>\\n') for chart in charts: html_output.write('var spec_{}", "same task, for the scatter plot: df_subset['task total runtime'] =", "'Title will be shown at the top of the report", "plot. Returns: An altair chart. \"\"\" columns_used = RUNTIME_COLUMNS d", "f: d = pd.read_csv(f, sep='\\t') else: d = pd.read_csv(path, sep='\\t')", "bar. title: A title for the plot. If a dict,", "total ' f'runtime of {total_runtime:.2f} hours.') return individual_region_bars( regions_with_zero_examples.nlargest(50, 'total", "df[columns_used] # Brushing on the task_scatter plot highlights the same", "title: Title to put at the top of the report.", "subset with some additional columns. \"\"\" # These are the", "format_runtime_string) df_subset['task num examples'] = df_subset['num examples'].sum() # These are", "== 0] runtime_of_zeros = regions_with_zero_examples['total runtime'].sum() / 3600 total_runtime =", "sort=None) ).properties(title=title) def correlation_scatter_charts(d: pd.DataFrame, title: str = '') ->", "embed_options = {'mode': 'vega-lite', 'downloadFileName': download_filename} html_output.write('vegaEmbed(\"#vis_{}\", spec_{}, {})\\n'.format( chart['id'],", "first chart to enable the # brushing on one to", "These are cumulative sums for the pareto curves: df_subset['task cumsum", "axis=alt.Axis(labelExpr=\"datum.value + 's'\")), y=alt.Y(alt.repeat('row'), type='quantitative'), tooltip='region' ).properties(width=100, height=100) \\ .repeat(", "by region. Use this script to visualize the runtime-by-region data", "import tensorflow as tf from third_party.nucleus.io import sharded_file_utils # Altair", "conditions and the following disclaimer in the # documentation and/or", "r\"\"\"Create a visual report of make_examples runtime by region. Use", "stage for all regions') }, { 'id': 'scatter_grid', 'chart': correlation_scatter_charts(df,", "task. \"\"\" df = read_sharded_runtime_tsvs(input_path) df = calculate_totals(df) by_task =", "LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING", "= df_subset['total runtime'].cumsum( ) / df_subset['total runtime'].sum() n = len(df_subset)", "= \"\"\" <style> body { font-family: sans-serif; } .chart-container {", "Args: charts: A list of altair chart objects. title: The", "runtime of each stage for individual regions. Args: small_df: A", "x=alt.X(alt.repeat('column'), type='quantitative', axis=alt.Axis(labelExpr=\"datum.value + 's'\")), y=alt.Y(alt.repeat('row'), type='quantitative'), tooltip='region' ).properties(width=100, height=100)", "= regions_with_zero_examples['total runtime'].sum() / 3600 total_runtime = df['total runtime'].sum() /", "for the plot. Returns: An altair chart \"\"\" columns_used =", "return output def calculate_totals(df: pd.DataFrame) -> pd.DataFrame: \"\"\"Calculates total runtime,", "copyright notice, # this list of conditions and the following", "html_output.write( '<div class=\"chart-container\" id=\"vis_{}\"></div>\\n'.format(chart['id'])) html_output.write('</div>') # Add JSON vega specs", "up to the divs with VegaEmbed. html_output.write('<script>\\n') for chart in", "{'mode': 'vega-lite', 'downloadFileName': download_filename} html_output.write('vegaEmbed(\"#vis_{}\", spec_{}, {})\\n'.format( chart['id'], chart['id'], embed_options))", "grouped = df.groupby(df['Task'], sort=False) df = grouped.apply(calculate_pareto_metrics) # Sample along", "(may be sharded). Returns: df: A dataframe with one row", "'num examples'] CSS_STYLES = \"\"\" <style> body { font-family: sans-serif;", "a histogram of runtimes stacked by stage. Args: d: A", "* 100:.2f}% of \" f\"the runtime in task {row['Task']}\") def", "len(argv) > 1: raise app.UsageError( 'Command line parsing failure: this", "of the total runtime.\" There is a curve for each", "all regions. Returns: An altair chart. \"\"\" regions_with_zero_examples = df[df['num", "order'] * 100:.2f}% of regions \" f\"account for {row['task cumsum", "for task'] ) \\ .properties(title='Total runtime for each task (drag", "into hours, minutes, and remaining seconds, formatted nicely. For example,", "= round(seconds, 3) output = '' if hours > 0:", "[ 'task cumsum order', 'task cumsum fraction', 'tooltip', 'Task', 'task", "computes a tooltip description. Args: row: A Pandas Series, one", "brush = alt.selection_interval() pareto_by_task = alt.Chart(df).mark_line(size=2).encode( x=alt.X( 'task cumsum order',", "3600 total_runtime = df['total runtime'].sum() / 3600 subtitle = (", "for make_examples on {len(df)} regions ' f'across {len(by_task)} task{\"(s)\" if", "else \"\"}') # Write the HTML report with all the", "pd.DataFrame: \"\"\"Imports data from a single or sharded path into", "'vega-lite', 'downloadFileName': download_filename} html_output.write('vegaEmbed(\"#vis_{}\", spec_{}, {})\\n'.format( chart['id'], chart['id'], embed_options)) html_output.write('</script>\\n')", ".encode( x=alt.X('runtime_by_stage:Q', bin=alt.Bin(maxbins=100), title='Runtime (seconds)'), y=alt.Y('count()', title='Count of regions', stack=None),", "' f'which is {runtime_of_zeros / total_runtime * 100:.2f}% of the", "all. charts.extend([{ 'id': 'histogram', 'chart': stage_histogram(df, title='Runtime by stage for", "curves: df_subset['task cumsum fraction'] = df_subset['total runtime'].cumsum( ) / df_subset['total", "LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS", "alt.selection_interval() pareto_by_task = alt.Chart(df).mark_line(size=2).encode( x=alt.X( 'task cumsum order', title='The longest-runtime", "title: A title for the plot. Returns: An altair chart", "this list of conditions and the following disclaimer. # #", "An altair chart. \"\"\" stage_totals_series = d.sum()[RUNTIME_COLUMNS] stage_totals = pd.DataFrame(", "IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,", "Returns: A dataframe matching the TSV file(s) but with added", "float) -> str: \"\"\"Creates a nice format string from a", "without # modification, are permitted provided that the following conditions", "not output: output += f'{seconds}s' return output def calculate_totals(df: pd.DataFrame)", "file object. Returns: None. Writes into the html_output file object.", "to use the same dataframe as the first chart to", "pd import tensorflow as tf from third_party.nucleus.io import sharded_file_utils #", "alt.Chart: \"\"\"Plots total runtimes for each stage. Args: d: A", "subtitle: The subtitle to show just below the title on", "where output will be written. \"\"\" # Load data into", "There is a curve for each task. Args: df: A", "a stacked bar charts of the top 20 and median", "A title for the plot. Returns: An altair chart. \"\"\"", "runtime'].sum() n = len(df_subset) df_subset['task cumsum order'] = list(map(lambda x:", "# 'total runtime' is a simple sum of the runtime", "PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,", "'write outputs' ] COUNT_COLUMNS = ['num reads', 'num candidates', 'num", "specific cumulative sum columns. Returns: A string to show as", "> 0: output += f'{int(minutes)}m' if seconds > 0 or", "title: A title for the plot. Returns: An altair chart.", "src=\"{}/vega@5\"></script>' '\\n'.format(VEGA_URL)) html_output.write( '<script type=\"text/javascript\" src=\"{}/vega-lite@4.8.1\"></script>' '\\n'.format(VEGA_URL)) html_output.write( '<script type=\"text/javascript\"", "as-is and one by task. Args: input_path: str, path of", "and composes the charts into an HTML report. Args: input_path:", "a visual report of make_examples runtime by region. Use this", "contain 'title' and/or 'subtitle'. Returns: An altair chart. \"\"\" columns_used", "df_subset def pareto_and_runtimes_by_task(df: pd.DataFrame) -> alt.Chart: \"\"\"Creates an interactive Pareto", "A string to show as the tooltip for a pareto", "Pandas Series, one row of a dataframe containing some specific", "for Y% of the total runtime', axis=alt.Axis(format='%')), tooltip='tooltip', color=alt.condition(brush, 'Task:N',", "to 0.24+, pd.read_csv will work for gs:// # without this", "'subtitle'. Returns: An altair chart. \"\"\" columns_used = ['region', 'Runtime']", "absl import flags import altair as alt import pandas as", "Start HTML document. Using GFile enables writing to GCS too.", "backslash # continuation to break this into separate lines makes", "runtimes stacked by stage. Args: d: A dataframe of runtimes,", "a # trick that causes bundling by task to avoid", "the total runtime for each task. Args: df: A dataframe", "}, { 'id': 'scatter_grid', 'chart': correlation_scatter_charts(df, title='Trends for all regions')", "composes the charts into an HTML report. Args: input_path: Path", "= sharded_file_utils.generate_sharded_filenames(path_string) else: paths = [path_string] list_of_dataframes = [] for", "all regions. Returns: An altair chart. \"\"\" grouped = df.groupby(df['Task'],", "of runtime by regions. title: A title for the plot.", "= round(num_rows / 2) return individual_region_bars(df.iloc[0:20], 'Top runtime regions') \\", "output_filename = FLAGS.output else: output_filename = f'{FLAGS.output}.html' # Start HTML", "images', 'write outputs' ] COUNT_COLUMNS = ['num reads', 'num candidates',", "dataframe of all regions. Returns: An altair chart. \"\"\" regions_with_zero_examples", "<= 5000: # With up to 5000 points, just show", "# # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS", "html_output = tf.io.gfile.GFile(output_filename, 'w') make_report( input_path=FLAGS.input, title=FLAGS.title, html_output=html_output) html_output.close() #", "as_=['Stage', 'runtime_by_stage']) \\ .mark_bar(opacity=0.3) \\ .encode( x=alt.X('runtime_by_stage:Q', bin=alt.Bin(maxbins=100), title='Runtime (seconds)'),", "html file.') RUNTIME_COLUMNS = [ 'get reads', 'find candidates', 'make", "make the text look funky. task_scatter = alt.Chart(df).mark_point(size=10).encode( x=alt.X('max(task total", "top 100') }, { 'id': 'scatter_grid_top_5000', 'chart': correlation_scatter_charts( top_5000, title='Trends", "# Sample the bottom 99% to avoid outliers that obscure", "row per task. Returns: list of dicts, each containing a", "materials provided with the distribution. # # 3. Neither the", "d = small_df[columns_used] return alt.Chart(d).transform_fold( RUNTIME_COLUMNS, as_=['Stage', 'runtime_by_stage']) \\ .mark_bar().encode(", "by_task: A dataframe with one row per task. Returns: list", "holder nor the names of its # contributors may be", "return alt.Chart(d).transform_fold( RUNTIME_COLUMNS, as_=['Stage', 'runtime_by_stage']) \\ .mark_bar().encode( x=alt.X('region:N', sort=None), y=alt.Y('runtime_by_stage:Q',", "permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT", "look funky. task_scatter = alt.Chart(df).mark_point(size=10).encode( x=alt.X('max(task total runtime)', title='Runtime (seconds)'),", "FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT", "\"\"\" charts = [{ 'id': 'total_by_stage', 'chart': totals_by_stage(by_task) }, {", "{ 'id': 'scatter_grid', 'chart': correlation_scatter_charts(df, title='Trends for all regions') }])", "gs:// # without this workaround. with tf.io.gfile.GFile(path) as f: d", "'w') make_report( input_path=FLAGS.input, title=FLAGS.title, html_output=html_output) html_output.close() # Abstracted out the", "FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO", "An altair chart. \"\"\" columns_used = ['region', 'Runtime'] + RUNTIME_COLUMNS", "None, 'Title will be shown at the top of the", "string from a potentially large number of seconds. Args: raw_seconds:", "task' ] df = df[columns_used] # Brushing on the task_scatter", "-> pd.DataFrame: \"\"\"Calculates total runtime, formats it nicely, and sorts", "Path of the input TSV file (or sharded files). title:", "\"\"\" regions_with_zero_examples = df[df['num examples'] == 0] runtime_of_zeros = regions_with_zero_examples['total", "IS\" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT", "GFile enables writing to GCS too. html_output = tf.io.gfile.GFile(output_filename, 'w')", "each stage. Args: d: A dataframe of runtimes. Returns: An", "output report, which will be an html file.') RUNTIME_COLUMNS =", "puts them in a list with their ID names. Args:", "of the html report. columns_used = [ 'task cumsum order',", "= [] for i, path in enumerate(paths): if path.startswith('gs://'): #", "the ' f'{len(regions_with_zero_examples)} regions that produced no examples, ' f'which", "alt.Chart(df).mark_point(size=10).encode( x=alt.X('max(task total runtime)', title='Runtime (seconds)'), y=alt.Y('task num examples:Q', title='Number", "runtime for each task. Args: df: A dataframe of runtime", "sans-serif; } .chart-container { padding: 30px; } </style> \"\"\" def", "fill=alt.Fill('Stage', sort=None)).properties(title='Overall runtime by stage') def pareto_by_task_tooltip(row: pd.Series) -> str:", "of runtimes of stages versus covariates. Args: d: A pandas", "the size of the html report. columns_used = [ 'task", "str, html_output: Any) -> None: \"\"\"Makes the html report with", "= d[columns_used] return alt.Chart(d).mark_circle(opacity=0.1).encode( x=alt.X(alt.repeat('column'), type='quantitative', axis=alt.Axis(labelExpr=\"datum.value + 's'\")), y=alt.Y(alt.repeat('row'),", "of runtimes. Returns: An altair chart. \"\"\" stage_totals_series = d.sum()[RUNTIME_COLUMNS]", "chart. \"\"\" regions_with_zero_examples = df[df['num examples'] == 0] runtime_of_zeros =", "the charts inserted. Args: charts: A list of altair chart", "is, \"The longest-running X% of regions account for Y% of", "padding: 30px; } </style> \"\"\" def read_sharded_runtime_tsvs(path_string: str) -> pd.DataFrame:", "RUNTIME_COLUMNS, as_=['Stage', 'runtime_by_stage']) \\ .mark_bar().encode( x=alt.X('region:N', sort=None), y=alt.Y('runtime_by_stage:Q', scale=alt.Scale(type='linear'), title='Runtime", "runtime.\" There is a curve for each task. Args: df:", "2. Redistributions in binary form must reproduce the above copyright", "return (f\"{row['task cumsum order'] * 100:.2f}% of regions \" f\"account", "RUNTIME_COLUMNS d = d[columns_used] return alt.Chart(d).transform_fold( RUNTIME_COLUMNS, as_=['Stage', 'runtime_by_stage']) \\", "each task') }, { 'id': 'selected_longest_and_median_regions', 'chart': selected_longest_and_median_regions(df) }, {", "MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED.", "OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT", "FLAGS = flags.FLAGS flags.DEFINE_string( 'input', None, 'TSV file that was", "stages versus covariates. Args: d: A pandas dataframe of runtime", "d = pd.read_csv(f, sep='\\t') else: d = pd.read_csv(path, sep='\\t') d['Task']", "fraction', 'tooltip', 'Task', 'task total runtime', 'task num examples', 'Runtime", "be sharded, e.g. /path/runtime@64.tsv.') flags.DEFINE_string( 'title', None, 'Title will be", "one task. Returns: The same dataframe subset with some additional", "color=alt.condition(brush, 'Task:N', alt.value('lightgray'))).properties( title='Pareto curve for each task').interactive() # This", "return pareto_by_task | task_scatter def individual_region_bars(small_df: pd.DataFrame, title: Union[str, Dict[str,", "regions that produced zero examples. Args: df: A dataframe of", "be shown at the top of the report and will", "and the following disclaimer in the # documentation and/or other", "brushing on one to affect the other. Using max(task) for", "TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF", "BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" # AND", "runtime') # Sample the bottom 99% to avoid outliers that", "'task cumsum fraction', title='Account for Y% of the total runtime',", "Args: row: A Pandas Series, one row of a dataframe", "# 2. Redistributions in binary form must reproduce the above", "Neither the name of the copyright holder nor the names", "altair charts. html_output.write('<script type=\"text/javascript\" src=\"{}/vega@5\"></script>' '\\n'.format(VEGA_URL)) html_output.write( '<script type=\"text/javascript\" src=\"{}/vega-lite@4.8.1\"></script>'", "'id': 'histogram_top_100', 'chart': stage_histogram( top_100, title='Runtime by stage for regions", "that produced no examples', 'subtitle': subtitle }) def write_to_html_report(charts: List[Dict[Text,", "if FLAGS.output.endswith('html'): output_filename = FLAGS.output else: output_filename = f'{FLAGS.output}.html' #", "dataframe of regions, each of which will be shown as", "2020 Google LLC. # # Redistribution and use in source", "'positional arguments, but found these extra arguments: \"{}\".' ''.format(str(argv[1:]))) #", "# # 1. Redistributions of source code must retain the", "in the # documentation and/or other materials provided with the", "above copyright notice, # this list of conditions and the", "{row['task cumsum fraction'] * 100:.2f}% of \" f\"the runtime in", "in the top 5000') }, { 'id': 'scatter_grid_bottom_99_percent', 'chart': correlation_scatter_charts(", "# Add styles (CSS). html_output.write(CSS_STYLES) html_output.write('</head>\\n<body>') html_output.write('<h1>{}</h1>\\n'.format(title)) html_output.write('<h2>{}</h2>\\n'.format(subtitle)) # Make", "# # Redistribution and use in source and binary forms,", "simple sum of the runtime columns. df['total runtime'] = df[RUNTIME_COLUMNS].sum(axis=1)", "tf from third_party.nucleus.io import sharded_file_utils # Altair uses a lot", "from a potentially large number of seconds. Args: raw_seconds: A", "dataframe with one row per task. Returns: list of dicts,", "scale=alt.Scale(type='linear'), title='Runtime (seconds)'), fill=alt.Fill('Stage:N', sort=None), tooltip='Runtime:N' ).properties(title=title) def selected_longest_and_median_regions(df: pd.DataFrame)", "regions in the same task, for the scatter plot: df_subset['task", "script does not accept ' 'positional arguments, but found these", "'chart': correlation_scatter_charts( top_5000, title='Trends for regions in the top 5000')", "-> str: \"\"\"For one row of a dataframe, computes a", "a lot of method chaining, such as # chart.mark_bar().encode(...).properties(...), so", "{ 'id': 'pareto_and_runtimes_by_task', 'chart': pareto_and_runtimes_by_task(df) }, { 'id': 'histogram_by_task', 'chart':", "to visualize the runtime-by-region data generated by running make_examples with", "'chart': correlation_scatter_charts(df, title='Trends for all regions') }]) else: # With", "alt.value('lightgray')), tooltip=['Task', 'Runtime for task'] ) \\ .properties(title='Total runtime for", "the html report with all the charts inserted. Args: charts:", "many points, make different subsets to show trends better. top_100", "bin=alt.Bin(maxbins=100), title='Runtime (seconds)'), y=alt.Y('count()', title='Count of regions', stack=None), color=alt.Color('Stage:N', sort=None)", "100:.2f}% of \" f\"the runtime in task {row['Task']}\") def calculate_pareto_metrics(df_subset:", "alt.Chart: \"\"\"Creates an interactive Pareto curve and scatter plot of", "# Start the HTML document. html_output.write('<!DOCTYPE html>\\n<html>\\n<head>') # Add dependencies", "'Runtime for task'] ) \\ .properties(title='Total runtime for each task", "Start the HTML document. html_output.write('<!DOCTYPE html>\\n<html>\\n<head>') # Add dependencies vega", "a single or sharded path into a pandas dataframe. Args:", "{ 'id': 'scatter_grid_bottom_99_percent', 'chart': correlation_scatter_charts( bottom_99_percent, title='Trends for regions in", "output = '' if hours > 0: output += f'{int(hours)}h'", "import altair as alt import pandas as pd import tensorflow", "bar chart with runtime of each stage for individual regions.", "of make_examples runtime by region. Use this script to visualize", "'Runtime'] + RUNTIME_COLUMNS d = small_df[columns_used] return alt.Chart(d).transform_fold( RUNTIME_COLUMNS, as_=['Stage',", "THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR", "regions. title: A title for the plot. Returns: An altair", "sort=None)).properties(title='Overall runtime by stage') def pareto_by_task_tooltip(row: pd.Series) -> str: \"\"\"For", "of regions \" f\"account for {row['task cumsum fraction'] * 100:.2f}%", "the divs with VegaEmbed. html_output.write('<script>\\n') for chart in charts: html_output.write('var", "Write a subtitle with some top-level stats. subtitle = (f'Runtime", "the following disclaimer. # # 2. Redistributions in binary form", "to show as the tooltip for a pareto curve. \"\"\"", "Dict, Sequence, List, Tuple, Text, Any, Union from absl import", "if len(df) > 5000: x = 1000 df = pd.concat([df.nlargest(x,", "examples'] CSS_STYLES = \"\"\" <style> body { font-family: sans-serif; }", "y=alt.Y('Stage', sort=None), tooltip=['Runtime'], fill=alt.Fill('Stage', sort=None)).properties(title='Overall runtime by stage') def pareto_by_task_tooltip(row:", "Pareto curve and scatter plot of task runtimes. Tracing each", "will be shown as a bar. title: A title for", "source and binary forms, with or without # modification, are", "points, make different subsets to show trends better. top_100 =", "output will be written. \"\"\" # Load data into pandas", "seconds. Args: raw_seconds: A number of seconds. Returns: The seconds", "with all the charts. write_to_html_report( charts=charts, title=title, subtitle=subtitle, html_output=html_output) def", "\"\"\" columns_used = ['region', 'Runtime'] + RUNTIME_COLUMNS d = small_df[columns_used]", "INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER", "number of seconds. Args: raw_seconds: A number of seconds. Returns:", "CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,", "of seconds. Args: raw_seconds: A number of seconds. Returns: The", "was produced when running make_examples ' 'with --runtime_by_region. Can be", "# documentation and/or other materials provided with the distribution. #", "the report. subtitle: The subtitle to show just below the", ".chart-container { padding: 30px; } </style> \"\"\" def read_sharded_runtime_tsvs(path_string: str)", "1: raise app.UsageError( 'Command line parsing failure: this script does", "read_sharded_runtime_tsvs(input_path) df = calculate_totals(df) by_task = summarize_by_task(df) return df, by_task", "str, subtitle: str, html_output: Any) -> None: \"\"\"Makes the html", "regions that produced no examples, ' f'which is {runtime_of_zeros /", "by_task.reset_index() def stage_histogram(d: pd.DataFrame, title: str = '') -> alt.Chart:", "total runtime'] = df_subset['total runtime'].sum() df_subset['Runtime for task'] = df_subset['task", "Sample along the Pareto curve, ensuring the longest regions are", "If a dict, it should contain 'title' and/or 'subtitle'. Returns:", "columns. df, by_task = read_data_and_make_dataframes(input_path) # Build all the charts.", "interactive Pareto curve and scatter plot of task runtimes. Tracing", "the report and will ' 'be used as a prefix", "examples'] == 0] runtime_of_zeros = regions_with_zero_examples['total runtime'].sum() / 3600 total_runtime", "tf.io.gfile.GFile) -> None: \"\"\"Reads data, creates charts, and composes the", "of 5000 data points. if len(df) <= 5000: # With", "-> alt.Chart: \"\"\"Makes a stacked bar chart with runtime of", "task. Returns: The same dataframe subset with some additional columns.", "pareto curves: df_subset['task cumsum fraction'] = df_subset['total runtime'].cumsum( ) /", "output: output += f'{seconds}s' return output def calculate_totals(df: pd.DataFrame) ->", "\\ | individual_region_bars(df.iloc[mid-10:mid+11], 'Median runtime regions') def top_regions_producing_zero_examples(df: pd.DataFrame) ->", "An altair chart. \"\"\" regions_with_zero_examples = df[df['num examples'] == 0]", "df_subset.apply(pareto_by_task_tooltip, axis=1) return df_subset def pareto_and_runtimes_by_task(df: pd.DataFrame) -> alt.Chart: \"\"\"Creates", "html_output.write('<h2>{}</h2>\\n'.format(subtitle)) # Make a div containing all the charts. html_output.write('<div>')", "a pareto curve. \"\"\" return (f\"{row['task cumsum order'] * 100:.2f}%", "/ df_subset['total runtime'].sum() n = len(df_subset) df_subset['task cumsum order'] =", "a list with their ID names. Args: df: A dataframe", "pd.read_csv will work for gs:// # without this workaround. with", "the same task, for the scatter plot: df_subset['task total runtime']", "import app from absl import flags import altair as alt", "a dict, it should contain 'title' and/or 'subtitle'. Returns: An", "is updated to 0.24+, pd.read_csv will work for gs:// #", "in the top 100') }, { 'id': 'scatter_grid_top_5000', 'chart': correlation_scatter_charts(", "the other. Using max(task) for 'text' is a # trick", "EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE", "which may be sharded. Returns: A dataframe matching the TSV", "Pareto # curve. brush = alt.selection_interval() pareto_by_task = alt.Chart(df).mark_line(size=2).encode( x=alt.X(", "pd.read_csv(path, sep='\\t') d['Task'] = i list_of_dataframes.append(d) return pd.concat(list_of_dataframes, axis=0, ignore_index=True)", "Args: df_subset: A dataframe subset of one task. Returns: The", "script to visualize the runtime-by-region data generated by running make_examples", "# this list of conditions and the following disclaimer. #", "if that is not already the suffix. if FLAGS.output.endswith('html'): output_filename", "the top of the report and will ' 'be used", "'id': 'total_by_stage', 'chart': totals_by_stage(by_task) }, { 'id': 'pareto_and_runtimes_by_task', 'chart': pareto_and_runtimes_by_task(df)", "/ 3600 total_runtime = df['total runtime'].sum() / 3600 subtitle =", "read_data_and_make_dataframes(input_path) # Build all the charts. charts = make_all_charts(df, by_task)", "regions', axis=alt.Axis(format='%')), y=alt.Y( 'task cumsum fraction', title='Account for Y% of", "scatter plot of task runtimes. Tracing each curve shows to", "id=\"vis_{}\"></div>\\n'.format(chart['id'])) html_output.write('</div>') # Add JSON vega specs and hook them", "sharded). Returns: df: A dataframe with one row per region.", "top of the report and will ' 'be used as", "\"\"\" # Start the HTML document. html_output.write('<!DOCTYPE html>\\n<html>\\n<head>') # Add", "The title to show at the top of the report.", "top-level stats. subtitle = (f'Runtime profiling for make_examples on {len(df)}", "= [ 'get reads', 'find candidates', 'make pileup images', 'write", "* .99), 'total runtime') if len(bottom_99_percent) > 5000: bottom_99_percent =", "cumsum order', title='The longest-runtime X% of regions', axis=alt.Axis(format='%')), y=alt.Y( 'task", "runtime regions') def top_regions_producing_zero_examples(df: pd.DataFrame) -> alt.Chart: \"\"\"Creates a chart", "for 'text' is a # trick that causes bundling by", "'chart': top_regions_producing_zero_examples(df) }] # Altair shows a max of 5000", "in charts: html_output.write( '<div class=\"chart-container\" id=\"vis_{}\"></div>\\n'.format(chart['id'])) html_output.write('</div>') # Add JSON", "pd.DataFrame]: \"\"\"Loads data from a file into one dataframe as-is", "fill=alt.Fill('Stage:N', sort=None), tooltip='Runtime:N' ).properties(title=title) def selected_longest_and_median_regions(df: pd.DataFrame) -> alt.Chart: \"\"\"Creates", "BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR", "by_task def make_all_charts( df: pd.DataFrame, by_task: pd.DataFrame) -> List[Dict[Text, Union[str,", "along the Pareto curve, ensuring the longest regions are shown.", "path_string: The path to the input file, which may be", "\"\"\" stage_totals_series = d.sum()[RUNTIME_COLUMNS] stage_totals = pd.DataFrame( stage_totals_series, columns=['Runtime (seconds)'])", "'chart': pareto_and_runtimes_by_task(df) }, { 'id': 'histogram_by_task', 'chart': stage_histogram(by_task, title='Stage runtimes", "for the scatter plot: df_subset['task total runtime'] = df_subset['total runtime'].sum()", "= f'{FLAGS.output}.html' # Start HTML document. Using GFile enables writing", "in the bottom 99%') }, { 'id': 'histogram_top_100', 'chart': stage_histogram(", "def format_runtime_string(raw_seconds: float) -> str: \"\"\"Creates a nice format string", "data into pandas dataframes and add summary columns. df, by_task", "pd.concat(list_of_dataframes, axis=0, ignore_index=True) def format_runtime_string(raw_seconds: float) -> str: \"\"\"Creates a", "by_task: A dataframe with one row per task. \"\"\" df", "provided that the following conditions # are met: # #", "name of the copyright holder nor the names of its", "is {runtime_of_zeros / total_runtime * 100:.2f}% of the total '", "path to the input file, which may be sharded. Returns:", "task_scatter = alt.Chart(df).mark_point(size=10).encode( x=alt.X('max(task total runtime)', title='Runtime (seconds)'), y=alt.Y('task num", "/path/runtime@64.tsv.') flags.DEFINE_string( 'title', None, 'Title will be shown at the", "# # 3. Neither the name of the copyright holder", "'chart': correlation_scatter_charts( bottom_99_percent, title='Trends for regions in the bottom 99%')", "df.nsmallest(int(len(df) * .99), 'total runtime') if len(bottom_99_percent) > 5000: bottom_99_percent", ").properties(title=title) def correlation_scatter_charts(d: pd.DataFrame, title: str = '') -> alt.Chart:", "the task_scatter plot highlights the same tasks in the Pareto", "'id': 'scatter_grid', 'chart': correlation_scatter_charts(df, title='Trends for all regions') }]) else:", "format string from a potentially large number of seconds. Args:", "by_task: pd.DataFrame) -> List[Dict[Text, Union[str, alt.Chart]]]: \"\"\"Creates charts and puts", "make different subsets to show trends better. top_100 = df.nlargest(100,", "curve. \"\"\" return (f\"{row['task cumsum order'] * 100:.2f}% of regions", "reduce the size of the html report. columns_used = [", "Using max(task) for 'text' is a # trick that causes", "output path if that is not already the suffix. if", "the top of the report. html_output: Writable file object where", "'' if hours > 0: output += f'{int(hours)}h' if minutes", "each of which will be shown as a bar. title:", "this script to visualize the runtime-by-region data generated by running", "the top of the report. subtitle: The subtitle to show", "Redistribution and use in source and binary forms, with or", "of runtimes, either by region or by task. title: A", "the distribution. # # 3. Neither the name of the", "top_5000 = df.nlargest(5000, 'total runtime') # Sample the bottom 99%", "{len(df)} regions ' f'across {len(by_task)} task{\"(s)\" if len(by_task) > 1", "html report with all the charts inserted. Args: charts: A", "= df.nlargest(100, 'total runtime') top_5000 = df.nlargest(5000, 'total runtime') #", "Args: d: A dataframe of runtimes, either by region or", "\"\"\"Calculates cumulative sums for a subset of a dataframe. Args:", "x=alt.X('region:N', sort=None), y=alt.Y('runtime_by_stage:Q', scale=alt.Scale(type='linear'), title='Runtime (seconds)'), fill=alt.Fill('Stage:N', sort=None), tooltip='Runtime:N' ).properties(title=title)", "] df = df[columns_used] # Brushing on the task_scatter plot", "row of a dataframe containing some specific cumulative sum columns.", "enumerate(paths): if path.startswith('gs://'): # Once pandas is updated to 0.24+,", "# Brushing on the task_scatter plot highlights the same tasks", "'task cumsum order', 'task cumsum fraction', 'tooltip', 'Task', 'task total", "a bar. title: A title for the plot. If a", "tooltips. df['Runtime'] = df['total runtime'].apply(format_runtime_string) # Sort by descending total", "Load data into pandas dataframes and add summary columns. df,", "pareto_and_runtimes_by_task(df) }, { 'id': 'histogram_by_task', 'chart': stage_histogram(by_task, title='Stage runtimes for", "= '') -> alt.Chart: \"\"\"Produces a grid of scatter plots", "', '_'), chart['id']) embed_options = {'mode': 'vega-lite', 'downloadFileName': download_filename} html_output.write('vegaEmbed(\"#vis_{}\",", "task_scatter plot highlights the same tasks in the Pareto #", "all the charts. charts = make_all_charts(df, by_task) # Write a", "top regions that produced zero examples. Args: df: A dataframe", "will ' 'be used as a prefix for downloaded image", "disclaimer in the # documentation and/or other materials provided with", "dataframe subset of one task. Returns: The same dataframe subset", "INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT", "CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) #", "the same dataframe as the first chart to enable the", "summarize_by_task(df) return df, by_task def make_all_charts( df: pd.DataFrame, by_task: pd.DataFrame)", "report. Args: input_path: Path of the input TSV file (or", "OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS", "of long-running regions contribute disproportionately to the overall runtime. That", "text look funky. task_scatter = alt.Chart(df).mark_point(size=10).encode( x=alt.X('max(task total runtime)', title='Runtime", "{total_runtime:.2f} hours.') return individual_region_bars( regions_with_zero_examples.nlargest(50, 'total runtime'), title={ 'text': 'The", "as a bar. title: A title for the plot. If", "for the plot. Returns: An altair chart. \"\"\" columns_used =", "regions. Returns: An altair chart. \"\"\" grouped = df.groupby(df['Task'], sort=False)", "> 1: raise app.UsageError( 'Command line parsing failure: this script", "def pareto_by_task_tooltip(row: pd.Series) -> str: \"\"\"For one row of a", "= pd.DataFrame( stage_totals_series, columns=['Runtime (seconds)']) stage_totals.reset_index(inplace=True) stage_totals = stage_totals.rename(columns={'index': 'Stage'})", "(seconds)'), y=alt.Y('task num examples:Q', title='Number of examples'), color=alt.condition(brush, 'Task:N', alt.value('lightgray')),", "overlapping # points which otherwise make the text look funky.", "title='Runtime (seconds)'), fill=alt.Fill('Stage:N', sort=None), tooltip='Runtime:N' ).properties(title=title) def selected_longest_and_median_regions(df: pd.DataFrame) ->", "for all regions') }]) else: # With too many points,", "'scatter_grid', 'chart': correlation_scatter_charts(df, title='Trends for all regions') }]) else: #", "'text' is a # trick that causes bundling by task", "for each task (drag to highlight)') \\ .add_selection(brush) return pareto_by_task", "dataframe containing some specific cumulative sum columns. Returns: A string", "\"\"\"Reads data, creates charts, and composes the charts into an", "runtime for each task (drag to highlight)') \\ .add_selection(brush) return", "profiling numbers. Returns: The dataframe grouped by task. \"\"\" by_task", "by_task = read_data_and_make_dataframes(input_path) # Build all the charts. charts =", "IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. r\"\"\"Create", "df['total runtime'] = df[RUNTIME_COLUMNS].sum(axis=1) # Create a formatted runtime string", "one row per task. \"\"\" df = read_sharded_runtime_tsvs(input_path) df =", "produced no examples, ' f'which is {runtime_of_zeros / total_runtime *", "parsing failure: this script does not accept ' 'positional arguments,", "regions. Returns: An altair chart. \"\"\" num_rows = len(df) mid", "alt.Chart: \"\"\"Produces a grid of scatter plots of runtimes of", "and hook them up to the divs with VegaEmbed. html_output.write('<script>\\n')", "bottom_99_percent = bottom_99_percent.sample(5000) charts.extend([{ 'id': 'histogram_bottom_99_percent', 'chart': stage_histogram( bottom_99_percent, title='Runtime", "of regions', stack=None), color=alt.Color('Stage:N', sort=None) ).properties(title=title) def correlation_scatter_charts(d: pd.DataFrame, title:", "= df.nlargest(5000, 'total runtime') # Sample the bottom 99% to", "tooltip for a pareto curve. \"\"\" return (f\"{row['task cumsum order']", "= df_subset['total runtime'].sum() df_subset['Runtime for task'] = df_subset['task total runtime'].apply(", "'text': 'The longest-running regions that produced no examples', 'subtitle': subtitle", "USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE #", "f'which is {runtime_of_zeros / total_runtime * 100:.2f}% of the total", "of {total_runtime:.2f} hours.') return individual_region_bars( regions_with_zero_examples.nlargest(50, 'total runtime'), title={ 'text':", "stage_totals.rename(columns={'index': 'Stage'}) stage_totals['Runtime'] = stage_totals['Runtime (seconds)'].apply( format_runtime_string) return alt.Chart(stage_totals).mark_bar().encode( x='Runtime", "A dataframe with one row per task. \"\"\" df =", "= (f'Runtime profiling for make_examples on {len(df)} regions ' f'across", "alt.Chart: \"\"\"Creates a stacked bar charts of the top 20", "make_examples on {len(df)} regions ' f'across {len(by_task)} task{\"(s)\" if len(by_task)", "str = '') -> alt.Chart: \"\"\"Produces a grid of scatter", "# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER", "sharded files). title: Title to put at the top of", "def selected_longest_and_median_regions(df: pd.DataFrame) -> alt.Chart: \"\"\"Creates a stacked bar charts", "20 regions. Args: df: A dataframe of all regions. Returns:", "d['Task'] = i list_of_dataframes.append(d) return pd.concat(list_of_dataframes, axis=0, ignore_index=True) def format_runtime_string(raw_seconds:", "POSSIBILITY OF SUCH DAMAGE. r\"\"\"Create a visual report of make_examples", "+ RUNTIME_COLUMNS d = small_df[columns_used] return alt.Chart(d).transform_fold( RUNTIME_COLUMNS, as_=['Stage', 'runtime_by_stage'])", "'with --runtime_by_region. Can be sharded, e.g. /path/runtime@64.tsv.') flags.DEFINE_string( 'title', None,", "get the total runtime for each task. Args: df: A", "'zero_examples', 'chart': top_regions_producing_zero_examples(df) }] # Altair shows a max of", "}, { 'id': 'scatter_grid_top_5000', 'chart': correlation_scatter_charts( top_5000, title='Trends for regions", "show them all. charts.extend([{ 'id': 'histogram', 'chart': stage_histogram(df, title='Runtime by", "in the Pareto # curve. brush = alt.selection_interval() pareto_by_task =", "html_output file object. \"\"\" # Start the HTML document. html_output.write('<!DOCTYPE", "show as the tooltip for a pareto curve. \"\"\" return", "{ 'id': 'scatter_grid_top_5000', 'chart': correlation_scatter_charts( top_5000, title='Trends for regions in", "HTML report. Args: input_path: Path of the input TSV file", "OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED", "title to show at the top of the report. subtitle:", "return alt.Chart(stage_totals).mark_bar().encode( x='Runtime (seconds)', y=alt.Y('Stage', sort=None), tooltip=['Runtime'], fill=alt.Fill('Stage', sort=None)).properties(title='Overall runtime", "the overall runtime. That is, \"The longest-running X% of regions", "shown as a bar. title: A title for the plot.", "LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION)", ").properties(width=100, height=100) \\ .repeat( column=['total runtime'] + RUNTIME_COLUMNS, row=COUNT_COLUMNS, ).properties(title=title)", "'id': 'histogram_by_task', 'chart': stage_histogram(by_task, title='Stage runtimes for each task') },", "title='Pareto curve for each task').interactive() # This chart needs to", "in a list with their ID names. Args: df: A", "runtime_of_zeros = regions_with_zero_examples['total runtime'].sum() / 3600 total_runtime = df['total runtime'].sum()", "'total runtime'] + RUNTIME_COLUMNS + COUNT_COLUMNS d = d[columns_used] return", "str, path of the input TSV file (may be sharded).", "THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY", "Text, Any, Union from absl import app from absl import", "be shown as a bar. title: A title for the", "dataframe as the first chart to enable the # brushing", "'task cumsum fraction', 'tooltip', 'Task', 'task total runtime', 'task num", "'histogram_top_100', 'chart': stage_histogram( top_100, title='Runtime by stage for regions in", "df: A dataframe of runtime profiling numbers. Returns: The same", "too many points, make different subsets to show trends better.", "An altair chart \"\"\" columns_used = ['region', 'total runtime'] +", "NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES;", "descending total region runtime. df.sort_values(by='total runtime', inplace=True, ascending=False) return df", "task. Args: df: A dataframe of all regions. Returns: An", "make_examples with --runtime_by_region. \"\"\" from typing import Dict, Sequence, List,", "minutes, and remaining seconds, formatted nicely. For example, 2h3m5.012s. \"\"\"", "Union[str, alt.Chart]]]: \"\"\"Creates charts and puts them in a list", "and sorts by it. Args: df: A dataframe of runtime", "'scatter_grid_bottom_99_percent', 'chart': correlation_scatter_charts( bottom_99_percent, title='Trends for regions in the bottom", "charts into an HTML report. Args: input_path: Path of the", "columns_used = RUNTIME_COLUMNS d = d[columns_used] return alt.Chart(d).transform_fold( RUNTIME_COLUMNS, as_=['Stage',", "columns. Returns: A string to show as the tooltip for", "total_runtime = df['total runtime'].sum() / 3600 subtitle = ( f'Spent", "file(s) but with added Task column. \"\"\" if sharded_file_utils.is_sharded_file_spec(path_string): paths", "Close HTML document. html_output.write('</body></html>') def read_data_and_make_dataframes( input_path: str) -> Tuple[pd.DataFrame,", "BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF", "divided into hours, minutes, and remaining seconds, formatted nicely. For", "a pandas dataframe. Args: path_string: The path to the input", "-> Tuple[pd.DataFrame, pd.DataFrame]: \"\"\"Loads data from a file into one", "5000 data points. if len(df) <= 5000: # With up", "'runtime_by_region_report.html', 'Path for the output report, which will be an", "charts=charts, title=title, subtitle=subtitle, html_output=html_output) def main(argv: Sequence[str]): if len(argv) >", "charts. html_output.write('<div>') for chart in charts: html_output.write( '<div class=\"chart-container\" id=\"vis_{}\"></div>\\n'.format(chart['id']))", "small_df[columns_used] return alt.Chart(d).transform_fold( RUNTIME_COLUMNS, as_=['Stage', 'runtime_by_stage']) \\ .mark_bar().encode( x=alt.X('region:N', sort=None),", "altair chart. \"\"\" num_rows = len(df) mid = round(num_rows /", "Add JSON vega specs and hook them up to the", "one row per task. Returns: list of dicts, each containing", "and use in source and binary forms, with or without", "to the output path if that is not already the", "make_examples runtime by region. Use this script to visualize the", "Tracing each curve shows to what extent a small proportion", "the plot. If a dict, it should contain 'title' and/or", "ignore_index=True) def format_runtime_string(raw_seconds: float) -> str: \"\"\"Creates a nice format", "output += f'{int(hours)}h' if minutes > 0: output += f'{int(minutes)}m'", "charts: html_output.write('var spec_{} = {};\\n'.format(chart['id'], chart['chart'].to_json())) download_filename = '{}_{}'.format(title.replace(' ',", "IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE", "'total_by_stage', 'chart': totals_by_stage(by_task) }, { 'id': 'pareto_and_runtimes_by_task', 'chart': pareto_and_runtimes_by_task(df) },", "path into a pandas dataframe. Args: path_string: The path to", "runtime. df.sort_values(by='total runtime', inplace=True, ascending=False) return df def summarize_by_task(df: pd.DataFrame)", "title='The longest-runtime X% of regions', axis=alt.Axis(format='%')), y=alt.Y( 'task cumsum fraction',", "highlights the same tasks in the Pareto # curve. brush", "= divmod(minutes, 60) seconds = round(seconds, 3) output = ''", "for individual regions. Args: small_df: A dataframe of regions, each", "specs and hook them up to the divs with VegaEmbed.", "the top 20 and median 20 regions. Args: df: A", "tooltip='Runtime:N' ).properties(title=title) def selected_longest_and_median_regions(df: pd.DataFrame) -> alt.Chart: \"\"\"Creates a stacked", ".repeat( column=['total runtime'] + RUNTIME_COLUMNS, row=COUNT_COLUMNS, ).properties(title=title) def totals_by_stage(d: pd.DataFrame)", "sharded path into a pandas dataframe. Args: path_string: The path", "'Stage'}) stage_totals['Runtime'] = stage_totals['Runtime (seconds)'].apply( format_runtime_string) return alt.Chart(stage_totals).mark_bar().encode( x='Runtime (seconds)',", "runtime'), title={ 'text': 'The longest-running regions that produced no examples',", "Any, Union from absl import app from absl import flags", "hours, minutes = divmod(minutes, 60) seconds = round(seconds, 3) output", "to greatly reduce the size of the html report. columns_used", "chart in charts: html_output.write( '<div class=\"chart-container\" id=\"vis_{}\"></div>\\n'.format(chart['id'])) html_output.write('</div>') # Add", "Returns: An altair chart \"\"\" columns_used = ['region', 'total runtime']", "= df[df['num examples'] == 0] runtime_of_zeros = regions_with_zero_examples['total runtime'].sum() /", "total runtime', axis=alt.Axis(format='%')), tooltip='tooltip', color=alt.condition(brush, 'Task:N', alt.value('lightgray'))).properties( title='Pareto curve for", "task to avoid showing multiple overlapping # points which otherwise", "'id': 'zero_examples', 'chart': top_regions_producing_zero_examples(df) }] # Altair shows a max", "with VegaEmbed. html_output.write('<script>\\n') for chart in charts: html_output.write('var spec_{} =", "using backslash # continuation to break this into separate lines", "inserted. Args: charts: A list of altair chart objects. title:", "Returns: An altair chart. \"\"\" columns_used = ['region', 'Runtime'] +", "forms, with or without # modification, are permitted provided that", "add summary columns. df, by_task = read_data_and_make_dataframes(input_path) # Build all", "div containing all the charts. html_output.write('<div>') for chart in charts:", "axis=alt.Axis(format='%')), y=alt.Y( 'task cumsum fraction', title='Account for Y% of the", "examples'), color=alt.condition(brush, 'Task:N', alt.value('lightgray')), tooltip=['Task', 'Runtime for task'] ) \\", "read_data_and_make_dataframes( input_path: str) -> Tuple[pd.DataFrame, pd.DataFrame]: \"\"\"Loads data from a", "HTML report with all the charts. write_to_html_report( charts=charts, title=title, subtitle=subtitle,", "runtime' is a simple sum of the runtime columns. df['total", "or not output: output += f'{seconds}s' return output def calculate_totals(df:", "with all the charts inserted. Args: charts: A list of", "the Pareto curve, ensuring the longest regions are shown. if", "total runtime, formats it nicely, and sorts by it. Args:", "charts. html_output.write('<script type=\"text/javascript\" src=\"{}/vega@5\"></script>' '\\n'.format(VEGA_URL)) html_output.write( '<script type=\"text/javascript\" src=\"{}/vega-lite@4.8.1\"></script>' '\\n'.format(VEGA_URL))", "highlight)') \\ .add_selection(brush) return pareto_by_task | task_scatter def individual_region_bars(small_df: pd.DataFrame,", "names. Args: df: A dataframe with one row per region.", "subtitle: str, html_output: Any) -> None: \"\"\"Makes the html report", "same for all regions in the same task, for the", "it. Args: df: A dataframe of runtime profiling numbers. Returns:", "\"\"\"Loads data from a file into one dataframe as-is and", "a dataframe containing some specific cumulative sum columns. Returns: A", "Copyright 2020 Google LLC. # # Redistribution and use in", "chart.mark_bar().encode(...).properties(...), so using backslash # continuation to break this into", "individual_region_bars(small_df: pd.DataFrame, title: Union[str, Dict[str, str]] = '') -> alt.Chart:", "the above copyright # notice, this list of conditions and", "columns_used = ['region', 'Runtime'] + RUNTIME_COLUMNS d = small_df[columns_used] return", "Union[str, Dict[str, str]] = '') -> alt.Chart: \"\"\"Makes a stacked", "RUNTIME_COLUMNS, row=COUNT_COLUMNS, ).properties(title=title) def totals_by_stage(d: pd.DataFrame) -> alt.Chart: \"\"\"Plots total", "dataframe. Args: df_subset: A dataframe subset of one task. Returns:", "histogram of runtimes stacked by stage. Args: d: A dataframe", "'be used as a prefix for downloaded image files.') flags.DEFINE_string('output',", "runtime in task {row['Task']}\") def calculate_pareto_metrics(df_subset: pd.DataFrame) -> pd.DataFrame: \"\"\"Calculates", "WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE #", "met: # # 1. Redistributions of source code must retain", "return by_task.reset_index() def stage_histogram(d: pd.DataFrame, title: str = '') ->", "a dataframe, computes a tooltip description. Args: row: A Pandas", "each task (drag to highlight)') \\ .add_selection(brush) return pareto_by_task |", "correlation_scatter_charts(df, title='Trends for all regions') }]) else: # With too", "ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR", "of method chaining, such as # chart.mark_bar().encode(...).properties(...), so using backslash", "LLC. # # Redistribution and use in source and binary", "# Redistribution and use in source and binary forms, with", "title for the plot. If a dict, it should contain", "the above copyright notice, # this list of conditions and", "a chart of the top regions that produced zero examples.", "f'runtime of {total_runtime:.2f} hours.') return individual_region_bars( regions_with_zero_examples.nlargest(50, 'total runtime'), title={", "derived from this # software without specific prior written permission.", "as a prefix for downloaded image files.') flags.DEFINE_string('output', 'runtime_by_region_report.html', 'Path", "large number of seconds. Args: raw_seconds: A number of seconds.", "-> pd.DataFrame: \"\"\"Imports data from a single or sharded path", "runtimes for each task') }, { 'id': 'selected_longest_and_median_regions', 'chart': selected_longest_and_median_regions(df)", "JSON vega specs and hook them up to the divs", "subset of a dataframe. Args: df_subset: A dataframe subset of", "# Build all the charts. charts = make_all_charts(df, by_task) #", "'chart': selected_longest_and_median_regions(df) }, { 'id': 'zero_examples', 'chart': top_regions_producing_zero_examples(df) }] #", "Returns: The same dataframe subset with some additional columns. \"\"\"", "LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN", "shows to what extent a small proportion of long-running regions", "selected_longest_and_median_regions(df) }, { 'id': 'zero_examples', 'chart': top_regions_producing_zero_examples(df) }] # Altair", "write_to_html_report(charts: List[Dict[Text, alt.Chart]], title: str, subtitle: str, html_output: Any) ->", "minutes = divmod(minutes, 60) seconds = round(seconds, 3) output =", "RUNTIME_COLUMNS = [ 'get reads', 'find candidates', 'make pileup images',", "# Add html to the output path if that is", "and scatter plot of task runtimes. Tracing each curve shows", "title='Runtime by stage for all regions') }, { 'id': 'scatter_grid',", "and/or 'subtitle'. Returns: An altair chart. \"\"\" columns_used = ['region',", "a descriptive ID. \"\"\" charts = [{ 'id': 'total_by_stage', 'chart':", "charts, and composes the charts into an HTML report. Args:", "# without this workaround. with tf.io.gfile.GFile(path) as f: d =", "at the top of the report. html_output: Writable file object", "# This chart needs to use the same dataframe as", "the charts into an HTML report. Args: input_path: Path of", "each task').interactive() # This chart needs to use the same", "DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS", "calculate_totals(df: pd.DataFrame) -> pd.DataFrame: \"\"\"Calculates total runtime, formats it nicely,", "def main(argv: Sequence[str]): if len(argv) > 1: raise app.UsageError( 'Command", "OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,", "path.startswith('gs://'): # Once pandas is updated to 0.24+, pd.read_csv will", "= stage_totals['Runtime (seconds)'].apply( format_runtime_string) return alt.Chart(stage_totals).mark_bar().encode( x='Runtime (seconds)', y=alt.Y('Stage', sort=None),", "x = 1000 df = pd.concat([df.nlargest(x, 'total runtime'), df.sample(5000 -", "# Close HTML document. html_output.write('</body></html>') def read_data_and_make_dataframes( input_path: str) ->", "flags.FLAGS flags.DEFINE_string( 'input', None, 'TSV file that was produced when", "\\ .encode( x=alt.X('runtime_by_stage:Q', bin=alt.Bin(maxbins=100), title='Runtime (seconds)'), y=alt.Y('count()', title='Count of regions',", "to endorse or promote products derived from this # software", "that is not already the suffix. if FLAGS.output.endswith('html'): output_filename =", "\\ .mark_bar().encode( x=alt.X('region:N', sort=None), y=alt.Y('runtime_by_stage:Q', scale=alt.Scale(type='linear'), title='Runtime (seconds)'), fill=alt.Fill('Stage:N', sort=None),", "pandas dataframes and add summary columns. df, by_task = read_data_and_make_dataframes(input_path)", "{runtime_of_zeros / total_runtime * 100:.2f}% of the total ' f'runtime", "by running make_examples with --runtime_by_region. \"\"\" from typing import Dict,", "task. Args: input_path: str, path of the input TSV file", "IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED", "'histogram', 'chart': stage_histogram(df, title='Runtime by stage for all regions') },", "file into one dataframe as-is and one by task. Args:", "{})\\n'.format( chart['id'], chart['id'], embed_options)) html_output.write('</script>\\n') # Close HTML document. html_output.write('</body></html>')", "title='Runtime by stage for regions in the top 100') },", "altair chart. \"\"\" columns_used = RUNTIME_COLUMNS d = d[columns_used] return", "alt.Chart(d).transform_fold( RUNTIME_COLUMNS, as_=['Stage', 'runtime_by_stage']) \\ .mark_bar(opacity=0.3) \\ .encode( x=alt.X('runtime_by_stage:Q', bin=alt.Bin(maxbins=100),", "bottom_99_percent.sample(5000) charts.extend([{ 'id': 'histogram_bottom_99_percent', 'chart': stage_histogram( bottom_99_percent, title='Runtime by stage", "SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH", "of all regions. Returns: An altair chart. \"\"\" num_rows =", "the names of its # contributors may be used to", "Returns: The dataframe grouped by task. \"\"\" by_task = df.groupby(by=['Task']).sum()", "A dataframe matching the TSV file(s) but with added Task", "# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND", "df: A dataframe of all regions. Returns: An altair chart.", "| task_scatter def individual_region_bars(small_df: pd.DataFrame, title: Union[str, Dict[str, str]] =", "pareto curve. \"\"\" return (f\"{row['task cumsum order'] * 100:.2f}% of", "pandas dataframe of runtime by regions. title: A title for", "# # 2. Redistributions in binary form must reproduce the", "workaround. with tf.io.gfile.GFile(path) as f: d = pd.read_csv(f, sep='\\t') else:", "curve. brush = alt.selection_interval() pareto_by_task = alt.Chart(df).mark_line(size=2).encode( x=alt.X( 'task cumsum", "for all regions in the same task, for the scatter", "Sort by descending total region runtime. df.sort_values(by='total runtime', inplace=True, ascending=False)", "An altair chart. \"\"\" num_rows = len(df) mid = round(num_rows", "dataframe of runtime profiling numbers. Returns: The dataframe grouped by", "= pd.concat([df.nlargest(x, 'total runtime'), df.sample(5000 - x)]) # Limit columns", "def top_regions_producing_zero_examples(df: pd.DataFrame) -> alt.Chart: \"\"\"Creates a chart of the", "disclaimer. # # 2. Redistributions in binary form must reproduce", "f'across {len(by_task)} task{\"(s)\" if len(by_task) > 1 else \"\"}') #", "the suffix. if FLAGS.output.endswith('html'): output_filename = FLAGS.output else: output_filename =", "to GCS too. html_output = tf.io.gfile.GFile(output_filename, 'w') make_report( input_path=FLAGS.input, title=FLAGS.title,", "notice, this list of conditions and the following disclaimer in", "2) return individual_region_bars(df.iloc[0:20], 'Top runtime regions') \\ | individual_region_bars(df.iloc[mid-10:mid+11], 'Median", "separate lines makes the code more readable. # pylint: disable=g-backslash-continuation", "extent a small proportion of long-running regions contribute disproportionately to", "= '') -> alt.Chart: \"\"\"Makes a stacked bar chart with", "retain the above copyright notice, # this list of conditions", "region. Use this script to visualize the runtime-by-region data generated", "return pd.concat(list_of_dataframes, axis=0, ignore_index=True) def format_runtime_string(raw_seconds: float) -> str: \"\"\"Creates", "return df_subset def pareto_and_runtimes_by_task(df: pd.DataFrame) -> alt.Chart: \"\"\"Creates an interactive", "the bottom 99%') }, { 'id': 'histogram_top_100', 'chart': stage_histogram( top_100,", "OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY", "'Task:N', alt.value('lightgray'))).properties( title='Pareto curve for each task').interactive() # This chart", "chart in charts: html_output.write('var spec_{} = {};\\n'.format(chart['id'], chart['chart'].to_json())) download_filename =", "100:.2f}% of regions \" f\"account for {row['task cumsum fraction'] *", "-> List[Dict[Text, Union[str, alt.Chart]]]: \"\"\"Creates charts and puts them in", "5000: bottom_99_percent = bottom_99_percent.sample(5000) charts.extend([{ 'id': 'histogram_bottom_99_percent', 'chart': stage_histogram( bottom_99_percent,", "WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE", "permitted provided that the following conditions # are met: #", "a simple sum of the runtime columns. df['total runtime'] =", "additional columns. \"\"\" # These are the same for all", "OF THE # POSSIBILITY OF SUCH DAMAGE. r\"\"\"Create a visual", "'<script type=\"text/javascript\" src=\"{}/vega-lite@4.8.1\"></script>' '\\n'.format(VEGA_URL)) html_output.write( '<script type=\"text/javascript\" src=\"{}/vega-embed@6\"></script>' '\\n'.format(VEGA_URL)) #", "html_output.write('</body></html>') def read_data_and_make_dataframes( input_path: str) -> Tuple[pd.DataFrame, pd.DataFrame]: \"\"\"Loads data", "Writes into the html_output file object. \"\"\" # Start the", "produced when running make_examples ' 'with --runtime_by_region. Can be sharded,", "Add dependencies vega and vega-lite, which render the altair charts.", "len(df) mid = round(num_rows / 2) return individual_region_bars(df.iloc[0:20], 'Top runtime", "nicely. For example, 2h3m5.012s. \"\"\" minutes, seconds = divmod(raw_seconds, 60)", "# ARISING IN ANY WAY OUT OF THE USE OF", "| individual_region_bars(df.iloc[mid-10:mid+11], 'Median runtime regions') def top_regions_producing_zero_examples(df: pd.DataFrame) -> alt.Chart:", "with their ID names. Args: df: A dataframe with one", "'chart': totals_by_stage(by_task) }, { 'id': 'pareto_and_runtimes_by_task', 'chart': pareto_and_runtimes_by_task(df) }, {", "THE # POSSIBILITY OF SUCH DAMAGE. r\"\"\"Create a visual report", "html_output.write(CSS_STYLES) html_output.write('</head>\\n<body>') html_output.write('<h1>{}</h1>\\n'.format(title)) html_output.write('<h2>{}</h2>\\n'.format(subtitle)) # Make a div containing all", "all regions in the same task, for the scatter plot:", "def read_data_and_make_dataframes( input_path: str) -> Tuple[pd.DataFrame, pd.DataFrame]: \"\"\"Loads data from", "are permitted provided that the following conditions # are met:", "cumsum order'] * 100:.2f}% of regions \" f\"account for {row['task", "the TSV file(s) but with added Task column. \"\"\" if", "= pd.read_csv(path, sep='\\t') d['Task'] = i list_of_dataframes.append(d) return pd.concat(list_of_dataframes, axis=0,", "else: output_filename = f'{FLAGS.output}.html' # Start HTML document. Using GFile", "but with added Task column. \"\"\" if sharded_file_utils.is_sharded_file_spec(path_string): paths =", "chart. \"\"\" columns_used = ['region', 'Runtime'] + RUNTIME_COLUMNS d =", "to break this into separate lines makes the code more", "running make_examples ' 'with --runtime_by_region. Can be sharded, e.g. /path/runtime@64.tsv.')", "input_path=FLAGS.input, title=FLAGS.title, html_output=html_output) html_output.close() # Abstracted out the file open/close", "for {row['task cumsum fraction'] * 100:.2f}% of \" f\"the runtime", "e.g. /path/runtime@64.tsv.') flags.DEFINE_string( 'title', None, 'Title will be shown at", "* 100:.2f}% of the total ' f'runtime of {total_runtime:.2f} hours.')", "hours, minutes, and remaining seconds, formatted nicely. For example, 2h3m5.012s.", "from absl import app from absl import flags import altair", "paths = sharded_file_utils.generate_sharded_filenames(path_string) else: paths = [path_string] list_of_dataframes = []", "the first chart to enable the # brushing on one", "\\ .add_selection(brush) return pareto_by_task | task_scatter def individual_region_bars(small_df: pd.DataFrame, title:", "def pareto_and_runtimes_by_task(df: pd.DataFrame) -> alt.Chart: \"\"\"Creates an interactive Pareto curve", "60) hours, minutes = divmod(minutes, 60) seconds = round(seconds, 3)", "sorts by it. Args: df: A dataframe of runtime profiling", "[] for i, path in enumerate(paths): if path.startswith('gs://'): # Once", "path of the input TSV file (may be sharded). Returns:", "for each task. Args: df: A dataframe of runtime profiling", "individual_region_bars(df.iloc[mid-10:mid+11], 'Median runtime regions') def top_regions_producing_zero_examples(df: pd.DataFrame) -> alt.Chart: \"\"\"Creates", "runtime'] = df_subset['total runtime'].sum() df_subset['Runtime for task'] = df_subset['task total", "of task runtimes. Tracing each curve shows to what extent", "size of the html report. columns_used = [ 'task cumsum", "alt.Chart: \"\"\"Creates a chart of the top regions that produced", "OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE #", "no examples, ' f'which is {runtime_of_zeros / total_runtime * 100:.2f}%", "visual report of make_examples runtime by region. Use this script", "same dataframe with some additional summary columns. \"\"\" # 'total", "SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED", "will be written. \"\"\" # Load data into pandas dataframes", "--runtime_by_region. Can be sharded, e.g. /path/runtime@64.tsv.') flags.DEFINE_string( 'title', None, 'Title", "for i, path in enumerate(paths): if path.startswith('gs://'): # Once pandas", "'Runtime for task' ] df = df[columns_used] # Brushing on", "download_filename} html_output.write('vegaEmbed(\"#vis_{}\", spec_{}, {})\\n'.format( chart['id'], chart['id'], embed_options)) html_output.write('</script>\\n') # Close", "NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE #", "'_'), chart['id']) embed_options = {'mode': 'vega-lite', 'downloadFileName': download_filename} html_output.write('vegaEmbed(\"#vis_{}\", spec_{},", "runtime by stage') def pareto_by_task_tooltip(row: pd.Series) -> str: \"\"\"For one", "all the charts inserted. Args: charts: A list of altair", "str) -> Tuple[pd.DataFrame, pd.DataFrame]: \"\"\"Loads data from a file into", "CSS_STYLES = \"\"\" <style> body { font-family: sans-serif; } .chart-container", "and puts them in a list with their ID names.", "the total runtime', axis=alt.Axis(format='%')), tooltip='tooltip', color=alt.condition(brush, 'Task:N', alt.value('lightgray'))).properties( title='Pareto curve", "the bottom 99% to avoid outliers that obscure general trends.", "n))) df_subset['tooltip'] = df_subset.apply(pareto_by_task_tooltip, axis=1) return df_subset def pareto_and_runtimes_by_task(df: pd.DataFrame)", "by stage for regions in the bottom 99%') }, {", "the following conditions # are met: # # 1. Redistributions", "{ padding: 30px; } </style> \"\"\" def read_sharded_runtime_tsvs(path_string: str) ->", "hours > 0: output += f'{int(hours)}h' if minutes > 0:", "pd.DataFrame( stage_totals_series, columns=['Runtime (seconds)']) stage_totals.reset_index(inplace=True) stage_totals = stage_totals.rename(columns={'index': 'Stage'}) stage_totals['Runtime']", "SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;", "dependencies vega and vega-lite, which render the altair charts. html_output.write('<script", "a grid of scatter plots of runtimes of stages versus", "seconds. Returns: The seconds divided into hours, minutes, and remaining", "A pandas dataframe of runtime by regions. title: A title", "5000') }, { 'id': 'scatter_grid_bottom_99_percent', 'chart': correlation_scatter_charts( bottom_99_percent, title='Trends for", "found these extra arguments: \"{}\".' ''.format(str(argv[1:]))) # Add html to", "of the report. subtitle: The subtitle to show just below", "list of altair chart objects. title: The title to show", "is not already the suffix. if FLAGS.output.endswith('html'): output_filename = FLAGS.output", "region. by_task: A dataframe with one row per task. \"\"\"", "Any) -> None: \"\"\"Makes the html report with all the", "for Y% of the total runtime.\" There is a curve", "-> alt.Chart: \"\"\"Creates a stacked bar charts of the top", "= i list_of_dataframes.append(d) return pd.concat(list_of_dataframes, axis=0, ignore_index=True) def format_runtime_string(raw_seconds: float)", "regions. Args: small_df: A dataframe of regions, each of which", "OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY", "\"\"\"Makes the html report with all the charts inserted. Args:", "}, { 'id': 'histogram_by_task', 'chart': stage_histogram(by_task, title='Stage runtimes for each", "COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" # AND ANY EXPRESS", "a chart and a descriptive ID. \"\"\" charts = [{", "containing some specific cumulative sum columns. Returns: A string to", "[{ 'id': 'total_by_stage', 'chart': totals_by_stage(by_task) }, { 'id': 'pareto_and_runtimes_by_task', 'chart':", "str) -> pd.DataFrame: \"\"\"Imports data from a single or sharded", "cumsum fraction'] = df_subset['total runtime'].cumsum( ) / df_subset['total runtime'].sum() n", "of all regions. Returns: An altair chart. \"\"\" grouped =", "following disclaimer in the # documentation and/or other materials provided", "by_task = df.groupby(by=['Task']).sum() return by_task.reset_index() def stage_histogram(d: pd.DataFrame, title: str", "df, by_task = read_data_and_make_dataframes(input_path) # Build all the charts. charts", "INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT", "regions', stack=None), color=alt.Color('Stage:N', sort=None) ).properties(title=title) def correlation_scatter_charts(d: pd.DataFrame, title: str", "same dataframe as the first chart to enable the #", "of a dataframe, computes a tooltip description. Args: row: A", "columns. \"\"\" # 'total runtime' is a simple sum of", "report of make_examples runtime by region. Use this script to", "dataframe of runtimes, either by region or by task. title:", "'total runtime' is a simple sum of the runtime columns.", "= {'mode': 'vega-lite', 'downloadFileName': download_filename} html_output.write('vegaEmbed(\"#vis_{}\", spec_{}, {})\\n'.format( chart['id'], chart['id'],", "alt.value('lightgray'))).properties( title='Pareto curve for each task').interactive() # This chart needs", "html_output.write('<div>') for chart in charts: html_output.write( '<div class=\"chart-container\" id=\"vis_{}\"></div>\\n'.format(chart['id'])) html_output.write('</div>')", "'\\n'.format(VEGA_URL)) # Add styles (CSS). html_output.write(CSS_STYLES) html_output.write('</head>\\n<body>') html_output.write('<h1>{}</h1>\\n'.format(title)) html_output.write('<h2>{}</h2>\\n'.format(subtitle)) #", "input_path: Path of the input TSV file (or sharded files).", "the plot. Returns: An altair chart \"\"\" columns_used = ['region',", "cumsum fraction', title='Account for Y% of the total runtime', axis=alt.Axis(format='%')),", "continuation to break this into separate lines makes the code", "bottom 99%') }]) return charts def make_report(input_path: str, title: str,", "when running make_examples ' 'with --runtime_by_region. Can be sharded, e.g.", "used to endorse or promote products derived from this #", "plot. If a dict, it should contain 'title' and/or 'subtitle'.", "'num candidates', 'num examples'] CSS_STYLES = \"\"\" <style> body {", "Using GFile enables writing to GCS too. html_output = tf.io.gfile.GFile(output_filename,", "different subsets to show trends better. top_100 = df.nlargest(100, 'total", "file, which may be sharded. Returns: A dataframe matching the", "THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" # AND ANY", "selected_longest_and_median_regions(df: pd.DataFrame) -> alt.Chart: \"\"\"Creates a stacked bar charts of", "examples'].sum() # These are cumulative sums for the pareto curves:", "ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,", "-> None: \"\"\"Reads data, creates charts, and composes the charts", "order', 'task cumsum fraction', 'tooltip', 'Task', 'task total runtime', 'task", "row of a dataframe, computes a tooltip description. Args: row:", "overall runtime. That is, \"The longest-running X% of regions account", "} </style> \"\"\" def read_sharded_runtime_tsvs(path_string: str) -> pd.DataFrame: \"\"\"Imports data", "just below the title on the report. html_output: a writable", "a stacked bar chart with runtime of each stage for", "Sequence[str]): if len(argv) > 1: raise app.UsageError( 'Command line parsing", "df_subset['num examples'].sum() # These are cumulative sums for the pareto", "per region. by_task: A dataframe with one row per task.", "total runtime.\" There is a curve for each task. Args:", "notice, # this list of conditions and the following disclaimer.", "them all. charts.extend([{ 'id': 'histogram', 'chart': stage_histogram(df, title='Runtime by stage", "'total runtime'), df.sample(5000 - x)]) # Limit columns to greatly", "# Abstracted out the file open/close to enable testing. print('Output", "sums for a subset of a dataframe. Args: df_subset: A", "with tf.io.gfile.GFile(path) as f: d = pd.read_csv(f, sep='\\t') else: d", "'task total runtime', 'task num examples', 'Runtime for task' ]", "Use this script to visualize the runtime-by-region data generated by", "avoid showing multiple overlapping # points which otherwise make the", "the top regions that produced zero examples. Args: df: A", "by stage for all regions') }, { 'id': 'scatter_grid', 'chart':", "/ 3600 subtitle = ( f'Spent {runtime_of_zeros:.2f} hours processing the", "processing the ' f'{len(regions_with_zero_examples)} regions that produced no examples, '", "regions') \\ | individual_region_bars(df.iloc[mid-10:mid+11], 'Median runtime regions') def top_regions_producing_zero_examples(df: pd.DataFrame)", "numbers. Returns: The same dataframe with some additional summary columns.", "documentation and/or other materials provided with the distribution. # #", "tooltip='tooltip', color=alt.condition(brush, 'Task:N', alt.value('lightgray'))).properties( title='Pareto curve for each task').interactive() #", "list of conditions and the following disclaimer in the #", "NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF", "tooltip description. Args: row: A Pandas Series, one row of", "be sharded. Returns: A dataframe matching the TSV file(s) but", "return charts def make_report(input_path: str, title: str, html_output: tf.io.gfile.GFile) ->", "numbers. Returns: The dataframe grouped by task. \"\"\" by_task =", "stacked by stage. Args: d: A dataframe of runtimes, either", "stage_totals_series = d.sum()[RUNTIME_COLUMNS] stage_totals = pd.DataFrame( stage_totals_series, columns=['Runtime (seconds)']) stage_totals.reset_index(inplace=True)", "bottom_99_percent, title='Trends for regions in the bottom 99%') }]) return", "bottom 99%') }, { 'id': 'histogram_top_100', 'chart': stage_histogram( top_100, title='Runtime", "}]) else: # With too many points, make different subsets", "regions_with_zero_examples.nlargest(50, 'total runtime'), title={ 'text': 'The longest-running regions that produced", "by descending total region runtime. df.sort_values(by='total runtime', inplace=True, ascending=False) return", "showing multiple overlapping # points which otherwise make the text", "may be sharded. Returns: A dataframe matching the TSV file(s)", "}, { 'id': 'pareto_and_runtimes_by_task', 'chart': pareto_and_runtimes_by_task(df) }, { 'id': 'histogram_by_task',", "df.sample(5000 - x)]) # Limit columns to greatly reduce the", "+ RUNTIME_COLUMNS + COUNT_COLUMNS d = d[columns_used] return alt.Chart(d).mark_circle(opacity=0.1).encode( x=alt.X(alt.repeat('column'),", "'Path for the output report, which will be an html", "from typing import Dict, Sequence, List, Tuple, Text, Any, Union", "flags.DEFINE_string( 'input', None, 'TSV file that was produced when running", "as tf from third_party.nucleus.io import sharded_file_utils # Altair uses a", "DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE", "calculate_totals(df) by_task = summarize_by_task(df) return df, by_task def make_all_charts( df:", "0.24+, pd.read_csv will work for gs:// # without this workaround.", "runtime by region. Use this script to visualize the runtime-by-region", "= [path_string] list_of_dataframes = [] for i, path in enumerate(paths):", "return alt.Chart(d).mark_circle(opacity=0.1).encode( x=alt.X(alt.repeat('column'), type='quantitative', axis=alt.Axis(labelExpr=\"datum.value + 's'\")), y=alt.Y(alt.repeat('row'), type='quantitative'), tooltip='region'", "one row per region. by_task: A dataframe with one row", "title={ 'text': 'The longest-running regions that produced no examples', 'subtitle':", "str, html_output: tf.io.gfile.GFile) -> None: \"\"\"Reads data, creates charts, and", "by_task) # Write a subtitle with some top-level stats. subtitle", "dataframe subset with some additional columns. \"\"\" # These are", "= alt.Chart(df).mark_point(size=10).encode( x=alt.X('max(task total runtime)', title='Runtime (seconds)'), y=alt.Y('task num examples:Q',", "'pareto_and_runtimes_by_task', 'chart': pareto_and_runtimes_by_task(df) }, { 'id': 'histogram_by_task', 'chart': stage_histogram(by_task, title='Stage", "stage. Args: d: A dataframe of runtimes, either by region", "+ 's'\")), y=alt.Y(alt.repeat('row'), type='quantitative'), tooltip='region' ).properties(width=100, height=100) \\ .repeat( column=['total", "'Median runtime regions') def top_regions_producing_zero_examples(df: pd.DataFrame) -> alt.Chart: \"\"\"Creates a", "same tasks in the Pareto # curve. brush = alt.selection_interval()", "= '' if hours > 0: output += f'{int(hours)}h' if", "alt.Chart(d).mark_circle(opacity=0.1).encode( x=alt.X(alt.repeat('column'), type='quantitative', axis=alt.Axis(labelExpr=\"datum.value + 's'\")), y=alt.Y(alt.repeat('row'), type='quantitative'), tooltip='region' ).properties(width=100,", "axis=0, ignore_index=True) def format_runtime_string(raw_seconds: float) -> str: \"\"\"Creates a nice", "f'{int(minutes)}m' if seconds > 0 or not output: output +=", "flags.DEFINE_string('output', 'runtime_by_region_report.html', 'Path for the output report, which will be", "} .chart-container { padding: 30px; } </style> \"\"\" def read_sharded_runtime_tsvs(path_string:", "+ COUNT_COLUMNS d = d[columns_used] return alt.Chart(d).mark_circle(opacity=0.1).encode( x=alt.X(alt.repeat('column'), type='quantitative', axis=alt.Axis(labelExpr=\"datum.value", "of runtime profiling numbers. Returns: The dataframe grouped by task.", "break this into separate lines makes the code more readable.", "total runtime)', title='Runtime (seconds)'), y=alt.Y('task num examples:Q', title='Number of examples'),", "the runtime columns. df['total runtime'] = df[RUNTIME_COLUMNS].sum(axis=1) # Create a", "app.UsageError( 'Command line parsing failure: this script does not accept", "the file open/close to enable testing. print('Output written to:', output_filename)", "--runtime_by_region. \"\"\" from typing import Dict, Sequence, List, Tuple, Text,", "f'{len(regions_with_zero_examples)} regions that produced no examples, ' f'which is {runtime_of_zeros", "'histogram_by_task', 'chart': stage_histogram(by_task, title='Stage runtimes for each task') }, {", "string for tooltips. df['Runtime'] = df['total runtime'].apply(format_runtime_string) # Sort by", "List, Tuple, Text, Any, Union from absl import app from", "reproduce the above copyright # notice, this list of conditions", "by_task = summarize_by_task(df) return df, by_task def make_all_charts( df: pd.DataFrame,", "stage_histogram( bottom_99_percent, title='Runtime by stage for regions in the bottom", "The seconds divided into hours, minutes, and remaining seconds, formatted", "= df[RUNTIME_COLUMNS].sum(axis=1) # Create a formatted runtime string for tooltips.", "the output report, which will be an html file.') RUNTIME_COLUMNS", "With up to 5000 points, just show them all. charts.extend([{", "Args: d: A pandas dataframe of runtime by regions. title:", "top 20 and median 20 regions. Args: df: A dataframe", "= ( f'Spent {runtime_of_zeros:.2f} hours processing the ' f'{len(regions_with_zero_examples)} regions", "to avoid showing multiple overlapping # points which otherwise make", "top_5000, title='Trends for regions in the top 5000') }, {", "sep='\\t') else: d = pd.read_csv(path, sep='\\t') d['Task'] = i list_of_dataframes.append(d)", "put at the top of the report. html_output: Writable file", "hours.') return individual_region_bars( regions_with_zero_examples.nlargest(50, 'total runtime'), title={ 'text': 'The longest-running", "the tooltip for a pareto curve. \"\"\" return (f\"{row['task cumsum", "better. top_100 = df.nlargest(100, 'total runtime') top_5000 = df.nlargest(5000, 'total", "title='Trends for regions in the top 5000') }, { 'id':", "ascending=False) return df def summarize_by_task(df: pd.DataFrame) -> pd.DataFrame: \"\"\"Groups regions", "or by task. title: A title for the plot. Returns:", "curve shows to what extent a small proportion of long-running", "( f'Spent {runtime_of_zeros:.2f} hours processing the ' f'{len(regions_with_zero_examples)} regions that", "correlation_scatter_charts( bottom_99_percent, title='Trends for regions in the bottom 99%') }])", "document. html_output.write('<!DOCTYPE html>\\n<html>\\n<head>') # Add dependencies vega and vega-lite, which", "for each task') }, { 'id': 'selected_longest_and_median_regions', 'chart': selected_longest_and_median_regions(df) },", "CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN #", "added Task column. \"\"\" if sharded_file_utils.is_sharded_file_spec(path_string): paths = sharded_file_utils.generate_sharded_filenames(path_string) else:", "dataframe of runtime by regions. title: A title for the", "such as # chart.mark_bar().encode(...).properties(...), so using backslash # continuation to", "of all regions. Returns: An altair chart. \"\"\" regions_with_zero_examples =", "An altair chart. \"\"\" grouped = df.groupby(df['Task'], sort=False) df =", "Returns: An altair chart. \"\"\" num_rows = len(df) mid =", "AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT,", "d = pd.read_csv(path, sep='\\t') d['Task'] = i list_of_dataframes.append(d) return pd.concat(list_of_dataframes,", "' 'positional arguments, but found these extra arguments: \"{}\".' ''.format(str(argv[1:])))", "\"{}\".' ''.format(str(argv[1:]))) # Add html to the output path if", "from a file into one dataframe as-is and one by", "> 5000: x = 1000 df = pd.concat([df.nlargest(x, 'total runtime'),", "inplace=True, ascending=False) return df def summarize_by_task(df: pd.DataFrame) -> pd.DataFrame: \"\"\"Groups", "of the top 20 and median 20 regions. Args: df:", "SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS #", "one dataframe as-is and one by task. Args: input_path: str,", "show at the top of the report. subtitle: The subtitle", "source code must retain the above copyright notice, # this", "pd.DataFrame) -> pd.DataFrame: \"\"\"Groups regions to get the total runtime", "to the divs with VegaEmbed. html_output.write('<script>\\n') for chart in charts:", "'input', None, 'TSV file that was produced when running make_examples", "+= f'{int(minutes)}m' if seconds > 0 or not output: output", "nice format string from a potentially large number of seconds.", "in enumerate(paths): if path.startswith('gs://'): # Once pandas is updated to", "potentially large number of seconds. Args: raw_seconds: A number of", "2h3m5.012s. \"\"\" minutes, seconds = divmod(raw_seconds, 60) hours, minutes =", "> 0 or not output: output += f'{seconds}s' return output", "alt.Chart: \"\"\"Plots a histogram of runtimes stacked by stage. Args:", "chart['id'], embed_options)) html_output.write('</script>\\n') # Close HTML document. html_output.write('</body></html>') def read_data_and_make_dataframes(", "chart objects. title: The title to show at the top", "stage_histogram(df, title='Runtime by stage for all regions') }, { 'id':", "{runtime_of_zeros:.2f} hours processing the ' f'{len(regions_with_zero_examples)} regions that produced no", "runtime'] + RUNTIME_COLUMNS, row=COUNT_COLUMNS, ).properties(title=title) def totals_by_stage(d: pd.DataFrame) -> alt.Chart:", "for all regions') }, { 'id': 'scatter_grid', 'chart': correlation_scatter_charts(df, title='Trends", "stage_totals = stage_totals.rename(columns={'index': 'Stage'}) stage_totals['Runtime'] = stage_totals['Runtime (seconds)'].apply( format_runtime_string) return", "f\"account for {row['task cumsum fraction'] * 100:.2f}% of \" f\"the", "points. if len(df) <= 5000: # With up to 5000", "and remaining seconds, formatted nicely. For example, 2h3m5.012s. \"\"\" minutes,", "(seconds)', y=alt.Y('Stage', sort=None), tooltip=['Runtime'], fill=alt.Fill('Stage', sort=None)).properties(title='Overall runtime by stage') def", "an HTML report. Args: input_path: Path of the input TSV", "EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE.", "'chart': stage_histogram(df, title='Runtime by stage for all regions') }, {", "= read_data_and_make_dataframes(input_path) # Build all the charts. charts = make_all_charts(df,", "20 and median 20 regions. Args: df: A dataframe of", "the charts. charts = make_all_charts(df, by_task) # Write a subtitle", "IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR", "regions to get the total runtime for each task. Args:", "tasks in the Pareto # curve. brush = alt.selection_interval() pareto_by_task", "of conditions and the following disclaimer. # # 2. Redistributions", "= ['region', 'Runtime'] + RUNTIME_COLUMNS d = small_df[columns_used] return alt.Chart(d).transform_fold(", "charts: A list of altair chart objects. title: The title", "'\\n'.format(VEGA_URL)) html_output.write( '<script type=\"text/javascript\" src=\"{}/vega-lite@4.8.1\"></script>' '\\n'.format(VEGA_URL)) html_output.write( '<script type=\"text/javascript\" src=\"{}/vega-embed@6\"></script>'", "chart. \"\"\" num_rows = len(df) mid = round(num_rows / 2)", "a writable file object. Returns: None. Writes into the html_output", "the altair charts. html_output.write('<script type=\"text/javascript\" src=\"{}/vega@5\"></script>' '\\n'.format(VEGA_URL)) html_output.write( '<script type=\"text/javascript\"", "round(num_rows / 2) return individual_region_bars(df.iloc[0:20], 'Top runtime regions') \\ |", "df['total runtime'].sum() / 3600 subtitle = ( f'Spent {runtime_of_zeros:.2f} hours", "None. Writes into the html_output file object. \"\"\" # Start", "PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" #", "round(seconds, 3) output = '' if hours > 0: output", "alt.Chart]]]: \"\"\"Creates charts and puts them in a list with", "title='Runtime by stage for regions in the bottom 99%') },", "report. html_output: Writable file object where output will be written.", "Args: df: A dataframe with one row per region. by_task:", "for regions in the top 100') }, { 'id': 'scatter_grid_top_5000',", "in the same task, for the scatter plot: df_subset['task total", "task (drag to highlight)') \\ .add_selection(brush) return pareto_by_task | task_scatter", "PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY", "TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY", "runtime-by-region data generated by running make_examples with --runtime_by_region. \"\"\" from", "will work for gs:// # without this workaround. with tf.io.gfile.GFile(path)", "= df_subset.apply(pareto_by_task_tooltip, axis=1) return df_subset def pareto_and_runtimes_by_task(df: pd.DataFrame) -> alt.Chart:", "for chart in charts: html_output.write( '<div class=\"chart-container\" id=\"vis_{}\"></div>\\n'.format(chart['id'])) html_output.write('</div>') #", "'{}_{}'.format(title.replace(' ', '_'), chart['id']) embed_options = {'mode': 'vega-lite', 'downloadFileName': download_filename}", "and/or other materials provided with the distribution. # # 3.", "one by task. Args: input_path: str, path of the input", "df = pd.concat([df.nlargest(x, 'total runtime'), df.sample(5000 - x)]) # Limit", "in source and binary forms, with or without # modification,", "make_all_charts(df, by_task) # Write a subtitle with some top-level stats.", "# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,", "task. \"\"\" by_task = df.groupby(by=['Task']).sum() return by_task.reset_index() def stage_histogram(d: pd.DataFrame,", "A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL", "AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED", "make_all_charts( df: pd.DataFrame, by_task: pd.DataFrame) -> List[Dict[Text, Union[str, alt.Chart]]]: \"\"\"Creates", "examples', 'subtitle': subtitle }) def write_to_html_report(charts: List[Dict[Text, alt.Chart]], title: str,", "greatly reduce the size of the html report. columns_used =", "sharded_file_utils.generate_sharded_filenames(path_string) else: paths = [path_string] list_of_dataframes = [] for i,", ").properties(title=title) def totals_by_stage(d: pd.DataFrame) -> alt.Chart: \"\"\"Plots total runtimes for", "> 5000: bottom_99_percent = bottom_99_percent.sample(5000) charts.extend([{ 'id': 'histogram_bottom_99_percent', 'chart': stage_histogram(", "must reproduce the above copyright # notice, this list of", "'<div class=\"chart-container\" id=\"vis_{}\"></div>\\n'.format(chart['id'])) html_output.write('</div>') # Add JSON vega specs and", "pandas as pd import tensorflow as tf from third_party.nucleus.io import", "candidates', 'make pileup images', 'write outputs' ] COUNT_COLUMNS = ['num", "alt import pandas as pd import tensorflow as tf from", "= df['total runtime'].apply(format_runtime_string) # Sort by descending total region runtime.", "by stage for regions in the top 100') }, {", "else: paths = [path_string] list_of_dataframes = [] for i, path", "stage. Args: d: A dataframe of runtimes. Returns: An altair", "pd.DataFrame) -> pd.DataFrame: \"\"\"Calculates cumulative sums for a subset of", "}, { 'id': 'selected_longest_and_median_regions', 'chart': selected_longest_and_median_regions(df) }, { 'id': 'zero_examples',", "\"\"\" grouped = df.groupby(df['Task'], sort=False) df = grouped.apply(calculate_pareto_metrics) # Sample", "= stage_totals.rename(columns={'index': 'Stage'}) stage_totals['Runtime'] = stage_totals['Runtime (seconds)'].apply( format_runtime_string) return alt.Chart(stage_totals).mark_bar().encode(", "formatted nicely. For example, 2h3m5.012s. \"\"\" minutes, seconds = divmod(raw_seconds,", "regions_with_zero_examples = df[df['num examples'] == 0] runtime_of_zeros = regions_with_zero_examples['total runtime'].sum()", "is a curve for each task. Args: df: A dataframe", "main(argv: Sequence[str]): if len(argv) > 1: raise app.UsageError( 'Command line", "\"\"\" from typing import Dict, Sequence, List, Tuple, Text, Any,", "{ font-family: sans-serif; } .chart-container { padding: 30px; } </style>", "file (may be sharded). Returns: df: A dataframe with one", "dataframe with one row per region. by_task: A dataframe with", "summarize_by_task(df: pd.DataFrame) -> pd.DataFrame: \"\"\"Groups regions to get the total", ".mark_bar(opacity=0.3) \\ .encode( x=alt.X('runtime_by_stage:Q', bin=alt.Bin(maxbins=100), title='Runtime (seconds)'), y=alt.Y('count()', title='Count of", "return df, by_task def make_all_charts( df: pd.DataFrame, by_task: pd.DataFrame) ->", "pd.DataFrame) -> alt.Chart: \"\"\"Creates an interactive Pareto curve and scatter", "else: # With too many points, make different subsets to", "altair chart. \"\"\" regions_with_zero_examples = df[df['num examples'] == 0] runtime_of_zeros", "title='Number of examples'), color=alt.condition(brush, 'Task:N', alt.value('lightgray')), tooltip=['Task', 'Runtime for task']", "THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF", "so using backslash # continuation to break this into separate", "title: Union[str, Dict[str, str]] = '') -> alt.Chart: \"\"\"Makes a", "code more readable. # pylint: disable=g-backslash-continuation VEGA_URL = 'https://storage.googleapis.com/deepvariant/lib/vega' FLAGS", "/ n, range(0, n))) df_subset['tooltip'] = df_subset.apply(pareto_by_task_tooltip, axis=1) return df_subset", "\"\"\" num_rows = len(df) mid = round(num_rows / 2) return", "plots of runtimes of stages versus covariates. Args: d: A", "a potentially large number of seconds. Args: raw_seconds: A number", "# modification, are permitted provided that the following conditions #", "this script does not accept ' 'positional arguments, but found", "regions are shown. if len(df) > 5000: x = 1000", "font-family: sans-serif; } .chart-container { padding: 30px; } </style> \"\"\"", "and add summary columns. df, by_task = read_data_and_make_dataframes(input_path) # Build", "objects. title: The title to show at the top of", "cumulative sum columns. Returns: A string to show as the", "OF SUCH DAMAGE. r\"\"\"Create a visual report of make_examples runtime", "of \" f\"the runtime in task {row['Task']}\") def calculate_pareto_metrics(df_subset: pd.DataFrame)", "with or without # modification, are permitted provided that the", "just show them all. charts.extend([{ 'id': 'histogram', 'chart': stage_histogram(df, title='Runtime", "# software without specific prior written permission. # # THIS", "seconds > 0 or not output: output += f'{seconds}s' return", "runtime', 'task num examples', 'Runtime for task' ] df =", "hours processing the ' f'{len(regions_with_zero_examples)} regions that produced no examples,", "will be shown at the top of the report and", "These are the same for all regions in the same", "= read_sharded_runtime_tsvs(input_path) df = calculate_totals(df) by_task = summarize_by_task(df) return df,", "= pd.read_csv(f, sep='\\t') else: d = pd.read_csv(path, sep='\\t') d['Task'] =", "HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT,", "Can be sharded, e.g. /path/runtime@64.tsv.') flags.DEFINE_string( 'title', None, 'Title will", "html_output.write('<h1>{}</h1>\\n'.format(title)) html_output.write('<h2>{}</h2>\\n'.format(subtitle)) # Make a div containing all the charts.", "\"\"\" <style> body { font-family: sans-serif; } .chart-container { padding:", "order'] = list(map(lambda x: x / n, range(0, n))) df_subset['tooltip']", "spec_{} = {};\\n'.format(chart['id'], chart['chart'].to_json())) download_filename = '{}_{}'.format(title.replace(' ', '_'), chart['id'])", "COUNT_COLUMNS d = d[columns_used] return alt.Chart(d).mark_circle(opacity=0.1).encode( x=alt.X(alt.repeat('column'), type='quantitative', axis=alt.Axis(labelExpr=\"datum.value +", "Args: raw_seconds: A number of seconds. Returns: The seconds divided", "}, { 'id': 'scatter_grid_bottom_99_percent', 'chart': correlation_scatter_charts( bottom_99_percent, title='Trends for regions", "'') -> alt.Chart: \"\"\"Makes a stacked bar chart with runtime", "seconds divided into hours, minutes, and remaining seconds, formatted nicely.", "the input TSV file (may be sharded). Returns: df: A", "# Sample along the Pareto curve, ensuring the longest regions", "for task' ] df = df[columns_used] # Brushing on the", "# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR", "df_subset['task cumsum order'] = list(map(lambda x: x / n, range(0,", "Returns: The same dataframe with some additional summary columns. \"\"\"", "object. \"\"\" # Start the HTML document. html_output.write('<!DOCTYPE html>\\n<html>\\n<head>') #", "avoid outliers that obscure general trends. bottom_99_percent = df.nsmallest(int(len(df) *", "to highlight)') \\ .add_selection(brush) return pareto_by_task | task_scatter def individual_region_bars(small_df:", "x=alt.X( 'task cumsum order', title='The longest-runtime X% of regions', axis=alt.Axis(format='%')),", "color=alt.Color('Stage:N', sort=None) ).properties(title=title) def correlation_scatter_charts(d: pd.DataFrame, title: str = '')", "uses a lot of method chaining, such as # chart.mark_bar().encode(...).properties(...),", "dataframe of runtimes. Returns: An altair chart. \"\"\" stage_totals_series =", "file.') RUNTIME_COLUMNS = [ 'get reads', 'find candidates', 'make pileup", "arguments: \"{}\".' ''.format(str(argv[1:]))) # Add html to the output path", "regions') }]) else: # With too many points, make different", "x)]) # Limit columns to greatly reduce the size of", "'id': 'histogram', 'chart': stage_histogram(df, title='Runtime by stage for all regions')", "= alt.Chart(df).mark_line(size=2).encode( x=alt.X( 'task cumsum order', title='The longest-runtime X% of", "max(task) for 'text' is a # trick that causes bundling", "some specific cumulative sum columns. Returns: A string to show", "regions in the top 100') }, { 'id': 'scatter_grid_top_5000', 'chart':", "of the runtime columns. df['total runtime'] = df[RUNTIME_COLUMNS].sum(axis=1) # Create", "A dataframe of runtime profiling numbers. Returns: The same dataframe", "columns_used = [ 'task cumsum order', 'task cumsum fraction', 'tooltip',", "downloaded image files.') flags.DEFINE_string('output', 'runtime_by_region_report.html', 'Path for the output report,", "cumsum order', 'task cumsum fraction', 'tooltip', 'Task', 'task total runtime',", "OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE", "Altair shows a max of 5000 data points. if len(df)", "df['Runtime'] = df['total runtime'].apply(format_runtime_string) # Sort by descending total region", "['num reads', 'num candidates', 'num examples'] CSS_STYLES = \"\"\" <style>", "\"\"\" return (f\"{row['task cumsum order'] * 100:.2f}% of regions \"", "a subset of a dataframe. Args: df_subset: A dataframe subset", "= make_all_charts(df, by_task) # Write a subtitle with some top-level", "path if that is not already the suffix. if FLAGS.output.endswith('html'):", "tf.io.gfile.GFile(output_filename, 'w') make_report( input_path=FLAGS.input, title=FLAGS.title, html_output=html_output) html_output.close() # Abstracted out", "# Add JSON vega specs and hook them up to", "'Command line parsing failure: this script does not accept '", "type='quantitative', axis=alt.Axis(labelExpr=\"datum.value + 's'\")), y=alt.Y(alt.repeat('row'), type='quantitative'), tooltip='region' ).properties(width=100, height=100) \\", "are met: # # 1. Redistributions of source code must", "OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF", "df: A dataframe of runtime profiling numbers. Returns: The dataframe", "input TSV file (may be sharded). Returns: df: A dataframe", "column. \"\"\" if sharded_file_utils.is_sharded_file_spec(path_string): paths = sharded_file_utils.generate_sharded_filenames(path_string) else: paths =", "runtime regions') \\ | individual_region_bars(df.iloc[mid-10:mid+11], 'Median runtime regions') def top_regions_producing_zero_examples(df:", "(f'Runtime profiling for make_examples on {len(df)} regions ' f'across {len(by_task)}", "cumsum fraction', 'tooltip', 'Task', 'task total runtime', 'task num examples',", "sums for the pareto curves: df_subset['task cumsum fraction'] = df_subset['total", "'id': 'pareto_and_runtimes_by_task', 'chart': pareto_and_runtimes_by_task(df) }, { 'id': 'histogram_by_task', 'chart': stage_histogram(by_task,", "trends better. top_100 = df.nlargest(100, 'total runtime') top_5000 = df.nlargest(5000,", "to the overall runtime. That is, \"The longest-running X% of", "generated by running make_examples with --runtime_by_region. \"\"\" from typing import", "binary forms, with or without # modification, are permitted provided", "writable file object. Returns: None. Writes into the html_output file", "altair chart. \"\"\" grouped = df.groupby(df['Task'], sort=False) df = grouped.apply(calculate_pareto_metrics)", "Y% of the total runtime.\" There is a curve for", "1000 df = pd.concat([df.nlargest(x, 'total runtime'), df.sample(5000 - x)]) #", "# pylint: disable=g-backslash-continuation VEGA_URL = 'https://storage.googleapis.com/deepvariant/lib/vega' FLAGS = flags.FLAGS flags.DEFINE_string(", "HTML document. html_output.write('</body></html>') def read_data_and_make_dataframes( input_path: str) -> Tuple[pd.DataFrame, pd.DataFrame]:", "contributors may be used to endorse or promote products derived", "stage_totals['Runtime'] = stage_totals['Runtime (seconds)'].apply( format_runtime_string) return alt.Chart(stage_totals).mark_bar().encode( x='Runtime (seconds)', y=alt.Y('Stage',", "= df_subset['num examples'].sum() # These are cumulative sums for the", "by it. Args: df: A dataframe of runtime profiling numbers.", "task') }, { 'id': 'selected_longest_and_median_regions', 'chart': selected_longest_and_median_regions(df) }, { 'id':", "str: \"\"\"For one row of a dataframe, computes a tooltip", "longest-running regions that produced no examples', 'subtitle': subtitle }) def", "runtime profiling numbers. Returns: The dataframe grouped by task. \"\"\"", "products derived from this # software without specific prior written", "def write_to_html_report(charts: List[Dict[Text, alt.Chart]], title: str, subtitle: str, html_output: Any)", "paths = [path_string] list_of_dataframes = [] for i, path in", "enable the # brushing on one to affect the other.", "100:.2f}% of the total ' f'runtime of {total_runtime:.2f} hours.') return", "the name of the copyright holder nor the names of", "an interactive Pareto curve and scatter plot of task runtimes.", "trends. bottom_99_percent = df.nsmallest(int(len(df) * .99), 'total runtime') if len(bottom_99_percent)", "of regions', axis=alt.Axis(format='%')), y=alt.Y( 'task cumsum fraction', title='Account for Y%", "pareto_by_task = alt.Chart(df).mark_line(size=2).encode( x=alt.X( 'task cumsum order', title='The longest-runtime X%", "which will be shown as a bar. title: A title", "df_subset: A dataframe subset of one task. Returns: The same", "\"\"\"Produces a grid of scatter plots of runtimes of stages", "pd.DataFrame: \"\"\"Calculates cumulative sums for a subset of a dataframe.", "List[Dict[Text, Union[str, alt.Chart]]]: \"\"\"Creates charts and puts them in a", "task').interactive() # This chart needs to use the same dataframe", "flags.DEFINE_string( 'title', None, 'Title will be shown at the top", "stacked bar chart with runtime of each stage for individual", "runtime'].apply( format_runtime_string) df_subset['task num examples'] = df_subset['num examples'].sum() # These", "them in a list with their ID names. Args: df:", "d = d[columns_used] return alt.Chart(d).transform_fold( RUNTIME_COLUMNS, as_=['Stage', 'runtime_by_stage']) \\ .mark_bar(opacity=0.3)", "top of the report. subtitle: The subtitle to show just", "def read_sharded_runtime_tsvs(path_string: str) -> pd.DataFrame: \"\"\"Imports data from a single", "y=alt.Y('task num examples:Q', title='Number of examples'), color=alt.condition(brush, 'Task:N', alt.value('lightgray')), tooltip=['Task',", "['region', 'Runtime'] + RUNTIME_COLUMNS d = small_df[columns_used] return alt.Chart(d).transform_fold( RUNTIME_COLUMNS,", "pd.DataFrame) -> pd.DataFrame: \"\"\"Calculates total runtime, formats it nicely, and", "f'{seconds}s' return output def calculate_totals(df: pd.DataFrame) -> pd.DataFrame: \"\"\"Calculates total", "return alt.Chart(d).transform_fold( RUNTIME_COLUMNS, as_=['Stage', 'runtime_by_stage']) \\ .mark_bar(opacity=0.3) \\ .encode( x=alt.X('runtime_by_stage:Q',", "regions in the bottom 99%') }, { 'id': 'histogram_top_100', 'chart':", "'title', None, 'Title will be shown at the top of", "\"\"\"Creates an interactive Pareto curve and scatter plot of task", "alt.Chart]], title: str, subtitle: str, html_output: Any) -> None: \"\"\"Makes", "ID. \"\"\" charts = [{ 'id': 'total_by_stage', 'chart': totals_by_stage(by_task) },", "following disclaimer. # # 2. Redistributions in binary form must", "longest-running X% of regions account for Y% of the total", "'total runtime'), title={ 'text': 'The longest-running regions that produced no", "title: str, subtitle: str, html_output: Any) -> None: \"\"\"Makes the", "stage_histogram( top_100, title='Runtime by stage for regions in the top", "'id': 'scatter_grid_top_5000', 'chart': correlation_scatter_charts( top_5000, title='Trends for regions in the", "them up to the divs with VegaEmbed. html_output.write('<script>\\n') for chart", "total runtime for each task. Args: df: A dataframe of", "of regions account for Y% of the total runtime.\" There", "'Task:N', alt.value('lightgray')), tooltip=['Task', 'Runtime for task'] ) \\ .properties(title='Total runtime", "Once pandas is updated to 0.24+, pd.read_csv will work for", "(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS", "as the tooltip for a pareto curve. \"\"\" return (f\"{row['task", "reads', 'num candidates', 'num examples'] CSS_STYLES = \"\"\" <style> body", "A dataframe of runtimes, either by region or by task.", "the HTML report with all the charts. write_to_html_report( charts=charts, title=title,", "may be used to endorse or promote products derived from", "curve for each task. Args: df: A dataframe of all", "dataframe of all regions. Returns: An altair chart. \"\"\" num_rows", "tf.io.gfile.GFile(path) as f: d = pd.read_csv(f, sep='\\t') else: d =", "regions. Args: df: A dataframe of all regions. Returns: An", "Writable file object where output will be written. \"\"\" #", "\"\"\"Groups regions to get the total runtime for each task.", "columns. \"\"\" # These are the same for all regions", "or sharded path into a pandas dataframe. Args: path_string: The", "shown. if len(df) > 5000: x = 1000 df =", "of the input TSV file (may be sharded). Returns: df:", "work for gs:// # without this workaround. with tf.io.gfile.GFile(path) as", "which otherwise make the text look funky. task_scatter = alt.Chart(df).mark_point(size=10).encode(", "of conditions and the following disclaimer in the # documentation", "for regions in the bottom 99%') }, { 'id': 'histogram_top_100',", "TSV file(s) but with added Task column. \"\"\" if sharded_file_utils.is_sharded_file_spec(path_string):", "\"\"\" by_task = df.groupby(by=['Task']).sum() return by_task.reset_index() def stage_histogram(d: pd.DataFrame, title:", "with one row per region. by_task: A dataframe with one", "which will be an html file.') RUNTIME_COLUMNS = [ 'get", "document. Using GFile enables writing to GCS too. html_output =", "n = len(df_subset) df_subset['task cumsum order'] = list(map(lambda x: x", "charts of the top 20 and median 20 regions. Args:", "scatter plot: df_subset['task total runtime'] = df_subset['total runtime'].sum() df_subset['Runtime for", "which render the altair charts. html_output.write('<script type=\"text/javascript\" src=\"{}/vega@5\"></script>' '\\n'.format(VEGA_URL)) html_output.write(", "read_sharded_runtime_tsvs(path_string: str) -> pd.DataFrame: \"\"\"Imports data from a single or", "and vega-lite, which render the altair charts. html_output.write('<script type=\"text/javascript\" src=\"{}/vega@5\"></script>'", "columns_used = ['region', 'total runtime'] + RUNTIME_COLUMNS + COUNT_COLUMNS d", "}, { 'id': 'zero_examples', 'chart': top_regions_producing_zero_examples(df) }] # Altair shows", "df_subset['total runtime'].cumsum( ) / df_subset['total runtime'].sum() n = len(df_subset) df_subset['task", "minutes, seconds = divmod(raw_seconds, 60) hours, minutes = divmod(minutes, 60)", "type='quantitative'), tooltip='region' ).properties(width=100, height=100) \\ .repeat( column=['total runtime'] + RUNTIME_COLUMNS,", "vega and vega-lite, which render the altair charts. html_output.write('<script type=\"text/javascript\"", "' f'runtime of {total_runtime:.2f} hours.') return individual_region_bars( regions_with_zero_examples.nlargest(50, 'total runtime'),", "the html_output file object. \"\"\" # Start the HTML document.", "if sharded_file_utils.is_sharded_file_spec(path_string): paths = sharded_file_utils.generate_sharded_filenames(path_string) else: paths = [path_string] list_of_dataframes", "curve and scatter plot of task runtimes. Tracing each curve", "len(bottom_99_percent) > 5000: bottom_99_percent = bottom_99_percent.sample(5000) charts.extend([{ 'id': 'histogram_bottom_99_percent', 'chart':", "by region or by task. title: A title for the", "and median 20 regions. Args: df: A dataframe of all", "Pareto curve, ensuring the longest regions are shown. if len(df)", "show trends better. top_100 = df.nlargest(100, 'total runtime') top_5000 =", "median 20 regions. Args: df: A dataframe of all regions.", "dataframe as-is and one by task. Args: input_path: str, path", "sep='\\t') d['Task'] = i list_of_dataframes.append(d) return pd.concat(list_of_dataframes, axis=0, ignore_index=True) def", "pd.read_csv(f, sep='\\t') else: d = pd.read_csv(path, sep='\\t') d['Task'] = i", "LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR #", "The path to the input file, which may be sharded.", "causes bundling by task to avoid showing multiple overlapping #", "# Altair uses a lot of method chaining, such as", "pylint: disable=g-backslash-continuation VEGA_URL = 'https://storage.googleapis.com/deepvariant/lib/vega' FLAGS = flags.FLAGS flags.DEFINE_string( 'input',", "with added Task column. \"\"\" if sharded_file_utils.is_sharded_file_spec(path_string): paths = sharded_file_utils.generate_sharded_filenames(path_string)", "html_output.write('</script>\\n') # Close HTML document. html_output.write('</body></html>') def read_data_and_make_dataframes( input_path: str)", "'\\n'.format(VEGA_URL)) html_output.write( '<script type=\"text/javascript\" src=\"{}/vega-embed@6\"></script>' '\\n'.format(VEGA_URL)) # Add styles (CSS).", "regions contribute disproportionately to the overall runtime. That is, \"The", "= summarize_by_task(df) return df, by_task def make_all_charts( df: pd.DataFrame, by_task:", "a small proportion of long-running regions contribute disproportionately to the", "string to show as the tooltip for a pareto curve.", "the # brushing on one to affect the other. Using", "runtime by regions. title: A title for the plot. Returns:", "Returns: list of dicts, each containing a chart and a", "this list of conditions and the following disclaimer in the", "grouped by task. \"\"\" by_task = df.groupby(by=['Task']).sum() return by_task.reset_index() def", "import flags import altair as alt import pandas as pd", "runtime'].sum() / 3600 total_runtime = df['total runtime'].sum() / 3600 subtitle", "title for the plot. Returns: An altair chart \"\"\" columns_used", "modification, are permitted provided that the following conditions # are", "of the copyright holder nor the names of its #", "funky. task_scatter = alt.Chart(df).mark_point(size=10).encode( x=alt.X('max(task total runtime)', title='Runtime (seconds)'), y=alt.Y('task", "import pandas as pd import tensorflow as tf from third_party.nucleus.io", "'<script type=\"text/javascript\" src=\"{}/vega-embed@6\"></script>' '\\n'.format(VEGA_URL)) # Add styles (CSS). html_output.write(CSS_STYLES) html_output.write('</head>\\n<body>')", "file that was produced when running make_examples ' 'with --runtime_by_region.", "number of seconds. Returns: The seconds divided into hours, minutes,", "by stage') def pareto_by_task_tooltip(row: pd.Series) -> str: \"\"\"For one row", "A dataframe of all regions. Returns: An altair chart. \"\"\"", "columns. df['total runtime'] = df[RUNTIME_COLUMNS].sum(axis=1) # Create a formatted runtime", "task_scatter def individual_region_bars(small_df: pd.DataFrame, title: Union[str, Dict[str, str]] = '')", "# Once pandas is updated to 0.24+, pd.read_csv will work", "pd.DataFrame) -> List[Dict[Text, Union[str, alt.Chart]]]: \"\"\"Creates charts and puts them", "be sharded). Returns: df: A dataframe with one row per", "the code more readable. # pylint: disable=g-backslash-continuation VEGA_URL = 'https://storage.googleapis.com/deepvariant/lib/vega'", "stage_histogram(by_task, title='Stage runtimes for each task') }, { 'id': 'selected_longest_and_median_regions',", "html>\\n<html>\\n<head>') # Add dependencies vega and vega-lite, which render the", "failure: this script does not accept ' 'positional arguments, but", "pandas dataframe. Args: path_string: The path to the input file,", "dict, it should contain 'title' and/or 'subtitle'. Returns: An altair", "60) seconds = round(seconds, 3) output = '' if hours", "= flags.FLAGS flags.DEFINE_string( 'input', None, 'TSV file that was produced", "with --runtime_by_region. \"\"\" from typing import Dict, Sequence, List, Tuple,", "task {row['Task']}\") def calculate_pareto_metrics(df_subset: pd.DataFrame) -> pd.DataFrame: \"\"\"Calculates cumulative sums", "100') }, { 'id': 'scatter_grid_top_5000', 'chart': correlation_scatter_charts( top_5000, title='Trends for", "-> pd.DataFrame: \"\"\"Groups regions to get the total runtime for", "on {len(df)} regions ' f'across {len(by_task)} task{\"(s)\" if len(by_task) >", "charts and puts them in a list with their ID", "\"\"}') # Write the HTML report with all the charts.", "ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. r\"\"\"Create a", "charts. charts = make_all_charts(df, by_task) # Write a subtitle with", "task'] ) \\ .properties(title='Total runtime for each task (drag to", "'find candidates', 'make pileup images', 'write outputs' ] COUNT_COLUMNS =", "runtime)', title='Runtime (seconds)'), y=alt.Y('task num examples:Q', title='Number of examples'), color=alt.condition(brush,", "\"\"\"Creates a stacked bar charts of the top 20 and", "the charts. html_output.write('<div>') for chart in charts: html_output.write( '<div class=\"chart-container\"", "the report. html_output: a writable file object. Returns: None. Writes", "altair as alt import pandas as pd import tensorflow as", "99%') }, { 'id': 'histogram_top_100', 'chart': stage_histogram( top_100, title='Runtime by", "seconds, formatted nicely. For example, 2h3m5.012s. \"\"\" minutes, seconds =", "color=alt.condition(brush, 'Task:N', alt.value('lightgray')), tooltip=['Task', 'Runtime for task'] ) \\ .properties(title='Total", "flags import altair as alt import pandas as pd import", "be written. \"\"\" # Load data into pandas dataframes and", "distribution. # # 3. Neither the name of the copyright", "title='Stage runtimes for each task') }, { 'id': 'selected_longest_and_median_regions', 'chart':", "= df.groupby(by=['Task']).sum() return by_task.reset_index() def stage_histogram(d: pd.DataFrame, title: str =", "df: pd.DataFrame, by_task: pd.DataFrame) -> List[Dict[Text, Union[str, alt.Chart]]]: \"\"\"Creates charts", "Sample the bottom 99% to avoid outliers that obscure general", "Redistributions in binary form must reproduce the above copyright #", "NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND", "chart of the top regions that produced zero examples. Args:", "that obscure general trends. bottom_99_percent = df.nsmallest(int(len(df) * .99), 'total", "['region', 'total runtime'] + RUNTIME_COLUMNS + COUNT_COLUMNS d = d[columns_used]", "file object. \"\"\" # Start the HTML document. html_output.write('<!DOCTYPE html>\\n<html>\\n<head>')", "(seconds)'), y=alt.Y('count()', title='Count of regions', stack=None), color=alt.Color('Stage:N', sort=None) ).properties(title=title) def", "stage_totals['Runtime (seconds)'].apply( format_runtime_string) return alt.Chart(stage_totals).mark_bar().encode( x='Runtime (seconds)', y=alt.Y('Stage', sort=None), tooltip=['Runtime'],", "by task. Args: input_path: str, path of the input TSV", "stage for regions in the top 100') }, { 'id':", "title='Account for Y% of the total runtime', axis=alt.Axis(format='%')), tooltip='tooltip', color=alt.condition(brush,", "output += f'{int(minutes)}m' if seconds > 0 or not output:", "of the report and will ' 'be used as a", "the Pareto # curve. brush = alt.selection_interval() pareto_by_task = alt.Chart(df).mark_line(size=2).encode(", "1. Redistributions of source code must retain the above copyright", "A title for the plot. Returns: An altair chart \"\"\"", "# Make a div containing all the charts. html_output.write('<div>') for", "total runtime'].apply( format_runtime_string) df_subset['task num examples'] = df_subset['num examples'].sum() #", "# Start HTML document. Using GFile enables writing to GCS", "PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE", "that was produced when running make_examples ' 'with --runtime_by_region. Can", "The same dataframe with some additional summary columns. \"\"\" #", "(seconds)'].apply( format_runtime_string) return alt.Chart(stage_totals).mark_bar().encode( x='Runtime (seconds)', y=alt.Y('Stage', sort=None), tooltip=['Runtime'], fill=alt.Fill('Stage',", "styles (CSS). html_output.write(CSS_STYLES) html_output.write('</head>\\n<body>') html_output.write('<h1>{}</h1>\\n'.format(title)) html_output.write('<h2>{}</h2>\\n'.format(subtitle)) # Make a div", "body { font-family: sans-serif; } .chart-container { padding: 30px; }", "title: str = '') -> alt.Chart: \"\"\"Plots a histogram of", "\"\"\"Creates a chart of the top regions that produced zero", "runtime'] = df[RUNTIME_COLUMNS].sum(axis=1) # Create a formatted runtime string for", "type=\"text/javascript\" src=\"{}/vega-lite@4.8.1\"></script>' '\\n'.format(VEGA_URL)) html_output.write( '<script type=\"text/javascript\" src=\"{}/vega-embed@6\"></script>' '\\n'.format(VEGA_URL)) # Add", "dataframe, computes a tooltip description. Args: row: A Pandas Series,", "Title to put at the top of the report. html_output:", "\\ .mark_bar(opacity=0.3) \\ .encode( x=alt.X('runtime_by_stage:Q', bin=alt.Bin(maxbins=100), title='Runtime (seconds)'), y=alt.Y('count()', title='Count", "additional summary columns. \"\"\" # 'total runtime' is a simple", "subtitle with some top-level stats. subtitle = (f'Runtime profiling for", "produced no examples', 'subtitle': subtitle }) def write_to_html_report(charts: List[Dict[Text, alt.Chart]],", "that the following conditions # are met: # # 1.", "to put at the top of the report. html_output: Writable", "charts: html_output.write( '<div class=\"chart-container\" id=\"vis_{}\"></div>\\n'.format(chart['id'])) html_output.write('</div>') # Add JSON vega", "Returns: df: A dataframe with one row per region. by_task:", "= df.groupby(df['Task'], sort=False) df = grouped.apply(calculate_pareto_metrics) # Sample along the", "'tooltip', 'Task', 'task total runtime', 'task num examples', 'Runtime for", "task runtimes. Tracing each curve shows to what extent a", "\"\"\"For one row of a dataframe, computes a tooltip description.", "small_df: A dataframe of regions, each of which will be", "into pandas dataframes and add summary columns. df, by_task =", "This chart needs to use the same dataframe as the", "d[columns_used] return alt.Chart(d).transform_fold( RUNTIME_COLUMNS, as_=['Stage', 'runtime_by_stage']) \\ .mark_bar(opacity=0.3) \\ .encode(", "for a pareto curve. \"\"\" return (f\"{row['task cumsum order'] *", "a formatted runtime string for tooltips. df['Runtime'] = df['total runtime'].apply(format_runtime_string)", "stack=None), color=alt.Color('Stage:N', sort=None) ).properties(title=title) def correlation_scatter_charts(d: pd.DataFrame, title: str =", "for task'] = df_subset['task total runtime'].apply( format_runtime_string) df_subset['task num examples']", "some top-level stats. subtitle = (f'Runtime profiling for make_examples on", "list of dicts, each containing a chart and a descriptive", "for tooltips. df['Runtime'] = df['total runtime'].apply(format_runtime_string) # Sort by descending", "conditions # are met: # # 1. Redistributions of source", "the same for all regions in the same task, for", "individual_region_bars(df.iloc[0:20], 'Top runtime regions') \\ | individual_region_bars(df.iloc[mid-10:mid+11], 'Median runtime regions')", "image files.') flags.DEFINE_string('output', 'runtime_by_region_report.html', 'Path for the output report, which", "trick that causes bundling by task to avoid showing multiple", "to enable testing. print('Output written to:', output_filename) if __name__ ==", "'id': 'selected_longest_and_median_regions', 'chart': selected_longest_and_median_regions(df) }, { 'id': 'zero_examples', 'chart': top_regions_producing_zero_examples(df)", "stage_histogram(d: pd.DataFrame, title: str = '') -> alt.Chart: \"\"\"Plots a", "y=alt.Y(alt.repeat('row'), type='quantitative'), tooltip='region' ).properties(width=100, height=100) \\ .repeat( column=['total runtime'] +" ]
[ "z: string, w: string}') # Selecting a single field b", "= nd.fields(a, 'z', 'y') self.assertEqual(nd.dtype_of(b), ndt.make_struct( [ndt.string, ndt.int32], ['z', 'y']))", "self.assertEqual(nd.as_py(b.z), nd.as_py(a.z)) self.assertEqual(nd.as_py(b.y), nd.as_py(a.y)) # Selecting three fields b =", "(9, 10, 'X', 'Y'), (11, 12, 'the', 'end')]], type='3 *", "= nd.fields(a, 'z', 'y') self.assertEqual(nd.type_of(b), ndt.make_fixed_dim(3, ndt.make_var_dim(ndt.make_struct( [ndt.string, ndt.int32], ['z',", "nd.as_py(a.y)) # Selecting three fields b = nd.fields(a, 'w', 'y',", "ndt.int32], ['z', 'y'])) self.assertEqual(nd.as_py(b.z), nd.as_py(a.z)) self.assertEqual(nd.as_py(b.y), nd.as_py(a.y)) # Selecting three", "b = nd.fields(a, 'w', 'y', 'z') self.assertEqual(nd.dtype_of(b), ndt.make_struct( [ndt.string, ndt.int32,", "'y', 'z') self.assertEqual(nd.dtype_of(b), ndt.make_struct( [ndt.string, ndt.int32, ndt.string], ['w', 'y', 'z']))", "[ndt.string, ndt.int32], ['z', 'y'])))) self.assertEqual(nd.as_py(b.z), nd.as_py(a.z)) self.assertEqual(nd.as_py(b.y), nd.as_py(a.y)) # Selecting", "'y') self.assertEqual(nd.type_of(b), ndt.make_fixed_dim(3, ndt.make_var_dim(ndt.make_struct( [ndt.string, ndt.int32], ['z', 'y'])))) self.assertEqual(nd.as_py(b.z), nd.as_py(a.z))", "'cd')], [(5, 6, 'def', 'ghi')], [(7, 8, 'alpha', 'beta'), (9,", "10, 'X', 'Y'), (11, 12, 'the', 'end')]], type='3 * var", "all four fields b = nd.fields(a, 'w', 'y', 'x', 'z')", "ndt.string], ['w', 'y', 'z'])) self.assertEqual(nd.as_py(b.w), nd.as_py(a.w)) self.assertEqual(nd.as_py(b.y), nd.as_py(a.y)) self.assertEqual(nd.as_py(b.z), nd.as_py(a.z))", "type='3 * var * {x: int32, y: int32, z: string,", "'y', 'z'])))) self.assertEqual(nd.as_py(b.w), nd.as_py(a.w)) self.assertEqual(nd.as_py(b.y), nd.as_py(a.y)) self.assertEqual(nd.as_py(b.z), nd.as_py(a.z)) # Reordering", "type='3 * {x: int32, y: int32, z: string, w: string}')", "[ndt.string, ndt.int32, ndt.string], ['w', 'y', 'z'])) self.assertEqual(nd.as_py(b.w), nd.as_py(a.w)) self.assertEqual(nd.as_py(b.y), nd.as_py(a.y))", "ndt.make_fixed_dim(3, ndt.make_var_dim(ndt.make_struct( [ndt.string, ndt.int32, ndt.string], ['w', 'y', 'z'])))) self.assertEqual(nd.as_py(b.w), nd.as_py(a.w))", "'w', 'y', 'z') self.assertEqual(nd.type_of(b), ndt.make_fixed_dim(3, ndt.make_var_dim(ndt.make_struct( [ndt.string, ndt.int32, ndt.string], ['w',", "[ndt.int32], ['x'])) self.assertEqual(nd.as_py(b.x), nd.as_py(a.x)) # Selecting two fields b =", "ndt.make_struct( [ndt.string, ndt.int32, ndt.string], ['w', 'y', 'z'])) self.assertEqual(nd.as_py(b.w), nd.as_py(a.w)) self.assertEqual(nd.as_py(b.y),", "nd.as_py(a.z)) def test_fixed_var(self): a = nd.array([ [(1, 2, 'a', 'b'),", "self.assertEqual(nd.as_py(b.x), nd.as_py(a.x)) self.assertEqual(nd.as_py(b.z), nd.as_py(a.z)) def test_bad_field_name(self): a = nd.array([ (1,", "nd.as_py(a.w)) self.assertEqual(nd.as_py(b.y), nd.as_py(a.y)) self.assertEqual(nd.as_py(b.z), nd.as_py(a.z)) # Reordering all four fields", "['w', 'y', 'z'])))) self.assertEqual(nd.as_py(b.w), nd.as_py(a.w)) self.assertEqual(nd.as_py(b.y), nd.as_py(a.y)) self.assertEqual(nd.as_py(b.z), nd.as_py(a.z)) #", "four fields b = nd.fields(a, 'w', 'y', 'x', 'z') self.assertEqual(nd.type_of(b),", "ndt.int32, ndt.string], ['w', 'y', 'z'])))) self.assertEqual(nd.as_py(b.w), nd.as_py(a.w)) self.assertEqual(nd.as_py(b.y), nd.as_py(a.y)) self.assertEqual(nd.as_py(b.z),", "[(7, 8, 'alpha', 'beta'), (9, 10, 'X', 'Y'), (11, 12,", "'Y'), (11, 12, 'the', 'end')]], type='3 * var * {x:", "'y', 'x', 'z'])))) self.assertEqual(nd.as_py(b.w), nd.as_py(a.w)) self.assertEqual(nd.as_py(b.y), nd.as_py(a.y)) self.assertEqual(nd.as_py(b.x), nd.as_py(a.x)) self.assertEqual(nd.as_py(b.z),", "= nd.fields(a, 'w', 'y', 'z') self.assertEqual(nd.dtype_of(b), ndt.make_struct( [ndt.string, ndt.int32, ndt.string],", "int32, y: int32, z: string, w: string}') # Selecting a", "'beta'), (9, 10, 'X', 'Y'), (11, 12, 'the', 'end')]], type='3", "12, 'the', 'end')]], type='3 * var * {x: int32, y:", "# Selecting two fields b = nd.fields(a, 'z', 'y') self.assertEqual(nd.type_of(b),", "# Selecting two fields b = nd.fields(a, 'z', 'y') self.assertEqual(nd.dtype_of(b),", "b = nd.fields(a, 'x') self.assertEqual(nd.type_of(b), ndt.make_fixed_dim(3, ndt.make_var_dim(ndt.make_struct( [ndt.int32], ['x'])))) self.assertEqual(nd.as_py(b.x),", "string}') # Selecting a single field b = nd.fields(a, 'x')", "b = nd.fields(a, 'w', 'y', 'x', 'z') self.assertEqual(nd.dtype_of(b), ndt.make_struct( [ndt.string,", "'w', 'y', 'x', 'z') self.assertEqual(nd.dtype_of(b), ndt.make_struct( [ndt.string, ndt.int32, ndt.int32, ndt.string],", "self.assertEqual(nd.type_of(b), ndt.make_fixed_dim(3, ndt.make_var_dim(ndt.make_struct( [ndt.string, ndt.int32], ['z', 'y'])))) self.assertEqual(nd.as_py(b.z), nd.as_py(a.z)) self.assertEqual(nd.as_py(b.y),", "['z', 'y'])) self.assertEqual(nd.as_py(b.z), nd.as_py(a.z)) self.assertEqual(nd.as_py(b.y), nd.as_py(a.y)) # Selecting three fields", "'ab', 'cd')], [(5, 6, 'def', 'ghi')], [(7, 8, 'alpha', 'beta'),", "self.assertRaises(RuntimeError, nd.fields, a, 'y', 'v') \"\"\" if __name__ == '__main__':", "'w', 'y', 'z') self.assertEqual(nd.dtype_of(b), ndt.make_struct( [ndt.string, ndt.int32, ndt.string], ['w', 'y',", "TestFields(unittest.TestCase): def test_simple(self): a = nd.array([ (1, 2, 'a', 'b'),", "import unittest from dynd import nd, ndt \"\"\" class TestFields(unittest.TestCase):", "ndt.make_fixed_dim(3, ndt.make_var_dim(ndt.make_struct( [ndt.string, ndt.int32], ['z', 'y'])))) self.assertEqual(nd.as_py(b.z), nd.as_py(a.z)) self.assertEqual(nd.as_py(b.y), nd.as_py(a.y))", "string, w: string}') # Selecting a single field b =", "'x', 'z') self.assertEqual(nd.type_of(b), ndt.make_fixed_dim(3, ndt.make_var_dim(ndt.make_struct( [ndt.string, ndt.int32, ndt.int32, ndt.string], ['w',", "'w', 'y', 'x', 'z') self.assertEqual(nd.type_of(b), ndt.make_fixed_dim(3, ndt.make_var_dim(ndt.make_struct( [ndt.string, ndt.int32, ndt.int32,", "'ghi')], type='3 * {x: int32, y: int32, z: string, w:", "'b'), (3, 4, 'ab', 'cd')], [(5, 6, 'def', 'ghi')], [(7,", "= nd.fields(a, 'x') self.assertEqual(nd.type_of(b), ndt.make_fixed_dim(3, ndt.make_var_dim(ndt.make_struct( [ndt.int32], ['x'])))) self.assertEqual(nd.as_py(b.x), nd.as_py(a.x))", "ndt.make_var_dim(ndt.make_struct( [ndt.int32], ['x'])))) self.assertEqual(nd.as_py(b.x), nd.as_py(a.x)) # Selecting two fields b", "Selecting three fields b = nd.fields(a, 'w', 'y', 'z') self.assertEqual(nd.type_of(b),", "three fields b = nd.fields(a, 'w', 'y', 'z') self.assertEqual(nd.type_of(b), ndt.make_fixed_dim(3,", "2, 'a', 'b'), (3, 4, 'ab', 'cd'), (5, 6, 'def',", "single field b = nd.fields(a, 'x') self.assertEqual(nd.dtype_of(b), ndt.make_struct( [ndt.int32], ['x']))", "ndt.int32], ['z', 'y'])))) self.assertEqual(nd.as_py(b.z), nd.as_py(a.z)) self.assertEqual(nd.as_py(b.y), nd.as_py(a.y)) # Selecting three", "ndt.make_fixed_dim(3, ndt.make_var_dim(ndt.make_struct( [ndt.string, ndt.int32, ndt.int32, ndt.string], ['w', 'y', 'x', 'z']))))", "'ab', 'cd'), (5, 6, 'def', 'ghi')], type='3 * {x: int32,", "ndt.make_var_dim(ndt.make_struct( [ndt.string, ndt.int32, ndt.string], ['w', 'y', 'z'])))) self.assertEqual(nd.as_py(b.w), nd.as_py(a.w)) self.assertEqual(nd.as_py(b.y),", "* {x: int32, y: int32, z: string, w: string}') self.assertRaises(RuntimeError,", "w: string}') # Selecting a single field b = nd.fields(a,", "four fields b = nd.fields(a, 'w', 'y', 'x', 'z') self.assertEqual(nd.dtype_of(b),", "test_bad_field_name(self): a = nd.array([ (1, 2, 'a', 'b'), (3, 4,", "['w', 'y', 'z'])) self.assertEqual(nd.as_py(b.w), nd.as_py(a.w)) self.assertEqual(nd.as_py(b.y), nd.as_py(a.y)) self.assertEqual(nd.as_py(b.z), nd.as_py(a.z)) #", "nd.fields(a, 'w', 'y', 'x', 'z') self.assertEqual(nd.type_of(b), ndt.make_fixed_dim(3, ndt.make_var_dim(ndt.make_struct( [ndt.string, ndt.int32,", "['z', 'y'])))) self.assertEqual(nd.as_py(b.z), nd.as_py(a.z)) self.assertEqual(nd.as_py(b.y), nd.as_py(a.y)) # Selecting three fields", "nd.array([ [(1, 2, 'a', 'b'), (3, 4, 'ab', 'cd')], [(5,", "(5, 6, 'def', 'ghi')], type='3 * {x: int32, y: int32,", "ndt.string], ['w', 'y', 'z'])))) self.assertEqual(nd.as_py(b.w), nd.as_py(a.w)) self.assertEqual(nd.as_py(b.y), nd.as_py(a.y)) self.assertEqual(nd.as_py(b.z), nd.as_py(a.z))", "def test_simple(self): a = nd.array([ (1, 2, 'a', 'b'), (3,", "self.assertEqual(nd.as_py(b.x), nd.as_py(a.x)) # Selecting two fields b = nd.fields(a, 'z',", "nd.as_py(a.y)) self.assertEqual(nd.as_py(b.z), nd.as_py(a.z)) # Reordering all four fields b =", "= nd.array([ (1, 2, 'a', 'b'), (3, 4, 'ab', 'cd'),", "nd.fields(a, 'z', 'y') self.assertEqual(nd.dtype_of(b), ndt.make_struct( [ndt.string, ndt.int32], ['z', 'y'])) self.assertEqual(nd.as_py(b.z),", "'def', 'ghi')], type='3 * {x: int32, y: int32, z: string,", "= nd.fields(a, 'w', 'y', 'x', 'z') self.assertEqual(nd.type_of(b), ndt.make_fixed_dim(3, ndt.make_var_dim(ndt.make_struct( [ndt.string,", "self.assertEqual(nd.as_py(b.w), nd.as_py(a.w)) self.assertEqual(nd.as_py(b.y), nd.as_py(a.y)) self.assertEqual(nd.as_py(b.x), nd.as_py(a.x)) self.assertEqual(nd.as_py(b.z), nd.as_py(a.z)) def test_bad_field_name(self):", "fields b = nd.fields(a, 'w', 'y', 'x', 'z') self.assertEqual(nd.type_of(b), ndt.make_fixed_dim(3,", "self.assertEqual(nd.dtype_of(b), ndt.make_struct( [ndt.int32], ['x'])) self.assertEqual(nd.as_py(b.x), nd.as_py(a.x)) # Selecting two fields", "test_fixed_var(self): a = nd.array([ [(1, 2, 'a', 'b'), (3, 4,", "2, 'a', 'b'), (3, 4, 'ab', 'cd')], [(5, 6, 'def',", "sys import unittest from dynd import nd, ndt \"\"\" class", "(3, 4, 'ab', 'cd'), (5, 6, 'def', 'ghi')], type='3 *", "field b = nd.fields(a, 'x') self.assertEqual(nd.type_of(b), ndt.make_fixed_dim(3, ndt.make_var_dim(ndt.make_struct( [ndt.int32], ['x']))))", "nd.fields(a, 'w', 'y', 'z') self.assertEqual(nd.type_of(b), ndt.make_fixed_dim(3, ndt.make_var_dim(ndt.make_struct( [ndt.string, ndt.int32, ndt.string],", "field b = nd.fields(a, 'x') self.assertEqual(nd.dtype_of(b), ndt.make_struct( [ndt.int32], ['x'])) self.assertEqual(nd.as_py(b.x),", "b = nd.fields(a, 'z', 'y') self.assertEqual(nd.dtype_of(b), ndt.make_struct( [ndt.string, ndt.int32], ['z',", "'y'])) self.assertEqual(nd.as_py(b.z), nd.as_py(a.z)) self.assertEqual(nd.as_py(b.y), nd.as_py(a.y)) # Selecting three fields b", "(3, 4, 'ab', 'cd')], [(5, 6, 'def', 'ghi')], [(7, 8,", "[ndt.int32], ['x'])))) self.assertEqual(nd.as_py(b.x), nd.as_py(a.x)) # Selecting two fields b =", "ndt.string], ['w', 'y', 'x', 'z'])))) self.assertEqual(nd.as_py(b.w), nd.as_py(a.w)) self.assertEqual(nd.as_py(b.y), nd.as_py(a.y)) self.assertEqual(nd.as_py(b.x),", "'ghi')], [(7, 8, 'alpha', 'beta'), (9, 10, 'X', 'Y'), (11,", "ndt.int32, ndt.string], ['w', 'y', 'x', 'z'])))) self.assertEqual(nd.as_py(b.w), nd.as_py(a.w)) self.assertEqual(nd.as_py(b.y), nd.as_py(a.y))", "'y', 'x', 'z'])) self.assertEqual(nd.as_py(b.w), nd.as_py(a.w)) self.assertEqual(nd.as_py(b.y), nd.as_py(a.y)) self.assertEqual(nd.as_py(b.x), nd.as_py(a.x)) self.assertEqual(nd.as_py(b.z),", "nd.as_py(a.x)) self.assertEqual(nd.as_py(b.z), nd.as_py(a.z)) def test_fixed_var(self): a = nd.array([ [(1, 2,", "b = nd.fields(a, 'w', 'y', 'x', 'z') self.assertEqual(nd.type_of(b), ndt.make_fixed_dim(3, ndt.make_var_dim(ndt.make_struct(", "def test_fixed_var(self): a = nd.array([ [(1, 2, 'a', 'b'), (3,", "'end')]], type='3 * var * {x: int32, y: int32, z:", "int32, z: string, w: string}') self.assertRaises(RuntimeError, nd.fields, a, 'y', 'v')", "4, 'ab', 'cd')], [(5, 6, 'def', 'ghi')], [(7, 8, 'alpha',", "8, 'alpha', 'beta'), (9, 10, 'X', 'Y'), (11, 12, 'the',", "ndt \"\"\" class TestFields(unittest.TestCase): def test_simple(self): a = nd.array([ (1,", "string, w: string}') self.assertRaises(RuntimeError, nd.fields, a, 'y', 'v') \"\"\" if", "6, 'def', 'ghi')], type='3 * {x: int32, y: int32, z:", "self.assertEqual(nd.as_py(b.w), nd.as_py(a.w)) self.assertEqual(nd.as_py(b.y), nd.as_py(a.y)) self.assertEqual(nd.as_py(b.z), nd.as_py(a.z)) # Reordering all four", "{x: int32, y: int32, z: string, w: string}') self.assertRaises(RuntimeError, nd.fields,", "a single field b = nd.fields(a, 'x') self.assertEqual(nd.type_of(b), ndt.make_fixed_dim(3, ndt.make_var_dim(ndt.make_struct(", "two fields b = nd.fields(a, 'z', 'y') self.assertEqual(nd.type_of(b), ndt.make_fixed_dim(3, ndt.make_var_dim(ndt.make_struct(", "fields b = nd.fields(a, 'z', 'y') self.assertEqual(nd.type_of(b), ndt.make_fixed_dim(3, ndt.make_var_dim(ndt.make_struct( [ndt.string,", "= nd.fields(a, 'w', 'y', 'z') self.assertEqual(nd.type_of(b), ndt.make_fixed_dim(3, ndt.make_var_dim(ndt.make_struct( [ndt.string, ndt.int32,", "'y', 'x', 'z') self.assertEqual(nd.type_of(b), ndt.make_fixed_dim(3, ndt.make_var_dim(ndt.make_struct( [ndt.string, ndt.int32, ndt.int32, ndt.string],", "{x: int32, y: int32, z: string, w: string}') # Selecting", "self.assertEqual(nd.dtype_of(b), ndt.make_struct( [ndt.string, ndt.int32], ['z', 'y'])) self.assertEqual(nd.as_py(b.z), nd.as_py(a.z)) self.assertEqual(nd.as_py(b.y), nd.as_py(a.y))", "'z') self.assertEqual(nd.dtype_of(b), ndt.make_struct( [ndt.string, ndt.int32, ndt.string], ['w', 'y', 'z'])) self.assertEqual(nd.as_py(b.w),", "'z', 'y') self.assertEqual(nd.type_of(b), ndt.make_fixed_dim(3, ndt.make_var_dim(ndt.make_struct( [ndt.string, ndt.int32], ['z', 'y'])))) self.assertEqual(nd.as_py(b.z),", "ndt.int32, ndt.int32, ndt.string], ['w', 'y', 'x', 'z'])))) self.assertEqual(nd.as_py(b.w), nd.as_py(a.w)) self.assertEqual(nd.as_py(b.y),", "nd.fields(a, 'x') self.assertEqual(nd.dtype_of(b), ndt.make_struct( [ndt.int32], ['x'])) self.assertEqual(nd.as_py(b.x), nd.as_py(a.x)) # Selecting", "Selecting a single field b = nd.fields(a, 'x') self.assertEqual(nd.type_of(b), ndt.make_fixed_dim(3,", "'y') self.assertEqual(nd.dtype_of(b), ndt.make_struct( [ndt.string, ndt.int32], ['z', 'y'])) self.assertEqual(nd.as_py(b.z), nd.as_py(a.z)) self.assertEqual(nd.as_py(b.y),", "'x', 'z'])) self.assertEqual(nd.as_py(b.w), nd.as_py(a.w)) self.assertEqual(nd.as_py(b.y), nd.as_py(a.y)) self.assertEqual(nd.as_py(b.x), nd.as_py(a.x)) self.assertEqual(nd.as_py(b.z), nd.as_py(a.z))", "[ndt.string, ndt.int32, ndt.int32, ndt.string], ['w', 'y', 'x', 'z'])))) self.assertEqual(nd.as_py(b.w), nd.as_py(a.w))", "def test_bad_field_name(self): a = nd.array([ (1, 2, 'a', 'b'), (3,", "'X', 'Y'), (11, 12, 'the', 'end')]], type='3 * var *", "'x', 'z'])))) self.assertEqual(nd.as_py(b.w), nd.as_py(a.w)) self.assertEqual(nd.as_py(b.y), nd.as_py(a.y)) self.assertEqual(nd.as_py(b.x), nd.as_py(a.x)) self.assertEqual(nd.as_py(b.z), nd.as_py(a.z))", "nd.fields, a, 'y', 'v') \"\"\" if __name__ == '__main__': unittest.main()", "'y'])))) self.assertEqual(nd.as_py(b.z), nd.as_py(a.z)) self.assertEqual(nd.as_py(b.y), nd.as_py(a.y)) # Selecting three fields b", "self.assertEqual(nd.type_of(b), ndt.make_fixed_dim(3, ndt.make_var_dim(ndt.make_struct( [ndt.string, ndt.int32, ndt.int32, ndt.string], ['w', 'y', 'x',", "Selecting a single field b = nd.fields(a, 'x') self.assertEqual(nd.dtype_of(b), ndt.make_struct(", "'z') self.assertEqual(nd.type_of(b), ndt.make_fixed_dim(3, ndt.make_var_dim(ndt.make_struct( [ndt.string, ndt.int32, ndt.int32, ndt.string], ['w', 'y',", "fields b = nd.fields(a, 'w', 'y', 'z') self.assertEqual(nd.dtype_of(b), ndt.make_struct( [ndt.string,", "three fields b = nd.fields(a, 'w', 'y', 'z') self.assertEqual(nd.dtype_of(b), ndt.make_struct(", "[ndt.string, ndt.int32], ['z', 'y'])) self.assertEqual(nd.as_py(b.z), nd.as_py(a.z)) self.assertEqual(nd.as_py(b.y), nd.as_py(a.y)) # Selecting", "nd.as_py(a.x)) # Selecting two fields b = nd.fields(a, 'z', 'y')", "self.assertEqual(nd.as_py(b.w), nd.as_py(a.w)) self.assertEqual(nd.as_py(b.y), nd.as_py(a.y)) self.assertEqual(nd.as_py(b.x), nd.as_py(a.x)) self.assertEqual(nd.as_py(b.z), nd.as_py(a.z)) def test_fixed_var(self):", "[(5, 6, 'def', 'ghi')], [(7, 8, 'alpha', 'beta'), (9, 10,", "6, 'def', 'ghi')], [(7, 8, 'alpha', 'beta'), (9, 10, 'X',", "= nd.fields(a, 'w', 'y', 'x', 'z') self.assertEqual(nd.dtype_of(b), ndt.make_struct( [ndt.string, ndt.int32,", "ndt.make_fixed_dim(3, ndt.make_var_dim(ndt.make_struct( [ndt.int32], ['x'])))) self.assertEqual(nd.as_py(b.x), nd.as_py(a.x)) # Selecting two fields", "a = nd.array([ [(1, 2, 'a', 'b'), (3, 4, 'ab',", "[ndt.string, ndt.int32, ndt.int32, ndt.string], ['w', 'y', 'x', 'z'])) self.assertEqual(nd.as_py(b.w), nd.as_py(a.w))", "Reordering all four fields b = nd.fields(a, 'w', 'y', 'x',", "<filename>pkgs/dynd-python-0.7.2-py27_0/lib/python2.7/site-packages/dynd/tests/test_nd_fields.py import sys import unittest from dynd import nd, ndt", "nd.array([ (1, 2, 'a', 'b'), (3, 4, 'ab', 'cd'), (5,", "int32, z: string, w: string}') # Selecting a single field", "[(1, 2, 'a', 'b'), (3, 4, 'ab', 'cd')], [(5, 6,", "= nd.fields(a, 'x') self.assertEqual(nd.dtype_of(b), ndt.make_struct( [ndt.int32], ['x'])) self.assertEqual(nd.as_py(b.x), nd.as_py(a.x)) #", "# Reordering all four fields b = nd.fields(a, 'w', 'y',", "test_simple(self): a = nd.array([ (1, 2, 'a', 'b'), (3, 4,", "ndt.make_var_dim(ndt.make_struct( [ndt.string, ndt.int32], ['z', 'y'])))) self.assertEqual(nd.as_py(b.z), nd.as_py(a.z)) self.assertEqual(nd.as_py(b.y), nd.as_py(a.y)) #", "'y', 'z') self.assertEqual(nd.type_of(b), ndt.make_fixed_dim(3, ndt.make_var_dim(ndt.make_struct( [ndt.string, ndt.int32, ndt.string], ['w', 'y',", "'b'), (3, 4, 'ab', 'cd'), (5, 6, 'def', 'ghi')], type='3", "import sys import unittest from dynd import nd, ndt \"\"\"", "self.assertEqual(nd.as_py(b.z), nd.as_py(a.z)) # Reordering all four fields b = nd.fields(a,", "'z'])))) self.assertEqual(nd.as_py(b.w), nd.as_py(a.w)) self.assertEqual(nd.as_py(b.y), nd.as_py(a.y)) self.assertEqual(nd.as_py(b.z), nd.as_py(a.z)) # Reordering all", "self.assertEqual(nd.as_py(b.z), nd.as_py(a.z)) def test_bad_field_name(self): a = nd.array([ (1, 2, 'a',", "ndt.make_var_dim(ndt.make_struct( [ndt.string, ndt.int32, ndt.int32, ndt.string], ['w', 'y', 'x', 'z'])))) self.assertEqual(nd.as_py(b.w),", "'the', 'end')]], type='3 * var * {x: int32, y: int32,", "'y', 'x', 'z') self.assertEqual(nd.dtype_of(b), ndt.make_struct( [ndt.string, ndt.int32, ndt.int32, ndt.string], ['w',", "import nd, ndt \"\"\" class TestFields(unittest.TestCase): def test_simple(self): a =", "ndt.make_struct( [ndt.string, ndt.int32, ndt.int32, ndt.string], ['w', 'y', 'x', 'z'])) self.assertEqual(nd.as_py(b.w),", "var * {x: int32, y: int32, z: string, w: string}')", "unittest from dynd import nd, ndt \"\"\" class TestFields(unittest.TestCase): def", "self.assertEqual(nd.type_of(b), ndt.make_fixed_dim(3, ndt.make_var_dim(ndt.make_struct( [ndt.int32], ['x'])))) self.assertEqual(nd.as_py(b.x), nd.as_py(a.x)) # Selecting two", "self.assertEqual(nd.type_of(b), ndt.make_fixed_dim(3, ndt.make_var_dim(ndt.make_struct( [ndt.string, ndt.int32, ndt.string], ['w', 'y', 'z'])))) self.assertEqual(nd.as_py(b.w),", "y: int32, z: string, w: string}') self.assertRaises(RuntimeError, nd.fields, a, 'y',", "nd.fields(a, 'z', 'y') self.assertEqual(nd.type_of(b), ndt.make_fixed_dim(3, ndt.make_var_dim(ndt.make_struct( [ndt.string, ndt.int32], ['z', 'y']))))", "nd.fields(a, 'w', 'y', 'z') self.assertEqual(nd.dtype_of(b), ndt.make_struct( [ndt.string, ndt.int32, ndt.string], ['w',", "self.assertEqual(nd.dtype_of(b), ndt.make_struct( [ndt.string, ndt.int32, ndt.string], ['w', 'y', 'z'])) self.assertEqual(nd.as_py(b.w), nd.as_py(a.w))", "'cd'), (5, 6, 'def', 'ghi')], type='3 * {x: int32, y:", "z: string, w: string}') self.assertRaises(RuntimeError, nd.fields, a, 'y', 'v') \"\"\"", "fields b = nd.fields(a, 'z', 'y') self.assertEqual(nd.dtype_of(b), ndt.make_struct( [ndt.string, ndt.int32],", "single field b = nd.fields(a, 'x') self.assertEqual(nd.type_of(b), ndt.make_fixed_dim(3, ndt.make_var_dim(ndt.make_struct( [ndt.int32],", "'z'])))) self.assertEqual(nd.as_py(b.w), nd.as_py(a.w)) self.assertEqual(nd.as_py(b.y), nd.as_py(a.y)) self.assertEqual(nd.as_py(b.x), nd.as_py(a.x)) self.assertEqual(nd.as_py(b.z), nd.as_py(a.z)) def", "w: string}') self.assertRaises(RuntimeError, nd.fields, a, 'y', 'v') \"\"\" if __name__", "string}') self.assertRaises(RuntimeError, nd.fields, a, 'y', 'v') \"\"\" if __name__ ==", "nd.as_py(a.w)) self.assertEqual(nd.as_py(b.y), nd.as_py(a.y)) self.assertEqual(nd.as_py(b.x), nd.as_py(a.x)) self.assertEqual(nd.as_py(b.z), nd.as_py(a.z)) def test_fixed_var(self): a", "a single field b = nd.fields(a, 'x') self.assertEqual(nd.dtype_of(b), ndt.make_struct( [ndt.int32],", "'z') self.assertEqual(nd.type_of(b), ndt.make_fixed_dim(3, ndt.make_var_dim(ndt.make_struct( [ndt.string, ndt.int32, ndt.string], ['w', 'y', 'z']))))", "b = nd.fields(a, 'z', 'y') self.assertEqual(nd.type_of(b), ndt.make_fixed_dim(3, ndt.make_var_dim(ndt.make_struct( [ndt.string, ndt.int32],", "(1, 2, 'a', 'b'), (3, 4, 'ab', 'cd'), (5, 6,", "['w', 'y', 'x', 'z'])) self.assertEqual(nd.as_py(b.w), nd.as_py(a.w)) self.assertEqual(nd.as_py(b.y), nd.as_py(a.y)) self.assertEqual(nd.as_py(b.x), nd.as_py(a.x))", "'x') self.assertEqual(nd.dtype_of(b), ndt.make_struct( [ndt.int32], ['x'])) self.assertEqual(nd.as_py(b.x), nd.as_py(a.x)) # Selecting two", "ndt.int32, ndt.int32, ndt.string], ['w', 'y', 'x', 'z'])) self.assertEqual(nd.as_py(b.w), nd.as_py(a.w)) self.assertEqual(nd.as_py(b.y),", "ndt.make_struct( [ndt.string, ndt.int32], ['z', 'y'])) self.assertEqual(nd.as_py(b.z), nd.as_py(a.z)) self.assertEqual(nd.as_py(b.y), nd.as_py(a.y)) #", "int32, y: int32, z: string, w: string}') self.assertRaises(RuntimeError, nd.fields, a,", "'x', 'z') self.assertEqual(nd.dtype_of(b), ndt.make_struct( [ndt.string, ndt.int32, ndt.int32, ndt.string], ['w', 'y',", "nd.as_py(a.z)) # Reordering all four fields b = nd.fields(a, 'w',", "= nd.array([ [(1, 2, 'a', 'b'), (3, 4, 'ab', 'cd')],", "'alpha', 'beta'), (9, 10, 'X', 'Y'), (11, 12, 'the', 'end')]],", "fields b = nd.fields(a, 'w', 'y', 'z') self.assertEqual(nd.type_of(b), ndt.make_fixed_dim(3, ndt.make_var_dim(ndt.make_struct(", "two fields b = nd.fields(a, 'z', 'y') self.assertEqual(nd.dtype_of(b), ndt.make_struct( [ndt.string,", "'def', 'ghi')], [(7, 8, 'alpha', 'beta'), (9, 10, 'X', 'Y'),", "4, 'ab', 'cd'), (5, 6, 'def', 'ghi')], type='3 * {x:", "# Selecting a single field b = nd.fields(a, 'x') self.assertEqual(nd.dtype_of(b),", "b = nd.fields(a, 'w', 'y', 'z') self.assertEqual(nd.type_of(b), ndt.make_fixed_dim(3, ndt.make_var_dim(ndt.make_struct( [ndt.string,", "self.assertEqual(nd.as_py(b.z), nd.as_py(a.z)) def test_fixed_var(self): a = nd.array([ [(1, 2, 'a',", "(11, 12, 'the', 'end')]], type='3 * var * {x: int32,", "'z'])) self.assertEqual(nd.as_py(b.w), nd.as_py(a.w)) self.assertEqual(nd.as_py(b.y), nd.as_py(a.y)) self.assertEqual(nd.as_py(b.x), nd.as_py(a.x)) self.assertEqual(nd.as_py(b.z), nd.as_py(a.z)) def", "self.assertEqual(nd.as_py(b.x), nd.as_py(a.x)) self.assertEqual(nd.as_py(b.z), nd.as_py(a.z)) def test_fixed_var(self): a = nd.array([ [(1,", "['x'])) self.assertEqual(nd.as_py(b.x), nd.as_py(a.x)) # Selecting two fields b = nd.fields(a,", "ndt.int32, ndt.string], ['w', 'y', 'z'])) self.assertEqual(nd.as_py(b.w), nd.as_py(a.w)) self.assertEqual(nd.as_py(b.y), nd.as_py(a.y)) self.assertEqual(nd.as_py(b.z),", "Selecting three fields b = nd.fields(a, 'w', 'y', 'z') self.assertEqual(nd.dtype_of(b),", "a = nd.array([ (1, 2, 'a', 'b'), (3, 4, 'ab',", "* {x: int32, y: int32, z: string, w: string}') #", "'y', 'z'])) self.assertEqual(nd.as_py(b.w), nd.as_py(a.w)) self.assertEqual(nd.as_py(b.y), nd.as_py(a.y)) self.assertEqual(nd.as_py(b.z), nd.as_py(a.z)) # Reordering", "nd.as_py(a.y)) self.assertEqual(nd.as_py(b.x), nd.as_py(a.x)) self.assertEqual(nd.as_py(b.z), nd.as_py(a.z)) def test_fixed_var(self): a = nd.array([", "['x'])))) self.assertEqual(nd.as_py(b.x), nd.as_py(a.x)) # Selecting two fields b = nd.fields(a,", "y: int32, z: string, w: string}') # Selecting a single", "['w', 'y', 'x', 'z'])))) self.assertEqual(nd.as_py(b.w), nd.as_py(a.w)) self.assertEqual(nd.as_py(b.y), nd.as_py(a.y)) self.assertEqual(nd.as_py(b.x), nd.as_py(a.x))", "Selecting two fields b = nd.fields(a, 'z', 'y') self.assertEqual(nd.dtype_of(b), ndt.make_struct(", "self.assertEqual(nd.as_py(b.y), nd.as_py(a.y)) self.assertEqual(nd.as_py(b.x), nd.as_py(a.x)) self.assertEqual(nd.as_py(b.z), nd.as_py(a.z)) def test_fixed_var(self): a =", "'x') self.assertEqual(nd.type_of(b), ndt.make_fixed_dim(3, ndt.make_var_dim(ndt.make_struct( [ndt.int32], ['x'])))) self.assertEqual(nd.as_py(b.x), nd.as_py(a.x)) # Selecting", "\"\"\" class TestFields(unittest.TestCase): def test_simple(self): a = nd.array([ (1, 2,", "* var * {x: int32, y: int32, z: string, w:", "self.assertEqual(nd.as_py(b.y), nd.as_py(a.y)) # Selecting three fields b = nd.fields(a, 'w',", "b = nd.fields(a, 'x') self.assertEqual(nd.dtype_of(b), ndt.make_struct( [ndt.int32], ['x'])) self.assertEqual(nd.as_py(b.x), nd.as_py(a.x))", "[ndt.string, ndt.int32, ndt.string], ['w', 'y', 'z'])))) self.assertEqual(nd.as_py(b.w), nd.as_py(a.w)) self.assertEqual(nd.as_py(b.y), nd.as_py(a.y))", "ndt.string], ['w', 'y', 'x', 'z'])) self.assertEqual(nd.as_py(b.w), nd.as_py(a.w)) self.assertEqual(nd.as_py(b.y), nd.as_py(a.y)) self.assertEqual(nd.as_py(b.x),", "ndt.int32, ndt.string], ['w', 'y', 'x', 'z'])) self.assertEqual(nd.as_py(b.w), nd.as_py(a.w)) self.assertEqual(nd.as_py(b.y), nd.as_py(a.y))", "Selecting two fields b = nd.fields(a, 'z', 'y') self.assertEqual(nd.type_of(b), ndt.make_fixed_dim(3,", "'a', 'b'), (3, 4, 'ab', 'cd')], [(5, 6, 'def', 'ghi')],", "nd.as_py(a.x)) self.assertEqual(nd.as_py(b.z), nd.as_py(a.z)) def test_bad_field_name(self): a = nd.array([ (1, 2,", "'a', 'b'), (3, 4, 'ab', 'cd'), (5, 6, 'def', 'ghi')],", "dynd import nd, ndt \"\"\" class TestFields(unittest.TestCase): def test_simple(self): a", "nd.as_py(a.z)) def test_bad_field_name(self): a = nd.array([ (1, 2, 'a', 'b'),", "nd.fields(a, 'x') self.assertEqual(nd.type_of(b), ndt.make_fixed_dim(3, ndt.make_var_dim(ndt.make_struct( [ndt.int32], ['x'])))) self.assertEqual(nd.as_py(b.x), nd.as_py(a.x)) #", "'z'])) self.assertEqual(nd.as_py(b.w), nd.as_py(a.w)) self.assertEqual(nd.as_py(b.y), nd.as_py(a.y)) self.assertEqual(nd.as_py(b.z), nd.as_py(a.z)) # Reordering all", "nd, ndt \"\"\" class TestFields(unittest.TestCase): def test_simple(self): a = nd.array([", "nd.as_py(a.w)) self.assertEqual(nd.as_py(b.y), nd.as_py(a.y)) self.assertEqual(nd.as_py(b.x), nd.as_py(a.x)) self.assertEqual(nd.as_py(b.z), nd.as_py(a.z)) def test_bad_field_name(self): a", "# Selecting three fields b = nd.fields(a, 'w', 'y', 'z')", "from dynd import nd, ndt \"\"\" class TestFields(unittest.TestCase): def test_simple(self):", "self.assertEqual(nd.as_py(b.y), nd.as_py(a.y)) self.assertEqual(nd.as_py(b.z), nd.as_py(a.z)) # Reordering all four fields b", "nd.fields(a, 'w', 'y', 'x', 'z') self.assertEqual(nd.dtype_of(b), ndt.make_struct( [ndt.string, ndt.int32, ndt.int32,", "nd.as_py(a.y)) self.assertEqual(nd.as_py(b.x), nd.as_py(a.x)) self.assertEqual(nd.as_py(b.z), nd.as_py(a.z)) def test_bad_field_name(self): a = nd.array([", "self.assertEqual(nd.dtype_of(b), ndt.make_struct( [ndt.string, ndt.int32, ndt.int32, ndt.string], ['w', 'y', 'x', 'z']))", "'z', 'y') self.assertEqual(nd.dtype_of(b), ndt.make_struct( [ndt.string, ndt.int32], ['z', 'y'])) self.assertEqual(nd.as_py(b.z), nd.as_py(a.z))", "nd.as_py(a.z)) self.assertEqual(nd.as_py(b.y), nd.as_py(a.y)) # Selecting three fields b = nd.fields(a,", "self.assertEqual(nd.as_py(b.y), nd.as_py(a.y)) self.assertEqual(nd.as_py(b.x), nd.as_py(a.x)) self.assertEqual(nd.as_py(b.z), nd.as_py(a.z)) def test_bad_field_name(self): a =", "class TestFields(unittest.TestCase): def test_simple(self): a = nd.array([ (1, 2, 'a',", "# Selecting a single field b = nd.fields(a, 'x') self.assertEqual(nd.type_of(b),", "'z') self.assertEqual(nd.dtype_of(b), ndt.make_struct( [ndt.string, ndt.int32, ndt.int32, ndt.string], ['w', 'y', 'x',", "fields b = nd.fields(a, 'w', 'y', 'x', 'z') self.assertEqual(nd.dtype_of(b), ndt.make_struct(", "ndt.make_struct( [ndt.int32], ['x'])) self.assertEqual(nd.as_py(b.x), nd.as_py(a.x)) # Selecting two fields b" ]
[ "fit_transform(self, X : pd.DataFrame, axis : int = 0) ->", "return super().transform_weights(weights) def back_transform(self, X : np.ndarray) -> pd.DataFrame: df", "Iterable[int]] = 0): X = self._convert2list(X) self.tfs = [_DataFrameTransformer().fit(x, axis=axis)", "super().fit(X=X.values, axis=axis) except AttributeError: err_msg = 'weights must be of", "err_msg = 'All individual arrays must have same number of", ": np.ndarray) -> pd.DataFrame: eofs = super().back_transform_eofs(X) return pd.DataFrame( eofs,", "``np.ndarry``.' def __init__(self): super().__init__() def fit(self, X : Union[pd.DataFrame, List[pd.DataFrame]],", "index=self.index_features, columns=range(1, eofs.shape[-1] + 1) ) def back_transform_pcs(self, X :", "from ..models._transformer import _ArrayTransformer, _MultiArrayTransformer class _DataFrameTransformer(_ArrayTransformer): '''`_ArrayTransformer` wrapper for", "..models._transformer import _ArrayTransformer, _MultiArrayTransformer class _DataFrameTransformer(_ArrayTransformer): '''`_ArrayTransformer` wrapper for `pandas.DataFrame`.", ") def back_transform_eofs(self, X : np.ndarray) -> pd.DataFrame: eofs =", "{:}.'.format(repr(pd.DataFrame)) raise TypeError(err_msg) return self def transform(self, X : pd.DataFrame)", "pcs.shape[-1] + 1) ) class _MultiDataFrameTransformer(_MultiArrayTransformer): 'Transform multiple 2D ``pd.DataFrame``", "is for `pandas.DataFrame` only') if isinstance(axis, list): axis = axis[0]", "as pd from ..models._transformer import _ArrayTransformer, _MultiArrayTransformer class _DataFrameTransformer(_ArrayTransformer): '''`_ArrayTransformer`", "X.columns elif axis == 1: self.index_samples = X.columns self.index_features =", "= 'weights must be of type {:}.'.format(repr(pd.DataFrame)) raise TypeError(err_msg) return", "axis=axis).transform(X) def back_transform(self, X : np.ndarray) -> pd.DataFrame: return super().back_transform(X=X)", "df, index=self.index_samples, columns=self.index_features ) def back_transform_eofs(self, X : np.ndarray) ->", "isinstance(axis, list): axis = axis[0] # Set sample and feature", "pd.DataFrame: eofs = super().back_transform_eofs(X) return pd.DataFrame( eofs, index=self.index_features, columns=range(1, eofs.shape[-1]", "def back_transform_eofs(self, X : np.ndarray) -> pd.DataFrame: return super().back_transform_eofs(X=X) def", "columns=range(1, eofs.shape[-1] + 1) ) def back_transform_pcs(self, X : np.ndarray)", "of samples.' raise ValueError(err_msg) self.idx_array_sep = np.cumsum([tf.n_valid_features for tf in", "np.ndarray: return super().transform(X=X) def transform_weights(self, weights : Union[pd.DataFrame, List[pd.DataFrame]]) ->", "df = super().back_transform(X) return pd.DataFrame( df, index=self.index_samples, columns=self.index_features ) def", "must be of type {:}.'.format(repr(pd.DataFrame)) raise TypeError(err_msg) def fit_transform(self, X", "0 or 1') # Fit the data try: super().fit(X=X.values, axis=axis)", "in X] if len(set([tf.n_valid_samples for tf in self.tfs])) > 1:", "def transform_weights(self, weights : pd.DataFrame) -> np.ndarray: try: return super().transform_weights(weights.values)", "= np.cumsum([tf.n_valid_features for tf in self.tfs]) self.axis_samples = self.tfs[0].axis_samples return", "interface is for `pandas.DataFrame` only') if isinstance(axis, list): axis =", "weights : Union[pd.DataFrame, List[pd.DataFrame]]) -> np.ndarray: return super().transform_weights(weights=weights) def fit_transform(", "super().transform_weights(weights) def back_transform(self, X : np.ndarray) -> pd.DataFrame: df =", "pd.DataFrame: return super().back_transform_eofs(X=X) def back_transform_pcs(self, X : np.ndarray) -> pd.DataFrame:", "pd.DataFrame( df, index=self.index_samples, columns=self.index_features ) def back_transform_eofs(self, X : np.ndarray)", "ValueError('This interface is for `pandas.DataFrame` only') if isinstance(axis, list): axis", "axis=axis).transform(X) def transform_weights(self, weights : pd.DataFrame) -> np.ndarray: try: return", "'All individual arrays must have same number of samples.' raise", "def transform(self, X : pd.DataFrame) -> np.ndarray: try: return super().transform(X.values)", "if isinstance(axis, list): axis = axis[0] # Set sample and", "if len(set([tf.n_valid_samples for tf in self.tfs])) > 1: err_msg =", ": Union[pd.DataFrame, List[pd.DataFrame]], axis : Union[int, Iterable[int]] = 0 )", "axis : Union[int, Iterable[int]] = 0 ) -> np.ndarray: return", "pd.DataFrame: return super().back_transform(X=X) def back_transform_eofs(self, X : np.ndarray) -> pd.DataFrame:", "transform_weights(self, weights : pd.DataFrame) -> np.ndarray: try: return super().transform_weights(weights.values) except", "type {:}.'.format(repr(pd.DataFrame)) raise TypeError(err_msg) return self def transform(self, X :", "List import numpy as np import pandas as pd from", "= 0) -> np.ndarray: return self.fit(X=X, axis=axis).transform(X) def transform_weights(self, weights", "def back_transform(self, X : np.ndarray) -> pd.DataFrame: return super().back_transform(X=X) def", "typing import Union, Iterable, List import numpy as np import", "single 2D ``np.ndarry``.' def __init__(self): super().__init__() def fit(self, X :", "index=self.index_samples, columns=self.index_features ) def back_transform_eofs(self, X : np.ndarray) -> pd.DataFrame:", "list): axis = axis[0] # Set sample and feature index", "axis=axis) for x in X] if len(set([tf.n_valid_samples for tf in", "np.ndarray) -> pd.DataFrame: return super().back_transform(X=X) def back_transform_eofs(self, X : np.ndarray)", "1: err_msg = 'All individual arrays must have same number", "'weights must be of type {:}.'.format(repr(pd.DataFrame)) raise TypeError(err_msg) return self", ": Union[pd.DataFrame, List[pd.DataFrame]]) -> np.ndarray: return super().transform(X=X) def transform_weights(self, weights", "a single 2D ``np.ndarry``.' def __init__(self): super().__init__() def fit(self, X", "have same number of samples.' raise ValueError(err_msg) self.idx_array_sep = np.cumsum([tf.n_valid_features", "fit(self, X : pd.DataFrame, axis : Union[int, Iterable[int]] = 0):", "back_transform_eofs(self, X : np.ndarray) -> pd.DataFrame: eofs = super().back_transform_eofs(X) return", "return pd.DataFrame( eofs, index=self.index_features, columns=range(1, eofs.shape[-1] + 1) ) def", "return self.fit(X=X, axis=axis).transform(X) def back_transform(self, X : np.ndarray) -> pd.DataFrame:", ": np.ndarray) -> pd.DataFrame: return super().back_transform_eofs(X=X) def back_transform_pcs(self, X :", "np.ndarray: return super().transform_weights(weights=weights) def fit_transform( self, X : Union[pd.DataFrame, List[pd.DataFrame]],", "X : np.ndarray) -> pd.DataFrame: df = super().back_transform(X) return pd.DataFrame(", "-> np.ndarray: try: return super().transform_weights(weights.values) except AttributeError: return super().transform_weights(weights) def", "self def transform(self, X : pd.DataFrame) -> np.ndarray: try: return", "def fit(self, X : pd.DataFrame, axis : Union[int, Iterable[int]] =", "eofs, index=self.index_features, columns=range(1, eofs.shape[-1] + 1) ) def back_transform_pcs(self, X", "X : np.ndarray) -> pd.DataFrame: pcs = super().back_transform_pcs(X) return pd.DataFrame(", "1') # Fit the data try: super().fit(X=X.values, axis=axis) except AttributeError:", "axis : int = 0) -> np.ndarray: return self.fit(X=X, axis=axis).transform(X)", "raise ValueError(err_msg) self.idx_array_sep = np.cumsum([tf.n_valid_features for tf in self.tfs]) self.axis_samples", "super().back_transform_eofs(X=X) def back_transform_pcs(self, X : np.ndarray) -> pd.DataFrame: return super().back_transform_pcs(X=X)", ": np.ndarray) -> pd.DataFrame: pcs = super().back_transform_pcs(X) return pd.DataFrame( pcs,", "np.ndarray: try: return super().transform(X.values) except AttributeError: err_msg = 'weights must", "Union[int, Iterable[int]] = 0 ) -> np.ndarray: return self.fit(X=X, axis=axis).transform(X)", "ValueError(err_msg) self.idx_array_sep = np.cumsum([tf.n_valid_features for tf in self.tfs]) self.axis_samples =", "eofs = super().back_transform_eofs(X) return pd.DataFrame( eofs, index=self.index_features, columns=range(1, eofs.shape[-1] +", "len(set([tf.n_valid_samples for tf in self.tfs])) > 1: err_msg = 'All", "pandas as pd from ..models._transformer import _ArrayTransformer, _MultiArrayTransformer class _DataFrameTransformer(_ArrayTransformer):", "== 0: self.index_samples = X.index self.index_features = X.columns elif axis", "= super().back_transform(X) return pd.DataFrame( df, index=self.index_samples, columns=self.index_features ) def back_transform_eofs(self,", "index if axis == 0: self.index_samples = X.index self.index_features =", "2D ``np.ndarry``.' def __init__(self): super().__init__() def fit(self, X : Union[pd.DataFrame,", "> 1: err_msg = 'All individual arrays must have same", "return super().transform_weights(weights.values) except AttributeError: return super().transform_weights(weights) def back_transform(self, X :", "def back_transform(self, X : np.ndarray) -> pd.DataFrame: df = super().back_transform(X)", "numpy as np import pandas as pd from ..models._transformer import", "super().__init__() def fit(self, X : Union[pd.DataFrame, List[pd.DataFrame]], axis : Union[int,", "= X.index else: raise ValueError('axis must be either 0 or", "super().__init__() def fit(self, X : pd.DataFrame, axis : Union[int, Iterable[int]]", "must be either 0 or 1') # Fit the data", "type {:}.'.format(repr(pd.DataFrame)) raise TypeError(err_msg) def fit_transform(self, X : pd.DataFrame, axis", "= 0): if not isinstance(X, pd.DataFrame): raise ValueError('This interface is", "return super().transform(X.values) except AttributeError: err_msg = 'weights must be of", "1) ) def back_transform_pcs(self, X : np.ndarray) -> pd.DataFrame: pcs", ": Union[pd.DataFrame, List[pd.DataFrame]]) -> np.ndarray: return super().transform_weights(weights=weights) def fit_transform( self,", "return super().transform_weights(weights=weights) def fit_transform( self, X : Union[pd.DataFrame, List[pd.DataFrame]], axis", "= X.index self.index_features = X.columns elif axis == 1: self.index_samples", "def back_transform_eofs(self, X : np.ndarray) -> pd.DataFrame: eofs = super().back_transform_eofs(X)", "isinstance(X, pd.DataFrame): raise ValueError('This interface is for `pandas.DataFrame` only') if", "'weights must be of type {:}.'.format(repr(pd.DataFrame)) raise TypeError(err_msg) def fit_transform(self,", "np.ndarray: return self.fit(X=X, axis=axis).transform(X) def transform_weights(self, weights : pd.DataFrame) ->", "Iterable[int]] = 0 ) -> np.ndarray: return self.fit(X=X, axis=axis).transform(X) def", ") class _MultiDataFrameTransformer(_MultiArrayTransformer): 'Transform multiple 2D ``pd.DataFrame`` to a single", "self._convert2list(X) self.tfs = [_DataFrameTransformer().fit(x, axis=axis) for x in X] if", "def transform(self, X : Union[pd.DataFrame, List[pd.DataFrame]]) -> np.ndarray: return super().transform(X=X)", ": Union[int, Iterable[int]] = 0 ) -> np.ndarray: return self.fit(X=X,", "'''`_ArrayTransformer` wrapper for `pandas.DataFrame`. ''' def __init__(self): super().__init__() def fit(self,", "for tf in self.tfs])) > 1: err_msg = 'All individual", "weights : pd.DataFrame) -> np.ndarray: try: return super().transform_weights(weights.values) except AttributeError:", "_MultiDataFrameTransformer(_MultiArrayTransformer): 'Transform multiple 2D ``pd.DataFrame`` to a single 2D ``np.ndarry``.'", "AttributeError: err_msg = 'weights must be of type {:}.'.format(repr(pd.DataFrame)) raise", "self.fit(X=X, axis=axis).transform(X) def transform_weights(self, weights : pd.DataFrame) -> np.ndarray: try:", "super().transform(X.values) except AttributeError: err_msg = 'weights must be of type", "= super().back_transform_eofs(X) return pd.DataFrame( eofs, index=self.index_features, columns=range(1, eofs.shape[-1] + 1)", "transform(self, X : pd.DataFrame) -> np.ndarray: try: return super().transform(X.values) except", "np.ndarray: try: return super().transform_weights(weights.values) except AttributeError: return super().transform_weights(weights) def back_transform(self,", "not isinstance(X, pd.DataFrame): raise ValueError('This interface is for `pandas.DataFrame` only')", "import _ArrayTransformer, _MultiArrayTransformer class _DataFrameTransformer(_ArrayTransformer): '''`_ArrayTransformer` wrapper for `pandas.DataFrame`. '''", "Union[pd.DataFrame, List[pd.DataFrame]]) -> np.ndarray: return super().transform(X=X) def transform_weights(self, weights :", "for `pandas.DataFrame`. ''' def __init__(self): super().__init__() def fit(self, X :", "'Transform multiple 2D ``pd.DataFrame`` to a single 2D ``np.ndarry``.' def", "multiple 2D ``pd.DataFrame`` to a single 2D ``np.ndarry``.' def __init__(self):", "tf in self.tfs]) self.axis_samples = self.tfs[0].axis_samples return self def transform(self,", "AttributeError: return super().transform_weights(weights) def back_transform(self, X : np.ndarray) -> pd.DataFrame:", "pcs, index=self.index_samples, columns=range(1, pcs.shape[-1] + 1) ) class _MultiDataFrameTransformer(_MultiArrayTransformer): 'Transform", "self.axis_samples = self.tfs[0].axis_samples return self def transform(self, X : Union[pd.DataFrame,", "pd.DataFrame) -> np.ndarray: try: return super().transform_weights(weights.values) except AttributeError: return super().transform_weights(weights)", "back_transform_pcs(self, X : np.ndarray) -> pd.DataFrame: pcs = super().back_transform_pcs(X) return", "Union, Iterable, List import numpy as np import pandas as", "if not isinstance(X, pd.DataFrame): raise ValueError('This interface is for `pandas.DataFrame`", "Union[int, Iterable[int]] = 0): if not isinstance(X, pd.DataFrame): raise ValueError('This", "err_msg = 'weights must be of type {:}.'.format(repr(pd.DataFrame)) raise TypeError(err_msg)", "if axis == 0: self.index_samples = X.index self.index_features = X.columns", "np.ndarray: return self.fit(X=X, axis=axis).transform(X) def back_transform(self, X : np.ndarray) ->", "-> np.ndarray: return self.fit(X=X, axis=axis).transform(X) def back_transform(self, X : np.ndarray)", ": pd.DataFrame) -> np.ndarray: try: return super().transform(X.values) except AttributeError: err_msg", "+ 1) ) class _MultiDataFrameTransformer(_MultiArrayTransformer): 'Transform multiple 2D ``pd.DataFrame`` to", "class _MultiDataFrameTransformer(_MultiArrayTransformer): 'Transform multiple 2D ``pd.DataFrame`` to a single 2D", "self.tfs]) self.axis_samples = self.tfs[0].axis_samples return self def transform(self, X :", "Union[pd.DataFrame, List[pd.DataFrame]], axis : Union[int, Iterable[int]] = 0): X =", "of type {:}.'.format(repr(pd.DataFrame)) raise TypeError(err_msg) return self def transform(self, X", "= 0): X = self._convert2list(X) self.tfs = [_DataFrameTransformer().fit(x, axis=axis) for", "either 0 or 1') # Fit the data try: super().fit(X=X.values,", "axis : Union[int, Iterable[int]] = 0): if not isinstance(X, pd.DataFrame):", "0): if not isinstance(X, pd.DataFrame): raise ValueError('This interface is for", "class _DataFrameTransformer(_ArrayTransformer): '''`_ArrayTransformer` wrapper for `pandas.DataFrame`. ''' def __init__(self): super().__init__()", "as np import pandas as pd from ..models._transformer import _ArrayTransformer,", "else: raise ValueError('axis must be either 0 or 1') #", "self.tfs[0].axis_samples return self def transform(self, X : Union[pd.DataFrame, List[pd.DataFrame]]) ->", "pd.DataFrame( pcs, index=self.index_samples, columns=range(1, pcs.shape[-1] + 1) ) class _MultiDataFrameTransformer(_MultiArrayTransformer):", "= super().back_transform_pcs(X) return pd.DataFrame( pcs, index=self.index_samples, columns=range(1, pcs.shape[-1] + 1)", "return pd.DataFrame( pcs, index=self.index_samples, columns=range(1, pcs.shape[-1] + 1) ) class", "super().transform_weights(weights.values) except AttributeError: return super().transform_weights(weights) def back_transform(self, X : np.ndarray)", "__init__(self): super().__init__() def fit(self, X : Union[pd.DataFrame, List[pd.DataFrame]], axis :", "index=self.index_samples, columns=range(1, pcs.shape[-1] + 1) ) class _MultiDataFrameTransformer(_MultiArrayTransformer): 'Transform multiple", "eofs.shape[-1] + 1) ) def back_transform_pcs(self, X : np.ndarray) ->", "= 0 ) -> np.ndarray: return self.fit(X=X, axis=axis).transform(X) def back_transform(self,", "= self.tfs[0].axis_samples return self def transform(self, X : Union[pd.DataFrame, List[pd.DataFrame]])", "transform_weights(self, weights : Union[pd.DataFrame, List[pd.DataFrame]]) -> np.ndarray: return super().transform_weights(weights=weights) def", "pd.DataFrame: df = super().back_transform(X) return pd.DataFrame( df, index=self.index_samples, columns=self.index_features )", "0: self.index_samples = X.index self.index_features = X.columns elif axis ==", "-> pd.DataFrame: eofs = super().back_transform_eofs(X) return pd.DataFrame( eofs, index=self.index_features, columns=range(1,", "feature index if axis == 0: self.index_samples = X.index self.index_features", ": np.ndarray) -> pd.DataFrame: df = super().back_transform(X) return pd.DataFrame( df,", "number of samples.' raise ValueError(err_msg) self.idx_array_sep = np.cumsum([tf.n_valid_features for tf", "axis = axis[0] # Set sample and feature index if", "np.ndarray) -> pd.DataFrame: pcs = super().back_transform_pcs(X) return pd.DataFrame( pcs, index=self.index_samples,", "must be of type {:}.'.format(repr(pd.DataFrame)) raise TypeError(err_msg) return self def", "import numpy as np import pandas as pd from ..models._transformer", "pcs = super().back_transform_pcs(X) return pd.DataFrame( pcs, index=self.index_samples, columns=range(1, pcs.shape[-1] +", "elif axis == 1: self.index_samples = X.columns self.index_features = X.index", "return pd.DataFrame( df, index=self.index_samples, columns=self.index_features ) def back_transform_eofs(self, X :", "self.index_features = X.index else: raise ValueError('axis must be either 0", "X.index self.index_features = X.columns elif axis == 1: self.index_samples =", "int = 0) -> np.ndarray: return self.fit(X=X, axis=axis).transform(X) def transform_weights(self,", ": pd.DataFrame, axis : Union[int, Iterable[int]] = 0): if not", "be of type {:}.'.format(repr(pd.DataFrame)) raise TypeError(err_msg) return self def transform(self,", "for tf in self.tfs]) self.axis_samples = self.tfs[0].axis_samples return self def", "X] if len(set([tf.n_valid_samples for tf in self.tfs])) > 1: err_msg", "from typing import Union, Iterable, List import numpy as np", "-> np.ndarray: return super().transform(X=X) def transform_weights(self, weights : Union[pd.DataFrame, List[pd.DataFrame]])", ": pd.DataFrame, axis : int = 0) -> np.ndarray: return", ": np.ndarray) -> pd.DataFrame: return super().back_transform(X=X) def back_transform_eofs(self, X :", ") def back_transform_pcs(self, X : np.ndarray) -> pd.DataFrame: pcs =", "axis == 1: self.index_samples = X.columns self.index_features = X.index else:", "pd.DataFrame) -> np.ndarray: try: return super().transform(X.values) except AttributeError: err_msg =", "List[pd.DataFrame]], axis : Union[int, Iterable[int]] = 0): X = self._convert2list(X)", "arrays must have same number of samples.' raise ValueError(err_msg) self.idx_array_sep", ") -> np.ndarray: return self.fit(X=X, axis=axis).transform(X) def back_transform(self, X :", "return super().back_transform(X=X) def back_transform_eofs(self, X : np.ndarray) -> pd.DataFrame: return", "to a single 2D ``np.ndarry``.' def __init__(self): super().__init__() def fit(self,", "self, X : Union[pd.DataFrame, List[pd.DataFrame]], axis : Union[int, Iterable[int]] =", "0): X = self._convert2list(X) self.tfs = [_DataFrameTransformer().fit(x, axis=axis) for x", "in self.tfs])) > 1: err_msg = 'All individual arrays must", "np.ndarray) -> pd.DataFrame: df = super().back_transform(X) return pd.DataFrame( df, index=self.index_samples,", "_DataFrameTransformer(_ArrayTransformer): '''`_ArrayTransformer` wrapper for `pandas.DataFrame`. ''' def __init__(self): super().__init__() def", "axis[0] # Set sample and feature index if axis ==", "columns=range(1, pcs.shape[-1] + 1) ) class _MultiDataFrameTransformer(_MultiArrayTransformer): 'Transform multiple 2D", "X : pd.DataFrame, axis : Union[int, Iterable[int]] = 0): if", "X : Union[pd.DataFrame, List[pd.DataFrame]], axis : Union[int, Iterable[int]] = 0):", "samples.' raise ValueError(err_msg) self.idx_array_sep = np.cumsum([tf.n_valid_features for tf in self.tfs])", "return self def transform(self, X : Union[pd.DataFrame, List[pd.DataFrame]]) -> np.ndarray:", "-> np.ndarray: try: return super().transform(X.values) except AttributeError: err_msg = 'weights", "``pd.DataFrame`` to a single 2D ``np.ndarry``.' def __init__(self): super().__init__() def", "for `pandas.DataFrame` only') if isinstance(axis, list): axis = axis[0] #", "be of type {:}.'.format(repr(pd.DataFrame)) raise TypeError(err_msg) def fit_transform(self, X :", "super().transform(X=X) def transform_weights(self, weights : Union[pd.DataFrame, List[pd.DataFrame]]) -> np.ndarray: return", "List[pd.DataFrame]]) -> np.ndarray: return super().transform_weights(weights=weights) def fit_transform( self, X :", "= X.columns elif axis == 1: self.index_samples = X.columns self.index_features", "0 ) -> np.ndarray: return self.fit(X=X, axis=axis).transform(X) def back_transform(self, X", "Set sample and feature index if axis == 0: self.index_samples", "= X.columns self.index_features = X.index else: raise ValueError('axis must be", "tf in self.tfs])) > 1: err_msg = 'All individual arrays", "def back_transform_pcs(self, X : np.ndarray) -> pd.DataFrame: pcs = super().back_transform_pcs(X)", "import pandas as pd from ..models._transformer import _ArrayTransformer, _MultiArrayTransformer class", "x in X] if len(set([tf.n_valid_samples for tf in self.tfs])) >", "in self.tfs]) self.axis_samples = self.tfs[0].axis_samples return self def transform(self, X", "def fit(self, X : Union[pd.DataFrame, List[pd.DataFrame]], axis : Union[int, Iterable[int]]", "def __init__(self): super().__init__() def fit(self, X : pd.DataFrame, axis :", "pd.DataFrame): raise ValueError('This interface is for `pandas.DataFrame` only') if isinstance(axis,", "axis : Union[int, Iterable[int]] = 0): X = self._convert2list(X) self.tfs", "self def transform(self, X : Union[pd.DataFrame, List[pd.DataFrame]]) -> np.ndarray: return", "2D ``pd.DataFrame`` to a single 2D ``np.ndarry``.' def __init__(self): super().__init__()", "{:}.'.format(repr(pd.DataFrame)) raise TypeError(err_msg) def fit_transform(self, X : pd.DataFrame, axis :", "TypeError(err_msg) def fit_transform(self, X : pd.DataFrame, axis : int =", "of type {:}.'.format(repr(pd.DataFrame)) raise TypeError(err_msg) def fit_transform(self, X : pd.DataFrame,", "X : np.ndarray) -> pd.DataFrame: eofs = super().back_transform_eofs(X) return pd.DataFrame(", "X : np.ndarray) -> pd.DataFrame: return super().back_transform_eofs(X=X) def back_transform_pcs(self, X", ": Union[pd.DataFrame, List[pd.DataFrame]], axis : Union[int, Iterable[int]] = 0): X", "TypeError(err_msg) return self def transform(self, X : pd.DataFrame) -> np.ndarray:", ": int = 0) -> np.ndarray: return self.fit(X=X, axis=axis).transform(X) def", "raise ValueError('This interface is for `pandas.DataFrame` only') if isinstance(axis, list):", "_MultiArrayTransformer class _DataFrameTransformer(_ArrayTransformer): '''`_ArrayTransformer` wrapper for `pandas.DataFrame`. ''' def __init__(self):", "back_transform(self, X : np.ndarray) -> pd.DataFrame: df = super().back_transform(X) return", "`pandas.DataFrame` only') if isinstance(axis, list): axis = axis[0] # Set", "or 1') # Fit the data try: super().fit(X=X.values, axis=axis) except", "return self.fit(X=X, axis=axis).transform(X) def transform_weights(self, weights : pd.DataFrame) -> np.ndarray:", "X : pd.DataFrame) -> np.ndarray: try: return super().transform(X.values) except AttributeError:", "X = self._convert2list(X) self.tfs = [_DataFrameTransformer().fit(x, axis=axis) for x in", "List[pd.DataFrame]], axis : Union[int, Iterable[int]] = 0 ) -> np.ndarray:", "np.cumsum([tf.n_valid_features for tf in self.tfs]) self.axis_samples = self.tfs[0].axis_samples return self", "= axis[0] # Set sample and feature index if axis", "pd.DataFrame( eofs, index=self.index_features, columns=range(1, eofs.shape[-1] + 1) ) def back_transform_pcs(self,", "-> np.ndarray: return self.fit(X=X, axis=axis).transform(X) def transform_weights(self, weights : pd.DataFrame)", ": Union[int, Iterable[int]] = 0): X = self._convert2list(X) self.tfs =", "[_DataFrameTransformer().fit(x, axis=axis) for x in X] if len(set([tf.n_valid_samples for tf", "X : Union[pd.DataFrame, List[pd.DataFrame]]) -> np.ndarray: return super().transform(X=X) def transform_weights(self,", "X.index else: raise ValueError('axis must be either 0 or 1')", "super().back_transform(X=X) def back_transform_eofs(self, X : np.ndarray) -> pd.DataFrame: return super().back_transform_eofs(X=X)", ": Union[int, Iterable[int]] = 0): if not isinstance(X, pd.DataFrame): raise", "-> pd.DataFrame: df = super().back_transform(X) return pd.DataFrame( df, index=self.index_samples, columns=self.index_features", "Union[pd.DataFrame, List[pd.DataFrame]]) -> np.ndarray: return super().transform_weights(weights=weights) def fit_transform( self, X", "fit(self, X : Union[pd.DataFrame, List[pd.DataFrame]], axis : Union[int, Iterable[int]] =", "= 'weights must be of type {:}.'.format(repr(pd.DataFrame)) raise TypeError(err_msg) def", "super().back_transform(X) return pd.DataFrame( df, index=self.index_samples, columns=self.index_features ) def back_transform_eofs(self, X", "def fit_transform(self, X : pd.DataFrame, axis : int = 0)", "Iterable, List import numpy as np import pandas as pd", "1: self.index_samples = X.columns self.index_features = X.index else: raise ValueError('axis", "pd.DataFrame, axis : Union[int, Iterable[int]] = 0): if not isinstance(X,", "self.index_samples = X.columns self.index_features = X.index else: raise ValueError('axis must", "-> pd.DataFrame: pcs = super().back_transform_pcs(X) return pd.DataFrame( pcs, index=self.index_samples, columns=range(1,", "for x in X] if len(set([tf.n_valid_samples for tf in self.tfs]))", "be either 0 or 1') # Fit the data try:", "columns=self.index_features ) def back_transform_eofs(self, X : np.ndarray) -> pd.DataFrame: eofs", "pd.DataFrame: pcs = super().back_transform_pcs(X) return pd.DataFrame( pcs, index=self.index_samples, columns=range(1, pcs.shape[-1]", "Iterable[int]] = 0): if not isinstance(X, pd.DataFrame): raise ValueError('This interface", "Fit the data try: super().fit(X=X.values, axis=axis) except AttributeError: err_msg =", "List[pd.DataFrame]]) -> np.ndarray: return super().transform(X=X) def transform_weights(self, weights : Union[pd.DataFrame,", "X : Union[pd.DataFrame, List[pd.DataFrame]], axis : Union[int, Iterable[int]] = 0", "must have same number of samples.' raise ValueError(err_msg) self.idx_array_sep =", "and feature index if axis == 0: self.index_samples = X.index", "return super().transform(X=X) def transform_weights(self, weights : Union[pd.DataFrame, List[pd.DataFrame]]) -> np.ndarray:", "X : np.ndarray) -> pd.DataFrame: return super().back_transform(X=X) def back_transform_eofs(self, X", "data try: super().fit(X=X.values, axis=axis) except AttributeError: err_msg = 'weights must", "raise ValueError('axis must be either 0 or 1') # Fit", "__init__(self): super().__init__() def fit(self, X : pd.DataFrame, axis : Union[int,", "try: return super().transform_weights(weights.values) except AttributeError: return super().transform_weights(weights) def back_transform(self, X", "transform(self, X : Union[pd.DataFrame, List[pd.DataFrame]]) -> np.ndarray: return super().transform(X=X) def", "-> pd.DataFrame: return super().back_transform(X=X) def back_transform_eofs(self, X : np.ndarray) ->", "def transform_weights(self, weights : Union[pd.DataFrame, List[pd.DataFrame]]) -> np.ndarray: return super().transform_weights(weights=weights)", ": pd.DataFrame) -> np.ndarray: try: return super().transform_weights(weights.values) except AttributeError: return", "X.columns self.index_features = X.index else: raise ValueError('axis must be either", "super().back_transform_eofs(X) return pd.DataFrame( eofs, index=self.index_features, columns=range(1, eofs.shape[-1] + 1) )", "ValueError('axis must be either 0 or 1') # Fit the", "except AttributeError: err_msg = 'weights must be of type {:}.'.format(repr(pd.DataFrame))", "self.tfs])) > 1: err_msg = 'All individual arrays must have", "def __init__(self): super().__init__() def fit(self, X : Union[pd.DataFrame, List[pd.DataFrame]], axis", "= 'All individual arrays must have same number of samples.'", "raise TypeError(err_msg) def fit_transform(self, X : pd.DataFrame, axis : int", "# Set sample and feature index if axis == 0:", "np.ndarray) -> pd.DataFrame: eofs = super().back_transform_eofs(X) return pd.DataFrame( eofs, index=self.index_features,", "= [_DataFrameTransformer().fit(x, axis=axis) for x in X] if len(set([tf.n_valid_samples for", "self.fit(X=X, axis=axis).transform(X) def back_transform(self, X : np.ndarray) -> pd.DataFrame: return", "individual arrays must have same number of samples.' raise ValueError(err_msg)", "raise TypeError(err_msg) return self def transform(self, X : pd.DataFrame) ->", "self.index_features = X.columns elif axis == 1: self.index_samples = X.columns", "-> np.ndarray: return super().transform_weights(weights=weights) def fit_transform( self, X : Union[pd.DataFrame,", "sample and feature index if axis == 0: self.index_samples =", "return super().back_transform_eofs(X=X) def back_transform_pcs(self, X : np.ndarray) -> pd.DataFrame: return", "np import pandas as pd from ..models._transformer import _ArrayTransformer, _MultiArrayTransformer", "import Union, Iterable, List import numpy as np import pandas", "X : pd.DataFrame, axis : int = 0) -> np.ndarray:", "axis == 0: self.index_samples = X.index self.index_features = X.columns elif", "self.index_samples = X.index self.index_features = X.columns elif axis == 1:", "super().transform_weights(weights=weights) def fit_transform( self, X : Union[pd.DataFrame, List[pd.DataFrame]], axis :", "pd from ..models._transformer import _ArrayTransformer, _MultiArrayTransformer class _DataFrameTransformer(_ArrayTransformer): '''`_ArrayTransformer` wrapper", "`pandas.DataFrame`. ''' def __init__(self): super().__init__() def fit(self, X : pd.DataFrame,", "''' def __init__(self): super().__init__() def fit(self, X : pd.DataFrame, axis", "_ArrayTransformer, _MultiArrayTransformer class _DataFrameTransformer(_ArrayTransformer): '''`_ArrayTransformer` wrapper for `pandas.DataFrame`. ''' def", "self.idx_array_sep = np.cumsum([tf.n_valid_features for tf in self.tfs]) self.axis_samples = self.tfs[0].axis_samples", "axis=axis) except AttributeError: err_msg = 'weights must be of type", "+ 1) ) def back_transform_pcs(self, X : np.ndarray) -> pd.DataFrame:", "try: return super().transform(X.values) except AttributeError: err_msg = 'weights must be", "back_transform(self, X : np.ndarray) -> pd.DataFrame: return super().back_transform(X=X) def back_transform_eofs(self,", "wrapper for `pandas.DataFrame`. ''' def __init__(self): super().__init__() def fit(self, X", "super().back_transform_pcs(X) return pd.DataFrame( pcs, index=self.index_samples, columns=range(1, pcs.shape[-1] + 1) )", "self.tfs = [_DataFrameTransformer().fit(x, axis=axis) for x in X] if len(set([tf.n_valid_samples", "-> pd.DataFrame: return super().back_transform_eofs(X=X) def back_transform_pcs(self, X : np.ndarray) ->", "except AttributeError: return super().transform_weights(weights) def back_transform(self, X : np.ndarray) ->", "same number of samples.' raise ValueError(err_msg) self.idx_array_sep = np.cumsum([tf.n_valid_features for", "fit_transform( self, X : Union[pd.DataFrame, List[pd.DataFrame]], axis : Union[int, Iterable[int]]", "Union[pd.DataFrame, List[pd.DataFrame]], axis : Union[int, Iterable[int]] = 0 ) ->", "only') if isinstance(axis, list): axis = axis[0] # Set sample", "try: super().fit(X=X.values, axis=axis) except AttributeError: err_msg = 'weights must be", "= self._convert2list(X) self.tfs = [_DataFrameTransformer().fit(x, axis=axis) for x in X]", "def fit_transform( self, X : Union[pd.DataFrame, List[pd.DataFrame]], axis : Union[int,", "return self def transform(self, X : pd.DataFrame) -> np.ndarray: try:", "Union[int, Iterable[int]] = 0): X = self._convert2list(X) self.tfs = [_DataFrameTransformer().fit(x,", "# Fit the data try: super().fit(X=X.values, axis=axis) except AttributeError: err_msg", "np.ndarray) -> pd.DataFrame: return super().back_transform_eofs(X=X) def back_transform_pcs(self, X : np.ndarray)", "the data try: super().fit(X=X.values, axis=axis) except AttributeError: err_msg = 'weights", "== 1: self.index_samples = X.columns self.index_features = X.index else: raise", "0) -> np.ndarray: return self.fit(X=X, axis=axis).transform(X) def transform_weights(self, weights :", "back_transform_eofs(self, X : np.ndarray) -> pd.DataFrame: return super().back_transform_eofs(X=X) def back_transform_pcs(self,", "pd.DataFrame, axis : int = 0) -> np.ndarray: return self.fit(X=X,", "1) ) class _MultiDataFrameTransformer(_MultiArrayTransformer): 'Transform multiple 2D ``pd.DataFrame`` to a" ]
[ "get the binary data of the NetCDF file net_cdf_path =", "by the adapter files = adapter.get_files() # use the parameters", "= os.path.join(fc_dir, \"python-adapter\") sys.path.append(python_adapter_dir) import adapter def fake_model(adapter): # check", "os.path.dirname(tests_dir) python_adapter_dir = os.path.join(fc_dir, \"python-adapter\") sys.path.append(python_adapter_dir) import adapter def fake_model(adapter):", "file net_cdf_path = files['net_cdf'] # mark the NetCDF file as", "return # have to call adapter in the adapter.py file", "adapter in the adapter.py file as adapter.adapter adapter = adapter.global_adapter", "mark the NetCDF file as an output file adapter.set_output_files(net_cdf_path) adapter.set_output_files(\"lipd-files\\\\\")", "print(\"\\n---\\nStart of the fake_model function\\n---\\n\") # the parameters are handed", "import lipd # import pythonAdapter, assumes in ../python-adapter/ tests_dir =", "function print(\"\\n---\\nStart of the fake_model function\\n---\\n\") # the parameters are", "# use the parameters given by the adapter to get", "given by the adapter to get the binary data of", "tests_dir = os.path.dirname(os.path.realpath(__file__)) fc_dir = os.path.dirname(tests_dir) python_adapter_dir = os.path.join(fc_dir, \"python-adapter\")", "<filename>tests/bogus_python_model.py import os import sys import lipd # import pythonAdapter,", "check to see inside function print(\"\\n---\\nStart of the fake_model function\\n---\\n\")", "files = adapter.get_files() # use the parameters given by the", "data of the LiPD file lipd.readLipd(files['weldeab']) # get the binary", "parameters given by the adapter to get the binary data", "# the parameters are handed to you by the adapter", "adapter files = adapter.get_files() # use the parameters given by", "see inside function print(\"\\n---\\nStart of the fake_model function\\n---\\n\") # the", "binary data of the NetCDF file net_cdf_path = files['net_cdf'] #", "in the adapter.py file as adapter.adapter adapter = adapter.global_adapter adapter.register(fake_model)", "= adapter.get_files() # use the parameters given by the adapter", "sys import lipd # import pythonAdapter, assumes in ../python-adapter/ tests_dir", "the NetCDF file as an output file adapter.set_output_files(net_cdf_path) adapter.set_output_files(\"lipd-files\\\\\") return", "adapter.set_output_files(\"lipd-files\\\\\") return # have to call adapter in the adapter.py", "of the fake_model function\\n---\\n\") # the parameters are handed to", "LiPD file lipd.readLipd(files['weldeab']) # get the binary data of the", "data of the NetCDF file net_cdf_path = files['net_cdf'] # mark", "get the binary data of the LiPD file lipd.readLipd(files['weldeab']) #", "NetCDF file net_cdf_path = files['net_cdf'] # mark the NetCDF file", "sys.path.append(python_adapter_dir) import adapter def fake_model(adapter): # check to see inside", "an output file adapter.set_output_files(net_cdf_path) adapter.set_output_files(\"lipd-files\\\\\") return # have to call", "# import pythonAdapter, assumes in ../python-adapter/ tests_dir = os.path.dirname(os.path.realpath(__file__)) fc_dir", "# have to call adapter in the adapter.py file as", "to you by the adapter files = adapter.get_files() # use", "the adapter files = adapter.get_files() # use the parameters given", "files['net_cdf'] # mark the NetCDF file as an output file", "file adapter.set_output_files(net_cdf_path) adapter.set_output_files(\"lipd-files\\\\\") return # have to call adapter in", "# mark the NetCDF file as an output file adapter.set_output_files(net_cdf_path)", "output file adapter.set_output_files(net_cdf_path) adapter.set_output_files(\"lipd-files\\\\\") return # have to call adapter", "os.path.dirname(os.path.realpath(__file__)) fc_dir = os.path.dirname(tests_dir) python_adapter_dir = os.path.join(fc_dir, \"python-adapter\") sys.path.append(python_adapter_dir) import", "in ../python-adapter/ tests_dir = os.path.dirname(os.path.realpath(__file__)) fc_dir = os.path.dirname(tests_dir) python_adapter_dir =", "the NetCDF file net_cdf_path = files['net_cdf'] # mark the NetCDF", "call adapter in the adapter.py file as adapter.adapter adapter =", "use the parameters given by the adapter to get the", "adapter def fake_model(adapter): # check to see inside function print(\"\\n---\\nStart", "\"python-adapter\") sys.path.append(python_adapter_dir) import adapter def fake_model(adapter): # check to see", "lipd # import pythonAdapter, assumes in ../python-adapter/ tests_dir = os.path.dirname(os.path.realpath(__file__))", "function\\n---\\n\") # the parameters are handed to you by the", "are handed to you by the adapter files = adapter.get_files()", "NetCDF file as an output file adapter.set_output_files(net_cdf_path) adapter.set_output_files(\"lipd-files\\\\\") return #", "../python-adapter/ tests_dir = os.path.dirname(os.path.realpath(__file__)) fc_dir = os.path.dirname(tests_dir) python_adapter_dir = os.path.join(fc_dir,", "import adapter def fake_model(adapter): # check to see inside function", "fake_model(adapter): # check to see inside function print(\"\\n---\\nStart of the", "the adapter.py file as adapter.adapter adapter = adapter.global_adapter adapter.register(fake_model) adapter.start_server()", "def fake_model(adapter): # check to see inside function print(\"\\n---\\nStart of", "of the NetCDF file net_cdf_path = files['net_cdf'] # mark the", "as an output file adapter.set_output_files(net_cdf_path) adapter.set_output_files(\"lipd-files\\\\\") return # have to", "the LiPD file lipd.readLipd(files['weldeab']) # get the binary data of", "inside function print(\"\\n---\\nStart of the fake_model function\\n---\\n\") # the parameters", "pythonAdapter, assumes in ../python-adapter/ tests_dir = os.path.dirname(os.path.realpath(__file__)) fc_dir = os.path.dirname(tests_dir)", "file lipd.readLipd(files['weldeab']) # get the binary data of the NetCDF", "binary data of the LiPD file lipd.readLipd(files['weldeab']) # get the", "file as an output file adapter.set_output_files(net_cdf_path) adapter.set_output_files(\"lipd-files\\\\\") return # have", "to see inside function print(\"\\n---\\nStart of the fake_model function\\n---\\n\") #", "# get the binary data of the NetCDF file net_cdf_path", "parameters are handed to you by the adapter files =", "the binary data of the NetCDF file net_cdf_path = files['net_cdf']", "handed to you by the adapter files = adapter.get_files() #", "import os import sys import lipd # import pythonAdapter, assumes", "import pythonAdapter, assumes in ../python-adapter/ tests_dir = os.path.dirname(os.path.realpath(__file__)) fc_dir =", "net_cdf_path = files['net_cdf'] # mark the NetCDF file as an", "import sys import lipd # import pythonAdapter, assumes in ../python-adapter/", "lipd.readLipd(files['weldeab']) # get the binary data of the NetCDF file", "# check to see inside function print(\"\\n---\\nStart of the fake_model", "fc_dir = os.path.dirname(tests_dir) python_adapter_dir = os.path.join(fc_dir, \"python-adapter\") sys.path.append(python_adapter_dir) import adapter", "the parameters given by the adapter to get the binary", "adapter.set_output_files(net_cdf_path) adapter.set_output_files(\"lipd-files\\\\\") return # have to call adapter in the", "to call adapter in the adapter.py file as adapter.adapter adapter", "= os.path.dirname(tests_dir) python_adapter_dir = os.path.join(fc_dir, \"python-adapter\") sys.path.append(python_adapter_dir) import adapter def", "you by the adapter files = adapter.get_files() # use the", "the binary data of the LiPD file lipd.readLipd(files['weldeab']) # get", "python_adapter_dir = os.path.join(fc_dir, \"python-adapter\") sys.path.append(python_adapter_dir) import adapter def fake_model(adapter): #", "fake_model function\\n---\\n\") # the parameters are handed to you by", "the parameters are handed to you by the adapter files", "the adapter to get the binary data of the LiPD", "adapter.get_files() # use the parameters given by the adapter to", "= files['net_cdf'] # mark the NetCDF file as an output", "os import sys import lipd # import pythonAdapter, assumes in", "by the adapter to get the binary data of the", "the fake_model function\\n---\\n\") # the parameters are handed to you", "= os.path.dirname(os.path.realpath(__file__)) fc_dir = os.path.dirname(tests_dir) python_adapter_dir = os.path.join(fc_dir, \"python-adapter\") sys.path.append(python_adapter_dir)", "adapter to get the binary data of the LiPD file", "os.path.join(fc_dir, \"python-adapter\") sys.path.append(python_adapter_dir) import adapter def fake_model(adapter): # check to", "of the LiPD file lipd.readLipd(files['weldeab']) # get the binary data", "to get the binary data of the LiPD file lipd.readLipd(files['weldeab'])", "assumes in ../python-adapter/ tests_dir = os.path.dirname(os.path.realpath(__file__)) fc_dir = os.path.dirname(tests_dir) python_adapter_dir", "have to call adapter in the adapter.py file as adapter.adapter" ]
[ "distance): return self.tello.move_left(distance) def telloMoveRight(self, distance): return self.tello.move_right(distance) def telloUp(self,", "by Tkinter :param tello: class interacts with the Tello drone.", "Tkinter,PIL and Macos,and it will # sometimes result the very", "to initial it if self.panel is None: self.panel = tki.Label(image=image)", "tki.Frame(panel, width=100, height=2) self.tmp_f.bind('<KeyPress-w>', self.on_keypress_w) self.tmp_f.bind('<KeyPress-s>', self.on_keypress_s) self.tmp_f.bind('<KeyPress-a>', self.on_keypress_a) self.tmp_f.bind('<KeyPress-d>',", "= threading.Thread(target=self._updateGUIImage,args=(image,)) thread_tmp.start() time.sleep(0.03) except RuntimeError as e: print(\"[INFO] caught", "command=self.telloFlip_l) self.btn_flipl.pack(side=\"bottom\", fill=\"both\", expand=\"yes\", padx=10, pady=5) self.btn_flipr = tki.Button( panel,", "relief=\"raised\", command=self.openFlipWindow) self.btn_landing.pack(side=\"bottom\", fill=\"both\", expand=\"yes\", padx=10, pady=5) self.distance_bar = Scale(panel,", "window and image panel self.root = tki.Tk() self.panel = None", "to=360, tickinterval=10, label='Degree') self.degree_bar.set(30) self.degree_bar.pack(side=\"right\") self.btn_distance = tki.Button(panel, text=\"Reset Degree\",", "to handle when the window is closed self.root.wm_title(\"TELLO Controller\") self.root.wm_protocol(\"WM_DELETE_WINDOW\",", "= \"{}.jpg\".format(ts.strftime(\"%Y-%m-%d_%H-%M-%S\")) p = os.path.sep.join((self.outputPath, filename)) # save the file", "video as a jpg file and put it into outputpath", "process to continue \"\"\" print(\"[INFO] closing...\") self.stopEvent.set() del self.tello self.root.quit()", "attempt to enter command mode. \"\"\" self.tello = tello #", "self.telloDown(self.distance) def on_keypress_a(self, event): print (\"ccw %d degree\" % self.degree)", "tki from tkinter import Toplevel, Scale import threading import datetime", "the current frame of the video as a jpg file", "= self.degree_bar.get() print ('reset distance to %d' % self.degree) def", "is None or self.frame.size == 0: continue # transfer the", "read from h264decoder and used for pose recognition self.thread =", "threading import datetime import cv2 import os import time import", "%d m\" % self.degree) self.tello.rotate_cw(self.degree) def on_keypress_up(self, event): print (\"forward", "initial it if self.panel is None: self.panel = tki.Label(image=image) self.panel.image", "self.tmp_f.focus_set() def onClose(self): \"\"\" set the stop event, cleanup the", "justify=\"left\") text1.pack(side=\"top\") self.btn_landing = tki.Button( panel, text=\"Land\", relief=\"raised\", command=self.telloLanding) self.btn_landing.pack(side=\"bottom\",", "self.tello.move_up(dist) def telloDown(self, dist): return self.tello.move_down(dist) def updateTrackBar(self): self.my_tello_hand.setThr(self.hand_thr_bar.get()) def", "self.panel.pack(side=\"left\", padx=10, pady=10) # otherwise, simply update the panel else:", "to Tello control commands\\n' 'Adjust the trackbar to reset distance", "stop computer waiting for response from tello \"\"\" self.quit_waiting_flag =", "when the window is closed self.root.wm_title(\"TELLO Controller\") self.root.wm_protocol(\"WM_DELETE_WINDOW\", self.onClose) #", "try: # start the thread that get GUI image and", "self.on_keypress_left) self.tmp_f.bind('<KeyPress-Right>', self.on_keypress_right) self.tmp_f.pack(side=\"bottom\") self.tmp_f.focus_set() self.btn_landing = tki.Button( panel, text=\"Flip\",", "fill=\"both\", expand=\"yes\", padx=10, pady=5) # start a thread that constantly", "# transfer the format from frame to image image =", "Command Panel\", relief=\"raised\", command=self.openCmdWindow) self.btn_landing.pack(side=\"bottom\", fill=\"both\", expand=\"yes\", padx=10, pady=5) #", "pady=5) self.degree_bar = Scale(panel, from_=1, to=360, tickinterval=10, label='Degree') self.degree_bar.set(30) self.degree_bar.pack(side=\"right\")", "padx=10, pady=5) def takeSnapshot(self): \"\"\" save the current frame of", "print(\"[INFO] saved {}\".format(filename)) def pauseVideo(self): \"\"\" Toggle the freeze/unfreze of", "event): if self.frame is not None: self.registerFace() self.tmp_f.focus_set() def onClose(self):", "self.frame is not None: self.registerFace() self.tmp_f.focus_set() def onClose(self): \"\"\" set", "mainloop self.stopEvent = None # control variables self.distance = 0.1", "openFlipWindow(self): \"\"\" open the flip window and initial all the", "tello every 5 second \"\"\" while True: self.tello.send_command('command') time.sleep(5) def", "import cv2 import os import time import platform class TelloUI:", "will stop waiting for the response from tello self.quit_waiting_flag =", "get GUI image and drwa skeleton time.sleep(0.5) self.sending_command_thread.start() while not", "pady=5) self.btn_landing = tki.Button( self.root, text=\"Open Command Panel\", relief=\"raised\", command=self.openCmdWindow)", "around a RunTime error that Tkinter throws due to threading.", "frame for GUI show self.frame = self.tello.read() if self.frame is", "self.distance = 0.1 # default distance for 'move' cmd self.degree", "command=self.openFlipWindow) self.btn_landing.pack(side=\"bottom\", fill=\"both\", expand=\"yes\", padx=10, pady=5) self.distance_bar = Scale(panel, from_=0.02,", "self.tello.move_right(distance) def telloUp(self, dist): return self.tello.move_up(dist) def telloDown(self, dist): return", "self.telloMoveRight(self.distance) def on_keypress_enter(self, event): if self.frame is not None: self.registerFace()", "tello every 5 seconds self.sending_command_thread = threading.Thread(target = self._sendingCommand) def", "command=self.pauseVideo) self.btn_pause.pack(side=\"bottom\", fill=\"both\", expand=\"yes\", padx=10, pady=5) self.btn_landing = tki.Button( self.root,", "Backward\\n' 'A - Rotate Tello Counter-Clockwise\\tArrow Left - Move Tello", "text=\"Flip\", relief=\"raised\", command=self.openFlipWindow) self.btn_landing.pack(side=\"bottom\", fill=\"both\", expand=\"yes\", padx=10, pady=5) self.distance_bar =", "the quit process to continue \"\"\" print(\"[INFO] closing...\") self.stopEvent.set() del", "return self.tello.move_down(dist) def updateTrackBar(self): self.my_tello_hand.setThr(self.hand_thr_bar.get()) def updateDistancebar(self): self.distance = self.distance_bar.get()", "\"\"\" try: # start the thread that get GUI image", "def telloFlip_b(self): return self.tello.flip('b') def telloCW(self, degree): return self.tello.rotate_cw(degree) def", "# otherwise, simply update the panel else: self.panel.configure(image=image) self.panel.image =", "dist): return self.tello.move_down(dist) def updateTrackBar(self): self.my_tello_hand.setThr(self.hand_thr_bar.get()) def updateDistancebar(self): self.distance =", "tki.Button(panel, text=\"Reset Degree\", relief=\"raised\", command=self.updateDegreebar) self.btn_distance.pack(side=\"right\", fill=\"both\", expand=\"yes\", padx=10, pady=5)", "tello # videostream device self.outputPath = outputpath # the path", "class interacts with the Tello drone. Raises: RuntimeError: If the", "the GUI panel \"\"\" image = ImageTk.PhotoImage(image) # if the", "file and put it into outputpath \"\"\" # grab the", "distance): return self.tello.move_backward(distance) def telloMoveLeft(self, distance): return self.tello.move_left(distance) def telloMoveRight(self,", "text= 'W - Move Tello Up\\t\\t\\tArrow Up - Move Tello", "% self.degree) def on_keypress_w(self, event): print (\"up %d m\" %", "if system ==\"Windows\" or system ==\"Linux\": self._updateGUIImage(image) else: thread_tmp =", "tello \"\"\" self.quit_waiting_flag = True def openCmdWindow(self): \"\"\" open the", "= None # frame read from h264decoder and used for", "self.thread = None # thread of the Tkinter mainloop self.stopEvent", "drone. Raises: RuntimeError: If the Tello rejects the attempt to", "as a jpg file and put it into outputpath \"\"\"", "# read the frame for GUI show self.frame = self.tello.read()", "updateDegreebar(self): self.degree = self.degree_bar.get() print ('reset distance to %d' %", "% self.degree) self.tello.rotate_cw(self.degree) def on_keypress_up(self, event): print (\"forward %d m\"", "self.tello.video_freeze(False) else: self.btn_pause.config(relief=\"sunken\") self.tello.video_freeze(True) def telloTakeOff(self): return self.tello.takeoff() def telloLanding(self):", "self.btn_takeoff.pack(side=\"bottom\", fill=\"both\", expand=\"yes\", padx=10, pady=5) # binding arrow keys to", "def _sendingCommand(self): \"\"\" start a while loop that sends 'command'", "self.degree) self.tello.rotate_cw(self.degree) def on_keypress_up(self, event): print (\"forward %d m\" %", "fill=\"both\", expand=\"yes\", padx=10, pady=5) # binding arrow keys to drone", "tkinter import Toplevel, Scale import threading import datetime import cv2", "command=self.telloLanding) self.btn_landing.pack(side=\"bottom\", fill=\"both\", expand=\"yes\", padx=10, pady=5) self.btn_takeoff = tki.Button( panel,", "save the file cv2.imwrite(p, cv2.cvtColor(self.frame, cv2.COLOR_RGB2BGR)) print(\"[INFO] saved {}\".format(filename)) def", "self.distance) self.telloDown(self.distance) def on_keypress_a(self, event): print (\"ccw %d degree\" %", "update the GUI panel \"\"\" image = ImageTk.PhotoImage(image) # if", "video \"\"\" if self.btn_pause.config('relief')[-1] == 'sunken': self.btn_pause.config(relief=\"raised\") self.tello.video_freeze(False) else: self.btn_pause.config(relief=\"sunken\")", "mainloop thread of Tkinter Raises: RuntimeError: To get around a", "RuntimeError as e: print(\"[INFO] caught a RuntimeError\") def _updateGUIImage(self,image): \"\"\"", "Left - Move Tello Left\\n' 'D - Rotate Tello Clockwise\\t\\tArrow", "Controller map keyboard inputs to Tello control commands\\n' 'Adjust the", "keyboard inputs to Tello control commands\\n' 'Adjust the trackbar to", "thread_tmp = threading.Thread(target=self._updateGUIImage,args=(image,)) thread_tmp.start() time.sleep(0.03) except RuntimeError as e: print(\"[INFO]", "else: thread_tmp = threading.Thread(target=self._updateGUIImage,args=(image,)) thread_tmp.start() time.sleep(0.03) except RuntimeError as e:", "start a while loop that sends 'command' to tello every", "== 0: continue # transfer the format from frame to", "Up\\t\\t\\tArrow Up - Move Tello Forward\\n' 'S - Move Tello", "text=\"Flip Backward\", relief=\"raised\", command=self.telloFlip_b) self.btn_flipb.pack(side=\"bottom\", fill=\"both\", expand=\"yes\", padx=10, pady=5) def", "freeze/unfreze of video \"\"\" if self.btn_pause.config('relief')[-1] == 'sunken': self.btn_pause.config(relief=\"raised\") self.tello.video_freeze(False)", "_updateGUIImage function. if system ==\"Windows\" or system ==\"Linux\": self._updateGUIImage(image) else:", "self.tello.flip('r') def telloFlip_f(self): return self.tello.flip('f') def telloFlip_b(self): return self.tello.flip('b') def", "thread will stop waiting for the response from tello self.quit_waiting_flag", "object of image,and update the GUI panel \"\"\" image =", "GUI,support by Tkinter :param tello: class interacts with the Tello", "clicking the takeSnapshot button self.frame = None # frame read", "= tki.Button(panel, text=\"Reset Distance\", relief=\"raised\", command=self.updateDistancebar, ) self.btn_distance.pack(side=\"left\", fill=\"both\", expand=\"yes\",", "'D - Rotate Tello Clockwise\\t\\tArrow Right - Move Tello Right',", "pady=5) # binding arrow keys to drone control self.tmp_f =", "on_keypress_left(self, event): print (\"left %d m\" % self.distance) self.telloMoveLeft(self.distance) def", "- Move Tello Forward\\n' 'S - Move Tello Down\\t\\t\\tArrow Down", "# save the file cv2.imwrite(p, cv2.cvtColor(self.frame, cv2.COLOR_RGB2BGR)) print(\"[INFO] saved {}\".format(filename))", "self.root, text=\"Open Command Panel\", relief=\"raised\", command=self.openCmdWindow) self.btn_landing.pack(side=\"bottom\", fill=\"both\", expand=\"yes\", padx=10,", "cleanup the camera, and allow the rest of the quit", "pady=5) # start a thread that constantly pools the video", "jpg file and put it into outputpath \"\"\" # grab", "self.root.wm_title(\"TELLO Controller\") self.root.wm_protocol(\"WM_DELETE_WINDOW\", self.onClose) # the sending_command will send command", "padx=10, pady=5) # binding arrow keys to drone control self.tmp_f", "pools the video sensor for # the most recently read", "text \"\"\" panel = Toplevel(self.root) panel.wm_title(\"Command Panel\") # create text", "that save pictures created by clicking the takeSnapshot button self.frame", "Tello Clockwise\\t\\tArrow Right - Move Tello Right', justify=\"left\") text1.pack(side=\"top\") self.btn_landing", "command=self.updateDistancebar, ) self.btn_distance.pack(side=\"left\", fill=\"both\", expand=\"yes\", padx=10, pady=5) self.degree_bar = Scale(panel,", "onClose(self): \"\"\" set the stop event, cleanup the camera, and", "self.btn_distance.pack(side=\"right\", fill=\"both\", expand=\"yes\", padx=10, pady=5) def openFlipWindow(self): \"\"\" open the", "return self.tello.flip('l') def telloFlip_r(self): return self.tello.flip('r') def telloFlip_f(self): return self.tello.flip('f')", "skeleton time.sleep(0.5) self.sending_command_thread.start() while not self.stopEvent.is_set(): system = platform.system() #", "initial the object of image,and update the GUI panel \"\"\"", "set the variable as TRUE,it will stop computer waiting for", "sometimes result the very long preriod of the \"ImageTk.PhotoImage\" function,", "system ==\"Windows\" or system ==\"Linux\": self._updateGUIImage(image) else: thread_tmp = threading.Thread(target=self._updateGUIImage,args=(image,))", "self.distance) self.telloMoveRight(self.distance) def on_keypress_enter(self, event): if self.frame is not None:", "= None # thread of the Tkinter mainloop self.stopEvent =", "self.btn_pause.config(relief=\"sunken\") self.tello.video_freeze(True) def telloTakeOff(self): return self.tello.takeoff() def telloLanding(self): return self.tello.land()", "self.btn_pause.config('relief')[-1] == 'sunken': self.btn_pause.config(relief=\"raised\") self.tello.video_freeze(False) else: self.btn_pause.config(relief=\"sunken\") self.tello.video_freeze(True) def telloTakeOff(self):", "expand=\"yes\", padx=10, pady=5) def openFlipWindow(self): \"\"\" open the flip window", "The mainloop thread of Tkinter Raises: RuntimeError: To get around", "self.btn_landing.pack(side=\"bottom\", fill=\"both\", expand=\"yes\", padx=10, pady=5) self.distance_bar = Scale(panel, from_=0.02, to=5,", "default distance for 'move' cmd self.degree = 30 # default", "file cv2.imwrite(p, cv2.cvtColor(self.frame, cv2.COLOR_RGB2BGR)) print(\"[INFO] saved {}\".format(filename)) def pauseVideo(self): \"\"\"", "return self.tello.flip('b') def telloCW(self, degree): return self.tello.rotate_cw(degree) def telloCCW(self, degree):", "to tello every 5 second \"\"\" while True: self.tello.send_command('command') time.sleep(5)", "tki.Button( panel, text=\"Land\", relief=\"raised\", command=self.telloLanding) self.btn_landing.pack(side=\"bottom\", fill=\"both\", expand=\"yes\", padx=10, pady=5)", "on_keypress_up(self, event): print (\"forward %d m\" % self.distance) self.telloMoveForward(self.distance) def", "from h264decoder and used for pose recognition self.thread = None", "execute the _updateGUIImage function. if system ==\"Windows\" or system ==\"Linux\":", "button and text \"\"\" panel = Toplevel(self.root) panel.wm_title(\"Command Panel\") #", "Image.fromarray(self.frame) # we found compatibility problem between Tkinter,PIL and Macos,and", "fill=\"both\", expand=\"yes\", padx=10, pady=5) def openFlipWindow(self): \"\"\" open the flip", "threading.Thread(target = self._sendingCommand) def videoLoop(self): \"\"\" The mainloop thread of", "telloLanding(self): return self.tello.land() def telloFlip_l(self): return self.tello.flip('l') def telloFlip_r(self): return", "from frame to image image = Image.fromarray(self.frame) # we found", "panel = Toplevel(self.root) panel.wm_title(\"Command Panel\") # create text input entry", "def telloCCW(self, degree): return self.tello.rotate_ccw(degree) def telloMoveForward(self, distance): return self.tello.move_forward(distance)", "self.btn_snapshot = tki.Button(self.root, text=\"Snapshot!\", command=self.takeSnapshot) self.btn_snapshot.pack(side=\"bottom\", fill=\"both\", expand=\"yes\", padx=10, pady=5)", "pauseVideo(self): \"\"\" Toggle the freeze/unfreze of video \"\"\" if self.btn_pause.config('relief')[-1]", "ImageTk.PhotoImage(image) # if the panel none ,we need to initial", "the root window and image panel self.root = tki.Tk() self.panel", "padx=10, pady=5) self.degree_bar = Scale(panel, from_=1, to=360, tickinterval=10, label='Degree') self.degree_bar.set(30)", "from PIL import Image from PIL import ImageTk import tkinter", "None # frame read from h264decoder and used for pose", "os import time import platform class TelloUI: \"\"\"Wrapper class to", "= self.tello.read() if self.frame is None or self.frame.size == 0:", "m\" % self.distance) self.telloMoveForward(self.distance) def on_keypress_down(self, event): print (\"backward %d", "padx=10, pady=5) self.btn_takeoff = tki.Button( panel, text=\"Takeoff\", relief=\"raised\", command=self.telloTakeOff) self.btn_takeoff.pack(side=\"bottom\",", "None # control variables self.distance = 0.1 # default distance", "expand=\"yes\", padx=10, pady=5) self.btn_takeoff = tki.Button( panel, text=\"Takeoff\", relief=\"raised\", command=self.telloTakeOff)", "self.distance_bar = Scale(panel, from_=0.02, to=5, tickinterval=0.01, digits=3, label='Distance(m)', resolution=0.01) self.distance_bar.set(0.2)", "(\"left %d m\" % self.distance) self.telloMoveLeft(self.distance) def on_keypress_right(self, event): print", "- Move Tello Up\\t\\t\\tArrow Up - Move Tello Forward\\n' 'S", "_updateGUIImage(self,image): \"\"\" Main operation to initial the object of image,and", "problem between Tkinter,PIL and Macos,and it will # sometimes result", "pose recognition self.thread = None # thread of the Tkinter", "\"\"\" while True: self.tello.send_command('command') time.sleep(5) def _setQuitWaitingFlag(self): \"\"\" set the", "m\" % self.degree) self.tello.rotate_cw(self.degree) def on_keypress_up(self, event): print (\"forward %d", "constantly pools the video sensor for # the most recently", "label='Degree') self.degree_bar.set(30) self.degree_bar.pack(side=\"right\") self.btn_distance = tki.Button(panel, text=\"Reset Degree\", relief=\"raised\", command=self.updateDegreebar)", "cmd window and initial all the button and text \"\"\"", "for 'cw' or 'ccw' cmd # if the flag is", "\"\"\" panel = Toplevel(self.root) panel.wm_title(\"Command Panel\") # create text input", "expand=\"yes\", padx=10, pady=5) self.btn_flipb = tki.Button( panel, text=\"Flip Backward\", relief=\"raised\",", "self.tello.rotate_cw(degree) def telloCCW(self, degree): return self.tello.rotate_ccw(degree) def telloMoveForward(self, distance): return", "def telloFlip_l(self): return self.tello.flip('l') def telloFlip_r(self): return self.tello.flip('r') def telloFlip_f(self):", "% self.distance) self.telloMoveForward(self.distance) def on_keypress_down(self, event): print (\"backward %d m\"", "need to initial it if self.panel is None: self.panel =", "\"\"\" save the current frame of the video as a", "caught a RuntimeError\") def _updateGUIImage(self,image): \"\"\" Main operation to initial", "read the frame for GUI show self.frame = self.tello.read() if", "outputpath \"\"\" # grab the current timestamp and use it", "the freeze/unfreze of video \"\"\" if self.btn_pause.config('relief')[-1] == 'sunken': self.btn_pause.config(relief=\"raised\")", "self._updateGUIImage(image) else: thread_tmp = threading.Thread(target=self._updateGUIImage,args=(image,)) thread_tmp.start() time.sleep(0.03) except RuntimeError as", "threading.Thread(target=self.videoLoop, args=()) self.thread.start() # set a callback to handle when", "Down\\t\\t\\tArrow Down - Move Tello Backward\\n' 'A - Rotate Tello", "stop event, cleanup the camera, and allow the rest of", "relief=\"raised\", command=self.telloFlip_r) self.btn_flipr.pack(side=\"bottom\", fill=\"both\", expand=\"yes\", padx=10, pady=5) self.btn_flipf = tki.Button(", "Toplevel(self.root) panel.wm_title(\"Gesture Recognition\") self.btn_flipl = tki.Button( panel, text=\"Flip Left\", relief=\"raised\",", "self.btn_flipl = tki.Button( panel, text=\"Flip Left\", relief=\"raised\", command=self.telloFlip_l) self.btn_flipl.pack(side=\"bottom\", fill=\"both\",", "expand=\"yes\", padx=10, pady=5) # start a thread that constantly pools", "= 0.1 # default distance for 'move' cmd self.degree =", "and text \"\"\" panel = Toplevel(self.root) panel.wm_title(\"Gesture Recognition\") self.btn_flipl =", "Tello rejects the attempt to enter command mode. \"\"\" self.tello", "on_keypress_s(self, event): print (\"down %d m\" % self.distance) self.telloDown(self.distance) def", "telloFlip_b(self): return self.tello.flip('b') def telloCW(self, degree): return self.tello.rotate_cw(degree) def telloCCW(self,", "self.registerFace() self.tmp_f.focus_set() def onClose(self): \"\"\" set the stop event, cleanup", "degree): return self.tello.rotate_cw(degree) def telloCCW(self, degree): return self.tello.rotate_ccw(degree) def telloMoveForward(self,", "system ==\"Linux\": self._updateGUIImage(image) else: thread_tmp = threading.Thread(target=self._updateGUIImage,args=(image,)) thread_tmp.start() time.sleep(0.03) except", "%d m\" % self.distance) self.telloMoveBackward(self.distance) def on_keypress_left(self, event): print (\"left", "image panel self.root = tki.Tk() self.panel = None # create", "telloMoveLeft(self, distance): return self.tello.move_left(distance) def telloMoveRight(self, distance): return self.tello.move_right(distance) def", "Clockwise\\t\\tArrow Right - Move Tello Right', justify=\"left\") text1.pack(side=\"top\") self.btn_landing =", "cv2.imwrite(p, cv2.cvtColor(self.frame, cv2.COLOR_RGB2BGR)) print(\"[INFO] saved {}\".format(filename)) def pauseVideo(self): \"\"\" Toggle", "panel, text=\"Flip\", relief=\"raised\", command=self.openFlipWindow) self.btn_landing.pack(side=\"bottom\", fill=\"both\", expand=\"yes\", padx=10, pady=5) self.distance_bar", "self.distance_bar.set(0.2) self.distance_bar.pack(side=\"left\") self.btn_distance = tki.Button(panel, text=\"Reset Distance\", relief=\"raised\", command=self.updateDistancebar, )", "# the sending_command will send command to tello every 5", "sends 'command' to tello every 5 second \"\"\" while True:", "Distance\", relief=\"raised\", command=self.updateDistancebar, ) self.btn_distance.pack(side=\"left\", fill=\"both\", expand=\"yes\", padx=10, pady=5) self.degree_bar", "(\"ccw %d degree\" % self.degree) self.tello.rotate_ccw(self.degree) def on_keypress_d(self, event): print", "frame of the video as a jpg file and put", "self.btn_distance = tki.Button(panel, text=\"Reset Degree\", relief=\"raised\", command=self.updateDegreebar) self.btn_distance.pack(side=\"right\", fill=\"both\", expand=\"yes\",", "Up - Move Tello Forward\\n' 'S - Move Tello Down\\t\\t\\tArrow", "self.sending_command_thread = threading.Thread(target = self._sendingCommand) def videoLoop(self): \"\"\" The mainloop", "# start a thread that constantly pools the video sensor", "tki.Label(image=image) self.panel.image = image self.panel.pack(side=\"left\", padx=10, pady=10) # otherwise, simply", "= platform.system() # read the frame for GUI show self.frame", "telloFlip_f(self): return self.tello.flip('f') def telloFlip_b(self): return self.tello.flip('b') def telloCW(self, degree):", "Raises: RuntimeError: If the Tello rejects the attempt to enter", "relief=\"raised\", command=self.pauseVideo) self.btn_pause.pack(side=\"bottom\", fill=\"both\", expand=\"yes\", padx=10, pady=5) self.btn_landing = tki.Button(", "Tkinter :param tello: class interacts with the Tello drone. Raises:", "self.btn_landing = tki.Button( self.root, text=\"Open Command Panel\", relief=\"raised\", command=self.openCmdWindow) self.btn_landing.pack(side=\"bottom\",", "operation to initial the object of image,and update the GUI", "\"\"\" if self.btn_pause.config('relief')[-1] == 'sunken': self.btn_pause.config(relief=\"raised\") self.tello.video_freeze(False) else: self.btn_pause.config(relief=\"sunken\") self.tello.video_freeze(True)", "def onClose(self): \"\"\" set the stop event, cleanup the camera,", "is TRUE,the auto-takeoff thread will stop waiting for the response", "self.distance) self.telloUp(self.distance) def on_keypress_s(self, event): print (\"down %d m\" %", "frame to image image = Image.fromarray(self.frame) # we found compatibility", "'command' to tello every 5 second \"\"\" while True: self.tello.send_command('command')", "and allow the rest of the quit process to continue", "Move Tello Right', justify=\"left\") text1.pack(side=\"top\") self.btn_landing = tki.Button( panel, text=\"Land\",", "padx=10, pady=10) # otherwise, simply update the panel else: self.panel.configure(image=image)", "of image,and update the GUI panel \"\"\" image = ImageTk.PhotoImage(image)", "show self.frame = self.tello.read() if self.frame is None or self.frame.size", "def telloTakeOff(self): return self.tello.takeoff() def telloLanding(self): return self.tello.land() def telloFlip_l(self):", "tkinter as tki from tkinter import Toplevel, Scale import threading", "distance and degree parameter', font='Helvetica 10 bold' ) text0.pack(side='top') text1", "Tkinter throws due to threading. \"\"\" try: # start the", "tki.Button( panel, text=\"Flip\", relief=\"raised\", command=self.openFlipWindow) self.btn_landing.pack(side=\"bottom\", fill=\"both\", expand=\"yes\", padx=10, pady=5)", "self.tello.rotate_ccw(self.degree) def on_keypress_d(self, event): print (\"cw %d m\" % self.degree)", "event, cleanup the camera, and allow the rest of the", "fill=\"both\", expand=\"yes\", padx=10, pady=5) self.btn_landing = tki.Button( self.root, text=\"Open Command", "= tki.Button( panel, text=\"Land\", relief=\"raised\", command=self.telloLanding) self.btn_landing.pack(side=\"bottom\", fill=\"both\", expand=\"yes\", padx=10,", "self.distance_bar.get() print ('reset distance to %.1f' % self.distance) def updateDegreebar(self):", "GUI show self.frame = self.tello.read() if self.frame is None or", "GUI.\"\"\" def __init__(self,tello,outputpath): \"\"\" Initial all the element of the", "self.tmp_f.bind('<KeyPress-a>', self.on_keypress_a) self.tmp_f.bind('<KeyPress-d>', self.on_keypress_d) self.tmp_f.bind('<KeyPress-Up>', self.on_keypress_up) self.tmp_f.bind('<KeyPress-Down>', self.on_keypress_down) self.tmp_f.bind('<KeyPress-Left>', self.on_keypress_left)", "platform class TelloUI: \"\"\"Wrapper class to enable the GUI.\"\"\" def", "relief=\"raised\", command=self.telloTakeOff) self.btn_takeoff.pack(side=\"bottom\", fill=\"both\", expand=\"yes\", padx=10, pady=5) # binding arrow", "quit process to continue \"\"\" print(\"[INFO] closing...\") self.stopEvent.set() del self.tello", "print (\"up %d m\" % self.distance) self.telloUp(self.distance) def on_keypress_s(self, event):", "self.btn_landing.pack(side=\"bottom\", fill=\"both\", expand=\"yes\", padx=10, pady=5) self.btn_takeoff = tki.Button( panel, text=\"Takeoff\",", "# default degree for 'cw' or 'ccw' cmd # if", "tickinterval=10, label='Degree') self.degree_bar.set(30) self.degree_bar.pack(side=\"right\") self.btn_distance = tki.Button(panel, text=\"Reset Degree\", relief=\"raised\",", "\"\"\" Initial all the element of the GUI,support by Tkinter", "self.distance) self.telloMoveLeft(self.distance) def on_keypress_right(self, event): print (\"right %d m\" %", "m\" % self.distance) self.telloMoveRight(self.distance) def on_keypress_enter(self, event): if self.frame is", "and drwa skeleton time.sleep(0.5) self.sending_command_thread.start() while not self.stopEvent.is_set(): system =", "and initial all the button and text \"\"\" panel =", "ImageTk import tkinter as tki from tkinter import Toplevel, Scale", "self.frame is None or self.frame.size == 0: continue # transfer", "long preriod of the \"ImageTk.PhotoImage\" function, # so for Macos,we", "trackbar to reset distance and degree parameter', font='Helvetica 10 bold'", "event): print (\"up %d m\" % self.distance) self.telloUp(self.distance) def on_keypress_s(self,", "tki.Button(self.root, text=\"Snapshot!\", command=self.takeSnapshot) self.btn_snapshot.pack(side=\"bottom\", fill=\"both\", expand=\"yes\", padx=10, pady=5) self.btn_pause =", "allow the rest of the quit process to continue \"\"\"", "saved {}\".format(filename)) def pauseVideo(self): \"\"\" Toggle the freeze/unfreze of video", "to enter command mode. \"\"\" self.tello = tello # videostream", "= tki.Button( panel, text=\"Flip Forward\", relief=\"raised\", command=self.telloFlip_f) self.btn_flipf.pack(side=\"bottom\", fill=\"both\", expand=\"yes\",", "function, # so for Macos,we start a new thread to", "dist): return self.tello.move_up(dist) def telloDown(self, dist): return self.tello.move_down(dist) def updateTrackBar(self):", "event): print (\"down %d m\" % self.distance) self.telloDown(self.distance) def on_keypress_a(self,", "print (\"ccw %d degree\" % self.degree) self.tello.rotate_ccw(self.degree) def on_keypress_d(self, event):", "print (\"backward %d m\" % self.distance) self.telloMoveBackward(self.distance) def on_keypress_left(self, event):", "the most recently read frame self.stopEvent = threading.Event() self.thread =", "and degree parameter', font='Helvetica 10 bold' ) text0.pack(side='top') text1 =", "telloFlip_l(self): return self.tello.flip('l') def telloFlip_r(self): return self.tello.flip('r') def telloFlip_f(self): return", "self.tmp_f.bind('<KeyPress-s>', self.on_keypress_s) self.tmp_f.bind('<KeyPress-a>', self.on_keypress_a) self.tmp_f.bind('<KeyPress-d>', self.on_keypress_d) self.tmp_f.bind('<KeyPress-Up>', self.on_keypress_up) self.tmp_f.bind('<KeyPress-Down>', self.on_keypress_down)", "event): print (\"backward %d m\" % self.distance) self.telloMoveBackward(self.distance) def on_keypress_left(self,", "\"\"\" set the variable as TRUE,it will stop computer waiting", "self.thread.start() # set a callback to handle when the window", "if self.frame is None or self.frame.size == 0: continue #", "import datetime import cv2 import os import time import platform", "created by clicking the takeSnapshot button self.frame = None #", "of the \"ImageTk.PhotoImage\" function, # so for Macos,we start a", "import time import platform class TelloUI: \"\"\"Wrapper class to enable", "\"\"\" image = ImageTk.PhotoImage(image) # if the panel none ,we", "panel, text=\"Flip Right\", relief=\"raised\", command=self.telloFlip_r) self.btn_flipr.pack(side=\"bottom\", fill=\"both\", expand=\"yes\", padx=10, pady=5)", "construct the filename ts = datetime.datetime.now() filename = \"{}.jpg\".format(ts.strftime(\"%Y-%m-%d_%H-%M-%S\")) p", "\"\"\" Toggle the freeze/unfreze of video \"\"\" if self.btn_pause.config('relief')[-1] ==", "Degree\", relief=\"raised\", command=self.updateDegreebar) self.btn_distance.pack(side=\"right\", fill=\"both\", expand=\"yes\", padx=10, pady=5) def openFlipWindow(self):", "- Rotate Tello Counter-Clockwise\\tArrow Left - Move Tello Left\\n' 'D", "all the button and text \"\"\" panel = Toplevel(self.root) panel.wm_title(\"Gesture", "image,and update the GUI panel \"\"\" image = ImageTk.PhotoImage(image) #", "so for Macos,we start a new thread to execute the", "= tki.Button( self.root, text=\"Open Command Panel\", relief=\"raised\", command=self.openCmdWindow) self.btn_landing.pack(side=\"bottom\", fill=\"both\",", "to %d' % self.degree) def on_keypress_w(self, event): print (\"up %d", "Tkinter mainloop self.stopEvent = None # control variables self.distance =", "%d m\" % self.distance) self.telloDown(self.distance) def on_keypress_a(self, event): print (\"ccw", "event): print (\"forward %d m\" % self.distance) self.telloMoveForward(self.distance) def on_keypress_down(self,", "return self.tello.takeoff() def telloLanding(self): return self.tello.land() def telloFlip_l(self): return self.tello.flip('l')", "second \"\"\" while True: self.tello.send_command('command') time.sleep(5) def _setQuitWaitingFlag(self): \"\"\" set", "thread_tmp.start() time.sleep(0.03) except RuntimeError as e: print(\"[INFO] caught a RuntimeError\")", "import os import time import platform class TelloUI: \"\"\"Wrapper class", "arrow keys to drone control self.tmp_f = tki.Frame(panel, width=100, height=2)", "simply update the panel else: self.panel.configure(image=image) self.panel.image = image def", "Macos,we start a new thread to execute the _updateGUIImage function.", "%d' % self.degree) def on_keypress_w(self, event): print (\"up %d m\"", "on_keypress_down(self, event): print (\"backward %d m\" % self.distance) self.telloMoveBackward(self.distance) def", "tki.Label(panel, text='This Controller map keyboard inputs to Tello control commands\\n'", "TRUE,it will stop computer waiting for response from tello \"\"\"", "self.btn_landing = tki.Button( panel, text=\"Land\", relief=\"raised\", command=self.telloLanding) self.btn_landing.pack(side=\"bottom\", fill=\"both\", expand=\"yes\",", "preriod of the \"ImageTk.PhotoImage\" function, # so for Macos,we start", "self.on_keypress_w) self.tmp_f.bind('<KeyPress-s>', self.on_keypress_s) self.tmp_f.bind('<KeyPress-a>', self.on_keypress_a) self.tmp_f.bind('<KeyPress-d>', self.on_keypress_d) self.tmp_f.bind('<KeyPress-Up>', self.on_keypress_up) self.tmp_f.bind('<KeyPress-Down>',", "self.tello.move_down(dist) def updateTrackBar(self): self.my_tello_hand.setThr(self.hand_thr_bar.get()) def updateDistancebar(self): self.distance = self.distance_bar.get() print", "print (\"left %d m\" % self.distance) self.telloMoveLeft(self.distance) def on_keypress_right(self, event):", "\"ImageTk.PhotoImage\" function, # so for Macos,we start a new thread", "and used for pose recognition self.thread = None # thread", "a while loop that sends 'command' to tello every 5", "self.degree = self.degree_bar.get() print ('reset distance to %d' % self.degree)", "it to construct the filename ts = datetime.datetime.now() filename =", "the sending_command will send command to tello every 5 seconds", "RunTime error that Tkinter throws due to threading. \"\"\" try:", "panel none ,we need to initial it if self.panel is", "Move Tello Forward\\n' 'S - Move Tello Down\\t\\t\\tArrow Down -", "None or self.frame.size == 0: continue # transfer the format", "all the element of the GUI,support by Tkinter :param tello:", "\"{}.jpg\".format(ts.strftime(\"%Y-%m-%d_%H-%M-%S\")) p = os.path.sep.join((self.outputPath, filename)) # save the file cv2.imwrite(p,", "flag is TRUE,the auto-takeoff thread will stop waiting for the", "padx=10, pady=5) # start a thread that constantly pools the", "10 bold' ) text0.pack(side='top') text1 = tki.Label(panel, text= 'W -", "RuntimeError\") def _updateGUIImage(self,image): \"\"\" Main operation to initial the object", "parameter', font='Helvetica 10 bold' ) text0.pack(side='top') text1 = tki.Label(panel, text=", "keys to drone control self.tmp_f = tki.Frame(panel, width=100, height=2) self.tmp_f.bind('<KeyPress-w>',", "pady=5) self.btn_flipf = tki.Button( panel, text=\"Flip Forward\", relief=\"raised\", command=self.telloFlip_f) self.btn_flipf.pack(side=\"bottom\",", "\"\"\" # grab the current timestamp and use it to", "found compatibility problem between Tkinter,PIL and Macos,and it will #", "m\" % self.distance) self.telloDown(self.distance) def on_keypress_a(self, event): print (\"ccw %d", "Tello control commands\\n' 'Adjust the trackbar to reset distance and", "the attempt to enter command mode. \"\"\" self.tello = tello", "# create buttons self.btn_snapshot = tki.Button(self.root, text=\"Snapshot!\", command=self.takeSnapshot) self.btn_snapshot.pack(side=\"bottom\", fill=\"both\",", "0: continue # transfer the format from frame to image", "root window and image panel self.root = tki.Tk() self.panel =", "Main operation to initial the object of image,and update the", "\"\"\" start a while loop that sends 'command' to tello", "= tki.Frame(panel, width=100, height=2) self.tmp_f.bind('<KeyPress-w>', self.on_keypress_w) self.tmp_f.bind('<KeyPress-s>', self.on_keypress_s) self.tmp_f.bind('<KeyPress-a>', self.on_keypress_a)", "self.tmp_f.bind('<KeyPress-Left>', self.on_keypress_left) self.tmp_f.bind('<KeyPress-Right>', self.on_keypress_right) self.tmp_f.pack(side=\"bottom\") self.tmp_f.focus_set() self.btn_landing = tki.Button( panel,", "{}\".format(filename)) def pauseVideo(self): \"\"\" Toggle the freeze/unfreze of video \"\"\"", "telloFlip_r(self): return self.tello.flip('r') def telloFlip_f(self): return self.tello.flip('f') def telloFlip_b(self): return", "self.quit_waiting_flag = True def openCmdWindow(self): \"\"\" open the cmd window", "None: self.panel = tki.Label(image=image) self.panel.image = image self.panel.pack(side=\"left\", padx=10, pady=10)", "print (\"right %d m\" % self.distance) self.telloMoveRight(self.distance) def on_keypress_enter(self, event):", "throws due to threading. \"\"\" try: # start the thread", "degree): return self.tello.rotate_ccw(degree) def telloMoveForward(self, distance): return self.tello.move_forward(distance) def telloMoveBackward(self,", "self.tmp_f = tki.Frame(panel, width=100, height=2) self.tmp_f.bind('<KeyPress-w>', self.on_keypress_w) self.tmp_f.bind('<KeyPress-s>', self.on_keypress_s) self.tmp_f.bind('<KeyPress-a>',", "pady=5) self.btn_pause = tki.Button(self.root, text=\"Pause\", relief=\"raised\", command=self.pauseVideo) self.btn_pause.pack(side=\"bottom\", fill=\"both\", expand=\"yes\",", "Raises: RuntimeError: To get around a RunTime error that Tkinter", "self.frame = self.tello.read() if self.frame is None or self.frame.size ==", "self.tello.flip('l') def telloFlip_r(self): return self.tello.flip('r') def telloFlip_f(self): return self.tello.flip('f') def", "('reset distance to %.1f' % self.distance) def updateDegreebar(self): self.degree =", "self.tmp_f.bind('<KeyPress-Down>', self.on_keypress_down) self.tmp_f.bind('<KeyPress-Left>', self.on_keypress_left) self.tmp_f.bind('<KeyPress-Right>', self.on_keypress_right) self.tmp_f.pack(side=\"bottom\") self.tmp_f.focus_set() self.btn_landing =", "panel, text=\"Flip Backward\", relief=\"raised\", command=self.telloFlip_b) self.btn_flipb.pack(side=\"bottom\", fill=\"both\", expand=\"yes\", padx=10, pady=5)", "self.my_tello_hand.setThr(self.hand_thr_bar.get()) def updateDistancebar(self): self.distance = self.distance_bar.get() print ('reset distance to", "pady=5) def openFlipWindow(self): \"\"\" open the flip window and initial", "panel, text=\"Flip Forward\", relief=\"raised\", command=self.telloFlip_f) self.btn_flipf.pack(side=\"bottom\", fill=\"both\", expand=\"yes\", padx=10, pady=5)", "def telloDown(self, dist): return self.tello.move_down(dist) def updateTrackBar(self): self.my_tello_hand.setThr(self.hand_thr_bar.get()) def updateDistancebar(self):", "= datetime.datetime.now() filename = \"{}.jpg\".format(ts.strftime(\"%Y-%m-%d_%H-%M-%S\")) p = os.path.sep.join((self.outputPath, filename)) #", "def _updateGUIImage(self,image): \"\"\" Main operation to initial the object of", "= Scale(panel, from_=1, to=360, tickinterval=10, label='Degree') self.degree_bar.set(30) self.degree_bar.pack(side=\"right\") self.btn_distance =", "relief=\"raised\", command=self.telloFlip_l) self.btn_flipl.pack(side=\"bottom\", fill=\"both\", expand=\"yes\", padx=10, pady=5) self.btn_flipr = tki.Button(", "is not None: self.registerFace() self.tmp_f.focus_set() def onClose(self): \"\"\" set the", "Scale import threading import datetime import cv2 import os import", "cv2 import os import time import platform class TelloUI: \"\"\"Wrapper", "cv2.COLOR_RGB2BGR)) print(\"[INFO] saved {}\".format(filename)) def pauseVideo(self): \"\"\" Toggle the freeze/unfreze", "panel, text=\"Land\", relief=\"raised\", command=self.telloLanding) self.btn_landing.pack(side=\"bottom\", fill=\"both\", expand=\"yes\", padx=10, pady=5) self.btn_takeoff", "expand=\"yes\", padx=10, pady=5) self.distance_bar = Scale(panel, from_=0.02, to=5, tickinterval=0.01, digits=3,", "filename = \"{}.jpg\".format(ts.strftime(\"%Y-%m-%d_%H-%M-%S\")) p = os.path.sep.join((self.outputPath, filename)) # save the", "Controller\") self.root.wm_protocol(\"WM_DELETE_WINDOW\", self.onClose) # the sending_command will send command to", "= tki.Button( panel, text=\"Flip Left\", relief=\"raised\", command=self.telloFlip_l) self.btn_flipl.pack(side=\"bottom\", fill=\"both\", expand=\"yes\",", "= tki.Label(panel, text='This Controller map keyboard inputs to Tello control", "self.tello.flip('f') def telloFlip_b(self): return self.tello.flip('b') def telloCW(self, degree): return self.tello.rotate_cw(degree)", "initialize the root window and image panel self.root = tki.Tk()", "fill=\"both\", expand=\"yes\", padx=10, pady=5) self.btn_flipr = tki.Button( panel, text=\"Flip Right\",", "self.tello.rotate_ccw(degree) def telloMoveForward(self, distance): return self.tello.move_forward(distance) def telloMoveBackward(self, distance): return", "# thread of the Tkinter mainloop self.stopEvent = None #", "% self.distance) self.telloDown(self.distance) def on_keypress_a(self, event): print (\"ccw %d degree\"", "= threading.Thread(target = self._sendingCommand) def videoLoop(self): \"\"\" The mainloop thread", "Initial all the element of the GUI,support by Tkinter :param", "use it to construct the filename ts = datetime.datetime.now() filename", "Rotate Tello Counter-Clockwise\\tArrow Left - Move Tello Left\\n' 'D -", "Toplevel, Scale import threading import datetime import cv2 import os", "frame read from h264decoder and used for pose recognition self.thread", "the trackbar to reset distance and degree parameter', font='Helvetica 10", "return self.tello.move_backward(distance) def telloMoveLeft(self, distance): return self.tello.move_left(distance) def telloMoveRight(self, distance):", "%d m\" % self.distance) self.telloUp(self.distance) def on_keypress_s(self, event): print (\"down", "'move' cmd self.degree = 30 # default degree for 'cw'", "Tkinter Raises: RuntimeError: To get around a RunTime error that", "'cw' or 'ccw' cmd # if the flag is TRUE,the", "\"\"\" set the stop event, cleanup the camera, and allow", "a new thread to execute the _updateGUIImage function. if system", "as TRUE,it will stop computer waiting for response from tello", "for 'move' cmd self.degree = 30 # default degree for", "update the panel else: self.panel.configure(image=image) self.panel.image = image def _sendingCommand(self):", "current frame of the video as a jpg file and", "takeSnapshot button self.frame = None # frame read from h264decoder", "GUI panel \"\"\" image = ImageTk.PhotoImage(image) # if the panel", "the video as a jpg file and put it into", "self.stopEvent = threading.Event() self.thread = threading.Thread(target=self.videoLoop, args=()) self.thread.start() # set", "- Move Tello Right', justify=\"left\") text1.pack(side=\"top\") self.btn_landing = tki.Button( panel,", "the variable as TRUE,it will stop computer waiting for response", "tki.Button( panel, text=\"Flip Forward\", relief=\"raised\", command=self.telloFlip_f) self.btn_flipf.pack(side=\"bottom\", fill=\"both\", expand=\"yes\", padx=10,", "while not self.stopEvent.is_set(): system = platform.system() # read the frame", "%d m\" % self.distance) self.telloMoveRight(self.distance) def on_keypress_enter(self, event): if self.frame", "command=self.openCmdWindow) self.btn_landing.pack(side=\"bottom\", fill=\"both\", expand=\"yes\", padx=10, pady=5) # start a thread", "def takeSnapshot(self): \"\"\" save the current frame of the video", "def on_keypress_d(self, event): print (\"cw %d m\" % self.degree) self.tello.rotate_cw(self.degree)", "# control variables self.distance = 0.1 # default distance for", "to initial the object of image,and update the GUI panel", "a callback to handle when the window is closed self.root.wm_title(\"TELLO", "%.1f' % self.distance) def updateDegreebar(self): self.degree = self.degree_bar.get() print ('reset", "control commands\\n' 'Adjust the trackbar to reset distance and degree", "telloUp(self, dist): return self.tello.move_up(dist) def telloDown(self, dist): return self.tello.move_down(dist) def", "self.btn_flipb.pack(side=\"bottom\", fill=\"both\", expand=\"yes\", padx=10, pady=5) def takeSnapshot(self): \"\"\" save the", "TRUE,the auto-takeoff thread will stop waiting for the response from", "buttons self.btn_snapshot = tki.Button(self.root, text=\"Snapshot!\", command=self.takeSnapshot) self.btn_snapshot.pack(side=\"bottom\", fill=\"both\", expand=\"yes\", padx=10,", "e: print(\"[INFO] caught a RuntimeError\") def _updateGUIImage(self,image): \"\"\" Main operation", "import ImageTk import tkinter as tki from tkinter import Toplevel,", "None # thread of the Tkinter mainloop self.stopEvent = None", "expand=\"yes\", padx=10, pady=5) self.degree_bar = Scale(panel, from_=1, to=360, tickinterval=10, label='Degree')", "platform.system() # read the frame for GUI show self.frame =", "openCmdWindow(self): \"\"\" open the cmd window and initial all the", "font='Helvetica 10 bold' ) text0.pack(side='top') text1 = tki.Label(panel, text= 'W", "ts = datetime.datetime.now() filename = \"{}.jpg\".format(ts.strftime(\"%Y-%m-%d_%H-%M-%S\")) p = os.path.sep.join((self.outputPath, filename))", "0.1 # default distance for 'move' cmd self.degree = 30", "start a thread that constantly pools the video sensor for", "to drone control self.tmp_f = tki.Frame(panel, width=100, height=2) self.tmp_f.bind('<KeyPress-w>', self.on_keypress_w)", "the stop event, cleanup the camera, and allow the rest", "send command to tello every 5 seconds self.sending_command_thread = threading.Thread(target", "self.stopEvent = None # control variables self.distance = 0.1 #", "Scale(panel, from_=0.02, to=5, tickinterval=0.01, digits=3, label='Distance(m)', resolution=0.01) self.distance_bar.set(0.2) self.distance_bar.pack(side=\"left\") self.btn_distance", "Backward\", relief=\"raised\", command=self.telloFlip_b) self.btn_flipb.pack(side=\"bottom\", fill=\"both\", expand=\"yes\", padx=10, pady=5) def takeSnapshot(self):", "= ImageTk.PhotoImage(image) # if the panel none ,we need to", "= Toplevel(self.root) panel.wm_title(\"Gesture Recognition\") self.btn_flipl = tki.Button( panel, text=\"Flip Left\",", "self._sendingCommand) def videoLoop(self): \"\"\" The mainloop thread of Tkinter Raises:", "\"\"\"Wrapper class to enable the GUI.\"\"\" def __init__(self,tello,outputpath): \"\"\" Initial", "def on_keypress_right(self, event): print (\"right %d m\" % self.distance) self.telloMoveRight(self.distance)", "self.tello.video_freeze(True) def telloTakeOff(self): return self.tello.takeoff() def telloLanding(self): return self.tello.land() def", "self.frame.size == 0: continue # transfer the format from frame", "the video sensor for # the most recently read frame", "fill=\"both\", expand=\"yes\", padx=10, pady=5) self.btn_flipb = tki.Button( panel, text=\"Flip Backward\",", "self.tello.move_left(distance) def telloMoveRight(self, distance): return self.tello.move_right(distance) def telloUp(self, dist): return", "command=self.takeSnapshot) self.btn_snapshot.pack(side=\"bottom\", fill=\"both\", expand=\"yes\", padx=10, pady=5) self.btn_pause = tki.Button(self.root, text=\"Pause\",", "tki.Button( panel, text=\"Takeoff\", relief=\"raised\", command=self.telloTakeOff) self.btn_takeoff.pack(side=\"bottom\", fill=\"both\", expand=\"yes\", padx=10, pady=5)", "def on_keypress_up(self, event): print (\"forward %d m\" % self.distance) self.telloMoveForward(self.distance)", "tki.Button(panel, text=\"Reset Distance\", relief=\"raised\", command=self.updateDistancebar, ) self.btn_distance.pack(side=\"left\", fill=\"both\", expand=\"yes\", padx=10,", "open the flip window and initial all the button and", "= tki.Tk() self.panel = None # create buttons self.btn_snapshot =", "_sendingCommand(self): \"\"\" start a while loop that sends 'command' to", "% self.distance) self.telloMoveLeft(self.distance) def on_keypress_right(self, event): print (\"right %d m\"", "or 'ccw' cmd # if the flag is TRUE,the auto-takeoff", "updateDistancebar(self): self.distance = self.distance_bar.get() print ('reset distance to %.1f' %", "thread that get GUI image and drwa skeleton time.sleep(0.5) self.sending_command_thread.start()", "\"\"\" self.quit_waiting_flag = True def openCmdWindow(self): \"\"\" open the cmd", "sensor for # the most recently read frame self.stopEvent =", "text=\"Open Command Panel\", relief=\"raised\", command=self.openCmdWindow) self.btn_landing.pack(side=\"bottom\", fill=\"both\", expand=\"yes\", padx=10, pady=5)", "for response from tello \"\"\" self.quit_waiting_flag = True def openCmdWindow(self):", "\"\"\" self.tello = tello # videostream device self.outputPath = outputpath", "datetime.datetime.now() filename = \"{}.jpg\".format(ts.strftime(\"%Y-%m-%d_%H-%M-%S\")) p = os.path.sep.join((self.outputPath, filename)) # save", "rest of the quit process to continue \"\"\" print(\"[INFO] closing...\")", ") text0.pack(side='top') text1 = tki.Label(panel, text= 'W - Move Tello", "self.btn_flipr.pack(side=\"bottom\", fill=\"both\", expand=\"yes\", padx=10, pady=5) self.btn_flipf = tki.Button( panel, text=\"Flip", "= tello # videostream device self.outputPath = outputpath # the", "image self.panel.pack(side=\"left\", padx=10, pady=10) # otherwise, simply update the panel", "text=\"Flip Forward\", relief=\"raised\", command=self.telloFlip_f) self.btn_flipf.pack(side=\"bottom\", fill=\"both\", expand=\"yes\", padx=10, pady=5) self.btn_flipb", "and text \"\"\" panel = Toplevel(self.root) panel.wm_title(\"Command Panel\") # create", "return self.tello.flip('f') def telloFlip_b(self): return self.tello.flip('b') def telloCW(self, degree): return", "command mode. \"\"\" self.tello = tello # videostream device self.outputPath", "not self.stopEvent.is_set(): system = platform.system() # read the frame for", "text=\"Pause\", relief=\"raised\", command=self.pauseVideo) self.btn_pause.pack(side=\"bottom\", fill=\"both\", expand=\"yes\", padx=10, pady=5) self.btn_landing =", "image = ImageTk.PhotoImage(image) # if the panel none ,we need", "control variables self.distance = 0.1 # default distance for 'move'", "the response from tello self.quit_waiting_flag = False # initialize the", "for # the most recently read frame self.stopEvent = threading.Event()", "drwa skeleton time.sleep(0.5) self.sending_command_thread.start() while not self.stopEvent.is_set(): system = platform.system()", "self.tmp_f.bind('<KeyPress-d>', self.on_keypress_d) self.tmp_f.bind('<KeyPress-Up>', self.on_keypress_up) self.tmp_f.bind('<KeyPress-Down>', self.on_keypress_down) self.tmp_f.bind('<KeyPress-Left>', self.on_keypress_left) self.tmp_f.bind('<KeyPress-Right>', self.on_keypress_right)", "telloMoveRight(self, distance): return self.tello.move_right(distance) def telloUp(self, dist): return self.tello.move_up(dist) def", "updateTrackBar(self): self.my_tello_hand.setThr(self.hand_thr_bar.get()) def updateDistancebar(self): self.distance = self.distance_bar.get() print ('reset distance", "Tello Counter-Clockwise\\tArrow Left - Move Tello Left\\n' 'D - Rotate", "text=\"Snapshot!\", command=self.takeSnapshot) self.btn_snapshot.pack(side=\"bottom\", fill=\"both\", expand=\"yes\", padx=10, pady=5) self.btn_pause = tki.Button(self.root,", "for GUI show self.frame = self.tello.read() if self.frame is None", "will stop computer waiting for response from tello \"\"\" self.quit_waiting_flag", "'W - Move Tello Up\\t\\t\\tArrow Up - Move Tello Forward\\n'", "print ('reset distance to %d' % self.degree) def on_keypress_w(self, event):", "callback to handle when the window is closed self.root.wm_title(\"TELLO Controller\")", "cv2.cvtColor(self.frame, cv2.COLOR_RGB2BGR)) print(\"[INFO] saved {}\".format(filename)) def pauseVideo(self): \"\"\" Toggle the", "the object of image,and update the GUI panel \"\"\" image", "set a callback to handle when the window is closed", "panel = Toplevel(self.root) panel.wm_title(\"Gesture Recognition\") self.btn_flipl = tki.Button( panel, text=\"Flip", "Panel\", relief=\"raised\", command=self.openCmdWindow) self.btn_landing.pack(side=\"bottom\", fill=\"both\", expand=\"yes\", padx=10, pady=5) # start", "continue # transfer the format from frame to image image", "that get GUI image and drwa skeleton time.sleep(0.5) self.sending_command_thread.start() while", "RuntimeError: If the Tello rejects the attempt to enter command", "read frame self.stopEvent = threading.Event() self.thread = threading.Thread(target=self.videoLoop, args=()) self.thread.start()", "# we found compatibility problem between Tkinter,PIL and Macos,and it", "not None: self.registerFace() self.tmp_f.focus_set() def onClose(self): \"\"\" set the stop", "that sends 'command' to tello every 5 second \"\"\" while", ",we need to initial it if self.panel is None: self.panel", "self.btn_flipf = tki.Button( panel, text=\"Flip Forward\", relief=\"raised\", command=self.telloFlip_f) self.btn_flipf.pack(side=\"bottom\", fill=\"both\",", "Tello drone. Raises: RuntimeError: If the Tello rejects the attempt", "= tki.Button( panel, text=\"Flip Right\", relief=\"raised\", command=self.telloFlip_r) self.btn_flipr.pack(side=\"bottom\", fill=\"both\", expand=\"yes\",", "Panel\") # create text input entry text0 = tki.Label(panel, text='This", ") self.btn_distance.pack(side=\"left\", fill=\"both\", expand=\"yes\", padx=10, pady=5) self.degree_bar = Scale(panel, from_=1,", "of the GUI,support by Tkinter :param tello: class interacts with", "fill=\"both\", expand=\"yes\", padx=10, pady=5) self.btn_pause = tki.Button(self.root, text=\"Pause\", relief=\"raised\", command=self.pauseVideo)", "text0.pack(side='top') text1 = tki.Label(panel, text= 'W - Move Tello Up\\t\\t\\tArrow", "to enable the GUI.\"\"\" def __init__(self,tello,outputpath): \"\"\" Initial all the", "self.on_keypress_d) self.tmp_f.bind('<KeyPress-Up>', self.on_keypress_up) self.tmp_f.bind('<KeyPress-Down>', self.on_keypress_down) self.tmp_f.bind('<KeyPress-Left>', self.on_keypress_left) self.tmp_f.bind('<KeyPress-Right>', self.on_keypress_right) self.tmp_f.pack(side=\"bottom\")", "tki.Button( panel, text=\"Flip Right\", relief=\"raised\", command=self.telloFlip_r) self.btn_flipr.pack(side=\"bottom\", fill=\"both\", expand=\"yes\", padx=10,", "= self._sendingCommand) def videoLoop(self): \"\"\" The mainloop thread of Tkinter", "stop waiting for the response from tello self.quit_waiting_flag = False", "most recently read frame self.stopEvent = threading.Event() self.thread = threading.Thread(target=self.videoLoop,", "transfer the format from frame to image image = Image.fromarray(self.frame)", "if self.frame is not None: self.registerFace() self.tmp_f.focus_set() def onClose(self): \"\"\"", "we found compatibility problem between Tkinter,PIL and Macos,and it will", "self.btn_pause.config(relief=\"raised\") self.tello.video_freeze(False) else: self.btn_pause.config(relief=\"sunken\") self.tello.video_freeze(True) def telloTakeOff(self): return self.tello.takeoff() def", "self.root.wm_protocol(\"WM_DELETE_WINDOW\", self.onClose) # the sending_command will send command to tello", "return self.tello.flip('r') def telloFlip_f(self): return self.tello.flip('f') def telloFlip_b(self): return self.tello.flip('b')", "self.on_keypress_a) self.tmp_f.bind('<KeyPress-d>', self.on_keypress_d) self.tmp_f.bind('<KeyPress-Up>', self.on_keypress_up) self.tmp_f.bind('<KeyPress-Down>', self.on_keypress_down) self.tmp_f.bind('<KeyPress-Left>', self.on_keypress_left) self.tmp_f.bind('<KeyPress-Right>',", "mode. \"\"\" self.tello = tello # videostream device self.outputPath =", "telloTakeOff(self): return self.tello.takeoff() def telloLanding(self): return self.tello.land() def telloFlip_l(self): return", "Tello Up\\t\\t\\tArrow Up - Move Tello Forward\\n' 'S - Move", "text0 = tki.Label(panel, text='This Controller map keyboard inputs to Tello", "# frame read from h264decoder and used for pose recognition", "30 # default degree for 'cw' or 'ccw' cmd #", "PIL import Image from PIL import ImageTk import tkinter as", "def telloFlip_r(self): return self.tello.flip('r') def telloFlip_f(self): return self.tello.flip('f') def telloFlip_b(self):", "variables self.distance = 0.1 # default distance for 'move' cmd", "telloCCW(self, degree): return self.tello.rotate_ccw(degree) def telloMoveForward(self, distance): return self.tello.move_forward(distance) def", "response from tello \"\"\" self.quit_waiting_flag = True def openCmdWindow(self): \"\"\"", "expand=\"yes\", padx=10, pady=5) def takeSnapshot(self): \"\"\" save the current frame", "self.btn_landing.pack(side=\"bottom\", fill=\"both\", expand=\"yes\", padx=10, pady=5) # start a thread that", "the flag is TRUE,the auto-takeoff thread will stop waiting for", "the frame for GUI show self.frame = self.tello.read() if self.frame", "# start the thread that get GUI image and drwa", "# binding arrow keys to drone control self.tmp_f = tki.Frame(panel,", "get around a RunTime error that Tkinter throws due to", "import tkinter as tki from tkinter import Toplevel, Scale import", "from tello \"\"\" self.quit_waiting_flag = True def openCmdWindow(self): \"\"\" open", "function. if system ==\"Windows\" or system ==\"Linux\": self._updateGUIImage(image) else: thread_tmp", "handle when the window is closed self.root.wm_title(\"TELLO Controller\") self.root.wm_protocol(\"WM_DELETE_WINDOW\", self.onClose)", "path that save pictures created by clicking the takeSnapshot button", "videostream device self.outputPath = outputpath # the path that save", "current timestamp and use it to construct the filename ts", "# so for Macos,we start a new thread to execute", "while loop that sends 'command' to tello every 5 second", "(\"up %d m\" % self.distance) self.telloUp(self.distance) def on_keypress_s(self, event): print", "(\"right %d m\" % self.distance) self.telloMoveRight(self.distance) def on_keypress_enter(self, event): if", "degree\" % self.degree) self.tello.rotate_ccw(self.degree) def on_keypress_d(self, event): print (\"cw %d", "def on_keypress_s(self, event): print (\"down %d m\" % self.distance) self.telloDown(self.distance)", "= 30 # default degree for 'cw' or 'ccw' cmd", "Right\", relief=\"raised\", command=self.telloFlip_r) self.btn_flipr.pack(side=\"bottom\", fill=\"both\", expand=\"yes\", padx=10, pady=5) self.btn_flipf =", "pady=5) self.btn_flipb = tki.Button( panel, text=\"Flip Backward\", relief=\"raised\", command=self.telloFlip_b) self.btn_flipb.pack(side=\"bottom\",", "event): print (\"cw %d m\" % self.degree) self.tello.rotate_cw(self.degree) def on_keypress_up(self,", "def on_keypress_enter(self, event): if self.frame is not None: self.registerFace() self.tmp_f.focus_set()", "- Move Tello Backward\\n' 'A - Rotate Tello Counter-Clockwise\\tArrow Left", "self.btn_distance.pack(side=\"left\", fill=\"both\", expand=\"yes\", padx=10, pady=5) self.degree_bar = Scale(panel, from_=1, to=360,", "expand=\"yes\", padx=10, pady=5) self.btn_pause = tki.Button(self.root, text=\"Pause\", relief=\"raised\", command=self.pauseVideo) self.btn_pause.pack(side=\"bottom\",", "distance for 'move' cmd self.degree = 30 # default degree", "padx=10, pady=5) def openFlipWindow(self): \"\"\" open the flip window and", "to=5, tickinterval=0.01, digits=3, label='Distance(m)', resolution=0.01) self.distance_bar.set(0.2) self.distance_bar.pack(side=\"left\") self.btn_distance = tki.Button(panel,", "is closed self.root.wm_title(\"TELLO Controller\") self.root.wm_protocol(\"WM_DELETE_WINDOW\", self.onClose) # the sending_command will", "pady=5) self.btn_takeoff = tki.Button( panel, text=\"Takeoff\", relief=\"raised\", command=self.telloTakeOff) self.btn_takeoff.pack(side=\"bottom\", fill=\"both\",", "def updateDistancebar(self): self.distance = self.distance_bar.get() print ('reset distance to %.1f'", "Tello Backward\\n' 'A - Rotate Tello Counter-Clockwise\\tArrow Left - Move", "self.panel = None # create buttons self.btn_snapshot = tki.Button(self.root, text=\"Snapshot!\",", "self.btn_snapshot.pack(side=\"bottom\", fill=\"both\", expand=\"yes\", padx=10, pady=5) self.btn_pause = tki.Button(self.root, text=\"Pause\", relief=\"raised\",", "Move Tello Left\\n' 'D - Rotate Tello Clockwise\\t\\tArrow Right -", "initial all the button and text \"\"\" panel = Toplevel(self.root)", "self.tello.takeoff() def telloLanding(self): return self.tello.land() def telloFlip_l(self): return self.tello.flip('l') def", "will send command to tello every 5 seconds self.sending_command_thread =", "def openCmdWindow(self): \"\"\" open the cmd window and initial all", "tki.Tk() self.panel = None # create buttons self.btn_snapshot = tki.Button(self.root,", "map keyboard inputs to Tello control commands\\n' 'Adjust the trackbar", "every 5 second \"\"\" while True: self.tello.send_command('command') time.sleep(5) def _setQuitWaitingFlag(self):", "waiting for the response from tello self.quit_waiting_flag = False #", "commands\\n' 'Adjust the trackbar to reset distance and degree parameter',", "self.telloMoveLeft(self.distance) def on_keypress_right(self, event): print (\"right %d m\" % self.distance)", "None: self.registerFace() self.tmp_f.focus_set() def onClose(self): \"\"\" set the stop event,", "Left\\n' 'D - Rotate Tello Clockwise\\t\\tArrow Right - Move Tello", "import Image from PIL import ImageTk import tkinter as tki", "and image panel self.root = tki.Tk() self.panel = None #", "it if self.panel is None: self.panel = tki.Label(image=image) self.panel.image =", "default degree for 'cw' or 'ccw' cmd # if the", "'sunken': self.btn_pause.config(relief=\"raised\") self.tello.video_freeze(False) else: self.btn_pause.config(relief=\"sunken\") self.tello.video_freeze(True) def telloTakeOff(self): return self.tello.takeoff()", "self.degree_bar.pack(side=\"right\") self.btn_distance = tki.Button(panel, text=\"Reset Degree\", relief=\"raised\", command=self.updateDegreebar) self.btn_distance.pack(side=\"right\", fill=\"both\",", "from tello self.quit_waiting_flag = False # initialize the root window", "of the quit process to continue \"\"\" print(\"[INFO] closing...\") self.stopEvent.set()", "degree for 'cw' or 'ccw' cmd # if the flag", "video sensor for # the most recently read frame self.stopEvent", "def telloUp(self, dist): return self.tello.move_up(dist) def telloDown(self, dist): return self.tello.move_down(dist)", "# initialize the root window and image panel self.root =", "fill=\"both\", expand=\"yes\", padx=10, pady=5) self.degree_bar = Scale(panel, from_=1, to=360, tickinterval=10,", "print (\"down %d m\" % self.distance) self.telloDown(self.distance) def on_keypress_a(self, event):", "= None # create buttons self.btn_snapshot = tki.Button(self.root, text=\"Snapshot!\", command=self.takeSnapshot)", "# set a callback to handle when the window is", "it will # sometimes result the very long preriod of", "True: self.tello.send_command('command') time.sleep(5) def _setQuitWaitingFlag(self): \"\"\" set the variable as", "Forward\\n' 'S - Move Tello Down\\t\\t\\tArrow Down - Move Tello", "print (\"forward %d m\" % self.distance) self.telloMoveForward(self.distance) def on_keypress_down(self, event):", "# the most recently read frame self.stopEvent = threading.Event() self.thread", "\"\"\" panel = Toplevel(self.root) panel.wm_title(\"Gesture Recognition\") self.btn_flipl = tki.Button( panel,", "text=\"Reset Distance\", relief=\"raised\", command=self.updateDistancebar, ) self.btn_distance.pack(side=\"left\", fill=\"both\", expand=\"yes\", padx=10, pady=5)", "the thread that get GUI image and drwa skeleton time.sleep(0.5)", "takeSnapshot(self): \"\"\" save the current frame of the video as", "the Tello rejects the attempt to enter command mode. \"\"\"", "reset distance and degree parameter', font='Helvetica 10 bold' ) text0.pack(side='top')", "def telloMoveForward(self, distance): return self.tello.move_forward(distance) def telloMoveBackward(self, distance): return self.tello.move_backward(distance)", "the path that save pictures created by clicking the takeSnapshot", "the GUI,support by Tkinter :param tello: class interacts with the", "def telloFlip_f(self): return self.tello.flip('f') def telloFlip_b(self): return self.tello.flip('b') def telloCW(self,", "of the Tkinter mainloop self.stopEvent = None # control variables", "= True def openCmdWindow(self): \"\"\" open the cmd window and", "args=()) self.thread.start() # set a callback to handle when the", "self.distance) self.telloMoveForward(self.distance) def on_keypress_down(self, event): print (\"backward %d m\" %", "tello: class interacts with the Tello drone. Raises: RuntimeError: If", "self.frame = None # frame read from h264decoder and used", "tickinterval=0.01, digits=3, label='Distance(m)', resolution=0.01) self.distance_bar.set(0.2) self.distance_bar.pack(side=\"left\") self.btn_distance = tki.Button(panel, text=\"Reset", "and Macos,and it will # sometimes result the very long", "% self.distance) self.telloMoveRight(self.distance) def on_keypress_enter(self, event): if self.frame is not", "% self.distance) self.telloUp(self.distance) def on_keypress_s(self, event): print (\"down %d m\"", "grab the current timestamp and use it to construct the", "a jpg file and put it into outputpath \"\"\" #", "= tki.Button(panel, text=\"Reset Degree\", relief=\"raised\", command=self.updateDegreebar) self.btn_distance.pack(side=\"right\", fill=\"both\", expand=\"yes\", padx=10,", "import threading import datetime import cv2 import os import time", "interacts with the Tello drone. Raises: RuntimeError: If the Tello", "_setQuitWaitingFlag(self): \"\"\" set the variable as TRUE,it will stop computer", "m\" % self.distance) self.telloUp(self.distance) def on_keypress_s(self, event): print (\"down %d", "thread that constantly pools the video sensor for # the", "digits=3, label='Distance(m)', resolution=0.01) self.distance_bar.set(0.2) self.distance_bar.pack(side=\"left\") self.btn_distance = tki.Button(panel, text=\"Reset Distance\",", "'S - Move Tello Down\\t\\t\\tArrow Down - Move Tello Backward\\n'", "5 second \"\"\" while True: self.tello.send_command('command') time.sleep(5) def _setQuitWaitingFlag(self): \"\"\"", "and use it to construct the filename ts = datetime.datetime.now()", "pady=5) self.btn_flipr = tki.Button( panel, text=\"Flip Right\", relief=\"raised\", command=self.telloFlip_r) self.btn_flipr.pack(side=\"bottom\",", "self.degree_bar.get() print ('reset distance to %d' % self.degree) def on_keypress_w(self,", "PIL import ImageTk import tkinter as tki from tkinter import", "with the Tello drone. Raises: RuntimeError: If the Tello rejects", "print(\"[INFO] caught a RuntimeError\") def _updateGUIImage(self,image): \"\"\" Main operation to", "Toplevel(self.root) panel.wm_title(\"Command Panel\") # create text input entry text0 =", "return self.tello.move_right(distance) def telloUp(self, dist): return self.tello.move_up(dist) def telloDown(self, dist):", "button and text \"\"\" panel = Toplevel(self.root) panel.wm_title(\"Gesture Recognition\") self.btn_flipl", "for Macos,we start a new thread to execute the _updateGUIImage", "def openFlipWindow(self): \"\"\" open the flip window and initial all", "== 'sunken': self.btn_pause.config(relief=\"raised\") self.tello.video_freeze(False) else: self.btn_pause.config(relief=\"sunken\") self.tello.video_freeze(True) def telloTakeOff(self): return", "else: self.panel.configure(image=image) self.panel.image = image def _sendingCommand(self): \"\"\" start a", "new thread to execute the _updateGUIImage function. if system ==\"Windows\"", "event): print (\"left %d m\" % self.distance) self.telloMoveLeft(self.distance) def on_keypress_right(self,", "pady=5) def takeSnapshot(self): \"\"\" save the current frame of the", "= tki.Button( panel, text=\"Flip Backward\", relief=\"raised\", command=self.telloFlip_b) self.btn_flipb.pack(side=\"bottom\", fill=\"both\", expand=\"yes\",", "command=self.telloFlip_r) self.btn_flipr.pack(side=\"bottom\", fill=\"both\", expand=\"yes\", padx=10, pady=5) self.btn_flipf = tki.Button( panel,", "def telloLanding(self): return self.tello.land() def telloFlip_l(self): return self.tello.flip('l') def telloFlip_r(self):", "Tello Forward\\n' 'S - Move Tello Down\\t\\t\\tArrow Down - Move", "def telloMoveRight(self, distance): return self.tello.move_right(distance) def telloUp(self, dist): return self.tello.move_up(dist)", "it into outputpath \"\"\" # grab the current timestamp and", "Down - Move Tello Backward\\n' 'A - Rotate Tello Counter-Clockwise\\tArrow", "for the response from tello self.quit_waiting_flag = False # initialize", "a thread that constantly pools the video sensor for #", "self.tello.read() if self.frame is None or self.frame.size == 0: continue", "self.tmp_f.pack(side=\"bottom\") self.tmp_f.focus_set() self.btn_landing = tki.Button( panel, text=\"Flip\", relief=\"raised\", command=self.openFlipWindow) self.btn_landing.pack(side=\"bottom\",", "from_=0.02, to=5, tickinterval=0.01, digits=3, label='Distance(m)', resolution=0.01) self.distance_bar.set(0.2) self.distance_bar.pack(side=\"left\") self.btn_distance =", "self.panel.image = image self.panel.pack(side=\"left\", padx=10, pady=10) # otherwise, simply update", "control self.tmp_f = tki.Frame(panel, width=100, height=2) self.tmp_f.bind('<KeyPress-w>', self.on_keypress_w) self.tmp_f.bind('<KeyPress-s>', self.on_keypress_s)", "label='Distance(m)', resolution=0.01) self.distance_bar.set(0.2) self.distance_bar.pack(side=\"left\") self.btn_distance = tki.Button(panel, text=\"Reset Distance\", relief=\"raised\",", "cmd self.degree = 30 # default degree for 'cw' or", "relief=\"raised\", command=self.telloFlip_f) self.btn_flipf.pack(side=\"bottom\", fill=\"both\", expand=\"yes\", padx=10, pady=5) self.btn_flipb = tki.Button(", "# create text input entry text0 = tki.Label(panel, text='This Controller", "m\" % self.distance) self.telloMoveBackward(self.distance) def on_keypress_left(self, event): print (\"left %d", "else: self.btn_pause.config(relief=\"sunken\") self.tello.video_freeze(True) def telloTakeOff(self): return self.tello.takeoff() def telloLanding(self): return", "except RuntimeError as e: print(\"[INFO] caught a RuntimeError\") def _updateGUIImage(self,image):", "self.btn_flipl.pack(side=\"bottom\", fill=\"both\", expand=\"yes\", padx=10, pady=5) self.btn_flipr = tki.Button( panel, text=\"Flip", "padx=10, pady=5) self.btn_pause = tki.Button(self.root, text=\"Pause\", relief=\"raised\", command=self.pauseVideo) self.btn_pause.pack(side=\"bottom\", fill=\"both\",", "time.sleep(0.5) self.sending_command_thread.start() while not self.stopEvent.is_set(): system = platform.system() # read", "of video \"\"\" if self.btn_pause.config('relief')[-1] == 'sunken': self.btn_pause.config(relief=\"raised\") self.tello.video_freeze(False) else:", "due to threading. \"\"\" try: # start the thread that", "= Toplevel(self.root) panel.wm_title(\"Command Panel\") # create text input entry text0", "of Tkinter Raises: RuntimeError: To get around a RunTime error", "relief=\"raised\", command=self.openCmdWindow) self.btn_landing.pack(side=\"bottom\", fill=\"both\", expand=\"yes\", padx=10, pady=5) # start a", "command=self.telloTakeOff) self.btn_takeoff.pack(side=\"bottom\", fill=\"both\", expand=\"yes\", padx=10, pady=5) # binding arrow keys", "panel self.root = tki.Tk() self.panel = None # create buttons", "the element of the GUI,support by Tkinter :param tello: class", "format from frame to image image = Image.fromarray(self.frame) # we", "fill=\"both\", expand=\"yes\", padx=10, pady=5) self.btn_flipf = tki.Button( panel, text=\"Flip Forward\",", "thread of the Tkinter mainloop self.stopEvent = None # control", "enter command mode. \"\"\" self.tello = tello # videostream device", "Macos,and it will # sometimes result the very long preriod", "into outputpath \"\"\" # grab the current timestamp and use", "- Move Tello Down\\t\\t\\tArrow Down - Move Tello Backward\\n' 'A", "on_keypress_w(self, event): print (\"up %d m\" % self.distance) self.telloUp(self.distance) def", "text=\"Land\", relief=\"raised\", command=self.telloLanding) self.btn_landing.pack(side=\"bottom\", fill=\"both\", expand=\"yes\", padx=10, pady=5) self.btn_takeoff =", "return self.tello.rotate_ccw(degree) def telloMoveForward(self, distance): return self.tello.move_forward(distance) def telloMoveBackward(self, distance):", "put it into outputpath \"\"\" # grab the current timestamp", "open the cmd window and initial all the button and", "False # initialize the root window and image panel self.root", "image def _sendingCommand(self): \"\"\" start a while loop that sends", "the window is closed self.root.wm_title(\"TELLO Controller\") self.root.wm_protocol(\"WM_DELETE_WINDOW\", self.onClose) # the", "binding arrow keys to drone control self.tmp_f = tki.Frame(panel, width=100,", "as tki from tkinter import Toplevel, Scale import threading import", "seconds self.sending_command_thread = threading.Thread(target = self._sendingCommand) def videoLoop(self): \"\"\" The", "padx=10, pady=5) self.distance_bar = Scale(panel, from_=0.02, to=5, tickinterval=0.01, digits=3, label='Distance(m)',", "command=self.telloFlip_b) self.btn_flipb.pack(side=\"bottom\", fill=\"both\", expand=\"yes\", padx=10, pady=5) def takeSnapshot(self): \"\"\" save", "class to enable the GUI.\"\"\" def __init__(self,tello,outputpath): \"\"\" Initial all", "pictures created by clicking the takeSnapshot button self.frame = None", "self.stopEvent.is_set(): system = platform.system() # read the frame for GUI", "def updateDegreebar(self): self.degree = self.degree_bar.get() print ('reset distance to %d'", "# sometimes result the very long preriod of the \"ImageTk.PhotoImage\"", "= image def _sendingCommand(self): \"\"\" start a while loop that", "= threading.Event() self.thread = threading.Thread(target=self.videoLoop, args=()) self.thread.start() # set a", "while True: self.tello.send_command('command') time.sleep(5) def _setQuitWaitingFlag(self): \"\"\" set the variable", "threading. \"\"\" try: # start the thread that get GUI", "self.distance_bar.pack(side=\"left\") self.btn_distance = tki.Button(panel, text=\"Reset Distance\", relief=\"raised\", command=self.updateDistancebar, ) self.btn_distance.pack(side=\"left\",", "auto-takeoff thread will stop waiting for the response from tello", "% self.distance) self.telloMoveBackward(self.distance) def on_keypress_left(self, event): print (\"left %d m\"", "return self.tello.move_left(distance) def telloMoveRight(self, distance): return self.tello.move_right(distance) def telloUp(self, dist):", "self.telloMoveBackward(self.distance) def on_keypress_left(self, event): print (\"left %d m\" % self.distance)", "the takeSnapshot button self.frame = None # frame read from", "telloMoveBackward(self, distance): return self.tello.move_backward(distance) def telloMoveLeft(self, distance): return self.tello.move_left(distance) def", "text=\"Takeoff\", relief=\"raised\", command=self.telloTakeOff) self.btn_takeoff.pack(side=\"bottom\", fill=\"both\", expand=\"yes\", padx=10, pady=5) # binding", "self.tello.flip('b') def telloCW(self, degree): return self.tello.rotate_cw(degree) def telloCCW(self, degree): return", "by clicking the takeSnapshot button self.frame = None # frame", "= tki.Button(self.root, text=\"Snapshot!\", command=self.takeSnapshot) self.btn_snapshot.pack(side=\"bottom\", fill=\"both\", expand=\"yes\", padx=10, pady=5) self.btn_pause", "text=\"Flip Left\", relief=\"raised\", command=self.telloFlip_l) self.btn_flipl.pack(side=\"bottom\", fill=\"both\", expand=\"yes\", padx=10, pady=5) self.btn_flipr", "a RuntimeError\") def _updateGUIImage(self,image): \"\"\" Main operation to initial the", "the flip window and initial all the button and text", "or system ==\"Linux\": self._updateGUIImage(image) else: thread_tmp = threading.Thread(target=self._updateGUIImage,args=(image,)) thread_tmp.start() time.sleep(0.03)", "time.sleep(0.03) except RuntimeError as e: print(\"[INFO] caught a RuntimeError\") def", "relief=\"raised\", command=self.telloLanding) self.btn_landing.pack(side=\"bottom\", fill=\"both\", expand=\"yes\", padx=10, pady=5) self.btn_takeoff = tki.Button(", "def telloCW(self, degree): return self.tello.rotate_cw(degree) def telloCCW(self, degree): return self.tello.rotate_ccw(degree)", "# if the panel none ,we need to initial it", "to image image = Image.fromarray(self.frame) # we found compatibility problem", "sending_command will send command to tello every 5 seconds self.sending_command_thread", "5 seconds self.sending_command_thread = threading.Thread(target = self._sendingCommand) def videoLoop(self): \"\"\"", "flip window and initial all the button and text \"\"\"", "padx=10, pady=5) self.btn_flipf = tki.Button( panel, text=\"Flip Forward\", relief=\"raised\", command=self.telloFlip_f)", "Forward\", relief=\"raised\", command=self.telloFlip_f) self.btn_flipf.pack(side=\"bottom\", fill=\"both\", expand=\"yes\", padx=10, pady=5) self.btn_flipb =", "RuntimeError: To get around a RunTime error that Tkinter throws", "Right - Move Tello Right', justify=\"left\") text1.pack(side=\"top\") self.btn_landing = tki.Button(", "__init__(self,tello,outputpath): \"\"\" Initial all the element of the GUI,support by", "return self.tello.rotate_cw(degree) def telloCCW(self, degree): return self.tello.rotate_ccw(degree) def telloMoveForward(self, distance):", "self.tello.land() def telloFlip_l(self): return self.tello.flip('l') def telloFlip_r(self): return self.tello.flip('r') def", "window is closed self.root.wm_title(\"TELLO Controller\") self.root.wm_protocol(\"WM_DELETE_WINDOW\", self.onClose) # the sending_command", "window and initial all the button and text \"\"\" panel", "(\"forward %d m\" % self.distance) self.telloMoveForward(self.distance) def on_keypress_down(self, event): print", "return self.tello.move_forward(distance) def telloMoveBackward(self, distance): return self.tello.move_backward(distance) def telloMoveLeft(self, distance):", "If the Tello rejects the attempt to enter command mode.", "fill=\"both\", expand=\"yes\", padx=10, pady=5) self.btn_takeoff = tki.Button( panel, text=\"Takeoff\", relief=\"raised\",", "self.tello.move_backward(distance) def telloMoveLeft(self, distance): return self.tello.move_left(distance) def telloMoveRight(self, distance): return", "create text input entry text0 = tki.Label(panel, text='This Controller map", "self.tmp_f.focus_set() self.btn_landing = tki.Button( panel, text=\"Flip\", relief=\"raised\", command=self.openFlipWindow) self.btn_landing.pack(side=\"bottom\", fill=\"both\",", "panel \"\"\" image = ImageTk.PhotoImage(image) # if the panel none", "height=2) self.tmp_f.bind('<KeyPress-w>', self.on_keypress_w) self.tmp_f.bind('<KeyPress-s>', self.on_keypress_s) self.tmp_f.bind('<KeyPress-a>', self.on_keypress_a) self.tmp_f.bind('<KeyPress-d>', self.on_keypress_d) self.tmp_f.bind('<KeyPress-Up>',", "to tello every 5 seconds self.sending_command_thread = threading.Thread(target = self._sendingCommand)", "('reset distance to %d' % self.degree) def on_keypress_w(self, event): print", "the camera, and allow the rest of the quit process", "= tki.Label(panel, text= 'W - Move Tello Up\\t\\t\\tArrow Up -", "= image self.panel.pack(side=\"left\", padx=10, pady=10) # otherwise, simply update the", "tki.Button( panel, text=\"Flip Backward\", relief=\"raised\", command=self.telloFlip_b) self.btn_flipb.pack(side=\"bottom\", fill=\"both\", expand=\"yes\", padx=10,", "the GUI.\"\"\" def __init__(self,tello,outputpath): \"\"\" Initial all the element of", "outputpath # the path that save pictures created by clicking", "self.on_keypress_s) self.tmp_f.bind('<KeyPress-a>', self.on_keypress_a) self.tmp_f.bind('<KeyPress-d>', self.on_keypress_d) self.tmp_f.bind('<KeyPress-Up>', self.on_keypress_up) self.tmp_f.bind('<KeyPress-Down>', self.on_keypress_down) self.tmp_f.bind('<KeyPress-Left>',", "- Move Tello Left\\n' 'D - Rotate Tello Clockwise\\t\\tArrow Right", "from_=1, to=360, tickinterval=10, label='Degree') self.degree_bar.set(30) self.degree_bar.pack(side=\"right\") self.btn_distance = tki.Button(panel, text=\"Reset", "Tello Left\\n' 'D - Rotate Tello Clockwise\\t\\tArrow Right - Move", "expand=\"yes\", padx=10, pady=5) # binding arrow keys to drone control", "frame self.stopEvent = threading.Event() self.thread = threading.Thread(target=self.videoLoop, args=()) self.thread.start() #", "self.btn_flipf.pack(side=\"bottom\", fill=\"both\", expand=\"yes\", padx=10, pady=5) self.btn_flipb = tki.Button( panel, text=\"Flip", "def telloMoveLeft(self, distance): return self.tello.move_left(distance) def telloMoveRight(self, distance): return self.tello.move_right(distance)", "closed self.root.wm_title(\"TELLO Controller\") self.root.wm_protocol(\"WM_DELETE_WINDOW\", self.onClose) # the sending_command will send", "self.distance = self.distance_bar.get() print ('reset distance to %.1f' % self.distance)", "if self.panel is None: self.panel = tki.Label(image=image) self.panel.image = image", "TelloUI: \"\"\"Wrapper class to enable the GUI.\"\"\" def __init__(self,tello,outputpath): \"\"\"", "(\"cw %d m\" % self.degree) self.tello.rotate_cw(self.degree) def on_keypress_up(self, event): print", "def on_keypress_w(self, event): print (\"up %d m\" % self.distance) self.telloUp(self.distance)", "width=100, height=2) self.tmp_f.bind('<KeyPress-w>', self.on_keypress_w) self.tmp_f.bind('<KeyPress-s>', self.on_keypress_s) self.tmp_f.bind('<KeyPress-a>', self.on_keypress_a) self.tmp_f.bind('<KeyPress-d>', self.on_keypress_d)", "that constantly pools the video sensor for # the most", "= Image.fromarray(self.frame) # we found compatibility problem between Tkinter,PIL and", "fill=\"both\", expand=\"yes\", padx=10, pady=5) self.distance_bar = Scale(panel, from_=0.02, to=5, tickinterval=0.01,", "text1 = tki.Label(panel, text= 'W - Move Tello Up\\t\\t\\tArrow Up", "self.tello.rotate_cw(self.degree) def on_keypress_up(self, event): print (\"forward %d m\" % self.distance)", "save the current frame of the video as a jpg", "Move Tello Backward\\n' 'A - Rotate Tello Counter-Clockwise\\tArrow Left -", "thread to execute the _updateGUIImage function. if system ==\"Windows\" or", "the button and text \"\"\" panel = Toplevel(self.root) panel.wm_title(\"Gesture Recognition\")", "device self.outputPath = outputpath # the path that save pictures", "will # sometimes result the very long preriod of the", "input entry text0 = tki.Label(panel, text='This Controller map keyboard inputs", "m\" % self.distance) self.telloMoveLeft(self.distance) def on_keypress_right(self, event): print (\"right %d", "the cmd window and initial all the button and text", "(\"backward %d m\" % self.distance) self.telloMoveBackward(self.distance) def on_keypress_left(self, event): print", "for pose recognition self.thread = None # thread of the", "expand=\"yes\", padx=10, pady=5) self.btn_flipf = tki.Button( panel, text=\"Flip Forward\", relief=\"raised\",", "None # create buttons self.btn_snapshot = tki.Button(self.root, text=\"Snapshot!\", command=self.takeSnapshot) self.btn_snapshot.pack(side=\"bottom\",", "every 5 seconds self.sending_command_thread = threading.Thread(target = self._sendingCommand) def videoLoop(self):", "\"\"\" open the cmd window and initial all the button", "waiting for response from tello \"\"\" self.quit_waiting_flag = True def", "Toggle the freeze/unfreze of video \"\"\" if self.btn_pause.config('relief')[-1] == 'sunken':", "start the thread that get GUI image and drwa skeleton", "self.degree = 30 # default degree for 'cw' or 'ccw'", "# the path that save pictures created by clicking the", "to threading. \"\"\" try: # start the thread that get", "is None: self.panel = tki.Label(image=image) self.panel.image = image self.panel.pack(side=\"left\", padx=10,", "command=self.updateDegreebar) self.btn_distance.pack(side=\"right\", fill=\"both\", expand=\"yes\", padx=10, pady=5) def openFlipWindow(self): \"\"\" open", "self.panel = tki.Label(image=image) self.panel.image = image self.panel.pack(side=\"left\", padx=10, pady=10) #", "tello self.quit_waiting_flag = False # initialize the root window and", "relief=\"raised\", command=self.updateDegreebar) self.btn_distance.pack(side=\"right\", fill=\"both\", expand=\"yes\", padx=10, pady=5) def openFlipWindow(self): \"\"\"", "self.btn_landing = tki.Button( panel, text=\"Flip\", relief=\"raised\", command=self.openFlipWindow) self.btn_landing.pack(side=\"bottom\", fill=\"both\", expand=\"yes\",", "response from tello self.quit_waiting_flag = False # initialize the root", "very long preriod of the \"ImageTk.PhotoImage\" function, # so for", "self.tmp_f.bind('<KeyPress-Up>', self.on_keypress_up) self.tmp_f.bind('<KeyPress-Down>', self.on_keypress_down) self.tmp_f.bind('<KeyPress-Left>', self.on_keypress_left) self.tmp_f.bind('<KeyPress-Right>', self.on_keypress_right) self.tmp_f.pack(side=\"bottom\") self.tmp_f.focus_set()", "# videostream device self.outputPath = outputpath # the path that", "relief=\"raised\", command=self.telloFlip_b) self.btn_flipb.pack(side=\"bottom\", fill=\"both\", expand=\"yes\", padx=10, pady=5) def takeSnapshot(self): \"\"\"", "self.btn_flipr = tki.Button( panel, text=\"Flip Right\", relief=\"raised\", command=self.telloFlip_r) self.btn_flipr.pack(side=\"bottom\", fill=\"both\",", "self.sending_command_thread.start() while not self.stopEvent.is_set(): system = platform.system() # read the", "= outputpath # the path that save pictures created by", "==\"Windows\" or system ==\"Linux\": self._updateGUIImage(image) else: thread_tmp = threading.Thread(target=self._updateGUIImage,args=(image,)) thread_tmp.start()", "if the panel none ,we need to initial it if", "pady=10) # otherwise, simply update the panel else: self.panel.configure(image=image) self.panel.image", "- Rotate Tello Clockwise\\t\\tArrow Right - Move Tello Right', justify=\"left\")", "self.root = tki.Tk() self.panel = None # create buttons self.btn_snapshot", "self.degree) def on_keypress_w(self, event): print (\"up %d m\" % self.distance)", "= Scale(panel, from_=0.02, to=5, tickinterval=0.01, digits=3, label='Distance(m)', resolution=0.01) self.distance_bar.set(0.2) self.distance_bar.pack(side=\"left\")", "def on_keypress_down(self, event): print (\"backward %d m\" % self.distance) self.telloMoveBackward(self.distance)", "self.onClose) # the sending_command will send command to tello every", "none ,we need to initial it if self.panel is None:", "threading.Event() self.thread = threading.Thread(target=self.videoLoop, args=()) self.thread.start() # set a callback", "% self.distance) def updateDegreebar(self): self.degree = self.degree_bar.get() print ('reset distance", "the panel else: self.panel.configure(image=image) self.panel.image = image def _sendingCommand(self): \"\"\"", "def __init__(self,tello,outputpath): \"\"\" Initial all the element of the GUI,support", "GUI image and drwa skeleton time.sleep(0.5) self.sending_command_thread.start() while not self.stopEvent.is_set():", "True def openCmdWindow(self): \"\"\" open the cmd window and initial", "Scale(panel, from_=1, to=360, tickinterval=10, label='Degree') self.degree_bar.set(30) self.degree_bar.pack(side=\"right\") self.btn_distance = tki.Button(panel,", "tki.Label(panel, text= 'W - Move Tello Up\\t\\t\\tArrow Up - Move", "on_keypress_a(self, event): print (\"ccw %d degree\" % self.degree) self.tello.rotate_ccw(self.degree) def", "text='This Controller map keyboard inputs to Tello control commands\\n' 'Adjust", "os.path.sep.join((self.outputPath, filename)) # save the file cv2.imwrite(p, cv2.cvtColor(self.frame, cv2.COLOR_RGB2BGR)) print(\"[INFO]", "as e: print(\"[INFO] caught a RuntimeError\") def _updateGUIImage(self,image): \"\"\" Main", "Move Tello Up\\t\\t\\tArrow Up - Move Tello Forward\\n' 'S -", "distance to %.1f' % self.distance) def updateDegreebar(self): self.degree = self.degree_bar.get()", "self.outputPath = outputpath # the path that save pictures created", "the \"ImageTk.PhotoImage\" function, # so for Macos,we start a new", "self.btn_takeoff = tki.Button( panel, text=\"Takeoff\", relief=\"raised\", command=self.telloTakeOff) self.btn_takeoff.pack(side=\"bottom\", fill=\"both\", expand=\"yes\",", "self.panel.image = image def _sendingCommand(self): \"\"\" start a while loop", "Left\", relief=\"raised\", command=self.telloFlip_l) self.btn_flipl.pack(side=\"bottom\", fill=\"both\", expand=\"yes\", padx=10, pady=5) self.btn_flipr =", "to reset distance and degree parameter', font='Helvetica 10 bold' )", "def updateTrackBar(self): self.my_tello_hand.setThr(self.hand_thr_bar.get()) def updateDistancebar(self): self.distance = self.distance_bar.get() print ('reset", "%d m\" % self.distance) self.telloMoveForward(self.distance) def on_keypress_down(self, event): print (\"backward", "Tello Right', justify=\"left\") text1.pack(side=\"top\") self.btn_landing = tki.Button( panel, text=\"Land\", relief=\"raised\",", "rejects the attempt to enter command mode. \"\"\" self.tello =", "def videoLoop(self): \"\"\" The mainloop thread of Tkinter Raises: RuntimeError:", "panel else: self.panel.configure(image=image) self.panel.image = image def _sendingCommand(self): \"\"\" start", "self.quit_waiting_flag = False # initialize the root window and image", "panel, text=\"Flip Left\", relief=\"raised\", command=self.telloFlip_l) self.btn_flipl.pack(side=\"bottom\", fill=\"both\", expand=\"yes\", padx=10, pady=5)", "on_keypress_enter(self, event): if self.frame is not None: self.registerFace() self.tmp_f.focus_set() def", "(\"down %d m\" % self.distance) self.telloDown(self.distance) def on_keypress_a(self, event): print", "that Tkinter throws due to threading. \"\"\" try: # start", "# default distance for 'move' cmd self.degree = 30 #", "To get around a RunTime error that Tkinter throws due", "image = Image.fromarray(self.frame) # we found compatibility problem between Tkinter,PIL", "\"\"\" Main operation to initial the object of image,and update", "expand=\"yes\", padx=10, pady=5) self.btn_landing = tki.Button( self.root, text=\"Open Command Panel\",", "padx=10, pady=5) self.btn_flipb = tki.Button( panel, text=\"Flip Backward\", relief=\"raised\", command=self.telloFlip_b)", "text=\"Flip Right\", relief=\"raised\", command=self.telloFlip_r) self.btn_flipr.pack(side=\"bottom\", fill=\"both\", expand=\"yes\", padx=10, pady=5) self.btn_flipf", "p = os.path.sep.join((self.outputPath, filename)) # save the file cv2.imwrite(p, cv2.cvtColor(self.frame,", "% self.degree) self.tello.rotate_ccw(self.degree) def on_keypress_d(self, event): print (\"cw %d m\"", "'ccw' cmd # if the flag is TRUE,the auto-takeoff thread", "= tki.Button( panel, text=\"Takeoff\", relief=\"raised\", command=self.telloTakeOff) self.btn_takeoff.pack(side=\"bottom\", fill=\"both\", expand=\"yes\", padx=10,", "= None # control variables self.distance = 0.1 # default", "recognition self.thread = None # thread of the Tkinter mainloop", "text input entry text0 = tki.Label(panel, text='This Controller map keyboard", "= False # initialize the root window and image panel", "from PIL import ImageTk import tkinter as tki from tkinter", "panel.wm_title(\"Gesture Recognition\") self.btn_flipl = tki.Button( panel, text=\"Flip Left\", relief=\"raised\", command=self.telloFlip_l)", "print (\"cw %d m\" % self.degree) self.tello.rotate_cw(self.degree) def on_keypress_up(self, event):", "threading.Thread(target=self._updateGUIImage,args=(image,)) thread_tmp.start() time.sleep(0.03) except RuntimeError as e: print(\"[INFO] caught a", "time import platform class TelloUI: \"\"\"Wrapper class to enable the", "= tki.Label(image=image) self.panel.image = image self.panel.pack(side=\"left\", padx=10, pady=10) # otherwise,", "image image = Image.fromarray(self.frame) # we found compatibility problem between", "Counter-Clockwise\\tArrow Left - Move Tello Left\\n' 'D - Rotate Tello", "'A - Rotate Tello Counter-Clockwise\\tArrow Left - Move Tello Left\\n'", "= tki.Button( panel, text=\"Flip\", relief=\"raised\", command=self.openFlipWindow) self.btn_landing.pack(side=\"bottom\", fill=\"both\", expand=\"yes\", padx=10,", "on_keypress_right(self, event): print (\"right %d m\" % self.distance) self.telloMoveRight(self.distance) def", "import platform class TelloUI: \"\"\"Wrapper class to enable the GUI.\"\"\"", "self.panel is None: self.panel = tki.Label(image=image) self.panel.image = image self.panel.pack(side=\"left\",", "the button and text \"\"\" panel = Toplevel(self.root) panel.wm_title(\"Command Panel\")", "tki.Button(self.root, text=\"Pause\", relief=\"raised\", command=self.pauseVideo) self.btn_pause.pack(side=\"bottom\", fill=\"both\", expand=\"yes\", padx=10, pady=5) self.btn_landing", "self.distance) self.telloMoveBackward(self.distance) def on_keypress_left(self, event): print (\"left %d m\" %", "entry text0 = tki.Label(panel, text='This Controller map keyboard inputs to", "Image from PIL import ImageTk import tkinter as tki from", "Rotate Tello Clockwise\\t\\tArrow Right - Move Tello Right', justify=\"left\") text1.pack(side=\"top\")", "%d degree\" % self.degree) self.tello.rotate_ccw(self.degree) def on_keypress_d(self, event): print (\"cw", "otherwise, simply update the panel else: self.panel.configure(image=image) self.panel.image = image", "to execute the _updateGUIImage function. if system ==\"Windows\" or system", "drone control self.tmp_f = tki.Frame(panel, width=100, height=2) self.tmp_f.bind('<KeyPress-w>', self.on_keypress_w) self.tmp_f.bind('<KeyPress-s>',", "self.tmp_f.bind('<KeyPress-w>', self.on_keypress_w) self.tmp_f.bind('<KeyPress-s>', self.on_keypress_s) self.tmp_f.bind('<KeyPress-a>', self.on_keypress_a) self.tmp_f.bind('<KeyPress-d>', self.on_keypress_d) self.tmp_f.bind('<KeyPress-Up>', self.on_keypress_up)", "self.degree_bar = Scale(panel, from_=1, to=360, tickinterval=10, label='Degree') self.degree_bar.set(30) self.degree_bar.pack(side=\"right\") self.btn_distance", "= self.distance_bar.get() print ('reset distance to %.1f' % self.distance) def", "panel.wm_title(\"Command Panel\") # create text input entry text0 = tki.Label(panel,", "Recognition\") self.btn_flipl = tki.Button( panel, text=\"Flip Left\", relief=\"raised\", command=self.telloFlip_l) self.btn_flipl.pack(side=\"bottom\",", "used for pose recognition self.thread = None # thread of", "self.on_keypress_down) self.tmp_f.bind('<KeyPress-Left>', self.on_keypress_left) self.tmp_f.bind('<KeyPress-Right>', self.on_keypress_right) self.tmp_f.pack(side=\"bottom\") self.tmp_f.focus_set() self.btn_landing = tki.Button(", "def on_keypress_left(self, event): print (\"left %d m\" % self.distance) self.telloMoveLeft(self.distance)", "cmd # if the flag is TRUE,the auto-takeoff thread will", "all the button and text \"\"\" panel = Toplevel(self.root) panel.wm_title(\"Command", "self.telloMoveForward(self.distance) def on_keypress_down(self, event): print (\"backward %d m\" % self.distance)", "element of the GUI,support by Tkinter :param tello: class interacts", "text=\"Reset Degree\", relief=\"raised\", command=self.updateDegreebar) self.btn_distance.pack(side=\"right\", fill=\"both\", expand=\"yes\", padx=10, pady=5) def", "to %.1f' % self.distance) def updateDegreebar(self): self.degree = self.degree_bar.get() print", "variable as TRUE,it will stop computer waiting for response from", "return self.tello.move_up(dist) def telloDown(self, dist): return self.tello.move_down(dist) def updateTrackBar(self): self.my_tello_hand.setThr(self.hand_thr_bar.get())", "the rest of the quit process to continue \"\"\" print(\"[INFO]", "loop that sends 'command' to tello every 5 second \"\"\"", "self.tello.send_command('command') time.sleep(5) def _setQuitWaitingFlag(self): \"\"\" set the variable as TRUE,it", "return self.tello.land() def telloFlip_l(self): return self.tello.flip('l') def telloFlip_r(self): return self.tello.flip('r')", "self.tello.move_forward(distance) def telloMoveBackward(self, distance): return self.tello.move_backward(distance) def telloMoveLeft(self, distance): return", "start a new thread to execute the _updateGUIImage function. if", "telloMoveForward(self, distance): return self.tello.move_forward(distance) def telloMoveBackward(self, distance): return self.tello.move_backward(distance) def", "self.degree) self.tello.rotate_ccw(self.degree) def on_keypress_d(self, event): print (\"cw %d m\" %", "the very long preriod of the \"ImageTk.PhotoImage\" function, # so", "event): print (\"right %d m\" % self.distance) self.telloMoveRight(self.distance) def on_keypress_enter(self,", "self.btn_pause.pack(side=\"bottom\", fill=\"both\", expand=\"yes\", padx=10, pady=5) self.btn_landing = tki.Button( self.root, text=\"Open", "distance to %d' % self.degree) def on_keypress_w(self, event): print (\"up", "expand=\"yes\", padx=10, pady=5) self.btn_flipr = tki.Button( panel, text=\"Flip Right\", relief=\"raised\",", "tki.Button( panel, text=\"Flip Left\", relief=\"raised\", command=self.telloFlip_l) self.btn_flipl.pack(side=\"bottom\", fill=\"both\", expand=\"yes\", padx=10,", "resolution=0.01) self.distance_bar.set(0.2) self.distance_bar.pack(side=\"left\") self.btn_distance = tki.Button(panel, text=\"Reset Distance\", relief=\"raised\", command=self.updateDistancebar,", "fill=\"both\", expand=\"yes\", padx=10, pady=5) def takeSnapshot(self): \"\"\" save the current", "self.degree_bar.set(30) self.degree_bar.pack(side=\"right\") self.btn_distance = tki.Button(panel, text=\"Reset Degree\", relief=\"raised\", command=self.updateDegreebar) self.btn_distance.pack(side=\"right\",", "and put it into outputpath \"\"\" # grab the current", "datetime import cv2 import os import time import platform class", "the panel none ,we need to initial it if self.panel", "enable the GUI.\"\"\" def __init__(self,tello,outputpath): \"\"\" Initial all the element", "= os.path.sep.join((self.outputPath, filename)) # save the file cv2.imwrite(p, cv2.cvtColor(self.frame, cv2.COLOR_RGB2BGR))", "videoLoop(self): \"\"\" The mainloop thread of Tkinter Raises: RuntimeError: To", "Move Tello Down\\t\\t\\tArrow Down - Move Tello Backward\\n' 'A -", "inputs to Tello control commands\\n' 'Adjust the trackbar to reset", "\"\"\" open the flip window and initial all the button", "error that Tkinter throws due to threading. \"\"\" try: #", "computer waiting for response from tello \"\"\" self.quit_waiting_flag = True", "the Tkinter mainloop self.stopEvent = None # control variables self.distance", "the format from frame to image image = Image.fromarray(self.frame) #", "==\"Linux\": self._updateGUIImage(image) else: thread_tmp = threading.Thread(target=self._updateGUIImage,args=(image,)) thread_tmp.start() time.sleep(0.03) except RuntimeError", "bold' ) text0.pack(side='top') text1 = tki.Label(panel, text= 'W - Move", "image and drwa skeleton time.sleep(0.5) self.sending_command_thread.start() while not self.stopEvent.is_set(): system", "def _setQuitWaitingFlag(self): \"\"\" set the variable as TRUE,it will stop", "telloDown(self, dist): return self.tello.move_down(dist) def updateTrackBar(self): self.my_tello_hand.setThr(self.hand_thr_bar.get()) def updateDistancebar(self): self.distance", "compatibility problem between Tkinter,PIL and Macos,and it will # sometimes", "relief=\"raised\", command=self.updateDistancebar, ) self.btn_distance.pack(side=\"left\", fill=\"both\", expand=\"yes\", padx=10, pady=5) self.degree_bar =", "self.on_keypress_up) self.tmp_f.bind('<KeyPress-Down>', self.on_keypress_down) self.tmp_f.bind('<KeyPress-Left>', self.on_keypress_left) self.tmp_f.bind('<KeyPress-Right>', self.on_keypress_right) self.tmp_f.pack(side=\"bottom\") self.tmp_f.focus_set() self.btn_landing", "event): print (\"ccw %d degree\" % self.degree) self.tello.rotate_ccw(self.degree) def on_keypress_d(self,", ":param tello: class interacts with the Tello drone. Raises: RuntimeError:", "create buttons self.btn_snapshot = tki.Button(self.root, text=\"Snapshot!\", command=self.takeSnapshot) self.btn_snapshot.pack(side=\"bottom\", fill=\"both\", expand=\"yes\",", "set the stop event, cleanup the camera, and allow the", "self.distance) def updateDegreebar(self): self.degree = self.degree_bar.get() print ('reset distance to", "result the very long preriod of the \"ImageTk.PhotoImage\" function, #", "text \"\"\" panel = Toplevel(self.root) panel.wm_title(\"Gesture Recognition\") self.btn_flipl = tki.Button(", "degree parameter', font='Helvetica 10 bold' ) text0.pack(side='top') text1 = tki.Label(panel,", "self.btn_flipb = tki.Button( panel, text=\"Flip Backward\", relief=\"raised\", command=self.telloFlip_b) self.btn_flipb.pack(side=\"bottom\", fill=\"both\",", "\"\"\" The mainloop thread of Tkinter Raises: RuntimeError: To get", "system = platform.system() # read the frame for GUI show", "camera, and allow the rest of the quit process to", "def telloMoveBackward(self, distance): return self.tello.move_backward(distance) def telloMoveLeft(self, distance): return self.tello.move_left(distance)", "Tello Down\\t\\t\\tArrow Down - Move Tello Backward\\n' 'A - Rotate", "on_keypress_d(self, event): print (\"cw %d m\" % self.degree) self.tello.rotate_cw(self.degree) def", "h264decoder and used for pose recognition self.thread = None #", "padx=10, pady=5) self.btn_landing = tki.Button( self.root, text=\"Open Command Panel\", relief=\"raised\",", "to construct the filename ts = datetime.datetime.now() filename = \"{}.jpg\".format(ts.strftime(\"%Y-%m-%d_%H-%M-%S\"))", "%d m\" % self.distance) self.telloMoveLeft(self.distance) def on_keypress_right(self, event): print (\"right", "text1.pack(side=\"top\") self.btn_landing = tki.Button( panel, text=\"Land\", relief=\"raised\", command=self.telloLanding) self.btn_landing.pack(side=\"bottom\", fill=\"both\",", "the file cv2.imwrite(p, cv2.cvtColor(self.frame, cv2.COLOR_RGB2BGR)) print(\"[INFO] saved {}\".format(filename)) def pauseVideo(self):", "recently read frame self.stopEvent = threading.Event() self.thread = threading.Thread(target=self.videoLoop, args=())", "if the flag is TRUE,the auto-takeoff thread will stop waiting", "the _updateGUIImage function. if system ==\"Windows\" or system ==\"Linux\": self._updateGUIImage(image)", "self.tmp_f.bind('<KeyPress-Right>', self.on_keypress_right) self.tmp_f.pack(side=\"bottom\") self.tmp_f.focus_set() self.btn_landing = tki.Button( panel, text=\"Flip\", relief=\"raised\",", "# grab the current timestamp and use it to construct", "def pauseVideo(self): \"\"\" Toggle the freeze/unfreze of video \"\"\" if", "class TelloUI: \"\"\"Wrapper class to enable the GUI.\"\"\" def __init__(self,tello,outputpath):", "filename)) # save the file cv2.imwrite(p, cv2.cvtColor(self.frame, cv2.COLOR_RGB2BGR)) print(\"[INFO] saved", "= tki.Button(self.root, text=\"Pause\", relief=\"raised\", command=self.pauseVideo) self.btn_pause.pack(side=\"bottom\", fill=\"both\", expand=\"yes\", padx=10, pady=5)", "padx=10, pady=5) self.btn_flipr = tki.Button( panel, text=\"Flip Right\", relief=\"raised\", command=self.telloFlip_r)", "command=self.telloFlip_f) self.btn_flipf.pack(side=\"bottom\", fill=\"both\", expand=\"yes\", padx=10, pady=5) self.btn_flipb = tki.Button( panel,", "if self.btn_pause.config('relief')[-1] == 'sunken': self.btn_pause.config(relief=\"raised\") self.tello.video_freeze(False) else: self.btn_pause.config(relief=\"sunken\") self.tello.video_freeze(True) def", "the Tello drone. Raises: RuntimeError: If the Tello rejects the", "button self.frame = None # frame read from h264decoder and", "self.btn_pause = tki.Button(self.root, text=\"Pause\", relief=\"raised\", command=self.pauseVideo) self.btn_pause.pack(side=\"bottom\", fill=\"both\", expand=\"yes\", padx=10,", "distance): return self.tello.move_right(distance) def telloUp(self, dist): return self.tello.move_up(dist) def telloDown(self,", "of the video as a jpg file and put it", "tki.Button( self.root, text=\"Open Command Panel\", relief=\"raised\", command=self.openCmdWindow) self.btn_landing.pack(side=\"bottom\", fill=\"both\", expand=\"yes\",", "Right', justify=\"left\") text1.pack(side=\"top\") self.btn_landing = tki.Button( panel, text=\"Land\", relief=\"raised\", command=self.telloLanding)", "self.telloUp(self.distance) def on_keypress_s(self, event): print (\"down %d m\" % self.distance)", "or self.frame.size == 0: continue # transfer the format from", "def on_keypress_a(self, event): print (\"ccw %d degree\" % self.degree) self.tello.rotate_ccw(self.degree)", "self.btn_distance = tki.Button(panel, text=\"Reset Distance\", relief=\"raised\", command=self.updateDistancebar, ) self.btn_distance.pack(side=\"left\", fill=\"both\",", "the filename ts = datetime.datetime.now() filename = \"{}.jpg\".format(ts.strftime(\"%Y-%m-%d_%H-%M-%S\")) p =", "panel, text=\"Takeoff\", relief=\"raised\", command=self.telloTakeOff) self.btn_takeoff.pack(side=\"bottom\", fill=\"both\", expand=\"yes\", padx=10, pady=5) #", "the current timestamp and use it to construct the filename", "telloCW(self, degree): return self.tello.rotate_cw(degree) def telloCCW(self, degree): return self.tello.rotate_ccw(degree) def", "distance): return self.tello.move_forward(distance) def telloMoveBackward(self, distance): return self.tello.move_backward(distance) def telloMoveLeft(self,", "self.on_keypress_right) self.tmp_f.pack(side=\"bottom\") self.tmp_f.focus_set() self.btn_landing = tki.Button( panel, text=\"Flip\", relief=\"raised\", command=self.openFlipWindow)", "between Tkinter,PIL and Macos,and it will # sometimes result the", "from tkinter import Toplevel, Scale import threading import datetime import", "thread of Tkinter Raises: RuntimeError: To get around a RunTime", "# if the flag is TRUE,the auto-takeoff thread will stop", "'Adjust the trackbar to reset distance and degree parameter', font='Helvetica", "print ('reset distance to %.1f' % self.distance) def updateDegreebar(self): self.degree", "self.panel.configure(image=image) self.panel.image = image def _sendingCommand(self): \"\"\" start a while", "pady=5) self.distance_bar = Scale(panel, from_=0.02, to=5, tickinterval=0.01, digits=3, label='Distance(m)', resolution=0.01)", "import Toplevel, Scale import threading import datetime import cv2 import", "command to tello every 5 seconds self.sending_command_thread = threading.Thread(target =", "self.tello = tello # videostream device self.outputPath = outputpath #", "= threading.Thread(target=self.videoLoop, args=()) self.thread.start() # set a callback to handle", "self.thread = threading.Thread(target=self.videoLoop, args=()) self.thread.start() # set a callback to", "timestamp and use it to construct the filename ts =", "a RunTime error that Tkinter throws due to threading. \"\"\"", "time.sleep(5) def _setQuitWaitingFlag(self): \"\"\" set the variable as TRUE,it will", "filename ts = datetime.datetime.now() filename = \"{}.jpg\".format(ts.strftime(\"%Y-%m-%d_%H-%M-%S\")) p = os.path.sep.join((self.outputPath,", "save pictures created by clicking the takeSnapshot button self.frame =" ]
[ "compas import compas_rhino from compas.datastructures import Mesh mesh = Mesh.from_ply(compas.get('stanford_dragon.ply'))", "<reponame>robin-gdwl/examples_topop-desc import compas import compas_rhino from compas.datastructures import Mesh mesh", "import compas_rhino from compas.datastructures import Mesh mesh = Mesh.from_ply(compas.get('stanford_dragon.ply')) compas_rhino.mesh_draw(mesh)", "import compas import compas_rhino from compas.datastructures import Mesh mesh =" ]
[ "# Neural Networks Demystified # Part 1: Data + Architecture", "YouTube series on artificial neural networks. # # <NAME> #", "test X = np.array(([3,5], [5,1], [10,2]), dtype=float) y = np.array(([75],", "y = Score on test X = np.array(([3,5], [5,1], [10,2]),", "Normalize X = X/np.amax(X, axis=0) y = y/100 #Max test", "code for short YouTube series on artificial neural networks. #", "X = (hours sleeping, hours studying), y = Score on", "# Normalize X = X/np.amax(X, axis=0) y = y/100 #Max", "[82], [93]), dtype=float) # Normalize X = X/np.amax(X, axis=0) y", "# X = (hours sleeping, hours studying), y = Score", "@stephencwelch import numpy as np # X = (hours sleeping,", "artificial neural networks. # # <NAME> # @stephencwelch import numpy", "Score on test X = np.array(([3,5], [5,1], [10,2]), dtype=float) y", "# Supporting code for short YouTube series on artificial neural", "+ Architecture # # Supporting code for short YouTube series", "y = np.array(([75], [82], [93]), dtype=float) # Normalize X =", "# @stephencwelch import numpy as np # X = (hours", "= Score on test X = np.array(([3,5], [5,1], [10,2]), dtype=float)", "import numpy as np # X = (hours sleeping, hours", "(hours sleeping, hours studying), y = Score on test X", "Neural Networks Demystified # Part 1: Data + Architecture #", "[10,2]), dtype=float) y = np.array(([75], [82], [93]), dtype=float) # Normalize", "np.array(([3,5], [5,1], [10,2]), dtype=float) y = np.array(([75], [82], [93]), dtype=float)", "Part 1: Data + Architecture # # Supporting code for", "dtype=float) # Normalize X = X/np.amax(X, axis=0) y = y/100", "studying), y = Score on test X = np.array(([3,5], [5,1],", "1: Data + Architecture # # Supporting code for short", "on test X = np.array(([3,5], [5,1], [10,2]), dtype=float) y =", "# # Supporting code for short YouTube series on artificial", "[5,1], [10,2]), dtype=float) y = np.array(([75], [82], [93]), dtype=float) #", "= (hours sleeping, hours studying), y = Score on test", "dtype=float) y = np.array(([75], [82], [93]), dtype=float) # Normalize X", "= np.array(([75], [82], [93]), dtype=float) # Normalize X = X/np.amax(X,", "for short YouTube series on artificial neural networks. # #", "X = X/np.amax(X, axis=0) y = y/100 #Max test score", "= np.array(([3,5], [5,1], [10,2]), dtype=float) y = np.array(([75], [82], [93]),", "sleeping, hours studying), y = Score on test X =", "# Part 1: Data + Architecture # # Supporting code", "series on artificial neural networks. # # <NAME> # @stephencwelch", "X = np.array(([3,5], [5,1], [10,2]), dtype=float) y = np.array(([75], [82],", "X/np.amax(X, axis=0) y = y/100 #Max test score is 100", "Networks Demystified # Part 1: Data + Architecture # #", "networks. # # <NAME> # @stephencwelch import numpy as np", "np # X = (hours sleeping, hours studying), y =", "= X/np.amax(X, axis=0) y = y/100 #Max test score is", "# # <NAME> # @stephencwelch import numpy as np #", "Demystified # Part 1: Data + Architecture # # Supporting", "short YouTube series on artificial neural networks. # # <NAME>", "Architecture # # Supporting code for short YouTube series on", "<NAME> # @stephencwelch import numpy as np # X =", "Data + Architecture # # Supporting code for short YouTube", "on artificial neural networks. # # <NAME> # @stephencwelch import", "np.array(([75], [82], [93]), dtype=float) # Normalize X = X/np.amax(X, axis=0)", "as np # X = (hours sleeping, hours studying), y", "neural networks. # # <NAME> # @stephencwelch import numpy as", "numpy as np # X = (hours sleeping, hours studying),", "hours studying), y = Score on test X = np.array(([3,5],", "[93]), dtype=float) # Normalize X = X/np.amax(X, axis=0) y =", "Supporting code for short YouTube series on artificial neural networks.", "# <NAME> # @stephencwelch import numpy as np # X" ]
[ "character cannot be numeric). Pass a dictionary to `variables` to", "`requests_cache.install_cache`. requests_cache may append an extension to this path, so", "requests_cache_path is not None: requests # require `import requests` in", "If a namespace is not provided, the JSON must contain", "+ len(affiliation_df)) affil_map_df = affil_map_df.merge(affiliation_df) name_to_numbers = { name: sorted(df.affiliation_number)", "= \"title\", \"keywords\", \"lang\" for key in move_to_pandoc: if key", "delimit fields.\\n\" \"Proceeding to reread TSV with delim_whitespace=True.\" ) tag_df", "manubot.cite.citekey import ( citekey_to_csl_item, shorten_citekey, is_valid_citekey, standardize_citekey, ) def check_collisions(citekeys_df):", "`manubot`: a dictionary for manubot-related information and metadata. Fields in", "get_text, ) from manubot.cite.citekey import ( citekey_to_csl_item, shorten_citekey, is_valid_citekey, standardize_citekey,", "in metadata: variables[\"pandoc\"][key] = metadata.pop(key) # Add date to metadata", "str: \"\"\" Convert citation-tags.tsv to markdown reference link syntax \"\"\"", "citekey_aliases.items(): text += f\"[@{key}]: {value}\\n\" logging.warning( \"citation-tags.tsv is deprecated. \"", "to disk and logs warnings for potential problems. \"\"\" #", "= get_thumbnail_url(metadata.pop(\"thumbnail\", None)) if thumbnail_url: variables[\"manubot\"][\"thumbnail_url\"] = thumbnail_url # Update", "with args.variables_path.open(\"w\", encoding=\"utf-8\") as write_file: json.dump(variables, write_file, ensure_ascii=False, indent=2) write_file.write(\"\\n\")", "variables) # Write manuscript for pandoc with args.manuscript_path.open(\"w\", encoding=\"utf-8\") as", "metadata.pop(\"authors\", []) if authors is None: authors = [] variables[\"pandoc\"][\"author-meta\"]", "is not None: logging.info( f\"requests-cache finished with {len(cache.responses)} cached responses\"", "List[str], variables: Optional[dict] = None) -> dict: \"\"\" Read multiple", "is not provided, the JSON must contain a dictionary as", "in `manubot` are either generated by Manubot or hard-coded by", "+ \"\\n\".join(conflicts) ) variables.update(obj) logging.debug( f\"Reading user-provided templating variables complete:\\n\"", "manubot.util import read_serialized_data, read_serialized_dict from manubot.process.bibliography import load_manual_references from manubot.process.ci", "a list of affiliation_numbers for each author and add a", "multi_df = citekeys_df[citekeys_df.standard_citekey.duplicated(keep=False)] if not multi_df.empty: table = multi_df.to_string( index=False,", "\"\"\" Compile manuscript, creating manuscript.md and references.json as inputs for", "requests_cache_path=args.requests_cache_path, clear_requests_cache=args.clear_requests_cache, ) # Write CSL JSON bibliography for Pandoc.", "authors] variables[\"manubot\"][\"authors\"] = authors add_author_affiliations(variables[\"manubot\"]) # Set repository version metadata", "to a JSON file at `path`. If `path` evaluates as", "for key in move_to_pandoc: if key in metadata: variables[\"pandoc\"][key] =", "not citekey_aliases: return \"\" text = \"\\n\\n\" for key, value", "metadata: authors = metadata.pop(\"author_info\", []) warnings.warn( \"metadata.yaml: 'author_info' is deprecated.", "error can be caused by using spaces rather than tabs", "multiple affiliations are `; ` separated. \" f\"Please switch affiliations", "args.references_path) return csl_items def write_csl_json(csl_items, path): \"\"\" Write CSL Items", "essential for monkey patching by requests_cache. requests_cache.install_cache(requests_cache_path, include_get_headers=True) cache =", "f\"missing {args.meta_yaml_path} file with yaml_metadata_block for pandoc\" ) # Interpreted", "collisions \"\"\" collision_df = citekeys_df[[\"standard_citekey\", \"short_citekey\"]].drop_duplicates() collision_df = collision_df[collision_df.short_citekey.duplicated(keep=False)] if", "variables[\"authors\"]: if \"affiliations\" not in author: continue if not isinstance(author[\"affiliations\"],", "jinja_environment = jinja2.Environment( loader=jinja2.BaseLoader(), undefined=jinja2.make_logging_undefined(logging.getLogger()), autoescape=False, comment_start_string=\"{##\", comment_end_string=\"##}\", extensions=[\"jinja2.ext.do\", \"jinja2.ext.loopcontrols\"],", "failure for {standard_citekey!r}\") failures.append(standard_citekey) # Uninstall cache if requests_cache_path is", "get_manuscript_urls, get_software_versions, ) from manubot.process.manuscript import ( datetime_now, get_manuscript_stats, get_text,", "- manual_refs: mapping from standard_citekey to csl_item for manual references", "update an existing dictionary rather than create a new dictionary.", "as keyword arguments. \"\"\" jinja_environment = jinja2.Environment( loader=jinja2.BaseLoader(), undefined=jinja2.make_logging_undefined(logging.getLogger()), autoescape=False,", "tabs to delimit fields.\\n\" \"Proceeding to reread TSV with delim_whitespace=True.\"", "generate_csl_items( citekeys=citekeys_df.standard_citekey.unique(), manual_refs=manual_refs, requests_cache_path=args.requests_cache_path, clear_requests_cache=args.clear_requests_cache, ) # Write CSL JSON", "= list() for standard_citekey in citekeys: if standard_citekey in manual_refs:", "metadata: variables[\"pandoc\"][key] = metadata.pop(key) # Add date to metadata now", "# Add manuscript URLs variables[\"manubot\"].update(get_manuscript_urls(metadata.pop(\"html_url\", None))) # Add software versions", "<head> variables[\"pandoc\"][\"header-includes\"] = get_header_includes(variables) assert args.skip_citations # Extend Pandoc's metadata.bibliography", "# http://jinja.pocoo.org/docs/2.10/api/#identifier-naming match = re.match(r\"([a-zA-Z_][a-zA-Z0-9_]*)=(.+)\", path) if match: namespace, path", "in citekeys_df. Writes references.json to disk and logs warnings for", "\"jinja2.ext.loopcontrols\"], ) template = jinja_environment.from_string(text) return template.render(**variables) def prepare_manuscript(args): \"\"\"", "affiliations, variables is left unmodified. \"\"\" rows = list() for", "URLs or local file paths). Paths can optionally have a", "ensure_ascii=False)}\" ) return variables def add_author_affiliations(variables: dict) -> dict: \"\"\"", "variables = read_variable_files(args.template_variables_path, variables) # Add header-includes metadata with <meta>", "bibliography for Pandoc. write_csl_json(csl_items, args.references_path) return csl_items def write_csl_json(csl_items, path):", "{len(citekeys_df)} unique citations strings extracted from text {citekeys_df.standard_citekey.nunique()} unique standard", "`path`. If `path` evaluates as False, do nothing. \"\"\" if", "List, Optional import jinja2 import pandas import requests import requests_cache", "`author_info`, now deprecated), `lang`, and `thumbnail`. - User-specified fields inserted", "get_citekeys_df(citekeys: list, citekey_aliases: dict = {}): \"\"\" Generate and return", "logging.info( f\"requests-cache finished with {len(cache.responses)} cached responses\" ) requests_cache.uninstall_cache() if", "- All fields from a manuscript's `metadata.yaml` that are not", "Data with a standard_citekey of {standard_citekey!r} not found in manual-references.json.", "\"detagged_citekey\"]) check_collisions(citekeys_df) check_multiple_citation_strings(citekeys_df) return citekeys_df def read_citations_tsv(path) -> dict: \"\"\"", "a new dictionary. \"\"\" if variables is None: variables =", "check_collisions(citekeys_df) check_multiple_citation_strings(citekeys_df) return citekeys_df def read_citations_tsv(path) -> dict: \"\"\" Read", "textwrap.dedent( f\"\"\"\\ {len(citekeys_df)} unique citations strings extracted from text {citekeys_df.standard_citekey.nunique()}", "def _citation_tags_to_reference_links(args) -> str: \"\"\" Convert citation-tags.tsv to markdown reference", "dictionary's top-level 'namespace_1=https://git.io/vbkqm', # store under 'namespace_1' key 'namespace_2=some_local_path.json', #", "Writes references.json to disk and logs warnings for potential problems.", "tag_df = pandas.read_csv(path, sep=\"\\t\") na_rows_df = tag_df[tag_df.isnull().any(axis=\"columns\")] if not na_rows_df.empty:", "typing import List, Optional import jinja2 import pandas import requests", "not provided, the JSON must contain a dictionary as its", "\"metadata.yaml: 'author_info' is deprecated. Use 'authors' instead.\", category=DeprecationWarning, ) else:", "tag_df[tag_df.isnull().any(axis=\"columns\")] if not na_rows_df.empty: logging.error( f\"{path} contains rows with missing", "= {} for path in paths: logging.info(f\"Reading user-provided templating variables", "a pandas.DataFrame with the following columns: - manuscript_citekey: citation keys", "of ASCII alphanumeric characters (includes underscores, first character cannot be", "names # http://jinja.pocoo.org/docs/2.10/api/#identifier-naming match = re.match(r\"([a-zA-Z_][a-zA-Z0-9_]*)=(.+)\", path) if match: namespace,", "f\"Using {now:%Z} timezone.\\n\" f\"Dating manuscript with the current datetime: {now.isoformat()}\"", "by `--template-variables-path` to generate manuscript variables available for jinja2 templating.", "level. Namespaces should consist only of ASCII alphanumeric characters (includes", "{}} # Read metadata which contains pandoc_yaml_metadata # as well", "key in metadata: variables[\"pandoc\"][key] = metadata.pop(key) # Add date to", "{namespace: read_serialized_data(path)} else: obj = read_serialized_dict(path) except Exception: logging.exception(f\"Error reading", "or local file paths). Paths can optionally have a namespace", "get_manuscript_stats(text) with args.variables_path.open(\"w\", encoding=\"utf-8\") as write_file: json.dump(variables, write_file, ensure_ascii=False, indent=2)", "value in citekey_aliases.items(): text += f\"[@{key}]: {value}\\n\" logging.warning( \"citation-tags.tsv is", "or `manubot` (dangerous). \"\"\" # Generated manuscript variables variables =", "ensure_ascii=False) write_file.write(\"\\n\") def template_with_jinja2(text, variables): \"\"\" Template using jinja2 with", "metadata with <meta> information for the HTML output's <head> variables[\"pandoc\"][\"header-includes\"]", "standard_citekey.startswith(\"raw:\"): logging.error( f\"CSL JSON Data with a standard_citekey of {standard_citekey!r}", "not multi_df.empty: table = multi_df.to_string( index=False, columns=[\"standard_citekey\", \"manuscript_citekey\"] ) logging.warning(f\"Multiple", "from citation-tags.tsv.\" ) return {} tag_df = pandas.read_csv(path, sep=\"\\t\") na_rows_df", "in author: continue if not isinstance(author[\"affiliations\"], list): warnings.warn( f\"Expected list", "author[\"affiliations\"].split(\"; \") for affiliation in author[\"affiliations\"]: rows.append((author[\"name\"], affiliation)) if not", "the HTML output's <head> variables[\"pandoc\"][\"header-includes\"] = get_header_includes(variables) assert args.skip_citations #", "sep=\"\\t\", index=False) def _citation_tags_to_reference_links(args) -> str: \"\"\" Convert citation-tags.tsv to", "if variables is None: variables = {} for path in", "Fields in `pandoc` are either generated by Manubot or hard-coded", "left unmodified. \"\"\" rows = list() for author in variables[\"authors\"]:", "jinja2 with the variables dictionary unpacked as keyword arguments. \"\"\"", "csl_items def _generate_csl_items(args, citekeys_df): \"\"\" General CSL (citeproc) items for", "Exception: logging.exception(f\"Error reading template variables from {path!r}\") continue assert isinstance(obj,", "standard_citekeys in citekeys_df. Writes references.json to disk and logs warnings", "= textwrap.dedent( f\"\"\"\\ {len(citekeys_df)} unique citations strings extracted from text", "variable names # http://jinja.pocoo.org/docs/2.10/api/#identifier-naming match = re.match(r\"([a-zA-Z_][a-zA-Z0-9_]*)=(.+)\", path) if match:", "isinstance(obj, dict) conflicts = variables.keys() & obj.keys() if conflicts: logging.warning(", "match.groups() logging.info( f\"Using the {namespace!r} namespace for template variables from", "Identify different citation strings referring the the same reference. \"\"\"", "\"\"\" General CSL (citeproc) items for standard_citekeys in citekeys_df. Writes", "= pandas.read_csv(path, delim_whitespace=True) tag_df[\"manuscript_citekey\"] = \"tag:\" + tag_df.tag tag_df =", "\"values for the following keys:\\n\" + \"\\n\".join(conflicts) ) variables.update(obj) logging.debug(", "thumbnail_url: variables[\"manubot\"][\"thumbnail_url\"] = thumbnail_url # Update variables with metadata.yaml pandoc/manubot", "loader=jinja2.BaseLoader(), undefined=jinja2.make_logging_undefined(logging.getLogger()), autoescape=False, comment_start_string=\"{##\", comment_end_string=\"##}\", extensions=[\"jinja2.ext.do\", \"jinja2.ext.loopcontrols\"], ) template =", "None, clear_requests_cache: Optional[bool] = False, ) -> list: \"\"\" General", "continue variables[key].update(dict_) # Update variables with uninterpreted metadata.yaml fields variables.update(metadata)", "= metadata.pop(key) # Add date to metadata now = datetime_now()", "existing dictionary rather than create a new dictionary. \"\"\" if", "affil_map_df = pandas.DataFrame(rows, columns=[\"name\", \"affiliation\"]) affiliation_df = affil_map_df[[\"affiliation\"]].drop_duplicates() affiliation_df[\"affiliation_number\"] =", "ci_params = get_continuous_integration_parameters() if ci_params: variables[\"manubot\"][\"ci_source\"] = ci_params # Add", "citation-tags.tsv to markdown reference link syntax \"\"\" citekey_aliases = read_citations_tsv(args.citation_tags_path)", "a JSON file at `path`. If `path` evaluates as False,", "# store under 'namespace_2' key ] ``` If a namespace", "namespace prepended. For example: ```python paths = [ 'https://git.io/vbkqm', #", "conflicts = variables.keys() & obj.keys() if conflicts: logging.warning( f\"Template variables", "elif standard_citekey.startswith(\"raw:\"): logging.error( f\"CSL JSON Data with a standard_citekey of", "and references.json as inputs for pandoc. \"\"\" text = get_text(args.content_directory)", "f\"Consider deleting citation-tags.tsv and inserting the following paragraph into your", "only of ASCII alphanumeric characters (includes underscores, first character cannot", "cached responses\" ) csl_items = list() failures = list() for", "Read multiple serialized data files into a user_variables dictionary. Provide", "logging.info( f\"no citation tags file at {path} \" \"Not reading", "pandas.DataFrame(rows, columns=[\"name\", \"affiliation\"]) affiliation_df = affil_map_df[[\"affiliation\"]].drop_duplicates() affiliation_df[\"affiliation_number\"] = range(1, 1", "metadata.pop(\"author_info\", []) warnings.warn( \"metadata.yaml: 'author_info' is deprecated. Use 'authors' instead.\",", "metadata.pop(key, {}) if not isinstance(dict_, dict): logging.warning( f\"load_variables expected metadata.yaml", "dict): logging.warning( f\"load_variables expected metadata.yaml field {key!r} to be a", "load_variables(args) variables[\"manubot\"][\"manuscript_stats\"] = get_manuscript_stats(text) with args.variables_path.open(\"w\", encoding=\"utf-8\") as write_file: json.dump(variables,", "Provide `paths` (a list of URLs or local file paths).", "first character cannot be numeric). Pass a dictionary to `variables`", "None) -> dict: \"\"\" Read multiple serialized data files into", "metadata.bibliography field with manual references paths bibliographies = variables[\"pandoc\"].get(\"bibliography\", [])", "enable pandoc-manubot-cite option to write bibliography to a file variables[\"pandoc\"][\"manubot-output-bibliography\"]", "pandoc with args.manuscript_path.open(\"w\", encoding=\"utf-8\") as write_file: yaml.dump( variables[\"pandoc\"], write_file, default_flow_style=False,", "metadata if \"author_info\" in metadata: authors = metadata.pop(\"author_info\", []) warnings.warn(", "text += _citation_tags_to_reference_links(args) variables = load_variables(args) variables[\"manubot\"][\"manuscript_stats\"] = get_manuscript_stats(text) with", ") logging.error(message) return csl_items def _generate_csl_items(args, citekeys_df): \"\"\" General CSL", "by the user if `metadata.yaml` includes a `manubot` dictionary. -", "dictionary for manubot-related information and metadata. Fields in `manubot` are", "if match: obj = {namespace: read_serialized_data(path)} else: obj = read_serialized_dict(path)", "os.fspath( args.requests_cache_path ) variables[\"pandoc\"][\"manubot-clear-requests-cache\"] = args.clear_requests_cache return variables def get_citekeys_df(citekeys:", "for existing keys like `pandoc` or `manubot` (dangerous). \"\"\" #", "path): if not path: return citekeys_df.to_csv(path, sep=\"\\t\", index=False) def _citation_tags_to_reference_links(args)", "in metadata: authors = metadata.pop(\"author_info\", []) warnings.warn( \"metadata.yaml: 'author_info' is", "fields include `pandoc`, `manubot`, `title`, `keywords`, `authors` (formerly `author_info`, now", "metadata.pop(key) # Add date to metadata now = datetime_now() logging.info(", "logging.info(f\"Reading user-provided templating variables at {path!r}\") # Match only namespaces", "f\"CSL JSON Data with a standard_citekey of {standard_citekey!r} not found", "logs warnings for potential problems. \"\"\" # Read manual references", "with delim_whitespace=True.\" ) tag_df = pandas.read_csv(path, delim_whitespace=True) tag_df[\"manuscript_citekey\"] = \"tag:\"", "following paragraph into your Markdown content:{text}\" ) return text def", "to Pandoc via the `yaml_metadata_block`. Fields in `pandoc` are either", "not always the exact path to the cache. If None,", "found in manual-references.json. \" \"Metadata must be provided for raw", "read_serialized_dict(args.meta_yaml_path) else: metadata = {} logging.warning( f\"missing {args.meta_yaml_path} file with", "references.json to disk and logs warnings for potential problems. \"\"\"", "in variables[\"authors\"]: if \"affiliations\" not in author: continue if not", "from manubot.process.metadata import ( get_header_includes, get_thumbnail_url, get_manuscript_urls, get_software_versions, ) from", ") variables.update(obj) logging.debug( f\"Reading user-provided templating variables complete:\\n\" f\"{json.dumps(variables, indent=2,", "_generate_csl_items(args, citekeys_df): \"\"\" General CSL (citeproc) items for standard_citekeys in", "standard_citekey to csl_item for manual references - requests_cache_path: path for", "\"citation-tags.tsv is deprecated. \" f\"Consider deleting citation-tags.tsv and inserting the", "- clear_requests_cache: If True, clear the requests cache before generating", "a dictionary as its top level. Namespaces should consist only", "except Exception: logging.exception(f\"Error reading template variables from {path!r}\") continue assert", "variables[\"affiliations\"] = affiliation_df.to_dict(orient=\"records\") return variables def load_variables(args) -> dict: \"\"\"", "{} logging.warning( f\"missing {args.meta_yaml_path} file with yaml_metadata_block for pandoc\" )", "of variables. If no authors have any affiliations, variables is", "pandas import requests import requests_cache import yaml from manubot.util import", "{now.isoformat()}\" ) variables[\"pandoc\"][\"date-meta\"] = now.date().isoformat() variables[\"manubot\"][\"date\"] = f\"{now:%B} {now.day}, {now.year}\"", "f\"no citation tags file at {path} \" \"Not reading citekey_aliases", "check_multiple_citation_strings(citekeys_df) return citekeys_df def read_citations_tsv(path) -> dict: \"\"\" Read citekey", "manuscript variables available for jinja2 templating. Returns a dictionary, refered", "in move_to_pandoc: if key in metadata: variables[\"pandoc\"][key] = metadata.pop(key) #", "= pandas.read_csv(path, sep=\"\\t\") na_rows_df = tag_df[tag_df.isnull().any(axis=\"columns\")] if not na_rows_df.empty: logging.error(", "create a shortened citekey \"\"\" citekeys_df = pandas.DataFrame( {\"manuscript_citekey\": list(citekeys)}", "path = match.groups() logging.info( f\"Using the {namespace!r} namespace for template", "by Manubot are copied to `variables`. Interpreted fields include `pandoc`,", "instead.\" ) continue variables[key].update(dict_) # Update variables with uninterpreted metadata.yaml", "that are intended for pandoc move_to_pandoc = \"title\", \"keywords\", \"lang\"", "return csl_items def write_csl_json(csl_items, path): \"\"\" Write CSL Items to", "conflicts: logging.warning( f\"Template variables in {path!r} overwrite existing \" \"values", "short_citekey hash collisions \"\"\" collision_df = citekeys_df[[\"standard_citekey\", \"short_citekey\"]].drop_duplicates() collision_df =", "following columns: - manuscript_citekey: citation keys extracted from the manuscript", "path.open(\"w\", encoding=\"utf-8\") as write_file: json.dump(csl_items, write_file, indent=2, ensure_ascii=False) write_file.write(\"\\n\") def", "def write_csl_json(csl_items, path): \"\"\" Write CSL Items to a JSON", "write_file: json.dump(variables, write_file, ensure_ascii=False, indent=2) write_file.write(\"\\n\") text = template_with_jinja2(text, variables)", "dict: \"\"\" Read `metadata.yaml` and files specified by `--template-variables-path` to", "output's <head> variables[\"pandoc\"][\"header-includes\"] = get_header_includes(variables) assert args.skip_citations # Extend Pandoc's", "import logging import os import pathlib import re import textwrap", "cache before generating citekey metadata. \"\"\" # Deduplicate citations citekeys", "= pandas.DataFrame( {\"manuscript_citekey\": list(citekeys)} ).drop_duplicates() citekeys_df[\"detagged_citekey\"] = citekeys_df.manuscript_citekey.map( lambda citekey:", "http://jinja.pocoo.org/docs/2.10/api/#identifier-naming match = re.match(r\"([a-zA-Z_][a-zA-Z0-9_]*)=(.+)\", path) if match: namespace, path =", "```python paths = [ 'https://git.io/vbkqm', # update the dictionary's top-level", "in citekeys: if standard_citekey in manual_refs: csl_items.append(manual_refs[standard_citekey]) continue elif standard_citekey.startswith(\"raw:\"):", "variables def get_citekeys_df(citekeys: list, citekey_aliases: dict = {}): \"\"\" Generate", "check_collisions(citekeys_df): \"\"\" Check for short_citekey hash collisions \"\"\" collision_df =", "numbered author affiliations. Specifically, add a list of affiliation_numbers for", "write_file: json.dump(csl_items, write_file, indent=2, ensure_ascii=False) write_file.write(\"\\n\") def template_with_jinja2(text, variables): \"\"\"", "strings extracted from text {citekeys_df.standard_citekey.nunique()} unique standard citations\\ \"\"\" )", "at {path} \" \"Not reading citekey_aliases from citation-tags.tsv.\" ) return", "standard_citekeys in citekeys_df. Parameters: - citekeys: list of standard_citekeys -", "if not na_rows_df.empty: logging.error( f\"{path} contains rows with missing values:\\n\"", "thumbnail URL if present thumbnail_url = get_thumbnail_url(metadata.pop(\"thumbnail\", None)) if thumbnail_url:", "return \"\" text = \"\\n\\n\" for key, value in citekey_aliases.items():", "if requests_cache_path is not None: requests # require `import requests`", "\"\"\" Template using jinja2 with the variables dictionary unpacked as", "{}): \"\"\" Generate and return citekeys_df. citekeys_df is a pandas.DataFrame", "citekeys_df.sort_values([\"standard_citekey\", \"detagged_citekey\"]) check_collisions(citekeys_df) check_multiple_citation_strings(citekeys_df) return citekeys_df def read_citations_tsv(path) -> dict:", "paths: logging.info(f\"Reading user-provided templating variables at {path!r}\") # Match only", "args.skip_citations text += _citation_tags_to_reference_links(args) variables = load_variables(args) variables[\"manubot\"][\"manuscript_stats\"] = get_manuscript_stats(text)", "if conflicts: logging.warning( f\"Template variables in {path!r} overwrite existing \"", "the `yaml_metadata_block`. Fields in `pandoc` are either generated by Manubot", "CSL manual_refs = load_manual_references(args.manual_references_paths) # Retrieve CSL Items csl_items =", "name_to_numbers = { name: sorted(df.affiliation_number) for name, df in affil_map_df.groupby(\"name\")", "bibliographies)) variables[\"pandoc\"][\"bibliography\"] = bibliographies # enable pandoc-manubot-cite option to write", "thumbnail_url # Update variables with metadata.yaml pandoc/manubot dicts for key", "rows.append((author[\"name\"], affiliation)) if not rows: return variables affil_map_df = pandas.DataFrame(rows,", "complete:\\n\" f\"{json.dumps(variables, indent=2, ensure_ascii=False)}\" ) return variables def add_author_affiliations(variables: dict)", "includes a `pandoc` dictionary. - `manubot`: a dictionary for manubot-related", "keys that are intended for pandoc move_to_pandoc = \"title\", \"keywords\",", "the variables dictionary unpacked as keyword arguments. \"\"\" jinja_environment =", "authors have any affiliations, variables is left unmodified. \"\"\" rows", "citation keys:\\n{}\".format( \"\\n\".join(failures) ) logging.error(message) return csl_items def _generate_csl_items(args, citekeys_df):", "variables[\"pandoc\"][\"manubot-requests-cache-path\"] = os.fspath( args.requests_cache_path ) variables[\"pandoc\"][\"manubot-clear-requests-cache\"] = args.clear_requests_cache return variables", "unpacked as keyword arguments. \"\"\" jinja_environment = jinja2.Environment( loader=jinja2.BaseLoader(), undefined=jinja2.make_logging_undefined(logging.getLogger()),", "numeric). Pass a dictionary to `variables` to update an existing", "variables take highest precedence and can overwrite values for existing", "= get_manuscript_stats(text) with args.variables_path.open(\"w\", encoding=\"utf-8\") as write_file: json.dump(variables, write_file, ensure_ascii=False,", "'namespace_1=https://git.io/vbkqm', # store under 'namespace_1' key 'namespace_2=some_local_path.json', # store under", "includes a `manubot` dictionary. - All fields from a manuscript's", "fields variables.update(metadata) # Update variables with user-provided variables here variables", "`import requests` in case this is essential for monkey patching", "os.fspath(args.references_path) variables[\"pandoc\"][\"manubot-output-citekeys\"] = os.fspath(args.citations_path) variables[\"pandoc\"][\"manubot-requests-cache-path\"] = os.fspath( args.requests_cache_path ) variables[\"pandoc\"][\"manubot-clear-requests-cache\"]", "\"\"\" text = get_text(args.content_directory) assert args.skip_citations text += _citation_tags_to_reference_links(args) variables", "If no authors have any affiliations, variables is left unmodified.", "standard_citekey in manual_refs: csl_items.append(manual_refs[standard_citekey]) continue elif standard_citekey.startswith(\"raw:\"): logging.error( f\"CSL JSON", "= [bibliographies] assert isinstance(bibliographies, list) bibliographies.extend(args.manual_references_paths) bibliographies = list(map(os.fspath, bibliographies))", "[ 'https://git.io/vbkqm', # update the dictionary's top-level 'namespace_1=https://git.io/vbkqm', # store", "requests_cache.uninstall_cache() if failures: message = \"CSL JSON Data retrieval failed", "# enable pandoc-manubot-cite option to write bibliography to a file", "\"\"\" jinja_environment = jinja2.Environment( loader=jinja2.BaseLoader(), undefined=jinja2.make_logging_undefined(logging.getLogger()), autoescape=False, comment_start_string=\"{##\", comment_end_string=\"##}\", extensions=[\"jinja2.ext.do\",", "if not multi_df.empty: table = multi_df.to_string( index=False, columns=[\"standard_citekey\", \"manuscript_citekey\"] )", "metadata. Fields in `manubot` are either generated by Manubot or", "must be provided for raw citekeys.\" ) failures.append(standard_citekey) try: csl_item", "# Interpreted keys that are intended for pandoc move_to_pandoc =", "citekey_aliases.get(citekey, citekey) ) for citation in citekeys_df.detagged_citekey: is_valid_citekey(citation, allow_raw=True) citekeys_df[\"standard_citekey\"]", "import ( datetime_now, get_manuscript_stats, get_text, ) from manubot.cite.citekey import (", "manual_refs = load_manual_references(args.manual_references_paths) # Retrieve CSL Items csl_items = generate_csl_items(", "logging.exception(f\"Error reading template variables from {path!r}\") continue assert isinstance(obj, dict)", "citekey aliases from a citation-tags.tsv file. \"\"\" if not path.is_file():", "do not use requests_cache. - clear_requests_cache: If True, clear the", "`title`, `keywords`, `authors` (formerly `author_info`, now deprecated), `lang`, and `thumbnail`.", "an existing dictionary rather than create a new dictionary. \"\"\"", "hashed to create a shortened citekey \"\"\" citekeys_df = pandas.DataFrame(", "not found in manual-references.json. \" \"Metadata must be provided for", "add_author_affiliations(variables: dict) -> dict: \"\"\" Edit variables to contain numbered", "template_with_jinja2(text, variables): \"\"\" Template using jinja2 with the variables dictionary", "df in affil_map_df.groupby(\"name\") } for author in variables[\"authors\"]: author[\"affiliation_numbers\"] =", "copied to `variables`. Interpreted fields include `pandoc`, `manubot`, `title`, `keywords`,", "rows = list() for author in variables[\"authors\"]: if \"affiliations\" not", "for the HTML output's <head> variables[\"pandoc\"][\"header-includes\"] = get_header_includes(variables) assert args.skip_citations", "use requests_cache. - clear_requests_cache: If True, clear the requests cache", "{now.year}\" # Process authors metadata if \"author_info\" in metadata: authors", "paths bibliographies = variables[\"pandoc\"].get(\"bibliography\", []) if isinstance(bibliographies, str): bibliographies =", "do nothing. \"\"\" if not path: return path = pathlib.Path(path)", "for author in variables[\"authors\"]: author[\"affiliation_numbers\"] = name_to_numbers.get(author[\"name\"], []) variables[\"affiliations\"] =", "variables dictionary unpacked as keyword arguments. \"\"\" jinja_environment = jinja2.Environment(", "list, citekey_aliases: dict = {}): \"\"\" Generate and return citekeys_df.", "= load_variables(args) variables[\"manubot\"][\"manuscript_stats\"] = get_manuscript_stats(text) with args.variables_path.open(\"w\", encoding=\"utf-8\") as write_file:", "Check for short_citekey hash collisions \"\"\" collision_df = citekeys_df[[\"standard_citekey\", \"short_citekey\"]].drop_duplicates()", "its top level. Namespaces should consist only of ASCII alphanumeric", "detagged_citekey: manuscript_citekey but with tag citekeys dereferenced - standard_citekey: detagged_citekey", "affil_map_df[[\"affiliation\"]].drop_duplicates() affiliation_df[\"affiliation_number\"] = range(1, 1 + len(affiliation_df)) affil_map_df = affil_map_df.merge(affiliation_df)", "local file paths). Paths can optionally have a namespace prepended.", ") failures.append(standard_citekey) try: csl_item = citekey_to_csl_item(standard_citekey) csl_items.append(csl_item) except Exception: logging.exception(f\"Citeproc", "standard_citekey in citekeys: if standard_citekey in manual_refs: csl_items.append(manual_refs[standard_citekey]) continue elif", "fields from a manuscript's `metadata.yaml` that are not interpreted by", "by using spaces rather than tabs to delimit fields.\\n\" \"Proceeding", "return citekeys_df. citekeys_df is a pandas.DataFrame with the following columns:", "variables.update(obj) logging.debug( f\"Reading user-provided templating variables complete:\\n\" f\"{json.dumps(variables, indent=2, ensure_ascii=False)}\"", "warnings from typing import List, Optional import jinja2 import pandas", "write_file.write(\"\\n\") text = template_with_jinja2(text, variables) # Write manuscript for pandoc", "a file variables[\"pandoc\"][\"manubot-output-bibliography\"] = os.fspath(args.references_path) variables[\"pandoc\"][\"manubot-output-citekeys\"] = os.fspath(args.citations_path) variables[\"pandoc\"][\"manubot-requests-cache-path\"] =", "def get_citekeys_df(citekeys: list, citekey_aliases: dict = {}): \"\"\" Generate and", "the same reference:\\n{table}\") return multi_df def read_variable_files(paths: List[str], variables: Optional[dict]", "for manual references - requests_cache_path: path for the requests cache", "variables) # Add header-includes metadata with <meta> information for the", "`metadata.yaml` includes a `pandoc` dictionary. - `manubot`: a dictionary for", "csl_items = generate_csl_items( citekeys=citekeys_df.standard_citekey.unique(), manual_refs=manual_refs, requests_cache_path=args.requests_cache_path, clear_requests_cache=args.clear_requests_cache, ) # Write", "[]) if isinstance(bibliographies, str): bibliographies = [bibliographies] assert isinstance(bibliographies, list)", "if args.meta_yaml_path.is_file(): metadata = read_serialized_dict(args.meta_yaml_path) else: metadata = {} logging.warning(", "hard-coded by the user if `metadata.yaml` includes a `pandoc` dictionary.", "the current datetime: {now.isoformat()}\" ) variables[\"pandoc\"][\"date-meta\"] = now.date().isoformat() variables[\"manubot\"][\"date\"] =", "args.manuscript_path.open(\"w\", encoding=\"utf-8\") as write_file: yaml.dump( variables[\"pandoc\"], write_file, default_flow_style=False, explicit_start=True, explicit_end=True,", "= range(1, 1 + len(affiliation_df)) affil_map_df = affil_map_df.merge(affiliation_df) name_to_numbers =", "if authors is None: authors = [] variables[\"pandoc\"][\"author-meta\"] = [author[\"name\"]", ") variables[\"pandoc\"][\"date-meta\"] = now.date().isoformat() variables[\"manubot\"][\"date\"] = f\"{now:%B} {now.day}, {now.year}\" #", "citekey \"\"\" citekeys_df = pandas.DataFrame( {\"manuscript_citekey\": list(citekeys)} ).drop_duplicates() citekeys_df[\"detagged_citekey\"] =", "f\"load_variables expected metadata.yaml field {key!r} to be a dict.\" f\"Received", "pandoc move_to_pandoc = \"title\", \"keywords\", \"lang\" for key in move_to_pandoc:", "+ tag_df.tag tag_df = tag_df.rename(columns={\"citation\": \"detagged_citekey\"}) citekey_aliases = dict( zip(tag_df[\"manuscript_citekey\"],", "is not None: requests # require `import requests` in case", "citekeys: if standard_citekey in manual_refs: csl_items.append(manual_refs[standard_citekey]) continue elif standard_citekey.startswith(\"raw:\"): logging.error(", "keys:\\n{}\".format( \"\\n\".join(failures) ) logging.error(message) return csl_items def _generate_csl_items(args, citekeys_df): \"\"\"", "nothing. \"\"\" if not path: return path = pathlib.Path(path) with", "not isinstance(author[\"affiliations\"], list): warnings.warn( f\"Expected list for {author['name']}'s affiliations. \"", "`metadata.yaml` that are not interpreted by Manubot are copied to", "else: obj = read_serialized_dict(path) except Exception: logging.exception(f\"Error reading template variables", "tags file at {path} \" \"Not reading citekey_aliases from citation-tags.tsv.\"", "inserted according to the `--template-variables-path` option. User-specified variables take highest", "\"\"\" Convert citation-tags.tsv to markdown reference link syntax \"\"\" citekey_aliases", "and return citekeys_df. citekeys_df is a pandas.DataFrame with the following", "\" \"Metadata must be provided for raw citekeys.\" ) failures.append(standard_citekey)", "None)) if thumbnail_url: variables[\"manubot\"][\"thumbnail_url\"] = thumbnail_url # Update variables with", "variables affil_map_df = pandas.DataFrame(rows, columns=[\"name\", \"affiliation\"]) affiliation_df = affil_map_df[[\"affiliation\"]].drop_duplicates() affiliation_df[\"affiliation_number\"]", "variables[\"manubot\"][\"date\"] = f\"{now:%B} {now.day}, {now.year}\" # Process authors metadata if", "pandas.DataFrame( {\"manuscript_citekey\": list(citekeys)} ).drop_duplicates() citekeys_df[\"detagged_citekey\"] = citekeys_df.manuscript_citekey.map( lambda citekey: citekey_aliases.get(citekey,", "option to write bibliography to a file variables[\"pandoc\"][\"manubot-output-bibliography\"] = os.fspath(args.references_path)", "user-provided variables here variables = read_variable_files(args.template_variables_path, variables) # Add header-includes", "write_file.write(\"\\n\") def template_with_jinja2(text, variables): \"\"\" Template using jinja2 with the", "requests_cache may append an extension to this path, so it", "it is not always the exact path to the cache.", "are valid jinja2 variable names # http://jinja.pocoo.org/docs/2.10/api/#identifier-naming match = re.match(r\"([a-zA-Z_][a-zA-Z0-9_]*)=(.+)\",", "Add date to metadata now = datetime_now() logging.info( f\"Using {now:%Z}", "content:{text}\" ) return text def generate_csl_items( citekeys: list, manual_refs: dict", "into a user_variables dictionary. Provide `paths` (a list of URLs", "\"\\n\".join(failures) ) logging.error(message) return csl_items def _generate_csl_items(args, citekeys_df): \"\"\" General", "Namespaces should consist only of ASCII alphanumeric characters (includes underscores,", "timezone.\\n\" f\"Dating manuscript with the current datetime: {now.isoformat()}\" ) variables[\"pandoc\"][\"date-meta\"]", "from text {citekeys_df.standard_citekey.nunique()} unique standard citations\\ \"\"\" ) logging.info(message) multi_df", "Deduplicate citations citekeys = list(dict.fromkeys(citekeys)) # Install cache if requests_cache_path", "for {standard_citekey!r}\") failures.append(standard_citekey) # Uninstall cache if requests_cache_path is not", "in variables[\"authors\"]: author[\"affiliation_numbers\"] = name_to_numbers.get(author[\"name\"], []) variables[\"affiliations\"] = affiliation_df.to_dict(orient=\"records\") return", "not na_rows_df.empty: logging.error( f\"{path} contains rows with missing values:\\n\" f\"{na_rows_df}\\n\"", "\"Not reading citekey_aliases from citation-tags.tsv.\" ) return {} tag_df =", "with metadata.yaml pandoc/manubot dicts for key in \"pandoc\", \"manubot\": dict_", ").drop_duplicates() citekeys_df[\"detagged_citekey\"] = citekeys_df.manuscript_citekey.map( lambda citekey: citekey_aliases.get(citekey, citekey) ) for", "no authors have any affiliations, variables is left unmodified. \"\"\"", "manuscript, creating manuscript.md and references.json as inputs for pandoc. \"\"\"", "get_thumbnail_url, get_manuscript_urls, get_software_versions, ) from manubot.process.manuscript import ( datetime_now, get_manuscript_stats,", "Set repository version metadata for CI builds ci_params = get_continuous_integration_parameters()", "list of standard_citekeys - manual_refs: mapping from standard_citekey to csl_item", "dict_ = metadata.pop(key, {}) if not isinstance(dict_, dict): logging.warning( f\"load_variables", "lambda citekey: citekey_aliases.get(citekey, citekey) ) for citation in citekeys_df.detagged_citekey: is_valid_citekey(citation,", "= get_header_includes(variables) assert args.skip_citations # Extend Pandoc's metadata.bibliography field with", "jinja2 variable names # http://jinja.pocoo.org/docs/2.10/api/#identifier-naming match = re.match(r\"([a-zA-Z_][a-zA-Z0-9_]*)=(.+)\", path) if", "write_citekeys_tsv(citekeys_df, path): if not path: return citekeys_df.to_csv(path, sep=\"\\t\", index=False) def", "standard_citekey: detagged_citekey standardized - short_citekey: standard_citekey hashed to create a", "in {path!r} overwrite existing \" \"values for the following keys:\\n\"", "# update the dictionary's top-level 'namespace_1=https://git.io/vbkqm', # store under 'namespace_1'", "if requests_cache_path is not None: logging.info( f\"requests-cache finished with {len(cache.responses)}", "get_thumbnail_url(metadata.pop(\"thumbnail\", None)) if thumbnail_url: variables[\"manubot\"][\"thumbnail_url\"] = thumbnail_url # Update variables", "pandas.read_csv(path, sep=\"\\t\") na_rows_df = tag_df[tag_df.isnull().any(axis=\"columns\")] if not na_rows_df.empty: logging.error( f\"{path}", "csl_items.append(csl_item) except Exception: logging.exception(f\"Citeproc retrieval failure for {standard_citekey!r}\") failures.append(standard_citekey) #", "manuscript.md and references.json as inputs for pandoc. \"\"\" text =", "user if `metadata.yaml` includes a `manubot` dictionary. - All fields", "are not interpreted by Manubot are copied to `variables`. Interpreted", "list(citekeys)} ).drop_duplicates() citekeys_df[\"detagged_citekey\"] = citekeys_df.manuscript_citekey.map( lambda citekey: citekey_aliases.get(citekey, citekey) )", "jinja2 import pandas import requests import requests_cache import yaml from", "variables def load_variables(args) -> dict: \"\"\" Read `metadata.yaml` and files", "interpreted by Manubot are copied to `variables`. Interpreted fields include", "by the user if `metadata.yaml` includes a `pandoc` dictionary. -", "citations strings extracted from text {citekeys_df.standard_citekey.nunique()} unique standard citations\\ \"\"\"", "to the `--template-variables-path` option. User-specified variables take highest precedence and", "from typing import List, Optional import jinja2 import pandas import", "failed for the following standardized citation keys:\\n{}\".format( \"\\n\".join(failures) ) logging.error(message)", "] ``` If a namespace is not provided, the JSON", "evaluates as False, do nothing. \"\"\" if not path: return", "of standard_citekeys - manual_refs: mapping from standard_citekey to csl_item for", "file variables[\"pandoc\"][\"manubot-output-bibliography\"] = os.fspath(args.references_path) variables[\"pandoc\"][\"manubot-output-citekeys\"] = os.fspath(args.citations_path) variables[\"pandoc\"][\"manubot-requests-cache-path\"] = os.fspath(", ") author[\"affiliations\"] = author[\"affiliations\"].split(\"; \") for affiliation in author[\"affiliations\"]: rows.append((author[\"name\"],", "`keywords`, `authors` (formerly `author_info`, now deprecated), `lang`, and `thumbnail`. -", "standard_citekey hashed to create a shortened citekey \"\"\" citekeys_df =", "CSL (citeproc) items for standard_citekeys in citekeys_df. Writes references.json to", "contain numbered author affiliations. Specifically, add a list of affiliation_numbers", "deleting citation-tags.tsv and inserting the following paragraph into your Markdown", ") variables[\"pandoc\"][\"manubot-clear-requests-cache\"] = args.clear_requests_cache return variables def get_citekeys_df(citekeys: list, citekey_aliases:", "problems. \"\"\" # Read manual references (overrides) in JSON CSL", "path.is_file(): logging.info( f\"no citation tags file at {path} \" \"Not", "update the dictionary's top-level 'namespace_1=https://git.io/vbkqm', # store under 'namespace_1' key", "Match only namespaces that are valid jinja2 variable names #", "= [ 'https://git.io/vbkqm', # update the dictionary's top-level 'namespace_1=https://git.io/vbkqm', #", "`path` evaluates as False, do nothing. \"\"\" if not path:", "is None: authors = [] variables[\"pandoc\"][\"author-meta\"] = [author[\"name\"] for author", "citekeys = list(dict.fromkeys(citekeys)) # Install cache if requests_cache_path is not", "_citation_tags_to_reference_links(args) variables = load_variables(args) variables[\"manubot\"][\"manuscript_stats\"] = get_manuscript_stats(text) with args.variables_path.open(\"w\", encoding=\"utf-8\")", "citation keys extracted from the manuscript content files. - detagged_citekey:", "separated. \" f\"Please switch affiliations to a list.\", category=DeprecationWarning, )", "the following paragraph into your Markdown content:{text}\" ) return text", "CI builds ci_params = get_continuous_integration_parameters() if ci_params: variables[\"manubot\"][\"ci_source\"] = ci_params", "= variables[\"pandoc\"].get(\"bibliography\", []) if isinstance(bibliographies, str): bibliographies = [bibliographies] assert", "as cache_name to `requests_cache.install_cache`. requests_cache may append an extension to", "text {citekeys_df.standard_citekey.nunique()} unique standard citations\\ \"\"\" ) logging.info(message) multi_df =", "be caused by using spaces rather than tabs to delimit", "here variables = read_variable_files(args.template_variables_path, variables) # Add header-includes metadata with", "get_header_includes, get_thumbnail_url, get_manuscript_urls, get_software_versions, ) from manubot.process.manuscript import ( datetime_now,", "citekeys_df[citekeys_df.standard_citekey.duplicated(keep=False)] if not multi_df.empty: table = multi_df.to_string( index=False, columns=[\"standard_citekey\", \"manuscript_citekey\"]", "unique standard citations\\ \"\"\" ) logging.info(message) multi_df = citekeys_df[citekeys_df.standard_citekey.duplicated(keep=False)] if", "arguments. \"\"\" jinja_environment = jinja2.Environment( loader=jinja2.BaseLoader(), undefined=jinja2.make_logging_undefined(logging.getLogger()), autoescape=False, comment_start_string=\"{##\", comment_end_string=\"##}\",", "import yaml from manubot.util import read_serialized_data, read_serialized_dict from manubot.process.bibliography import", "author in authors] variables[\"manubot\"][\"authors\"] = authors add_author_affiliations(variables[\"manubot\"]) # Set repository", "csl_items = list() failures = list() for standard_citekey in citekeys:", "variables to contain numbered author affiliations. Specifically, add a list", "or hard-coded by the user if `metadata.yaml` includes a `manubot`", "for the same reference:\\n{table}\") return multi_df def read_variable_files(paths: List[str], variables:", "= os.fspath( args.requests_cache_path ) variables[\"pandoc\"][\"manubot-clear-requests-cache\"] = args.clear_requests_cache return variables def", "tag_df[\"detagged_citekey\"]) ) return citekey_aliases def write_citekeys_tsv(citekeys_df, path): if not path:", "multi_df.to_string( index=False, columns=[\"standard_citekey\", \"manuscript_citekey\"] ) logging.warning(f\"Multiple citekeys detected for the", "failures: message = \"CSL JSON Data retrieval failed for the", "bibliographies.extend(args.manual_references_paths) bibliographies = list(map(os.fspath, bibliographies)) variables[\"pandoc\"][\"bibliography\"] = bibliographies # enable", "from a citation-tags.tsv file. \"\"\" if not path.is_file(): logging.info( f\"no", "requests import requests_cache import yaml from manubot.util import read_serialized_data, read_serialized_dict", "import requests_cache import yaml from manubot.util import read_serialized_data, read_serialized_dict from", "citekeys: list, manual_refs: dict = {}, requests_cache_path: Optional[str] = None,", "to markdown reference link syntax \"\"\" citekey_aliases = read_citations_tsv(args.citation_tags_path) if", "template_with_jinja2(text, variables) # Write manuscript for pandoc with args.manuscript_path.open(\"w\", encoding=\"utf-8\")", "f\"{json.dumps(variables, indent=2, ensure_ascii=False)}\" ) return variables def add_author_affiliations(variables: dict) ->", "collision_df[collision_df.short_citekey.duplicated(keep=False)] if not collision_df.empty: logging.error(f\"OMF! Hash collision. Congratulations.\\n{collision_df}\") return collision_df", "strings referring the the same reference. \"\"\" message = textwrap.dedent(", "extensions=[\"jinja2.ext.do\", \"jinja2.ext.loopcontrols\"], ) template = jinja_environment.from_string(text) return template.render(**variables) def prepare_manuscript(args):", "or hard-coded by the user if `metadata.yaml` includes a `pandoc`", "keys extracted from the manuscript content files. - detagged_citekey: manuscript_citekey", "citekey) ) for citation in citekeys_df.detagged_citekey: is_valid_citekey(citation, allow_raw=True) citekeys_df[\"standard_citekey\"] =", "import load_manual_references from manubot.process.ci import get_continuous_integration_parameters from manubot.process.metadata import (", "variables[\"manubot\"].update(get_software_versions()) # Add thumbnail URL if present thumbnail_url = get_thumbnail_url(metadata.pop(\"thumbnail\",", "reading template variables from {path!r}\") continue assert isinstance(obj, dict) conflicts", "highest precedence and can overwrite values for existing keys like", "\"manubot\": {}} # Read metadata which contains pandoc_yaml_metadata # as", "\"lang\" for key in move_to_pandoc: if key in metadata: variables[\"pandoc\"][key]", "{\"manuscript_citekey\": list(citekeys)} ).drop_duplicates() citekeys_df[\"detagged_citekey\"] = citekeys_df.manuscript_citekey.map( lambda citekey: citekey_aliases.get(citekey, citekey)", "Add manuscript URLs variables[\"manubot\"].update(get_manuscript_urls(metadata.pop(\"html_url\", None))) # Add software versions variables[\"manubot\"].update(get_software_versions())", "Read metadata which contains pandoc_yaml_metadata # as well as authors", "keys like `pandoc` or `manubot` (dangerous). \"\"\" # Generated manuscript", "with the following columns: - manuscript_citekey: citation keys extracted from", "files. - detagged_citekey: manuscript_citekey but with tag citekeys dereferenced -", "at `path`. If `path` evaluates as False, do nothing. \"\"\"", "builds ci_params = get_continuous_integration_parameters() if ci_params: variables[\"manubot\"][\"ci_source\"] = ci_params #", "bibliographies = [bibliographies] assert isinstance(bibliographies, list) bibliographies.extend(args.manual_references_paths) bibliographies = list(map(os.fspath,", "args.clear_requests_cache return variables def get_citekeys_df(citekeys: list, citekey_aliases: dict = {}):", "= list(map(os.fspath, bibliographies)) variables[\"pandoc\"][\"bibliography\"] = bibliographies # enable pandoc-manubot-cite option", "Passed as cache_name to `requests_cache.install_cache`. requests_cache may append an extension", "import textwrap import warnings from typing import List, Optional import", "f\"\"\"\\ {len(citekeys_df)} unique citations strings extracted from text {citekeys_df.standard_citekey.nunique()} unique", "now deprecated), `lang`, and `thumbnail`. - User-specified fields inserted according", ") continue variables[key].update(dict_) # Update variables with uninterpreted metadata.yaml fields", "Pandoc. write_csl_json(csl_items, args.references_path) return csl_items def write_csl_json(csl_items, path): \"\"\" Write", "bibliographies # enable pandoc-manubot-cite option to write bibliography to a", "standardized citation keys:\\n{}\".format( \"\\n\".join(failures) ) logging.error(message) return csl_items def _generate_csl_items(args,", "from a manuscript's `metadata.yaml` that are not interpreted by Manubot", "return path = pathlib.Path(path) with path.open(\"w\", encoding=\"utf-8\") as write_file: json.dump(csl_items,", "as write_file: json.dump(csl_items, write_file, indent=2, ensure_ascii=False) write_file.write(\"\\n\") def template_with_jinja2(text, variables):", "# Update variables with metadata.yaml pandoc/manubot dicts for key in", "this is essential for monkey patching by requests_cache. requests_cache.install_cache(requests_cache_path, include_get_headers=True)", "path: return path = pathlib.Path(path) with path.open(\"w\", encoding=\"utf-8\") as write_file:", "Update variables with uninterpreted metadata.yaml fields variables.update(metadata) # Update variables", "responses\" ) csl_items = list() failures = list() for standard_citekey", "is_valid_citekey(citation, allow_raw=True) citekeys_df[\"standard_citekey\"] = citekeys_df.detagged_citekey.map( standardize_citekey ) citekeys_df[\"short_citekey\"] = citekeys_df.standard_citekey.map(shorten_citekey)", "generating citekey metadata. \"\"\" # Deduplicate citations citekeys = list(dict.fromkeys(citekeys))", "manubot.process.ci import get_continuous_integration_parameters from manubot.process.metadata import ( get_header_includes, get_thumbnail_url, get_manuscript_urls,", "rather than tabs to delimit fields.\\n\" \"Proceeding to reread TSV", "return template.render(**variables) def prepare_manuscript(args): \"\"\" Compile manuscript, creating manuscript.md and", "affil_map_df.merge(affiliation_df) name_to_numbers = { name: sorted(df.affiliation_number) for name, df in", "intended for pandoc move_to_pandoc = \"title\", \"keywords\", \"lang\" for key", "return csl_items def _generate_csl_items(args, citekeys_df): \"\"\" General CSL (citeproc) items", "text = template_with_jinja2(text, variables) # Write manuscript for pandoc with", "Read manual references (overrides) in JSON CSL manual_refs = load_manual_references(args.manual_references_paths)", "f\"Dating manuscript with the current datetime: {now.isoformat()}\" ) variables[\"pandoc\"][\"date-meta\"] =", "information for the HTML output's <head> variables[\"pandoc\"][\"header-includes\"] = get_header_includes(variables) assert", "is_valid_citekey, standardize_citekey, ) def check_collisions(citekeys_df): \"\"\" Check for short_citekey hash", "``` If a namespace is not provided, the JSON must", "return citekeys_df def read_citations_tsv(path) -> dict: \"\"\" Read citekey aliases", "= {} logging.warning( f\"missing {args.meta_yaml_path} file with yaml_metadata_block for pandoc\"", "may append an extension to this path, so it is", "return {} tag_df = pandas.read_csv(path, sep=\"\\t\") na_rows_df = tag_df[tag_df.isnull().any(axis=\"columns\")] if", "variables[\"manubot\"][\"authors\"] = authors add_author_affiliations(variables[\"manubot\"]) # Set repository version metadata for", "Generated manuscript variables variables = {\"pandoc\": {}, \"manubot\": {}} #", "dict) conflicts = variables.keys() & obj.keys() if conflicts: logging.warning( f\"Template", "for short_citekey hash collisions \"\"\" collision_df = citekeys_df[[\"standard_citekey\", \"short_citekey\"]].drop_duplicates() collision_df", "cache database. Passed as cache_name to `requests_cache.install_cache`. requests_cache may append", "Parameters: - citekeys: list of standard_citekeys - manual_refs: mapping from", "the following standardized citation keys:\\n{}\".format( \"\\n\".join(failures) ) logging.error(message) return csl_items", "`--template-variables-path` option. User-specified variables take highest precedence and can overwrite", ") return text def generate_csl_items( citekeys: list, manual_refs: dict =", "a user_variables dictionary. Provide `paths` (a list of URLs or", "`; ` separated. \" f\"Please switch affiliations to a list.\",", "def generate_csl_items( citekeys: list, manual_refs: dict = {}, requests_cache_path: Optional[str]", "so it is not always the exact path to the", "return multi_df def read_variable_files(paths: List[str], variables: Optional[dict] = None) ->", "multiple serialized data files into a user_variables dictionary. Provide `paths`", "variables def add_author_affiliations(variables: dict) -> dict: \"\"\" Edit variables to", "prepare_manuscript(args): \"\"\" Compile manuscript, creating manuscript.md and references.json as inputs", "+= _citation_tags_to_reference_links(args) variables = load_variables(args) variables[\"manubot\"][\"manuscript_stats\"] = get_manuscript_stats(text) with args.variables_path.open(\"w\",", "# Read manual references (overrides) in JSON CSL manual_refs =", "variables with uninterpreted metadata.yaml fields variables.update(metadata) # Update variables with", "= now.date().isoformat() variables[\"manubot\"][\"date\"] = f\"{now:%B} {now.day}, {now.year}\" # Process authors", "`--template-variables-path` to generate manuscript variables available for jinja2 templating. Returns", "\"\"\" citekeys_df = pandas.DataFrame( {\"manuscript_citekey\": list(citekeys)} ).drop_duplicates() citekeys_df[\"detagged_citekey\"] = citekeys_df.manuscript_citekey.map(", "is a pandas.DataFrame with the following columns: - manuscript_citekey: citation", "pandas.read_csv(path, delim_whitespace=True) tag_df[\"manuscript_citekey\"] = \"tag:\" + tag_df.tag tag_df = tag_df.rename(columns={\"citation\":", "requests_cache. - clear_requests_cache: If True, clear the requests cache before", "for citation in citekeys_df.detagged_citekey: is_valid_citekey(citation, allow_raw=True) citekeys_df[\"standard_citekey\"] = citekeys_df.detagged_citekey.map( standardize_citekey", "characters (includes underscores, first character cannot be numeric). Pass a", "either generated by Manubot or hard-coded by the user if", "affiliation_df.to_dict(orient=\"records\") return variables def load_variables(args) -> dict: \"\"\" Read `metadata.yaml`", "def read_citations_tsv(path) -> dict: \"\"\" Read citekey aliases from a", "write_file: yaml.dump( variables[\"pandoc\"], write_file, default_flow_style=False, explicit_start=True, explicit_end=True, width=float(\"inf\"), ) write_file.write(\"\\n\")", "_citation_tags_to_reference_links(args) -> str: \"\"\" Convert citation-tags.tsv to markdown reference link", "current datetime: {now.isoformat()}\" ) variables[\"pandoc\"][\"date-meta\"] = now.date().isoformat() variables[\"manubot\"][\"date\"] = f\"{now:%B}", "collision_df = citekeys_df[[\"standard_citekey\", \"short_citekey\"]].drop_duplicates() collision_df = collision_df[collision_df.short_citekey.duplicated(keep=False)] if not collision_df.empty:", "logging import os import pathlib import re import textwrap import", ") return {} tag_df = pandas.read_csv(path, sep=\"\\t\") na_rows_df = tag_df[tag_df.isnull().any(axis=\"columns\")]", ") from manubot.cite.citekey import ( citekey_to_csl_item, shorten_citekey, is_valid_citekey, standardize_citekey, )", "for author in authors] variables[\"manubot\"][\"authors\"] = authors add_author_affiliations(variables[\"manubot\"]) # Set", "# Match only namespaces that are valid jinja2 variable names", "as False, do nothing. \"\"\" if not path: return path", "requests_cache. requests_cache.install_cache(requests_cache_path, include_get_headers=True) cache = requests_cache.get_cache() if clear_requests_cache: logging.info(\"Clearing requests-cache\")", "logging.warning(f\"Multiple citekeys detected for the same reference:\\n{table}\") return multi_df def", "args.meta_yaml_path.is_file(): metadata = read_serialized_dict(args.meta_yaml_path) else: metadata = {} logging.warning( f\"missing", "-> dict: \"\"\" Read citekey aliases from a citation-tags.tsv file.", "len(affiliation_df)) affil_map_df = affil_map_df.merge(affiliation_df) name_to_numbers = { name: sorted(df.affiliation_number) for", "in citekeys_df.detagged_citekey: is_valid_citekey(citation, allow_raw=True) citekeys_df[\"standard_citekey\"] = citekeys_df.detagged_citekey.map( standardize_citekey ) citekeys_df[\"short_citekey\"]", "template.render(**variables) def prepare_manuscript(args): \"\"\" Compile manuscript, creating manuscript.md and references.json", "list() failures = list() for standard_citekey in citekeys: if standard_citekey", "\"short_citekey\"]].drop_duplicates() collision_df = collision_df[collision_df.short_citekey.duplicated(keep=False)] if not collision_df.empty: logging.error(f\"OMF! Hash collision.", "a namespace is not provided, the JSON must contain a", "if isinstance(bibliographies, str): bibliographies = [bibliographies] assert isinstance(bibliographies, list) bibliographies.extend(args.manual_references_paths)", "If `path` evaluates as False, do nothing. \"\"\" if not", "reading citekey_aliases from citation-tags.tsv.\" ) return {} tag_df = pandas.read_csv(path,", "reread TSV with delim_whitespace=True.\" ) tag_df = pandas.read_csv(path, delim_whitespace=True) tag_df[\"manuscript_citekey\"]", "f\"Using the {namespace!r} namespace for template variables from {path!r}\" )", "can optionally have a namespace prepended. For example: ```python paths", "references - requests_cache_path: path for the requests cache database. Passed", "file paths). Paths can optionally have a namespace prepended. For", "path, so it is not always the exact path to", "not use requests_cache. - clear_requests_cache: If True, clear the requests", "manuscript variables variables = {\"pandoc\": {}, \"manubot\": {}} # Read", "return variables affil_map_df = pandas.DataFrame(rows, columns=[\"name\", \"affiliation\"]) affiliation_df = affil_map_df[[\"affiliation\"]].drop_duplicates()", "are either generated by Manubot or hard-coded by the user", "standardized - short_citekey: standard_citekey hashed to create a shortened citekey", "continue if not isinstance(author[\"affiliations\"], list): warnings.warn( f\"Expected list for {author['name']}'s", "author in variables[\"authors\"]: author[\"affiliation_numbers\"] = name_to_numbers.get(author[\"name\"], []) variables[\"affiliations\"] = affiliation_df.to_dict(orient=\"records\")", "index=False) def _citation_tags_to_reference_links(args) -> str: \"\"\" Convert citation-tags.tsv to markdown", "\"\" text = \"\\n\\n\" for key, value in citekey_aliases.items(): text", "dictionary to `variables` to update an existing dictionary rather than", "# Install cache if requests_cache_path is not None: requests #", "for the following standardized citation keys:\\n{}\".format( \"\\n\".join(failures) ) logging.error(message) return", "name, df in affil_map_df.groupby(\"name\") } for author in variables[\"authors\"]: author[\"affiliation_numbers\"]", "csl_items.append(manual_refs[standard_citekey]) continue elif standard_citekey.startswith(\"raw:\"): logging.error( f\"CSL JSON Data with a", "for each author and add a list of affiliations to", "variables complete:\\n\" f\"{json.dumps(variables, indent=2, ensure_ascii=False)}\" ) return variables def add_author_affiliations(variables:", "General CSL (citeproc) items for standard_citekeys in citekeys_df. Writes references.json", "path to the cache. If None, do not use requests_cache.", "textwrap import warnings from typing import List, Optional import jinja2", "version metadata for CI builds ci_params = get_continuous_integration_parameters() if ci_params:", "retrieval failure for {standard_citekey!r}\") failures.append(standard_citekey) # Uninstall cache if requests_cache_path", "# Process authors metadata if \"author_info\" in metadata: authors =", "the user if `metadata.yaml` includes a `pandoc` dictionary. - `manubot`:", "comment_end_string=\"##}\", extensions=[\"jinja2.ext.do\", \"jinja2.ext.loopcontrols\"], ) template = jinja_environment.from_string(text) return template.render(**variables) def", "\" f\"Please switch affiliations to a list.\", category=DeprecationWarning, ) author[\"affiliations\"]", "add_author_affiliations(variables[\"manubot\"]) # Set repository version metadata for CI builds ci_params", "- `pandoc`: a dictionary for passing options to Pandoc via", "If True, clear the requests cache before generating citekey metadata.", "citekeys_df. Parameters: - citekeys: list of standard_citekeys - manual_refs: mapping", "if failures: message = \"CSL JSON Data retrieval failed for", "Generate and return citekeys_df. citekeys_df is a pandas.DataFrame with the", "top-level 'namespace_1=https://git.io/vbkqm', # store under 'namespace_1' key 'namespace_2=some_local_path.json', # store", "\"author_info\" in metadata: authors = metadata.pop(\"author_info\", []) warnings.warn( \"metadata.yaml: 'author_info'", "dictionary. Provide `paths` (a list of URLs or local file", "metadata now = datetime_now() logging.info( f\"Using {now:%Z} timezone.\\n\" f\"Dating manuscript", "Congratulations.\\n{collision_df}\") return collision_df def check_multiple_citation_strings(citekeys_df): \"\"\" Identify different citation strings", "affiliation_df[\"affiliation_number\"] = range(1, 1 + len(affiliation_df)) affil_map_df = affil_map_df.merge(affiliation_df) name_to_numbers", "{citekeys_df.standard_citekey.nunique()} unique standard citations\\ \"\"\" ) logging.info(message) multi_df = citekeys_df[citekeys_df.standard_citekey.duplicated(keep=False)]", "= citekeys_df.detagged_citekey.map( standardize_citekey ) citekeys_df[\"short_citekey\"] = citekeys_df.standard_citekey.map(shorten_citekey) citekeys_df = citekeys_df.sort_values([\"standard_citekey\",", "encoding=\"utf-8\") as write_file: yaml.dump( variables[\"pandoc\"], write_file, default_flow_style=False, explicit_start=True, explicit_end=True, width=float(\"inf\"),", "obj.keys() if conflicts: logging.warning( f\"Template variables in {path!r} overwrite existing", "Write manuscript for pandoc with args.manuscript_path.open(\"w\", encoding=\"utf-8\") as write_file: yaml.dump(", "citekeys_df = citekeys_df.sort_values([\"standard_citekey\", \"detagged_citekey\"]) check_collisions(citekeys_df) check_multiple_citation_strings(citekeys_df) return citekeys_df def read_citations_tsv(path)", "an extension to this path, so it is not always", "variables in {path!r} overwrite existing \" \"values for the following", "{key!r} to be a dict.\" f\"Received a {dict_.__class__.__name__!r} instead.\" )", "Process authors metadata if \"author_info\" in metadata: authors = metadata.pop(\"author_info\",", "finished with {len(cache.responses)} cached responses\" ) requests_cache.uninstall_cache() if failures: message", "json import logging import os import pathlib import re import", "file with yaml_metadata_block for pandoc\" ) # Interpreted keys that", "affiliations to a list.\", category=DeprecationWarning, ) author[\"affiliations\"] = author[\"affiliations\"].split(\"; \")", "a shortened citekey \"\"\" citekeys_df = pandas.DataFrame( {\"manuscript_citekey\": list(citekeys)} ).drop_duplicates()", "None: variables = {} for path in paths: logging.info(f\"Reading user-provided", "hard-coded by the user if `metadata.yaml` includes a `manubot` dictionary.", "authors = [] variables[\"pandoc\"][\"author-meta\"] = [author[\"name\"] for author in authors]", "list of affiliation_numbers for each author and add a list", "to `variables` to update an existing dictionary rather than create", "if standard_citekey in manual_refs: csl_items.append(manual_refs[standard_citekey]) continue elif standard_citekey.startswith(\"raw:\"): logging.error( f\"CSL", "encoding=\"utf-8\") as write_file: json.dump(csl_items, write_file, indent=2, ensure_ascii=False) write_file.write(\"\\n\") def template_with_jinja2(text,", "`pandoc` are either generated by Manubot or hard-coded by the", "potential problems. \"\"\" # Read manual references (overrides) in JSON", "= metadata.pop(\"author_info\", []) warnings.warn( \"metadata.yaml: 'author_info' is deprecated. Use 'authors'", "content files. - detagged_citekey: manuscript_citekey but with tag citekeys dereferenced", "{} for path in paths: logging.info(f\"Reading user-provided templating variables at", "f\"{path} contains rows with missing values:\\n\" f\"{na_rows_df}\\n\" \"This error can", "\"\"\" Generate and return citekeys_df. citekeys_df is a pandas.DataFrame with", "return collision_df def check_multiple_citation_strings(citekeys_df): \"\"\" Identify different citation strings referring", "get_manuscript_stats, get_text, ) from manubot.cite.citekey import ( citekey_to_csl_item, shorten_citekey, is_valid_citekey,", "citekeys detected for the same reference:\\n{table}\") return multi_df def read_variable_files(paths:", "if \"affiliations\" not in author: continue if not isinstance(author[\"affiliations\"], list):", ") return citekey_aliases def write_citekeys_tsv(citekeys_df, path): if not path: return", "\"manuscript_citekey\"] ) logging.warning(f\"Multiple citekeys detected for the same reference:\\n{table}\") return", "args.requests_cache_path ) variables[\"pandoc\"][\"manubot-clear-requests-cache\"] = args.clear_requests_cache return variables def get_citekeys_df(citekeys: list,", "a dictionary, refered to as `variables`, with the following keys:", "a `manubot` dictionary. - All fields from a manuscript's `metadata.yaml`", "list() for standard_citekey in citekeys: if standard_citekey in manual_refs: csl_items.append(manual_refs[standard_citekey])", "available for jinja2 templating. Returns a dictionary, refered to as", "manual_refs=manual_refs, requests_cache_path=args.requests_cache_path, clear_requests_cache=args.clear_requests_cache, ) # Write CSL JSON bibliography for", "generated by Manubot or hard-coded by the user if `metadata.yaml`", "= requests_cache.get_cache() if clear_requests_cache: logging.info(\"Clearing requests-cache\") requests_cache.clear() logging.info( f\"requests-cache starting", "{namespace!r} namespace for template variables from {path!r}\" ) try: if", "for CI builds ci_params = get_continuous_integration_parameters() if ci_params: variables[\"manubot\"][\"ci_source\"] =", "= collision_df[collision_df.short_citekey.duplicated(keep=False)] if not collision_df.empty: logging.error(f\"OMF! Hash collision. Congratulations.\\n{collision_df}\") return", "Use 'authors' instead.\", category=DeprecationWarning, ) else: authors = metadata.pop(\"authors\", [])", "User-specified fields inserted according to the `--template-variables-path` option. User-specified variables", "name_to_numbers.get(author[\"name\"], []) variables[\"affiliations\"] = affiliation_df.to_dict(orient=\"records\") return variables def load_variables(args) ->", "Optional import jinja2 import pandas import requests import requests_cache import", "obj = read_serialized_dict(path) except Exception: logging.exception(f\"Error reading template variables from", "items for standard_citekeys in citekeys_df. Parameters: - citekeys: list of", "requests cache database. Passed as cache_name to `requests_cache.install_cache`. requests_cache may", "# Update variables with uninterpreted metadata.yaml fields variables.update(metadata) # Update", "= authors add_author_affiliations(variables[\"manubot\"]) # Set repository version metadata for CI", "following standardized citation keys:\\n{}\".format( \"\\n\".join(failures) ) logging.error(message) return csl_items def", "read_variable_files(args.template_variables_path, variables) # Add header-includes metadata with <meta> information for", "citation tags file at {path} \" \"Not reading citekey_aliases from", "dictionary, refered to as `variables`, with the following keys: -", "table = multi_df.to_string( index=False, columns=[\"standard_citekey\", \"manuscript_citekey\"] ) logging.warning(f\"Multiple citekeys detected", "if `metadata.yaml` includes a `pandoc` dictionary. - `manubot`: a dictionary", "pandoc-manubot-cite option to write bibliography to a file variables[\"pandoc\"][\"manubot-output-bibliography\"] =", "provided, the JSON must contain a dictionary as its top", "citekey_aliases def write_citekeys_tsv(citekeys_df, path): if not path: return citekeys_df.to_csv(path, sep=\"\\t\",", "-> list: \"\"\" General CSL (citeproc) items for standard_citekeys in", "{dict_.__class__.__name__!r} instead.\" ) continue variables[key].update(dict_) # Update variables with uninterpreted", "na_rows_df = tag_df[tag_df.isnull().any(axis=\"columns\")] if not na_rows_df.empty: logging.error( f\"{path} contains rows", "return text def generate_csl_items( citekeys: list, manual_refs: dict = {},", "\") for affiliation in author[\"affiliations\"]: rows.append((author[\"name\"], affiliation)) if not rows:", "paths). Paths can optionally have a namespace prepended. For example:", "= read_serialized_dict(args.meta_yaml_path) else: metadata = {} logging.warning( f\"missing {args.meta_yaml_path} file", "multi_df def read_variable_files(paths: List[str], variables: Optional[dict] = None) -> dict:", "isinstance(bibliographies, str): bibliographies = [bibliographies] assert isinstance(bibliographies, list) bibliographies.extend(args.manual_references_paths) bibliographies", "continue elif standard_citekey.startswith(\"raw:\"): logging.error( f\"CSL JSON Data with a standard_citekey", "# Retrieve CSL Items csl_items = generate_csl_items( citekeys=citekeys_df.standard_citekey.unique(), manual_refs=manual_refs, requests_cache_path=args.requests_cache_path,", "If None, do not use requests_cache. - clear_requests_cache: If True,", "contains pandoc_yaml_metadata # as well as authors information. if args.meta_yaml_path.is_file():", "from the manuscript content files. - detagged_citekey: manuscript_citekey but with", ") tag_df = pandas.read_csv(path, delim_whitespace=True) tag_df[\"manuscript_citekey\"] = \"tag:\" + tag_df.tag", "can be caused by using spaces rather than tabs to", "the requests cache database. Passed as cache_name to `requests_cache.install_cache`. requests_cache", "yaml_metadata_block for pandoc\" ) # Interpreted keys that are intended", "store under 'namespace_1' key 'namespace_2=some_local_path.json', # store under 'namespace_2' key", "variables at {path!r}\") # Match only namespaces that are valid", "{}, \"manubot\": {}} # Read metadata which contains pandoc_yaml_metadata #", "comment_start_string=\"{##\", comment_end_string=\"##}\", extensions=[\"jinja2.ext.do\", \"jinja2.ext.loopcontrols\"], ) template = jinja_environment.from_string(text) return template.render(**variables)", "files specified by `--template-variables-path` to generate manuscript variables available for", "overwrite existing \" \"values for the following keys:\\n\" + \"\\n\".join(conflicts)", "authors add_author_affiliations(variables[\"manubot\"]) # Set repository version metadata for CI builds", "as `variables`, with the following keys: - `pandoc`: a dictionary", "CSL Items to a JSON file at `path`. If `path`", "items for standard_citekeys in citekeys_df. Writes references.json to disk and", "`metadata.yaml` and files specified by `--template-variables-path` to generate manuscript variables", "and logs warnings for potential problems. \"\"\" # Read manual", "to as `variables`, with the following keys: - `pandoc`: a", "\"\"\" if not path: return path = pathlib.Path(path) with path.open(\"w\",", "paragraph into your Markdown content:{text}\" ) return text def generate_csl_items(", "keys: - `pandoc`: a dictionary for passing options to Pandoc", "Pass a dictionary to `variables` to update an existing dictionary", "dict) -> dict: \"\"\" Edit variables to contain numbered author", "None))) # Add software versions variables[\"manubot\"].update(get_software_versions()) # Add thumbnail URL", "= variables.keys() & obj.keys() if conflicts: logging.warning( f\"Template variables in", "read_variable_files(paths: List[str], variables: Optional[dict] = None) -> dict: \"\"\" Read", ") for citation in citekeys_df.detagged_citekey: is_valid_citekey(citation, allow_raw=True) citekeys_df[\"standard_citekey\"] = citekeys_df.detagged_citekey.map(", "{}) if not isinstance(dict_, dict): logging.warning( f\"load_variables expected metadata.yaml field", "datetime: {now.isoformat()}\" ) variables[\"pandoc\"][\"date-meta\"] = now.date().isoformat() variables[\"manubot\"][\"date\"] = f\"{now:%B} {now.day},", "authors is None: authors = [] variables[\"pandoc\"][\"author-meta\"] = [author[\"name\"] for", "`pandoc` or `manubot` (dangerous). \"\"\" # Generated manuscript variables variables", "to the cache. If None, do not use requests_cache. -", "tag_df = tag_df.rename(columns={\"citation\": \"detagged_citekey\"}) citekey_aliases = dict( zip(tag_df[\"manuscript_citekey\"], tag_df[\"detagged_citekey\"]) )", "variables variables = {\"pandoc\": {}, \"manubot\": {}} # Read metadata", "Write CSL Items to a JSON file at `path`. If", "metadata = {} logging.warning( f\"missing {args.meta_yaml_path} file with yaml_metadata_block for", ") -> list: \"\"\" General CSL (citeproc) items for standard_citekeys", "jinja_environment.from_string(text) return template.render(**variables) def prepare_manuscript(args): \"\"\" Compile manuscript, creating manuscript.md", "- requests_cache_path: path for the requests cache database. Passed as", "the top-level of variables. If no authors have any affiliations,", "standardize_citekey, ) def check_collisions(citekeys_df): \"\"\" Check for short_citekey hash collisions", "logging.exception(f\"Citeproc retrieval failure for {standard_citekey!r}\") failures.append(standard_citekey) # Uninstall cache if", "for raw citekeys.\" ) failures.append(standard_citekey) try: csl_item = citekey_to_csl_item(standard_citekey) csl_items.append(csl_item)", "# Write manuscript for pandoc with args.manuscript_path.open(\"w\", encoding=\"utf-8\") as write_file:", "using spaces rather than tabs to delimit fields.\\n\" \"Proceeding to", "with the following keys: - `pandoc`: a dictionary for passing", "= pathlib.Path(path) with path.open(\"w\", encoding=\"utf-8\") as write_file: json.dump(csl_items, write_file, indent=2,", "None: requests # require `import requests` in case this is", "at {path!r}\") # Match only namespaces that are valid jinja2", "thumbnail_url = get_thumbnail_url(metadata.pop(\"thumbnail\", None)) if thumbnail_url: variables[\"manubot\"][\"thumbnail_url\"] = thumbnail_url #", "def _generate_csl_items(args, citekeys_df): \"\"\" General CSL (citeproc) items for standard_citekeys", "template = jinja_environment.from_string(text) return template.render(**variables) def prepare_manuscript(args): \"\"\" Compile manuscript,", "- `manubot`: a dictionary for manubot-related information and metadata. Fields", "alphanumeric characters (includes underscores, first character cannot be numeric). Pass", "requests cache before generating citekey metadata. \"\"\" # Deduplicate citations", "\"\\n\\n\" for key, value in citekey_aliases.items(): text += f\"[@{key}]: {value}\\n\"", "unique citations strings extracted from text {citekeys_df.standard_citekey.nunique()} unique standard citations\\", "\"\"\" Identify different citation strings referring the the same reference.", "be provided for raw citekeys.\" ) failures.append(standard_citekey) try: csl_item =", "namespaces that are valid jinja2 variable names # http://jinja.pocoo.org/docs/2.10/api/#identifier-naming match", "that are valid jinja2 variable names # http://jinja.pocoo.org/docs/2.10/api/#identifier-naming match =", "metadata.yaml fields variables.update(metadata) # Update variables with user-provided variables here", "dict = {}): \"\"\" Generate and return citekeys_df. citekeys_df is", "the {namespace!r} namespace for template variables from {path!r}\" ) try:", "is deprecated. \" f\"Consider deleting citation-tags.tsv and inserting the following", "requests_cache.clear() logging.info( f\"requests-cache starting with {len(cache.responses)} cached responses\" ) csl_items", "as authors information. if args.meta_yaml_path.is_file(): metadata = read_serialized_dict(args.meta_yaml_path) else: metadata", "\"\"\" General CSL (citeproc) items for standard_citekeys in citekeys_df. Parameters:", "( get_header_includes, get_thumbnail_url, get_manuscript_urls, get_software_versions, ) from manubot.process.manuscript import (", "collision_df = collision_df[collision_df.short_citekey.duplicated(keep=False)] if not collision_df.empty: logging.error(f\"OMF! Hash collision. Congratulations.\\n{collision_df}\")", "key 'namespace_2=some_local_path.json', # store under 'namespace_2' key ] ``` If", "author affiliations. Specifically, add a list of affiliation_numbers for each", "`yaml_metadata_block`. Fields in `pandoc` are either generated by Manubot or", "Fields in `manubot` are either generated by Manubot or hard-coded", "new dictionary. \"\"\" if variables is None: variables = {}", "category=DeprecationWarning, ) author[\"affiliations\"] = author[\"affiliations\"].split(\"; \") for affiliation in author[\"affiliations\"]:", "for pandoc. \"\"\" text = get_text(args.content_directory) assert args.skip_citations text +=", "software versions variables[\"manubot\"].update(get_software_versions()) # Add thumbnail URL if present thumbnail_url", "into your Markdown content:{text}\" ) return text def generate_csl_items( citekeys:", "using jinja2 with the variables dictionary unpacked as keyword arguments.", "have a namespace prepended. For example: ```python paths = [", "# Extend Pandoc's metadata.bibliography field with manual references paths bibliographies", "serialized data files into a user_variables dictionary. Provide `paths` (a", "def check_collisions(citekeys_df): \"\"\" Check for short_citekey hash collisions \"\"\" collision_df", "(citeproc) items for standard_citekeys in citekeys_df. Parameters: - citekeys: list", "if present thumbnail_url = get_thumbnail_url(metadata.pop(\"thumbnail\", None)) if thumbnail_url: variables[\"manubot\"][\"thumbnail_url\"] =", "reference link syntax \"\"\" citekey_aliases = read_citations_tsv(args.citation_tags_path) if not citekey_aliases:", "variables = {\"pandoc\": {}, \"manubot\": {}} # Read metadata which", "deprecated. Use 'authors' instead.\", category=DeprecationWarning, ) else: authors = metadata.pop(\"authors\",", "clear_requests_cache=args.clear_requests_cache, ) # Write CSL JSON bibliography for Pandoc. write_csl_json(csl_items,", "pandoc\" ) # Interpreted keys that are intended for pandoc", "list of affiliations to the top-level of variables. If no", "import json import logging import os import pathlib import re", "to a list.\", category=DeprecationWarning, ) author[\"affiliations\"] = author[\"affiliations\"].split(\"; \") for", "\" f\"Consider deleting citation-tags.tsv and inserting the following paragraph into", "author[\"affiliations\"] = author[\"affiliations\"].split(\"; \") for affiliation in author[\"affiliations\"]: rows.append((author[\"name\"], affiliation))", "existing keys like `pandoc` or `manubot` (dangerous). \"\"\" # Generated", "Template using jinja2 with the variables dictionary unpacked as keyword", "if match: namespace, path = match.groups() logging.info( f\"Using the {namespace!r}", "namespace for template variables from {path!r}\" ) try: if match:", "category=DeprecationWarning, ) else: authors = metadata.pop(\"authors\", []) if authors is", "reference:\\n{table}\") return multi_df def read_variable_files(paths: List[str], variables: Optional[dict] = None)", "citations\\ \"\"\" ) logging.info(message) multi_df = citekeys_df[citekeys_df.standard_citekey.duplicated(keep=False)] if not multi_df.empty:", "= pandas.DataFrame(rows, columns=[\"name\", \"affiliation\"]) affiliation_df = affil_map_df[[\"affiliation\"]].drop_duplicates() affiliation_df[\"affiliation_number\"] = range(1,", "f\"{now:%B} {now.day}, {now.year}\" # Process authors metadata if \"author_info\" in", "read_serialized_dict(path) except Exception: logging.exception(f\"Error reading template variables from {path!r}\") continue", "variables.update(metadata) # Update variables with user-provided variables here variables =", "(overrides) in JSON CSL manual_refs = load_manual_references(args.manual_references_paths) # Retrieve CSL", "match: namespace, path = match.groups() logging.info( f\"Using the {namespace!r} namespace", "json.dump(csl_items, write_file, indent=2, ensure_ascii=False) write_file.write(\"\\n\") def template_with_jinja2(text, variables): \"\"\" Template", "variables[\"pandoc\"][\"manubot-output-bibliography\"] = os.fspath(args.references_path) variables[\"pandoc\"][\"manubot-output-citekeys\"] = os.fspath(args.citations_path) variables[\"pandoc\"][\"manubot-requests-cache-path\"] = os.fspath( args.requests_cache_path", "instead.\", category=DeprecationWarning, ) else: authors = metadata.pop(\"authors\", []) if authors", "# Read metadata which contains pandoc_yaml_metadata # as well as", "retrieval failed for the following standardized citation keys:\\n{}\".format( \"\\n\".join(failures) )", "for manubot-related information and metadata. Fields in `manubot` are either", "message = \"CSL JSON Data retrieval failed for the following", "manubot.process.bibliography import load_manual_references from manubot.process.ci import get_continuous_integration_parameters from manubot.process.metadata import", "f\"Reading user-provided templating variables complete:\\n\" f\"{json.dumps(variables, indent=2, ensure_ascii=False)}\" ) return", "`thumbnail`. - User-specified fields inserted according to the `--template-variables-path` option.", "clear_requests_cache: logging.info(\"Clearing requests-cache\") requests_cache.clear() logging.info( f\"requests-cache starting with {len(cache.responses)} cached", "store under 'namespace_2' key ] ``` If a namespace is", "ci_params # Add manuscript URLs variables[\"manubot\"].update(get_manuscript_urls(metadata.pop(\"html_url\", None))) # Add software", "# Update variables with user-provided variables here variables = read_variable_files(args.template_variables_path,", "is left unmodified. \"\"\" rows = list() for author in", "but with tag citekeys dereferenced - standard_citekey: detagged_citekey standardized -", "Read `metadata.yaml` and files specified by `--template-variables-path` to generate manuscript", "write_csl_json(csl_items, args.references_path) return csl_items def write_csl_json(csl_items, path): \"\"\" Write CSL", "citekey_aliases: return \"\" text = \"\\n\\n\" for key, value in", "in affil_map_df.groupby(\"name\") } for author in variables[\"authors\"]: author[\"affiliation_numbers\"] = name_to_numbers.get(author[\"name\"],", "for potential problems. \"\"\" # Read manual references (overrides) in", "is deprecated. Use 'authors' instead.\", category=DeprecationWarning, ) else: authors =", "with {len(cache.responses)} cached responses\" ) csl_items = list() failures =", "csl_item for manual references - requests_cache_path: path for the requests", "to `requests_cache.install_cache`. requests_cache may append an extension to this path,", "for pandoc move_to_pandoc = \"title\", \"keywords\", \"lang\" for key in", "= get_text(args.content_directory) assert args.skip_citations text += _citation_tags_to_reference_links(args) variables = load_variables(args)", "# Add date to metadata now = datetime_now() logging.info( f\"Using", "according to the `--template-variables-path` option. User-specified variables take highest precedence", "file at {path} \" \"Not reading citekey_aliases from citation-tags.tsv.\" )", "versions variables[\"manubot\"].update(get_software_versions()) # Add thumbnail URL if present thumbnail_url =", "affiliation_numbers for each author and add a list of affiliations", "text = \"\\n\\n\" for key, value in citekey_aliases.items(): text +=", "write_file, indent=2, ensure_ascii=False) write_file.write(\"\\n\") def template_with_jinja2(text, variables): \"\"\" Template using", ") logging.info(message) multi_df = citekeys_df[citekeys_df.standard_citekey.duplicated(keep=False)] if not multi_df.empty: table =", "author[\"affiliation_numbers\"] = name_to_numbers.get(author[\"name\"], []) variables[\"affiliations\"] = affiliation_df.to_dict(orient=\"records\") return variables def", "# require `import requests` in case this is essential for", "not rows: return variables affil_map_df = pandas.DataFrame(rows, columns=[\"name\", \"affiliation\"]) affiliation_df", "citekeys_df.to_csv(path, sep=\"\\t\", index=False) def _citation_tags_to_reference_links(args) -> str: \"\"\" Convert citation-tags.tsv", "variables[\"manubot\"][\"ci_source\"] = ci_params # Add manuscript URLs variables[\"manubot\"].update(get_manuscript_urls(metadata.pop(\"html_url\", None))) #", "citekeys_df.detagged_citekey.map( standardize_citekey ) citekeys_df[\"short_citekey\"] = citekeys_df.standard_citekey.map(shorten_citekey) citekeys_df = citekeys_df.sort_values([\"standard_citekey\", \"detagged_citekey\"])", "if not isinstance(dict_, dict): logging.warning( f\"load_variables expected metadata.yaml field {key!r}", "bibliography to a file variables[\"pandoc\"][\"manubot-output-bibliography\"] = os.fspath(args.references_path) variables[\"pandoc\"][\"manubot-output-citekeys\"] = os.fspath(args.citations_path)", "sep=\"\\t\") na_rows_df = tag_df[tag_df.isnull().any(axis=\"columns\")] if not na_rows_df.empty: logging.error( f\"{path} contains", "the the same reference. \"\"\" message = textwrap.dedent( f\"\"\"\\ {len(citekeys_df)}", "Compile manuscript, creating manuscript.md and references.json as inputs for pandoc.", "citation strings referring the the same reference. \"\"\" message =", "= citekey_to_csl_item(standard_citekey) csl_items.append(csl_item) except Exception: logging.exception(f\"Citeproc retrieval failure for {standard_citekey!r}\")", "are `; ` separated. \" f\"Please switch affiliations to a", "list for {author['name']}'s affiliations. \" f\"Assuming multiple affiliations are `;", "clear the requests cache before generating citekey metadata. \"\"\" #", "assert isinstance(obj, dict) conflicts = variables.keys() & obj.keys() if conflicts:", "user-provided templating variables complete:\\n\" f\"{json.dumps(variables, indent=2, ensure_ascii=False)}\" ) return variables", "values:\\n\" f\"{na_rows_df}\\n\" \"This error can be caused by using spaces", "= citekeys_df[[\"standard_citekey\", \"short_citekey\"]].drop_duplicates() collision_df = collision_df[collision_df.short_citekey.duplicated(keep=False)] if not collision_df.empty: logging.error(f\"OMF!", "variables[\"manubot\"][\"thumbnail_url\"] = thumbnail_url # Update variables with metadata.yaml pandoc/manubot dicts", "Items to a JSON file at `path`. If `path` evaluates", "path in paths: logging.info(f\"Reading user-provided templating variables at {path!r}\") #", ") try: if match: obj = {namespace: read_serialized_data(path)} else: obj", "manual_refs: mapping from standard_citekey to csl_item for manual references -", "referring the the same reference. \"\"\" message = textwrap.dedent( f\"\"\"\\", "logging.warning( f\"missing {args.meta_yaml_path} file with yaml_metadata_block for pandoc\" ) #", "HTML output's <head> variables[\"pandoc\"][\"header-includes\"] = get_header_includes(variables) assert args.skip_citations # Extend", "and add a list of affiliations to the top-level of", "read_serialized_data(path)} else: obj = read_serialized_dict(path) except Exception: logging.exception(f\"Error reading template", "text += f\"[@{key}]: {value}\\n\" logging.warning( \"citation-tags.tsv is deprecated. \" f\"Consider", "- short_citekey: standard_citekey hashed to create a shortened citekey \"\"\"", "affiliations are `; ` separated. \" f\"Please switch affiliations to", "of {standard_citekey!r} not found in manual-references.json. \" \"Metadata must be", "\"\"\" rows = list() for author in variables[\"authors\"]: if \"affiliations\"", "import requests import requests_cache import yaml from manubot.util import read_serialized_data,", "rows: return variables affil_map_df = pandas.DataFrame(rows, columns=[\"name\", \"affiliation\"]) affiliation_df =", "author: continue if not isinstance(author[\"affiliations\"], list): warnings.warn( f\"Expected list for", "Exception: logging.exception(f\"Citeproc retrieval failure for {standard_citekey!r}\") failures.append(standard_citekey) # Uninstall cache", "affiliations. Specifically, add a list of affiliation_numbers for each author", "-> dict: \"\"\" Edit variables to contain numbered author affiliations.", "standard citations\\ \"\"\" ) logging.info(message) multi_df = citekeys_df[citekeys_df.standard_citekey.duplicated(keep=False)] if not", "citation-tags.tsv.\" ) return {} tag_df = pandas.read_csv(path, sep=\"\\t\") na_rows_df =", "affiliation_df = affil_map_df[[\"affiliation\"]].drop_duplicates() affiliation_df[\"affiliation_number\"] = range(1, 1 + len(affiliation_df)) affil_map_df", "if not isinstance(author[\"affiliations\"], list): warnings.warn( f\"Expected list for {author['name']}'s affiliations.", "of URLs or local file paths). Paths can optionally have", "'authors' instead.\", category=DeprecationWarning, ) else: authors = metadata.pop(\"authors\", []) if", "undefined=jinja2.make_logging_undefined(logging.getLogger()), autoescape=False, comment_start_string=\"{##\", comment_end_string=\"##}\", extensions=[\"jinja2.ext.do\", \"jinja2.ext.loopcontrols\"], ) template = jinja_environment.from_string(text)", "a dictionary for passing options to Pandoc via the `yaml_metadata_block`.", "tag_df = pandas.read_csv(path, delim_whitespace=True) tag_df[\"manuscript_citekey\"] = \"tag:\" + tag_df.tag tag_df", "citekeys.\" ) failures.append(standard_citekey) try: csl_item = citekey_to_csl_item(standard_citekey) csl_items.append(csl_item) except Exception:", "add a list of affiliation_numbers for each author and add", "variables[\"pandoc\"].get(\"bibliography\", []) if isinstance(bibliographies, str): bibliographies = [bibliographies] assert isinstance(bibliographies,", "top level. Namespaces should consist only of ASCII alphanumeric characters", "\"\"\" Read citekey aliases from a citation-tags.tsv file. \"\"\" if", "= jinja2.Environment( loader=jinja2.BaseLoader(), undefined=jinja2.make_logging_undefined(logging.getLogger()), autoescape=False, comment_start_string=\"{##\", comment_end_string=\"##}\", extensions=[\"jinja2.ext.do\", \"jinja2.ext.loopcontrols\"], )", "list(map(os.fspath, bibliographies)) variables[\"pandoc\"][\"bibliography\"] = bibliographies # enable pandoc-manubot-cite option to", "dictionary for passing options to Pandoc via the `yaml_metadata_block`. Fields", "patching by requests_cache. requests_cache.install_cache(requests_cache_path, include_get_headers=True) cache = requests_cache.get_cache() if clear_requests_cache:", "logging.info(message) multi_df = citekeys_df[citekeys_df.standard_citekey.duplicated(keep=False)] if not multi_df.empty: table = multi_df.to_string(", "affiliation)) if not rows: return variables affil_map_df = pandas.DataFrame(rows, columns=[\"name\",", "requests` in case this is essential for monkey patching by", "standard_citekey of {standard_citekey!r} not found in manual-references.json. \" \"Metadata must", "to a file variables[\"pandoc\"][\"manubot-output-bibliography\"] = os.fspath(args.references_path) variables[\"pandoc\"][\"manubot-output-citekeys\"] = os.fspath(args.citations_path) variables[\"pandoc\"][\"manubot-requests-cache-path\"]", "= citekeys_df.sort_values([\"standard_citekey\", \"detagged_citekey\"]) check_collisions(citekeys_df) check_multiple_citation_strings(citekeys_df) return citekeys_df def read_citations_tsv(path) ->", "can overwrite values for existing keys like `pandoc` or `manubot`", "contains rows with missing values:\\n\" f\"{na_rows_df}\\n\" \"This error can be", "str): bibliographies = [bibliographies] assert isinstance(bibliographies, list) bibliographies.extend(args.manual_references_paths) bibliographies =", "any affiliations, variables is left unmodified. \"\"\" rows = list()", "\"This error can be caused by using spaces rather than", "Add software versions variables[\"manubot\"].update(get_software_versions()) # Add thumbnail URL if present", "\"\\n\".join(conflicts) ) variables.update(obj) logging.debug( f\"Reading user-provided templating variables complete:\\n\" f\"{json.dumps(variables,", "read_serialized_dict from manubot.process.bibliography import load_manual_references from manubot.process.ci import get_continuous_integration_parameters from", "keys:\\n\" + \"\\n\".join(conflicts) ) variables.update(obj) logging.debug( f\"Reading user-provided templating variables", "for key in \"pandoc\", \"manubot\": dict_ = metadata.pop(key, {}) if", "} for author in variables[\"authors\"]: author[\"affiliation_numbers\"] = name_to_numbers.get(author[\"name\"], []) variables[\"affiliations\"]", "= { name: sorted(df.affiliation_number) for name, df in affil_map_df.groupby(\"name\") }", "Markdown content:{text}\" ) return text def generate_csl_items( citekeys: list, manual_refs:", "= metadata.pop(\"authors\", []) if authors is None: authors = []", "`manubot`, `title`, `keywords`, `authors` (formerly `author_info`, now deprecated), `lang`, and", "Interpreted keys that are intended for pandoc move_to_pandoc = \"title\",", "(includes underscores, first character cannot be numeric). Pass a dictionary", "manuscript for pandoc with args.manuscript_path.open(\"w\", encoding=\"utf-8\") as write_file: yaml.dump( variables[\"pandoc\"],", "\"\"\" ) logging.info(message) multi_df = citekeys_df[citekeys_df.standard_citekey.duplicated(keep=False)] if not multi_df.empty: table", "citekeys_df[\"short_citekey\"] = citekeys_df.standard_citekey.map(shorten_citekey) citekeys_df = citekeys_df.sort_values([\"standard_citekey\", \"detagged_citekey\"]) check_collisions(citekeys_df) check_multiple_citation_strings(citekeys_df) return", "the requests cache before generating citekey metadata. \"\"\" # Deduplicate", "warnings for potential problems. \"\"\" # Read manual references (overrides)", "dictionary rather than create a new dictionary. \"\"\" if variables", "same reference:\\n{table}\") return multi_df def read_variable_files(paths: List[str], variables: Optional[dict] =", "precedence and can overwrite values for existing keys like `pandoc`", "variables with user-provided variables here variables = read_variable_files(args.template_variables_path, variables) #", "def load_variables(args) -> dict: \"\"\" Read `metadata.yaml` and files specified", "\"\"\" Read `metadata.yaml` and files specified by `--template-variables-path` to generate", "return variables def get_citekeys_df(citekeys: list, citekey_aliases: dict = {}): \"\"\"", "& obj.keys() if conflicts: logging.warning( f\"Template variables in {path!r} overwrite", "the `--template-variables-path` option. User-specified variables take highest precedence and can", "warnings.warn( f\"Expected list for {author['name']}'s affiliations. \" f\"Assuming multiple affiliations", "variables[\"pandoc\"][\"manubot-clear-requests-cache\"] = args.clear_requests_cache return variables def get_citekeys_df(citekeys: list, citekey_aliases: dict", "path) if match: namespace, path = match.groups() logging.info( f\"Using the", "= affil_map_df[[\"affiliation\"]].drop_duplicates() affiliation_df[\"affiliation_number\"] = range(1, 1 + len(affiliation_df)) affil_map_df =", "keyword arguments. \"\"\" jinja_environment = jinja2.Environment( loader=jinja2.BaseLoader(), undefined=jinja2.make_logging_undefined(logging.getLogger()), autoescape=False, comment_start_string=\"{##\",", "read_citations_tsv(path) -> dict: \"\"\" Read citekey aliases from a citation-tags.tsv", "= bibliographies # enable pandoc-manubot-cite option to write bibliography to", "in citekey_aliases.items(): text += f\"[@{key}]: {value}\\n\" logging.warning( \"citation-tags.tsv is deprecated.", "must contain a dictionary as its top level. Namespaces should", "manuscript's `metadata.yaml` that are not interpreted by Manubot are copied", "than create a new dictionary. \"\"\" if variables is None:", "# Write CSL JSON bibliography for Pandoc. write_csl_json(csl_items, args.references_path) return", "and metadata. Fields in `manubot` are either generated by Manubot", "logging.warning( f\"load_variables expected metadata.yaml field {key!r} to be a dict.\"", "manuscript URLs variables[\"manubot\"].update(get_manuscript_urls(metadata.pop(\"html_url\", None))) # Add software versions variables[\"manubot\"].update(get_software_versions()) #", "variables = {} for path in paths: logging.info(f\"Reading user-provided templating", "namespace is not provided, the JSON must contain a dictionary", "options to Pandoc via the `yaml_metadata_block`. Fields in `pandoc` are", "f\"requests-cache finished with {len(cache.responses)} cached responses\" ) requests_cache.uninstall_cache() if failures:", "datetime_now() logging.info( f\"Using {now:%Z} timezone.\\n\" f\"Dating manuscript with the current", "{} tag_df = pandas.read_csv(path, sep=\"\\t\") na_rows_df = tag_df[tag_df.isnull().any(axis=\"columns\")] if not", "+= f\"[@{key}]: {value}\\n\" logging.warning( \"citation-tags.tsv is deprecated. \" f\"Consider deleting", "`pandoc` dictionary. - `manubot`: a dictionary for manubot-related information and", "= jinja_environment.from_string(text) return template.render(**variables) def prepare_manuscript(args): \"\"\" Compile manuscript, creating", "variables from {path!r}\") continue assert isinstance(obj, dict) conflicts = variables.keys()", "logging.info( f\"Using {now:%Z} timezone.\\n\" f\"Dating manuscript with the current datetime:", "requests_cache.install_cache(requests_cache_path, include_get_headers=True) cache = requests_cache.get_cache() if clear_requests_cache: logging.info(\"Clearing requests-cache\") requests_cache.clear()", "missing values:\\n\" f\"{na_rows_df}\\n\" \"This error can be caused by using", "citekeys_df = pandas.DataFrame( {\"manuscript_citekey\": list(citekeys)} ).drop_duplicates() citekeys_df[\"detagged_citekey\"] = citekeys_df.manuscript_citekey.map( lambda", "references.json as inputs for pandoc. \"\"\" text = get_text(args.content_directory) assert", "from manubot.cite.citekey import ( citekey_to_csl_item, shorten_citekey, is_valid_citekey, standardize_citekey, ) def", "template variables from {path!r}\" ) try: if match: obj =", ") def check_collisions(citekeys_df): \"\"\" Check for short_citekey hash collisions \"\"\"", "\"CSL JSON Data retrieval failed for the following standardized citation", "import get_continuous_integration_parameters from manubot.process.metadata import ( get_header_includes, get_thumbnail_url, get_manuscript_urls, get_software_versions,", "ensure_ascii=False, indent=2) write_file.write(\"\\n\") text = template_with_jinja2(text, variables) # Write manuscript", "cache if requests_cache_path is not None: logging.info( f\"requests-cache finished with", "a `pandoc` dictionary. - `manubot`: a dictionary for manubot-related information", "[]) variables[\"affiliations\"] = affiliation_df.to_dict(orient=\"records\") return variables def load_variables(args) -> dict:", "key ] ``` If a namespace is not provided, the", "def read_variable_files(paths: List[str], variables: Optional[dict] = None) -> dict: \"\"\"", "- standard_citekey: detagged_citekey standardized - short_citekey: standard_citekey hashed to create", "= match.groups() logging.info( f\"Using the {namespace!r} namespace for template variables", "obj = {namespace: read_serialized_data(path)} else: obj = read_serialized_dict(path) except Exception:", "cache. If None, do not use requests_cache. - clear_requests_cache: If", "to the top-level of variables. If no authors have any", "dict = {}, requests_cache_path: Optional[str] = None, clear_requests_cache: Optional[bool] =", "f\"[@{key}]: {value}\\n\" logging.warning( \"citation-tags.tsv is deprecated. \" f\"Consider deleting citation-tags.tsv", "indent=2, ensure_ascii=False) write_file.write(\"\\n\") def template_with_jinja2(text, variables): \"\"\" Template using jinja2", "exact path to the cache. If None, do not use", "with a standard_citekey of {standard_citekey!r} not found in manual-references.json. \"", "[]) if authors is None: authors = [] variables[\"pandoc\"][\"author-meta\"] =", "database. Passed as cache_name to `requests_cache.install_cache`. requests_cache may append an", "isinstance(bibliographies, list) bibliographies.extend(args.manual_references_paths) bibliographies = list(map(os.fspath, bibliographies)) variables[\"pandoc\"][\"bibliography\"] = bibliographies", "metadata. \"\"\" # Deduplicate citations citekeys = list(dict.fromkeys(citekeys)) # Install", "= dict( zip(tag_df[\"manuscript_citekey\"], tag_df[\"detagged_citekey\"]) ) return citekey_aliases def write_citekeys_tsv(citekeys_df, path):", "isinstance(dict_, dict): logging.warning( f\"load_variables expected metadata.yaml field {key!r} to be", "requests # require `import requests` in case this is essential", "` separated. \" f\"Please switch affiliations to a list.\", category=DeprecationWarning,", "specified by `--template-variables-path` to generate manuscript variables available for jinja2", "affil_map_df = affil_map_df.merge(affiliation_df) name_to_numbers = { name: sorted(df.affiliation_number) for name,", "append an extension to this path, so it is not", "a manuscript's `metadata.yaml` that are not interpreted by Manubot are", "paths = [ 'https://git.io/vbkqm', # update the dictionary's top-level 'namespace_1=https://git.io/vbkqm',", "citekeys=citekeys_df.standard_citekey.unique(), manual_refs=manual_refs, requests_cache_path=args.requests_cache_path, clear_requests_cache=args.clear_requests_cache, ) # Write CSL JSON bibliography", "key in move_to_pandoc: if key in metadata: variables[\"pandoc\"][key] = metadata.pop(key)", "variables is left unmodified. \"\"\" rows = list() for author", "`manubot` dictionary. - All fields from a manuscript's `metadata.yaml` that", "{path!r} overwrite existing \" \"values for the following keys:\\n\" +", "with missing values:\\n\" f\"{na_rows_df}\\n\" \"This error can be caused by", "= get_continuous_integration_parameters() if ci_params: variables[\"manubot\"][\"ci_source\"] = ci_params # Add manuscript", "by Manubot or hard-coded by the user if `metadata.yaml` includes", "else: authors = metadata.pop(\"authors\", []) if authors is None: authors", "starting with {len(cache.responses)} cached responses\" ) csl_items = list() failures", "optionally have a namespace prepended. For example: ```python paths =", "f\"Assuming multiple affiliations are `; ` separated. \" f\"Please switch", "affil_map_df.groupby(\"name\") } for author in variables[\"authors\"]: author[\"affiliation_numbers\"] = name_to_numbers.get(author[\"name\"], [])", "import ( citekey_to_csl_item, shorten_citekey, is_valid_citekey, standardize_citekey, ) def check_collisions(citekeys_df): \"\"\"", "requests-cache\") requests_cache.clear() logging.info( f\"requests-cache starting with {len(cache.responses)} cached responses\" )", "import re import textwrap import warnings from typing import List,", "Update variables with user-provided variables here variables = read_variable_files(args.template_variables_path, variables)", "dict( zip(tag_df[\"manuscript_citekey\"], tag_df[\"detagged_citekey\"]) ) return citekey_aliases def write_citekeys_tsv(citekeys_df, path): if", "in JSON CSL manual_refs = load_manual_references(args.manual_references_paths) # Retrieve CSL Items", "None: authors = [] variables[\"pandoc\"][\"author-meta\"] = [author[\"name\"] for author in", "= tag_df[tag_df.isnull().any(axis=\"columns\")] if not na_rows_df.empty: logging.error( f\"{path} contains rows with", "metadata.yaml pandoc/manubot dicts for key in \"pandoc\", \"manubot\": dict_ =", "variables: Optional[dict] = None) -> dict: \"\"\" Read multiple serialized", "{path!r}\") continue assert isinstance(obj, dict) conflicts = variables.keys() & obj.keys()", "`manubot` (dangerous). \"\"\" # Generated manuscript variables variables = {\"pandoc\":", "citekeys_df is a pandas.DataFrame with the following columns: - manuscript_citekey:", "variables[\"pandoc\"][\"manubot-output-citekeys\"] = os.fspath(args.citations_path) variables[\"pandoc\"][\"manubot-requests-cache-path\"] = os.fspath( args.requests_cache_path ) variables[\"pandoc\"][\"manubot-clear-requests-cache\"] =", "variables here variables = read_variable_files(args.template_variables_path, variables) # Add header-includes metadata", "templating variables complete:\\n\" f\"{json.dumps(variables, indent=2, ensure_ascii=False)}\" ) return variables def", "write_file, ensure_ascii=False, indent=2) write_file.write(\"\\n\") text = template_with_jinja2(text, variables) # Write", "dictionary unpacked as keyword arguments. \"\"\" jinja_environment = jinja2.Environment( loader=jinja2.BaseLoader(),", "# Add header-includes metadata with <meta> information for the HTML", "extracted from text {citekeys_df.standard_citekey.nunique()} unique standard citations\\ \"\"\" ) logging.info(message)", "for jinja2 templating. Returns a dictionary, refered to as `variables`,", "inserting the following paragraph into your Markdown content:{text}\" ) return", "{\"pandoc\": {}, \"manubot\": {}} # Read metadata which contains pandoc_yaml_metadata", "citekeys dereferenced - standard_citekey: detagged_citekey standardized - short_citekey: standard_citekey hashed", "= f\"{now:%B} {now.day}, {now.year}\" # Process authors metadata if \"author_info\"", "\"pandoc\", \"manubot\": dict_ = metadata.pop(key, {}) if not isinstance(dict_, dict):", "if clear_requests_cache: logging.info(\"Clearing requests-cache\") requests_cache.clear() logging.info( f\"requests-cache starting with {len(cache.responses)}", "markdown reference link syntax \"\"\" citekey_aliases = read_citations_tsv(args.citation_tags_path) if not", "move_to_pandoc: if key in metadata: variables[\"pandoc\"][key] = metadata.pop(key) # Add", "the following columns: - manuscript_citekey: citation keys extracted from the", "= metadata.pop(key, {}) if not isinstance(dict_, dict): logging.warning( f\"load_variables expected", "[] variables[\"pandoc\"][\"author-meta\"] = [author[\"name\"] for author in authors] variables[\"manubot\"][\"authors\"] =", "with yaml_metadata_block for pandoc\" ) # Interpreted keys that are", "deprecated), `lang`, and `thumbnail`. - User-specified fields inserted according to", "f\"{na_rows_df}\\n\" \"This error can be caused by using spaces rather", "json.dump(variables, write_file, ensure_ascii=False, indent=2) write_file.write(\"\\n\") text = template_with_jinja2(text, variables) #", "Edit variables to contain numbered author affiliations. Specifically, add a", "under 'namespace_2' key ] ``` If a namespace is not", "{}, requests_cache_path: Optional[str] = None, clear_requests_cache: Optional[bool] = False, )", "detagged_citekey standardized - short_citekey: standard_citekey hashed to create a shortened", "f\"requests-cache starting with {len(cache.responses)} cached responses\" ) csl_items = list()", "key, value in citekey_aliases.items(): text += f\"[@{key}]: {value}\\n\" logging.warning( \"citation-tags.tsv", "if ci_params: variables[\"manubot\"][\"ci_source\"] = ci_params # Add manuscript URLs variables[\"manubot\"].update(get_manuscript_urls(metadata.pop(\"html_url\",", "Items csl_items = generate_csl_items( citekeys=citekeys_df.standard_citekey.unique(), manual_refs=manual_refs, requests_cache_path=args.requests_cache_path, clear_requests_cache=args.clear_requests_cache, ) #", "'author_info' is deprecated. Use 'authors' instead.\", category=DeprecationWarning, ) else: authors", "CSL Items csl_items = generate_csl_items( citekeys=citekeys_df.standard_citekey.unique(), manual_refs=manual_refs, requests_cache_path=args.requests_cache_path, clear_requests_cache=args.clear_requests_cache, )", "= list() failures = list() for standard_citekey in citekeys: if", "= {namespace: read_serialized_data(path)} else: obj = read_serialized_dict(path) except Exception: logging.exception(f\"Error", "in authors] variables[\"manubot\"][\"authors\"] = authors add_author_affiliations(variables[\"manubot\"]) # Set repository version", "require `import requests` in case this is essential for monkey", "[author[\"name\"] for author in authors] variables[\"manubot\"][\"authors\"] = authors add_author_affiliations(variables[\"manubot\"]) #", "Paths can optionally have a namespace prepended. For example: ```python", "Hash collision. Congratulations.\\n{collision_df}\") return collision_df def check_multiple_citation_strings(citekeys_df): \"\"\" Identify different", ") # Write CSL JSON bibliography for Pandoc. write_csl_json(csl_items, args.references_path)", "create a new dictionary. \"\"\" if variables is None: variables", "syntax \"\"\" citekey_aliases = read_citations_tsv(args.citation_tags_path) if not citekey_aliases: return \"\"", "include_get_headers=True) cache = requests_cache.get_cache() if clear_requests_cache: logging.info(\"Clearing requests-cache\") requests_cache.clear() logging.info(", "variables = load_variables(args) variables[\"manubot\"][\"manuscript_stats\"] = get_manuscript_stats(text) with args.variables_path.open(\"w\", encoding=\"utf-8\") as", "\"\"\" # Generated manuscript variables variables = {\"pandoc\": {}, \"manubot\":", "'namespace_2' key ] ``` If a namespace is not provided,", "and files specified by `--template-variables-path` to generate manuscript variables available", "to metadata now = datetime_now() logging.info( f\"Using {now:%Z} timezone.\\n\" f\"Dating", "authors = metadata.pop(\"author_info\", []) warnings.warn( \"metadata.yaml: 'author_info' is deprecated. Use", "a standard_citekey of {standard_citekey!r} not found in manual-references.json. \" \"Metadata", "manubot.process.manuscript import ( datetime_now, get_manuscript_stats, get_text, ) from manubot.cite.citekey import", "not path: return path = pathlib.Path(path) with path.open(\"w\", encoding=\"utf-8\") as", "in manual-references.json. \" \"Metadata must be provided for raw citekeys.\"", "in \"pandoc\", \"manubot\": dict_ = metadata.pop(key, {}) if not isinstance(dict_,", "{path!r}\") # Match only namespaces that are valid jinja2 variable", "indent=2) write_file.write(\"\\n\") text = template_with_jinja2(text, variables) # Write manuscript for", "manuscript content files. - detagged_citekey: manuscript_citekey but with tag citekeys", "load_variables(args) -> dict: \"\"\" Read `metadata.yaml` and files specified by", "False, do nothing. \"\"\" if not path: return path =", "to reread TSV with delim_whitespace=True.\" ) tag_df = pandas.read_csv(path, delim_whitespace=True)", "if not citekey_aliases: return \"\" text = \"\\n\\n\" for key,", "manubot.process.metadata import ( get_header_includes, get_thumbnail_url, get_manuscript_urls, get_software_versions, ) from manubot.process.manuscript", "not interpreted by Manubot are copied to `variables`. Interpreted fields", "\" f\"Assuming multiple affiliations are `; ` separated. \" f\"Please", "Read citekey aliases from a citation-tags.tsv file. \"\"\" if not", "aliases from a citation-tags.tsv file. \"\"\" if not path.is_file(): logging.info(", "import pathlib import re import textwrap import warnings from typing", "\"manubot\": dict_ = metadata.pop(key, {}) if not isinstance(dict_, dict): logging.warning(", "def template_with_jinja2(text, variables): \"\"\" Template using jinja2 with the variables", "f\"Received a {dict_.__class__.__name__!r} instead.\" ) continue variables[key].update(dict_) # Update variables", "user if `metadata.yaml` includes a `pandoc` dictionary. - `manubot`: a", "case this is essential for monkey patching by requests_cache. requests_cache.install_cache(requests_cache_path,", "variables is None: variables = {} for path in paths:", "authors = metadata.pop(\"authors\", []) if authors is None: authors =", "get_continuous_integration_parameters from manubot.process.metadata import ( get_header_includes, get_thumbnail_url, get_manuscript_urls, get_software_versions, )", "def write_citekeys_tsv(citekeys_df, path): if not path: return citekeys_df.to_csv(path, sep=\"\\t\", index=False)", "return citekeys_df.to_csv(path, sep=\"\\t\", index=False) def _citation_tags_to_reference_links(args) -> str: \"\"\" Convert", "sorted(df.affiliation_number) for name, df in affil_map_df.groupby(\"name\") } for author in", "For example: ```python paths = [ 'https://git.io/vbkqm', # update the", "Install cache if requests_cache_path is not None: requests # require", "in manual_refs: csl_items.append(manual_refs[standard_citekey]) continue elif standard_citekey.startswith(\"raw:\"): logging.error( f\"CSL JSON Data", "[]) warnings.warn( \"metadata.yaml: 'author_info' is deprecated. Use 'authors' instead.\", category=DeprecationWarning,", "load_manual_references from manubot.process.ci import get_continuous_integration_parameters from manubot.process.metadata import ( get_header_includes,", "information. if args.meta_yaml_path.is_file(): metadata = read_serialized_dict(args.meta_yaml_path) else: metadata = {}", "= affiliation_df.to_dict(orient=\"records\") return variables def load_variables(args) -> dict: \"\"\" Read", "metadata = read_serialized_dict(args.meta_yaml_path) else: metadata = {} logging.warning( f\"missing {args.meta_yaml_path}", "move_to_pandoc = \"title\", \"keywords\", \"lang\" for key in move_to_pandoc: if", "not None: requests # require `import requests` in case this", "the same reference. \"\"\" message = textwrap.dedent( f\"\"\"\\ {len(citekeys_df)} unique", "JSON Data with a standard_citekey of {standard_citekey!r} not found in", "(a list of URLs or local file paths). Paths can", "(dangerous). \"\"\" # Generated manuscript variables variables = {\"pandoc\": {},", "\"affiliations\" not in author: continue if not isinstance(author[\"affiliations\"], list): warnings.warn(", "requests_cache import yaml from manubot.util import read_serialized_data, read_serialized_dict from manubot.process.bibliography", "args.variables_path.open(\"w\", encoding=\"utf-8\") as write_file: json.dump(variables, write_file, ensure_ascii=False, indent=2) write_file.write(\"\\n\") text", "path: return citekeys_df.to_csv(path, sep=\"\\t\", index=False) def _citation_tags_to_reference_links(args) -> str: \"\"\"", "following keys:\\n\" + \"\\n\".join(conflicts) ) variables.update(obj) logging.debug( f\"Reading user-provided templating", "citekeys_df. citekeys_df is a pandas.DataFrame with the following columns: -", "= author[\"affiliations\"].split(\"; \") for affiliation in author[\"affiliations\"]: rows.append((author[\"name\"], affiliation)) if", "Optional[dict] = None) -> dict: \"\"\" Read multiple serialized data", "= os.fspath(args.references_path) variables[\"pandoc\"][\"manubot-output-citekeys\"] = os.fspath(args.citations_path) variables[\"pandoc\"][\"manubot-requests-cache-path\"] = os.fspath( args.requests_cache_path )", "a citation-tags.tsv file. \"\"\" if not path.is_file(): logging.info( f\"no citation", "text def generate_csl_items( citekeys: list, manual_refs: dict = {}, requests_cache_path:", "are copied to `variables`. Interpreted fields include `pandoc`, `manubot`, `title`,", "citekey metadata. \"\"\" # Deduplicate citations citekeys = list(dict.fromkeys(citekeys)) #", "citations citekeys = list(dict.fromkeys(citekeys)) # Install cache if requests_cache_path is", "take highest precedence and can overwrite values for existing keys", "- User-specified fields inserted according to the `--template-variables-path` option. User-specified", "na_rows_df.empty: logging.error( f\"{path} contains rows with missing values:\\n\" f\"{na_rows_df}\\n\" \"This", "different citation strings referring the the same reference. \"\"\" message", "Manubot are copied to `variables`. Interpreted fields include `pandoc`, `manubot`,", "ci_params: variables[\"manubot\"][\"ci_source\"] = ci_params # Add manuscript URLs variables[\"manubot\"].update(get_manuscript_urls(metadata.pop(\"html_url\", None)))", "from manubot.process.bibliography import load_manual_references from manubot.process.ci import get_continuous_integration_parameters from manubot.process.metadata", "from standard_citekey to csl_item for manual references - requests_cache_path: path", "autoescape=False, comment_start_string=\"{##\", comment_end_string=\"##}\", extensions=[\"jinja2.ext.do\", \"jinja2.ext.loopcontrols\"], ) template = jinja_environment.from_string(text) return", "\"keywords\", \"lang\" for key in move_to_pandoc: if key in metadata:", "= [author[\"name\"] for author in authors] variables[\"manubot\"][\"authors\"] = authors add_author_affiliations(variables[\"manubot\"])", "collision_df.empty: logging.error(f\"OMF! Hash collision. Congratulations.\\n{collision_df}\") return collision_df def check_multiple_citation_strings(citekeys_df): \"\"\"", "jinja2 templating. Returns a dictionary, refered to as `variables`, with", "'https://git.io/vbkqm', # update the dictionary's top-level 'namespace_1=https://git.io/vbkqm', # store under", "rather than create a new dictionary. \"\"\" if variables is", "affiliations to the top-level of variables. If no authors have", "metadata.yaml field {key!r} to be a dict.\" f\"Received a {dict_.__class__.__name__!r}", "Interpreted fields include `pandoc`, `manubot`, `title`, `keywords`, `authors` (formerly `author_info`,", "citekeys_df[\"standard_citekey\"] = citekeys_df.detagged_citekey.map( standardize_citekey ) citekeys_df[\"short_citekey\"] = citekeys_df.standard_citekey.map(shorten_citekey) citekeys_df =", "pandoc/manubot dicts for key in \"pandoc\", \"manubot\": dict_ = metadata.pop(key,", "to create a shortened citekey \"\"\" citekeys_df = pandas.DataFrame( {\"manuscript_citekey\":", "Extend Pandoc's metadata.bibliography field with manual references paths bibliographies =", "metadata which contains pandoc_yaml_metadata # as well as authors information.", "check_multiple_citation_strings(citekeys_df): \"\"\" Identify different citation strings referring the the same", "`variables`. Interpreted fields include `pandoc`, `manubot`, `title`, `keywords`, `authors` (formerly", "tag_df[\"manuscript_citekey\"] = \"tag:\" + tag_df.tag tag_df = tag_df.rename(columns={\"citation\": \"detagged_citekey\"}) citekey_aliases", "zip(tag_df[\"manuscript_citekey\"], tag_df[\"detagged_citekey\"]) ) return citekey_aliases def write_citekeys_tsv(citekeys_df, path): if not", "as well as authors information. if args.meta_yaml_path.is_file(): metadata = read_serialized_dict(args.meta_yaml_path)", "template variables from {path!r}\") continue assert isinstance(obj, dict) conflicts =", "add a list of affiliations to the top-level of variables.", "`variables` to update an existing dictionary rather than create a", "URL if present thumbnail_url = get_thumbnail_url(metadata.pop(\"thumbnail\", None)) if thumbnail_url: variables[\"manubot\"][\"thumbnail_url\"]", "bibliographies = list(map(os.fspath, bibliographies)) variables[\"pandoc\"][\"bibliography\"] = bibliographies # enable pandoc-manubot-cite", "Write CSL JSON bibliography for Pandoc. write_csl_json(csl_items, args.references_path) return csl_items", "citekeys_df.detagged_citekey: is_valid_citekey(citation, allow_raw=True) citekeys_df[\"standard_citekey\"] = citekeys_df.detagged_citekey.map( standardize_citekey ) citekeys_df[\"short_citekey\"] =", "JSON must contain a dictionary as its top level. Namespaces", "`authors` (formerly `author_info`, now deprecated), `lang`, and `thumbnail`. - User-specified", "provided for raw citekeys.\" ) failures.append(standard_citekey) try: csl_item = citekey_to_csl_item(standard_citekey)", "to `variables`. Interpreted fields include `pandoc`, `manubot`, `title`, `keywords`, `authors`", "dictionary. - `manubot`: a dictionary for manubot-related information and metadata.", "the dictionary's top-level 'namespace_1=https://git.io/vbkqm', # store under 'namespace_1' key 'namespace_2=some_local_path.json',", ") from manubot.process.manuscript import ( datetime_now, get_manuscript_stats, get_text, ) from", "dictionary. \"\"\" if variables is None: variables = {} for", "with args.manuscript_path.open(\"w\", encoding=\"utf-8\") as write_file: yaml.dump( variables[\"pandoc\"], write_file, default_flow_style=False, explicit_start=True,", "`variables`, with the following keys: - `pandoc`: a dictionary for", "have any affiliations, variables is left unmodified. \"\"\" rows =", "unmodified. \"\"\" rows = list() for author in variables[\"authors\"]: if", "to csl_item for manual references - requests_cache_path: path for the", "import List, Optional import jinja2 import pandas import requests import", "this path, so it is not always the exact path", "data files into a user_variables dictionary. Provide `paths` (a list", "( citekey_to_csl_item, shorten_citekey, is_valid_citekey, standardize_citekey, ) def check_collisions(citekeys_df): \"\"\" Check", "manuscript with the current datetime: {now.isoformat()}\" ) variables[\"pandoc\"][\"date-meta\"] = now.date().isoformat()", "'namespace_2=some_local_path.json', # store under 'namespace_2' key ] ``` If a", "present thumbnail_url = get_thumbnail_url(metadata.pop(\"thumbnail\", None)) if thumbnail_url: variables[\"manubot\"][\"thumbnail_url\"] = thumbnail_url", "= list(dict.fromkeys(citekeys)) # Install cache if requests_cache_path is not None:", "dict: \"\"\" Read multiple serialized data files into a user_variables", "mapping from standard_citekey to csl_item for manual references - requests_cache_path:", "spaces rather than tabs to delimit fields.\\n\" \"Proceeding to reread", "for key, value in citekey_aliases.items(): text += f\"[@{key}]: {value}\\n\" logging.warning(", "if `metadata.yaml` includes a `manubot` dictionary. - All fields from", "well as authors information. if args.meta_yaml_path.is_file(): metadata = read_serialized_dict(args.meta_yaml_path) else:", "assert args.skip_citations text += _citation_tags_to_reference_links(args) variables = load_variables(args) variables[\"manubot\"][\"manuscript_stats\"] =", "{len(cache.responses)} cached responses\" ) requests_cache.uninstall_cache() if failures: message = \"CSL", "# Add thumbnail URL if present thumbnail_url = get_thumbnail_url(metadata.pop(\"thumbnail\", None))", "False, ) -> list: \"\"\" General CSL (citeproc) items for", "get_software_versions, ) from manubot.process.manuscript import ( datetime_now, get_manuscript_stats, get_text, )", "with <meta> information for the HTML output's <head> variables[\"pandoc\"][\"header-includes\"] =", "following keys: - `pandoc`: a dictionary for passing options to", "= thumbnail_url # Update variables with metadata.yaml pandoc/manubot dicts for", "dictionary as its top level. Namespaces should consist only of", "references (overrides) in JSON CSL manual_refs = load_manual_references(args.manual_references_paths) # Retrieve", "list): warnings.warn( f\"Expected list for {author['name']}'s affiliations. \" f\"Assuming multiple", "\"detagged_citekey\"}) citekey_aliases = dict( zip(tag_df[\"manuscript_citekey\"], tag_df[\"detagged_citekey\"]) ) return citekey_aliases def", "Update variables with metadata.yaml pandoc/manubot dicts for key in \"pandoc\",", "to be a dict.\" f\"Received a {dict_.__class__.__name__!r} instead.\" ) continue", "\"\"\" Check for short_citekey hash collisions \"\"\" collision_df = citekeys_df[[\"standard_citekey\",", "rows with missing values:\\n\" f\"{na_rows_df}\\n\" \"This error can be caused", "from manubot.process.manuscript import ( datetime_now, get_manuscript_stats, get_text, ) from manubot.cite.citekey", "Pandoc via the `yaml_metadata_block`. Fields in `pandoc` are either generated", "for affiliation in author[\"affiliations\"]: rows.append((author[\"name\"], affiliation)) if not rows: return", "and can overwrite values for existing keys like `pandoc` or", "now = datetime_now() logging.info( f\"Using {now:%Z} timezone.\\n\" f\"Dating manuscript with", "\" \"Not reading citekey_aliases from citation-tags.tsv.\" ) return {} tag_df", "manual_refs: dict = {}, requests_cache_path: Optional[str] = None, clear_requests_cache: Optional[bool]", "1 + len(affiliation_df)) affil_map_df = affil_map_df.merge(affiliation_df) name_to_numbers = { name:", "'namespace_1' key 'namespace_2=some_local_path.json', # store under 'namespace_2' key ] ```", "match = re.match(r\"([a-zA-Z_][a-zA-Z0-9_]*)=(.+)\", path) if match: namespace, path = match.groups()", "logging.warning( \"citation-tags.tsv is deprecated. \" f\"Consider deleting citation-tags.tsv and inserting", "`metadata.yaml` includes a `manubot` dictionary. - All fields from a", "load_manual_references(args.manual_references_paths) # Retrieve CSL Items csl_items = generate_csl_items( citekeys=citekeys_df.standard_citekey.unique(), manual_refs=manual_refs,", "variables[\"manubot\"].update(get_manuscript_urls(metadata.pop(\"html_url\", None))) # Add software versions variables[\"manubot\"].update(get_software_versions()) # Add thumbnail", "for template variables from {path!r}\" ) try: if match: obj", "re import textwrap import warnings from typing import List, Optional", "columns=[\"standard_citekey\", \"manuscript_citekey\"] ) logging.warning(f\"Multiple citekeys detected for the same reference:\\n{table}\")", "= {}, requests_cache_path: Optional[str] = None, clear_requests_cache: Optional[bool] = False,", "columns: - manuscript_citekey: citation keys extracted from the manuscript content", "with uninterpreted metadata.yaml fields variables.update(metadata) # Update variables with user-provided", "monkey patching by requests_cache. requests_cache.install_cache(requests_cache_path, include_get_headers=True) cache = requests_cache.get_cache() if", "= name_to_numbers.get(author[\"name\"], []) variables[\"affiliations\"] = affiliation_df.to_dict(orient=\"records\") return variables def load_variables(args)", "shortened citekey \"\"\" citekeys_df = pandas.DataFrame( {\"manuscript_citekey\": list(citekeys)} ).drop_duplicates() citekeys_df[\"detagged_citekey\"]", "are intended for pandoc move_to_pandoc = \"title\", \"keywords\", \"lang\" for", "fields inserted according to the `--template-variables-path` option. User-specified variables take", "read_citations_tsv(args.citation_tags_path) if not citekey_aliases: return \"\" text = \"\\n\\n\" for", "list(dict.fromkeys(citekeys)) # Install cache if requests_cache_path is not None: requests", "prepended. For example: ```python paths = [ 'https://git.io/vbkqm', # update", "- citekeys: list of standard_citekeys - manual_refs: mapping from standard_citekey", "for {author['name']}'s affiliations. \" f\"Assuming multiple affiliations are `; `", ") else: authors = metadata.pop(\"authors\", []) if authors is None:", "to write bibliography to a file variables[\"pandoc\"][\"manubot-output-bibliography\"] = os.fspath(args.references_path) variables[\"pandoc\"][\"manubot-output-citekeys\"]", "csl_items def write_csl_json(csl_items, path): \"\"\" Write CSL Items to a", "in author[\"affiliations\"]: rows.append((author[\"name\"], affiliation)) if not rows: return variables affil_map_df", "JSON file at `path`. If `path` evaluates as False, do", "import ( get_header_includes, get_thumbnail_url, get_manuscript_urls, get_software_versions, ) from manubot.process.manuscript import", "- detagged_citekey: manuscript_citekey but with tag citekeys dereferenced - standard_citekey:", "fields.\\n\" \"Proceeding to reread TSV with delim_whitespace=True.\" ) tag_df =", "pandoc. \"\"\" text = get_text(args.content_directory) assert args.skip_citations text += _citation_tags_to_reference_links(args)", "disk and logs warnings for potential problems. \"\"\" # Read", "citekey_aliases: dict = {}): \"\"\" Generate and return citekeys_df. citekeys_df", "-> str: \"\"\" Convert citation-tags.tsv to markdown reference link syntax", "f\"Please switch affiliations to a list.\", category=DeprecationWarning, ) author[\"affiliations\"] =", "{value}\\n\" logging.warning( \"citation-tags.tsv is deprecated. \" f\"Consider deleting citation-tags.tsv and", "and `thumbnail`. - User-specified fields inserted according to the `--template-variables-path`", "citekeys_df.manuscript_citekey.map( lambda citekey: citekey_aliases.get(citekey, citekey) ) for citation in citekeys_df.detagged_citekey:", "= args.clear_requests_cache return variables def get_citekeys_df(citekeys: list, citekey_aliases: dict =", "{path!r}\" ) try: if match: obj = {namespace: read_serialized_data(path)} else:", "variables from {path!r}\" ) try: if match: obj = {namespace:", "extension to this path, so it is not always the", "extracted from the manuscript content files. - detagged_citekey: manuscript_citekey but", "citekeys_df. Writes references.json to disk and logs warnings for potential", "for passing options to Pandoc via the `yaml_metadata_block`. Fields in", "<meta> information for the HTML output's <head> variables[\"pandoc\"][\"header-includes\"] = get_header_includes(variables)", "variables[\"manubot\"][\"manuscript_stats\"] = get_manuscript_stats(text) with args.variables_path.open(\"w\", encoding=\"utf-8\") as write_file: json.dump(variables, write_file,", "requests_cache_path: Optional[str] = None, clear_requests_cache: Optional[bool] = False, ) ->", "f\"Template variables in {path!r} overwrite existing \" \"values for the", "dict.\" f\"Received a {dict_.__class__.__name__!r} instead.\" ) continue variables[key].update(dict_) # Update", "\"Proceeding to reread TSV with delim_whitespace=True.\" ) tag_df = pandas.read_csv(path,", "in paths: logging.info(f\"Reading user-provided templating variables at {path!r}\") # Match", "warnings.warn( \"metadata.yaml: 'author_info' is deprecated. Use 'authors' instead.\", category=DeprecationWarning, )", "User-specified variables take highest precedence and can overwrite values for", "- manuscript_citekey: citation keys extracted from the manuscript content files.", "variables[key].update(dict_) # Update variables with uninterpreted metadata.yaml fields variables.update(metadata) #", "citation in citekeys_df.detagged_citekey: is_valid_citekey(citation, allow_raw=True) citekeys_df[\"standard_citekey\"] = citekeys_df.detagged_citekey.map( standardize_citekey )", "consist only of ASCII alphanumeric characters (includes underscores, first character", "repository version metadata for CI builds ci_params = get_continuous_integration_parameters() if", "delim_whitespace=True.\" ) tag_df = pandas.read_csv(path, delim_whitespace=True) tag_df[\"manuscript_citekey\"] = \"tag:\" +", "logging.error( f\"CSL JSON Data with a standard_citekey of {standard_citekey!r} not", "overwrite values for existing keys like `pandoc` or `manubot` (dangerous).", "should consist only of ASCII alphanumeric characters (includes underscores, first", "collision. Congratulations.\\n{collision_df}\") return collision_df def check_multiple_citation_strings(citekeys_df): \"\"\" Identify different citation", "manual-references.json. \" \"Metadata must be provided for raw citekeys.\" )", "TSV with delim_whitespace=True.\" ) tag_df = pandas.read_csv(path, delim_whitespace=True) tag_df[\"manuscript_citekey\"] =", "citekey_to_csl_item, shorten_citekey, is_valid_citekey, standardize_citekey, ) def check_collisions(citekeys_df): \"\"\" Check for", "that are not interpreted by Manubot are copied to `variables`.", "import jinja2 import pandas import requests import requests_cache import yaml", "for pandoc\" ) # Interpreted keys that are intended for", "import pandas import requests import requests_cache import yaml from manubot.util", ") requests_cache.uninstall_cache() if failures: message = \"CSL JSON Data retrieval", "\"\"\" collision_df = citekeys_df[[\"standard_citekey\", \"short_citekey\"]].drop_duplicates() collision_df = collision_df[collision_df.short_citekey.duplicated(keep=False)] if not", "for the requests cache database. Passed as cache_name to `requests_cache.install_cache`.", "contain a dictionary as its top level. Namespaces should consist", "\"\"\" Read multiple serialized data files into a user_variables dictionary.", "{path} \" \"Not reading citekey_aliases from citation-tags.tsv.\" ) return {}", "\"\"\" message = textwrap.dedent( f\"\"\"\\ {len(citekeys_df)} unique citations strings extracted", "variables.keys() & obj.keys() if conflicts: logging.warning( f\"Template variables in {path!r}", "from manubot.util import read_serialized_data, read_serialized_dict from manubot.process.bibliography import load_manual_references from", "variables. If no authors have any affiliations, variables is left", "responses\" ) requests_cache.uninstall_cache() if failures: message = \"CSL JSON Data", "f\"Expected list for {author['name']}'s affiliations. \" f\"Assuming multiple affiliations are", "for name, df in affil_map_df.groupby(\"name\") } for author in variables[\"authors\"]:", "variables[\"pandoc\"][\"header-includes\"] = get_header_includes(variables) assert args.skip_citations # Extend Pandoc's metadata.bibliography field", "user_variables dictionary. Provide `paths` (a list of URLs or local", "with the variables dictionary unpacked as keyword arguments. \"\"\" jinja_environment", "= read_variable_files(args.template_variables_path, variables) # Add header-includes metadata with <meta> information", "for standard_citekeys in citekeys_df. Writes references.json to disk and logs", "clear_requests_cache: If True, clear the requests cache before generating citekey", "authors metadata if \"author_info\" in metadata: authors = metadata.pop(\"author_info\", [])", "logging.error( f\"{path} contains rows with missing values:\\n\" f\"{na_rows_df}\\n\" \"This error", "= citekeys_df.manuscript_citekey.map( lambda citekey: citekey_aliases.get(citekey, citekey) ) for citation in", "the following keys: - `pandoc`: a dictionary for passing options", "like `pandoc` or `manubot` (dangerous). \"\"\" # Generated manuscript variables", "`manubot` are either generated by Manubot or hard-coded by the", "# Generated manuscript variables variables = {\"pandoc\": {}, \"manubot\": {}}", "def add_author_affiliations(variables: dict) -> dict: \"\"\" Edit variables to contain", "except Exception: logging.exception(f\"Citeproc retrieval failure for {standard_citekey!r}\") failures.append(standard_citekey) # Uninstall", "for author in variables[\"authors\"]: if \"affiliations\" not in author: continue", "range(1, 1 + len(affiliation_df)) affil_map_df = affil_map_df.merge(affiliation_df) name_to_numbers = {", ") csl_items = list() failures = list() for standard_citekey in", "match: obj = {namespace: read_serialized_data(path)} else: obj = read_serialized_dict(path) except", "citekey_aliases = dict( zip(tag_df[\"manuscript_citekey\"], tag_df[\"detagged_citekey\"]) ) return citekey_aliases def write_citekeys_tsv(citekeys_df,", "CSL (citeproc) items for standard_citekeys in citekeys_df. Parameters: - citekeys:", "multi_df.empty: table = multi_df.to_string( index=False, columns=[\"standard_citekey\", \"manuscript_citekey\"] ) logging.warning(f\"Multiple citekeys", "list, manual_refs: dict = {}, requests_cache_path: Optional[str] = None, clear_requests_cache:", "{standard_citekey!r}\") failures.append(standard_citekey) # Uninstall cache if requests_cache_path is not None:", "if not collision_df.empty: logging.error(f\"OMF! Hash collision. Congratulations.\\n{collision_df}\") return collision_df def", "= multi_df.to_string( index=False, columns=[\"standard_citekey\", \"manuscript_citekey\"] ) logging.warning(f\"Multiple citekeys detected for", "= {\"pandoc\": {}, \"manubot\": {}} # Read metadata which contains", "file at `path`. If `path` evaluates as False, do nothing.", "if not rows: return variables affil_map_df = pandas.DataFrame(rows, columns=[\"name\", \"affiliation\"])", "# Set repository version metadata for CI builds ci_params =", "list: \"\"\" General CSL (citeproc) items for standard_citekeys in citekeys_df.", "each author and add a list of affiliations to the", "manual_refs: csl_items.append(manual_refs[standard_citekey]) continue elif standard_citekey.startswith(\"raw:\"): logging.error( f\"CSL JSON Data with", "cache = requests_cache.get_cache() if clear_requests_cache: logging.info(\"Clearing requests-cache\") requests_cache.clear() logging.info( f\"requests-cache", "key in \"pandoc\", \"manubot\": dict_ = metadata.pop(key, {}) if not", "author in variables[\"authors\"]: if \"affiliations\" not in author: continue if", "\"\"\" Write CSL Items to a JSON file at `path`.", "shorten_citekey, is_valid_citekey, standardize_citekey, ) def check_collisions(citekeys_df): \"\"\" Check for short_citekey", "citekeys_df.standard_citekey.map(shorten_citekey) citekeys_df = citekeys_df.sort_values([\"standard_citekey\", \"detagged_citekey\"]) check_collisions(citekeys_df) check_multiple_citation_strings(citekeys_df) return citekeys_df def", "manual references (overrides) in JSON CSL manual_refs = load_manual_references(args.manual_references_paths) #", "delim_whitespace=True) tag_df[\"manuscript_citekey\"] = \"tag:\" + tag_df.tag tag_df = tag_df.rename(columns={\"citation\": \"detagged_citekey\"})", "= \"CSL JSON Data retrieval failed for the following standardized", "None: logging.info( f\"requests-cache finished with {len(cache.responses)} cached responses\" ) requests_cache.uninstall_cache()", "affiliation in author[\"affiliations\"]: rows.append((author[\"name\"], affiliation)) if not rows: return variables", "cache_name to `requests_cache.install_cache`. requests_cache may append an extension to this", "the user if `metadata.yaml` includes a `manubot` dictionary. - All", "as write_file: json.dump(variables, write_file, ensure_ascii=False, indent=2) write_file.write(\"\\n\") text = template_with_jinja2(text,", "from manubot.process.ci import get_continuous_integration_parameters from manubot.process.metadata import ( get_header_includes, get_thumbnail_url,", "JSON CSL manual_refs = load_manual_references(args.manual_references_paths) # Retrieve CSL Items csl_items", "a list.\", category=DeprecationWarning, ) author[\"affiliations\"] = author[\"affiliations\"].split(\"; \") for affiliation", "pathlib.Path(path) with path.open(\"w\", encoding=\"utf-8\") as write_file: json.dump(csl_items, write_file, indent=2, ensure_ascii=False)", "Optional[bool] = False, ) -> list: \"\"\" General CSL (citeproc)", "if not path.is_file(): logging.info( f\"no citation tags file at {path}", "is not always the exact path to the cache. If", "\"\"\" # Read manual references (overrides) in JSON CSL manual_refs", "your Markdown content:{text}\" ) return text def generate_csl_items( citekeys: list,", "= read_citations_tsv(args.citation_tags_path) if not citekey_aliases: return \"\" text = \"\\n\\n\"", "for pandoc with args.manuscript_path.open(\"w\", encoding=\"utf-8\") as write_file: yaml.dump( variables[\"pandoc\"], write_file,", "short_citekey: standard_citekey hashed to create a shortened citekey \"\"\" citekeys_df", "return variables def add_author_affiliations(variables: dict) -> dict: \"\"\" Edit variables", "yaml from manubot.util import read_serialized_data, read_serialized_dict from manubot.process.bibliography import load_manual_references", "= affil_map_df.merge(affiliation_df) name_to_numbers = { name: sorted(df.affiliation_number) for name, df", "write bibliography to a file variables[\"pandoc\"][\"manubot-output-bibliography\"] = os.fspath(args.references_path) variables[\"pandoc\"][\"manubot-output-citekeys\"] =", ") # Interpreted keys that are intended for pandoc move_to_pandoc", "path for the requests cache database. Passed as cache_name to", "if \"author_info\" in metadata: authors = metadata.pop(\"author_info\", []) warnings.warn( \"metadata.yaml:", "as inputs for pandoc. \"\"\" text = get_text(args.content_directory) assert args.skip_citations", "{args.meta_yaml_path} file with yaml_metadata_block for pandoc\" ) # Interpreted keys", "Convert citation-tags.tsv to markdown reference link syntax \"\"\" citekey_aliases =", "path): \"\"\" Write CSL Items to a JSON file at", "isinstance(author[\"affiliations\"], list): warnings.warn( f\"Expected list for {author['name']}'s affiliations. \" f\"Assuming", "via the `yaml_metadata_block`. Fields in `pandoc` are either generated by", "requests_cache.get_cache() if clear_requests_cache: logging.info(\"Clearing requests-cache\") requests_cache.clear() logging.info( f\"requests-cache starting with", "(citeproc) items for standard_citekeys in citekeys_df. Writes references.json to disk", "citation-tags.tsv and inserting the following paragraph into your Markdown content:{text}\"", "citekey: citekey_aliases.get(citekey, citekey) ) for citation in citekeys_df.detagged_citekey: is_valid_citekey(citation, allow_raw=True)", "generate_csl_items( citekeys: list, manual_refs: dict = {}, requests_cache_path: Optional[str] =", ") return variables def add_author_affiliations(variables: dict) -> dict: \"\"\" Edit", "with user-provided variables here variables = read_variable_files(args.template_variables_path, variables) # Add", "dicts for key in \"pandoc\", \"manubot\": dict_ = metadata.pop(key, {})", "if key in metadata: variables[\"pandoc\"][key] = metadata.pop(key) # Add date", "manuscript_citekey but with tag citekeys dereferenced - standard_citekey: detagged_citekey standardized", "import warnings from typing import List, Optional import jinja2 import", "True, clear the requests cache before generating citekey metadata. \"\"\"", "dict: \"\"\" Read citekey aliases from a citation-tags.tsv file. \"\"\"", "variables[\"pandoc\"][\"date-meta\"] = now.date().isoformat() variables[\"manubot\"][\"date\"] = f\"{now:%B} {now.day}, {now.year}\" # Process", "to generate manuscript variables available for jinja2 templating. Returns a", "variables): \"\"\" Template using jinja2 with the variables dictionary unpacked", "variables[\"pandoc\"][\"author-meta\"] = [author[\"name\"] for author in authors] variables[\"manubot\"][\"authors\"] = authors", "the cache. If None, do not use requests_cache. - clear_requests_cache:", "author[\"affiliations\"]: rows.append((author[\"name\"], affiliation)) if not rows: return variables affil_map_df =", "refered to as `variables`, with the following keys: - `pandoc`:", "= datetime_now() logging.info( f\"Using {now:%Z} timezone.\\n\" f\"Dating manuscript with the", ") citekeys_df[\"short_citekey\"] = citekeys_df.standard_citekey.map(shorten_citekey) citekeys_df = citekeys_df.sort_values([\"standard_citekey\", \"detagged_citekey\"]) check_collisions(citekeys_df) check_multiple_citation_strings(citekeys_df)", "URLs variables[\"manubot\"].update(get_manuscript_urls(metadata.pop(\"html_url\", None))) # Add software versions variables[\"manubot\"].update(get_software_versions()) # Add", "get_text(args.content_directory) assert args.skip_citations text += _citation_tags_to_reference_links(args) variables = load_variables(args) variables[\"manubot\"][\"manuscript_stats\"]", "-> dict: \"\"\" Read multiple serialized data files into a", "os.fspath(args.citations_path) variables[\"pandoc\"][\"manubot-requests-cache-path\"] = os.fspath( args.requests_cache_path ) variables[\"pandoc\"][\"manubot-clear-requests-cache\"] = args.clear_requests_cache return", "Manubot or hard-coded by the user if `metadata.yaml` includes a", "citekey_to_csl_item(standard_citekey) csl_items.append(csl_item) except Exception: logging.exception(f\"Citeproc retrieval failure for {standard_citekey!r}\") failures.append(standard_citekey)", "{standard_citekey!r} not found in manual-references.json. \" \"Metadata must be provided", "values for existing keys like `pandoc` or `manubot` (dangerous). \"\"\"", "<gh_stars>0 import json import logging import os import pathlib import", "in `pandoc` are either generated by Manubot or hard-coded by", "`paths` (a list of URLs or local file paths). Paths", "\" \"values for the following keys:\\n\" + \"\\n\".join(conflicts) ) variables.update(obj)", "the JSON must contain a dictionary as its top level.", "Data retrieval failed for the following standardized citation keys:\\n{}\".format( \"\\n\".join(failures)", "{now.day}, {now.year}\" # Process authors metadata if \"author_info\" in metadata:", "= read_serialized_dict(path) except Exception: logging.exception(f\"Error reading template variables from {path!r}\")", "name: sorted(df.affiliation_number) for name, df in affil_map_df.groupby(\"name\") } for author", "def prepare_manuscript(args): \"\"\" Compile manuscript, creating manuscript.md and references.json as", "logging.error(f\"OMF! Hash collision. Congratulations.\\n{collision_df}\") return collision_df def check_multiple_citation_strings(citekeys_df): \"\"\" Identify", "# Add software versions variables[\"manubot\"].update(get_software_versions()) # Add thumbnail URL if", "return variables def load_variables(args) -> dict: \"\"\" Read `metadata.yaml` and", "top-level of variables. If no authors have any affiliations, variables", "than tabs to delimit fields.\\n\" \"Proceeding to reread TSV with", "switch affiliations to a list.\", category=DeprecationWarning, ) author[\"affiliations\"] = author[\"affiliations\"].split(\";", "variables with metadata.yaml pandoc/manubot dicts for key in \"pandoc\", \"manubot\":", "JSON Data retrieval failed for the following standardized citation keys:\\n{}\".format(", "reference. \"\"\" message = textwrap.dedent( f\"\"\"\\ {len(citekeys_df)} unique citations strings", "information and metadata. Fields in `manubot` are either generated by", "General CSL (citeproc) items for standard_citekeys in citekeys_df. Parameters: -", "allow_raw=True) citekeys_df[\"standard_citekey\"] = citekeys_df.detagged_citekey.map( standardize_citekey ) citekeys_df[\"short_citekey\"] = citekeys_df.standard_citekey.map(shorten_citekey) citekeys_df", "existing \" \"values for the following keys:\\n\" + \"\\n\".join(conflicts) )", "else: metadata = {} logging.warning( f\"missing {args.meta_yaml_path} file with yaml_metadata_block", "path = pathlib.Path(path) with path.open(\"w\", encoding=\"utf-8\") as write_file: json.dump(csl_items, write_file,", "generate manuscript variables available for jinja2 templating. Returns a dictionary,", "field with manual references paths bibliographies = variables[\"pandoc\"].get(\"bibliography\", []) if", "manuscript_citekey: citation keys extracted from the manuscript content files. -", "= \"\\n\\n\" for key, value in citekey_aliases.items(): text += f\"[@{key}]:", "is essential for monkey patching by requests_cache. requests_cache.install_cache(requests_cache_path, include_get_headers=True) cache", "os import pathlib import re import textwrap import warnings from", "Returns a dictionary, refered to as `variables`, with the following", "for path in paths: logging.info(f\"Reading user-provided templating variables at {path!r}\")", "import read_serialized_data, read_serialized_dict from manubot.process.bibliography import load_manual_references from manubot.process.ci import", "jinja2.Environment( loader=jinja2.BaseLoader(), undefined=jinja2.make_logging_undefined(logging.getLogger()), autoescape=False, comment_start_string=\"{##\", comment_end_string=\"##}\", extensions=[\"jinja2.ext.do\", \"jinja2.ext.loopcontrols\"], ) template", "be numeric). Pass a dictionary to `variables` to update an", "`pandoc`: a dictionary for passing options to Pandoc via the", "dictionary. - All fields from a manuscript's `metadata.yaml` that are", "manual references - requests_cache_path: path for the requests cache database.", "in citekeys_df. Parameters: - citekeys: list of standard_citekeys - manual_refs:", "columns=[\"name\", \"affiliation\"]) affiliation_df = affil_map_df[[\"affiliation\"]].drop_duplicates() affiliation_df[\"affiliation_number\"] = range(1, 1 +", "-> dict: \"\"\" Read `metadata.yaml` and files specified by `--template-variables-path`", "\"affiliation\"]) affiliation_df = affil_map_df[[\"affiliation\"]].drop_duplicates() affiliation_df[\"affiliation_number\"] = range(1, 1 + len(affiliation_df))", "\"\"\" citekey_aliases = read_citations_tsv(args.citation_tags_path) if not citekey_aliases: return \"\" text", "a list of affiliations to the top-level of variables. If", "failures = list() for standard_citekey in citekeys: if standard_citekey in", "citation-tags.tsv file. \"\"\" if not path.is_file(): logging.info( f\"no citation tags", "`pandoc`, `manubot`, `title`, `keywords`, `authors` (formerly `author_info`, now deprecated), `lang`,", "example: ```python paths = [ 'https://git.io/vbkqm', # update the dictionary's", "of affiliations to the top-level of variables. If no authors", "pandas.DataFrame with the following columns: - manuscript_citekey: citation keys extracted", "= generate_csl_items( citekeys=citekeys_df.standard_citekey.unique(), manual_refs=manual_refs, requests_cache_path=args.requests_cache_path, clear_requests_cache=args.clear_requests_cache, ) # Write CSL", "return citekey_aliases def write_citekeys_tsv(citekeys_df, path): if not path: return citekeys_df.to_csv(path,", "cache if requests_cache_path is not None: requests # require `import", "not path.is_file(): logging.info( f\"no citation tags file at {path} \"", "inputs for pandoc. \"\"\" text = get_text(args.content_directory) assert args.skip_citations text", "a dictionary for manubot-related information and metadata. Fields in `manubot`", "tag_df.tag tag_df = tag_df.rename(columns={\"citation\": \"detagged_citekey\"}) citekey_aliases = dict( zip(tag_df[\"manuscript_citekey\"], tag_df[\"detagged_citekey\"])", "dict: \"\"\" Edit variables to contain numbered author affiliations. Specifically,", "a dictionary to `variables` to update an existing dictionary rather", "logging.info( f\"requests-cache starting with {len(cache.responses)} cached responses\" ) csl_items =", "\"tag:\" + tag_df.tag tag_df = tag_df.rename(columns={\"citation\": \"detagged_citekey\"}) citekey_aliases = dict(", "caused by using spaces rather than tabs to delimit fields.\\n\"", "write_csl_json(csl_items, path): \"\"\" Write CSL Items to a JSON file", "not isinstance(dict_, dict): logging.warning( f\"load_variables expected metadata.yaml field {key!r} to", "uninterpreted metadata.yaml fields variables.update(metadata) # Update variables with user-provided variables", "\"\"\" Edit variables to contain numbered author affiliations. Specifically, add", "= load_manual_references(args.manual_references_paths) # Retrieve CSL Items csl_items = generate_csl_items( citekeys=citekeys_df.standard_citekey.unique(),", "= citekeys_df[citekeys_df.standard_citekey.duplicated(keep=False)] if not multi_df.empty: table = multi_df.to_string( index=False, columns=[\"standard_citekey\",", "dereferenced - standard_citekey: detagged_citekey standardized - short_citekey: standard_citekey hashed to", "= False, ) -> list: \"\"\" General CSL (citeproc) items", "Add header-includes metadata with <meta> information for the HTML output's", "( datetime_now, get_manuscript_stats, get_text, ) from manubot.cite.citekey import ( citekey_to_csl_item,", "= None, clear_requests_cache: Optional[bool] = False, ) -> list: \"\"\"", "failures.append(standard_citekey) try: csl_item = citekey_to_csl_item(standard_citekey) csl_items.append(csl_item) except Exception: logging.exception(f\"Citeproc retrieval", "templating. Returns a dictionary, refered to as `variables`, with the", "get_continuous_integration_parameters() if ci_params: variables[\"manubot\"][\"ci_source\"] = ci_params # Add manuscript URLs", "yaml.dump( variables[\"pandoc\"], write_file, default_flow_style=False, explicit_start=True, explicit_end=True, width=float(\"inf\"), ) write_file.write(\"\\n\") write_file.write(text)", "from {path!r}\") continue assert isinstance(obj, dict) conflicts = variables.keys() &", "logging.info(\"Clearing requests-cache\") requests_cache.clear() logging.info( f\"requests-cache starting with {len(cache.responses)} cached responses\"", "a namespace prepended. For example: ```python paths = [ 'https://git.io/vbkqm',", "# Uninstall cache if requests_cache_path is not None: logging.info( f\"requests-cache", "variables[\"authors\"]: author[\"affiliation_numbers\"] = name_to_numbers.get(author[\"name\"], []) variables[\"affiliations\"] = affiliation_df.to_dict(orient=\"records\") return variables", "valid jinja2 variable names # http://jinja.pocoo.org/docs/2.10/api/#identifier-naming match = re.match(r\"([a-zA-Z_][a-zA-Z0-9_]*)=(.+)\", path)", "as write_file: yaml.dump( variables[\"pandoc\"], write_file, default_flow_style=False, explicit_start=True, explicit_end=True, width=float(\"inf\"), )", "encoding=\"utf-8\") as write_file: json.dump(variables, write_file, ensure_ascii=False, indent=2) write_file.write(\"\\n\") text =", "tag citekeys dereferenced - standard_citekey: detagged_citekey standardized - short_citekey: standard_citekey", "cached responses\" ) requests_cache.uninstall_cache() if failures: message = \"CSL JSON", "CSL JSON bibliography for Pandoc. write_csl_json(csl_items, args.references_path) return csl_items def", "passing options to Pandoc via the `yaml_metadata_block`. Fields in `pandoc`", "user-provided templating variables at {path!r}\") # Match only namespaces that", "is None: variables = {} for path in paths: logging.info(f\"Reading", "requests_cache_path: path for the requests cache database. Passed as cache_name", "to delimit fields.\\n\" \"Proceeding to reread TSV with delim_whitespace=True.\" )", "args.skip_citations # Extend Pandoc's metadata.bibliography field with manual references paths", "logging.warning( f\"Template variables in {path!r} overwrite existing \" \"values for", "= template_with_jinja2(text, variables) # Write manuscript for pandoc with args.manuscript_path.open(\"w\",", "\"\"\" # Deduplicate citations citekeys = list(dict.fromkeys(citekeys)) # Install cache", "metadata for CI builds ci_params = get_continuous_integration_parameters() if ci_params: variables[\"manubot\"][\"ci_source\"]", "list.\", category=DeprecationWarning, ) author[\"affiliations\"] = author[\"affiliations\"].split(\"; \") for affiliation in", "\"\"\" if not path.is_file(): logging.info( f\"no citation tags file at", "not path: return citekeys_df.to_csv(path, sep=\"\\t\", index=False) def _citation_tags_to_reference_links(args) -> str:", "\"\"\" if variables is None: variables = {} for path", "assert isinstance(bibliographies, list) bibliographies.extend(args.manual_references_paths) bibliographies = list(map(os.fspath, bibliographies)) variables[\"pandoc\"][\"bibliography\"] =", "try: csl_item = citekey_to_csl_item(standard_citekey) csl_items.append(csl_item) except Exception: logging.exception(f\"Citeproc retrieval failure", "clear_requests_cache: Optional[bool] = False, ) -> list: \"\"\" General CSL", "get_header_includes(variables) assert args.skip_citations # Extend Pandoc's metadata.bibliography field with manual", "variables[\"pandoc\"][\"bibliography\"] = bibliographies # enable pandoc-manubot-cite option to write bibliography", "raw citekeys.\" ) failures.append(standard_citekey) try: csl_item = citekey_to_csl_item(standard_citekey) csl_items.append(csl_item) except", "under 'namespace_1' key 'namespace_2=some_local_path.json', # store under 'namespace_2' key ]", "citekeys_df): \"\"\" General CSL (citeproc) items for standard_citekeys in citekeys_df.", "tag_df.rename(columns={\"citation\": \"detagged_citekey\"}) citekey_aliases = dict( zip(tag_df[\"manuscript_citekey\"], tag_df[\"detagged_citekey\"]) ) return citekey_aliases", "a dict.\" f\"Received a {dict_.__class__.__name__!r} instead.\" ) continue variables[key].update(dict_) #", "templating variables at {path!r}\") # Match only namespaces that are", "def check_multiple_citation_strings(citekeys_df): \"\"\" Identify different citation strings referring the the", "include `pandoc`, `manubot`, `title`, `keywords`, `authors` (formerly `author_info`, now deprecated),", "re.match(r\"([a-zA-Z_][a-zA-Z0-9_]*)=(.+)\", path) if match: namespace, path = match.groups() logging.info( f\"Using", "for standard_citekeys in citekeys_df. Parameters: - citekeys: list of standard_citekeys", "= [] variables[\"pandoc\"][\"author-meta\"] = [author[\"name\"] for author in authors] variables[\"manubot\"][\"authors\"]", "logging.debug( f\"Reading user-provided templating variables complete:\\n\" f\"{json.dumps(variables, indent=2, ensure_ascii=False)}\" )", "read_serialized_data, read_serialized_dict from manubot.process.bibliography import load_manual_references from manubot.process.ci import get_continuous_integration_parameters", "manubot-related information and metadata. Fields in `manubot` are either generated", "for the following keys:\\n\" + \"\\n\".join(conflicts) ) variables.update(obj) logging.debug( f\"Reading", "citekey_aliases = read_citations_tsv(args.citation_tags_path) if not citekey_aliases: return \"\" text =", "not in author: continue if not isinstance(author[\"affiliations\"], list): warnings.warn( f\"Expected", "indent=2, ensure_ascii=False)}\" ) return variables def add_author_affiliations(variables: dict) -> dict:", "to contain numbered author affiliations. Specifically, add a list of", "with the current datetime: {now.isoformat()}\" ) variables[\"pandoc\"][\"date-meta\"] = now.date().isoformat() variables[\"manubot\"][\"date\"]", "try: if match: obj = {namespace: read_serialized_data(path)} else: obj =", "# store under 'namespace_1' key 'namespace_2=some_local_path.json', # store under 'namespace_2'", "continue assert isinstance(obj, dict) conflicts = variables.keys() & obj.keys() if", "for standard_citekey in citekeys: if standard_citekey in manual_refs: csl_items.append(manual_refs[standard_citekey]) continue", ") logging.warning(f\"Multiple citekeys detected for the same reference:\\n{table}\") return multi_df", "with path.open(\"w\", encoding=\"utf-8\") as write_file: json.dump(csl_items, write_file, indent=2, ensure_ascii=False) write_file.write(\"\\n\")", "logging.info( f\"Using the {namespace!r} namespace for template variables from {path!r}\"", "Pandoc's metadata.bibliography field with manual references paths bibliographies = variables[\"pandoc\"].get(\"bibliography\",", "which contains pandoc_yaml_metadata # as well as authors information. if", "{len(cache.responses)} cached responses\" ) csl_items = list() failures = list()", "\"title\", \"keywords\", \"lang\" for key in move_to_pandoc: if key in", "field {key!r} to be a dict.\" f\"Received a {dict_.__class__.__name__!r} instead.\"", "with {len(cache.responses)} cached responses\" ) requests_cache.uninstall_cache() if failures: message =", "with manual references paths bibliographies = variables[\"pandoc\"].get(\"bibliography\", []) if isinstance(bibliographies,", "for Pandoc. write_csl_json(csl_items, args.references_path) return csl_items def write_csl_json(csl_items, path): \"\"\"", "creating manuscript.md and references.json as inputs for pandoc. \"\"\" text", "to update an existing dictionary rather than create a new", "expected metadata.yaml field {key!r} to be a dict.\" f\"Received a", "pathlib import re import textwrap import warnings from typing import", "deprecated. \" f\"Consider deleting citation-tags.tsv and inserting the following paragraph", "and inserting the following paragraph into your Markdown content:{text}\" )", "cannot be numeric). Pass a dictionary to `variables` to update", "Add thumbnail URL if present thumbnail_url = get_thumbnail_url(metadata.pop(\"thumbnail\", None)) if", "message = textwrap.dedent( f\"\"\"\\ {len(citekeys_df)} unique citations strings extracted from", "# Deduplicate citations citekeys = list(dict.fromkeys(citekeys)) # Install cache if", "assert args.skip_citations # Extend Pandoc's metadata.bibliography field with manual references", "logging.error(message) return csl_items def _generate_csl_items(args, citekeys_df): \"\"\" General CSL (citeproc)", "list() for author in variables[\"authors\"]: if \"affiliations\" not in author:", "link syntax \"\"\" citekey_aliases = read_citations_tsv(args.citation_tags_path) if not citekey_aliases: return", "Uninstall cache if requests_cache_path is not None: logging.info( f\"requests-cache finished", "by requests_cache. requests_cache.install_cache(requests_cache_path, include_get_headers=True) cache = requests_cache.get_cache() if clear_requests_cache: logging.info(\"Clearing", "header-includes metadata with <meta> information for the HTML output's <head>", "citekeys_df[[\"standard_citekey\", \"short_citekey\"]].drop_duplicates() collision_df = collision_df[collision_df.short_citekey.duplicated(keep=False)] if not collision_df.empty: logging.error(f\"OMF! Hash", "text = get_text(args.content_directory) assert args.skip_citations text += _citation_tags_to_reference_links(args) variables =", "[bibliographies] assert isinstance(bibliographies, list) bibliographies.extend(args.manual_references_paths) bibliographies = list(map(os.fspath, bibliographies)) variables[\"pandoc\"][\"bibliography\"]", "as its top level. Namespaces should consist only of ASCII", "Specifically, add a list of affiliation_numbers for each author and", "for monkey patching by requests_cache. requests_cache.install_cache(requests_cache_path, include_get_headers=True) cache = requests_cache.get_cache()", "csl_item = citekey_to_csl_item(standard_citekey) csl_items.append(csl_item) except Exception: logging.exception(f\"Citeproc retrieval failure for", "{now:%Z} timezone.\\n\" f\"Dating manuscript with the current datetime: {now.isoformat()}\" )", "not collision_df.empty: logging.error(f\"OMF! Hash collision. Congratulations.\\n{collision_df}\") return collision_df def check_multiple_citation_strings(citekeys_df):", "the exact path to the cache. If None, do not", "None, do not use requests_cache. - clear_requests_cache: If True, clear", "hash collisions \"\"\" collision_df = citekeys_df[[\"standard_citekey\", \"short_citekey\"]].drop_duplicates() collision_df = collision_df[collision_df.short_citekey.duplicated(keep=False)]", "= re.match(r\"([a-zA-Z_][a-zA-Z0-9_]*)=(.+)\", path) if match: namespace, path = match.groups() logging.info(", "`lang`, and `thumbnail`. - User-specified fields inserted according to the", "files into a user_variables dictionary. Provide `paths` (a list of", "All fields from a manuscript's `metadata.yaml` that are not interpreted", "standardize_citekey ) citekeys_df[\"short_citekey\"] = citekeys_df.standard_citekey.map(shorten_citekey) citekeys_df = citekeys_df.sort_values([\"standard_citekey\", \"detagged_citekey\"]) check_collisions(citekeys_df)", "to this path, so it is not always the exact", "list of URLs or local file paths). Paths can optionally", "the manuscript content files. - detagged_citekey: manuscript_citekey but with tag", "requests_cache_path is not None: logging.info( f\"requests-cache finished with {len(cache.responses)} cached", "affiliations. \" f\"Assuming multiple affiliations are `; ` separated. \"", "now.date().isoformat() variables[\"manubot\"][\"date\"] = f\"{now:%B} {now.day}, {now.year}\" # Process authors metadata", "list) bibliographies.extend(args.manual_references_paths) bibliographies = list(map(os.fspath, bibliographies)) variables[\"pandoc\"][\"bibliography\"] = bibliographies #", "option. User-specified variables take highest precedence and can overwrite values", "citekeys_df[\"detagged_citekey\"] = citekeys_df.manuscript_citekey.map( lambda citekey: citekey_aliases.get(citekey, citekey) ) for citation", "(formerly `author_info`, now deprecated), `lang`, and `thumbnail`. - User-specified fields", "only namespaces that are valid jinja2 variable names # http://jinja.pocoo.org/docs/2.10/api/#identifier-naming", "same reference. \"\"\" message = textwrap.dedent( f\"\"\"\\ {len(citekeys_df)} unique citations", "authors information. if args.meta_yaml_path.is_file(): metadata = read_serialized_dict(args.meta_yaml_path) else: metadata =", "a {dict_.__class__.__name__!r} instead.\" ) continue variables[key].update(dict_) # Update variables with", "underscores, first character cannot be numeric). Pass a dictionary to", "= \"tag:\" + tag_df.tag tag_df = tag_df.rename(columns={\"citation\": \"detagged_citekey\"}) citekey_aliases =", "references paths bibliographies = variables[\"pandoc\"].get(\"bibliography\", []) if isinstance(bibliographies, str): bibliographies", "date to metadata now = datetime_now() logging.info( f\"Using {now:%Z} timezone.\\n\"", "file. \"\"\" if not path.is_file(): logging.info( f\"no citation tags file", "not None: logging.info( f\"requests-cache finished with {len(cache.responses)} cached responses\" )", "{ name: sorted(df.affiliation_number) for name, df in affil_map_df.groupby(\"name\") } for", "variables[\"pandoc\"][key] = metadata.pop(key) # Add date to metadata now =", "citekeys: list of standard_citekeys - manual_refs: mapping from standard_citekey to", "before generating citekey metadata. \"\"\" # Deduplicate citations citekeys =", "if not path: return citekeys_df.to_csv(path, sep=\"\\t\", index=False) def _citation_tags_to_reference_links(args) ->", "JSON bibliography for Pandoc. write_csl_json(csl_items, args.references_path) return csl_items def write_csl_json(csl_items,", "= {}): \"\"\" Generate and return citekeys_df. citekeys_df is a", "namespace, path = match.groups() logging.info( f\"Using the {namespace!r} namespace for", "= citekeys_df.standard_citekey.map(shorten_citekey) citekeys_df = citekeys_df.sort_values([\"standard_citekey\", \"detagged_citekey\"]) check_collisions(citekeys_df) check_multiple_citation_strings(citekeys_df) return citekeys_df", "= None) -> dict: \"\"\" Read multiple serialized data files", "the following keys:\\n\" + \"\\n\".join(conflicts) ) variables.update(obj) logging.debug( f\"Reading user-provided", "index=False, columns=[\"standard_citekey\", \"manuscript_citekey\"] ) logging.warning(f\"Multiple citekeys detected for the same", "if thumbnail_url: variables[\"manubot\"][\"thumbnail_url\"] = thumbnail_url # Update variables with metadata.yaml", "with tag citekeys dereferenced - standard_citekey: detagged_citekey standardized - short_citekey:", "= list() for author in variables[\"authors\"]: if \"affiliations\" not in", "variables available for jinja2 templating. Returns a dictionary, refered to", ") template = jinja_environment.from_string(text) return template.render(**variables) def prepare_manuscript(args): \"\"\" Compile", "bibliographies = variables[\"pandoc\"].get(\"bibliography\", []) if isinstance(bibliographies, str): bibliographies = [bibliographies]", "{author['name']}'s affiliations. \" f\"Assuming multiple affiliations are `; ` separated.", "manual references paths bibliographies = variables[\"pandoc\"].get(\"bibliography\", []) if isinstance(bibliographies, str):", "= ci_params # Add manuscript URLs variables[\"manubot\"].update(get_manuscript_urls(metadata.pop(\"html_url\", None))) # Add", "of affiliation_numbers for each author and add a list of", "failures.append(standard_citekey) # Uninstall cache if requests_cache_path is not None: logging.info(", "Optional[str] = None, clear_requests_cache: Optional[bool] = False, ) -> list:", "Retrieve CSL Items csl_items = generate_csl_items( citekeys=citekeys_df.standard_citekey.unique(), manual_refs=manual_refs, requests_cache_path=args.requests_cache_path, clear_requests_cache=args.clear_requests_cache,", "citekeys_df def read_citations_tsv(path) -> dict: \"\"\" Read citekey aliases from", "standard_citekeys - manual_refs: mapping from standard_citekey to csl_item for manual", "from {path!r}\" ) try: if match: obj = {namespace: read_serialized_data(path)}", "collision_df def check_multiple_citation_strings(citekeys_df): \"\"\" Identify different citation strings referring the", "be a dict.\" f\"Received a {dict_.__class__.__name__!r} instead.\" ) continue variables[key].update(dict_)", "\"Metadata must be provided for raw citekeys.\" ) failures.append(standard_citekey) try:", "detected for the same reference:\\n{table}\") return multi_df def read_variable_files(paths: List[str],", "import os import pathlib import re import textwrap import warnings", "# as well as authors information. if args.meta_yaml_path.is_file(): metadata =", "pandoc_yaml_metadata # as well as authors information. if args.meta_yaml_path.is_file(): metadata", "citekey_aliases from citation-tags.tsv.\" ) return {} tag_df = pandas.read_csv(path, sep=\"\\t\")", "ASCII alphanumeric characters (includes underscores, first character cannot be numeric).", "author and add a list of affiliations to the top-level", "if not path: return path = pathlib.Path(path) with path.open(\"w\", encoding=\"utf-8\")", "datetime_now, get_manuscript_stats, get_text, ) from manubot.cite.citekey import ( citekey_to_csl_item, shorten_citekey,", "= tag_df.rename(columns={\"citation\": \"detagged_citekey\"}) citekey_aliases = dict( zip(tag_df[\"manuscript_citekey\"], tag_df[\"detagged_citekey\"]) ) return", "always the exact path to the cache. If None, do", "= os.fspath(args.citations_path) variables[\"pandoc\"][\"manubot-requests-cache-path\"] = os.fspath( args.requests_cache_path ) variables[\"pandoc\"][\"manubot-clear-requests-cache\"] = args.clear_requests_cache", "in case this is essential for monkey patching by requests_cache." ]
[ "= children[n+1].text if style is None: try: style = children[n+1].find('span').text", "in detail_tree.find(\".//div[@class='col-sm-9']\").iterchildren(): if use_next and child.tag == 'p': recipes[name]['IBA_description'] =", "= {'1': 'one', '2': 'two', 'A': 'one'} try: recipes[name]['ingredients'][' '.join([w.lower()", "len(ingredient.split()) == 1: recipes[name]['ingredients'][ingredient.lower()] = '' continue unit = ingredient.split()[1].lower()", "fp.readlines(): if line.lstrip().startswith(r'<h3>'): print line.lstrip() # super hax if line.startswith(r'<p>'):", "' '.join([word.capitalize() for word in name.split()]) body = item.find(\".//div[@class='blog_text']\") recipes[name]", "sys import xml.etree.ElementTree as ET from lxml import html import", "== 'bar' or unit == 'to': # bar spoon recipes[name]['ingredients']['", "'http://iba-world.com/iba-cocktails/' jsonfile = 'IBA_unforgettables.json' url = 'http://iba-world.com/contemporary-classics/' jsonfile = 'IBA_contemporary_classics.json'", "ingredient.split()[2:]])] = ' '.join(ingredient.split()[:2]) elif unit == 'dash': recipes[name]['ingredients'][' '.join([w.lower()", "# Get full description from the link ref_url = item.find(\".//a[@class='top_hover_image']\").attrib.get('href')", "== 'ul': n = -1 style = children[n+1].text if style", "if style is None: try: style = children[n+1].find('span').text except: pass", "with open(jsonfile, 'w') as fp: json.dump(recipes, fp, indent=4, separators=(',', ':", "'dash' else: print \"using literal: \", ingredient literal = {'1':", "as {}\".format(jsonfile) sys.exit(0) raw = sys.argv[1] with open(raw) as fp:", "= 'http://iba-world.com/iba-cocktails/' jsonfile = 'IBA_unforgettables.json' url = 'http://iba-world.com/contemporary-classics/' jsonfile =", "bar spoon recipes[name]['ingredients'][' '.join([w.lower() for w in ingredient.split()[3:]])] = '", "for w in ingredient.split()[3:]])] = ' '.join(ingredient.split()[:3]) elif unit ==", "child.tag == 'p': recipes[name]['IBA_description'] = child.text break if child.tag =='ul':", "'IBA_new_era_drinks.json' url = 'http://iba-world.com/iba-cocktails/' jsonfile = 'IBA_unforgettables.json' url = 'http://iba-world.com/contemporary-classics/'", "not children[n+2].tag == 'ul': print \"adapting <p> ingredients:\", children[n+2].text ing_list", "requests.get(url) tree = html.fromstring(page.content) items = tree.findall(\".//div[@class='blog_list_item_lists']\") for item in", "'.join([word.capitalize() for word in name.split()]) body = item.find(\".//div[@class='blog_text']\") recipes[name] =", "import pprint from collections import OrderedDict import json url =", "# super hax if line.startswith(r'<p>'): print line if line.startswith(r'<li>'): print", "n = 0 if children[1].tag == 'ul': n = -1", "<p> ingredients:\", children[n+2].text ing_list = ET.tostring(children[n+2]).lstrip('<p>').rstrip('</p>\\n').split('<br />\\n') else: ing_list =", "ingredients:\", children[n+2].text ing_list = ET.tostring(children[n+2]).lstrip('<p>').rstrip('</p>\\n').split('<br />\\n') else: ing_list = [i.text", "w in ingredient.split()[1:]])] = literal[ingredient.split()[0]] except: recipes[name]['ingredients'][ingredient.lower()] = '' #", "lxml import html import requests from pprint import pprint from", "= [i.text for i in children[n+2].iterchildren()] for ingredient in ing_list:", "'with': recipes[name]['ingredients'][' '.join([w.lower() for w in ingredient.split()[2:]])] = ' '.join(ingredient.split()[:2])", "the IBA pages for cocktail lists import sys import xml.etree.ElementTree", "== 'ul': print \"adapting <p> ingredients:\", children[n+2].text ing_list = ET.tostring(children[n+2]).lstrip('<p>').rstrip('</p>\\n').split('<br", "continue unit = ingredient.split()[1].lower() if unit == 'cl': recipes[name]['ingredients'][' '.join([w.lower()", "[c for c in body.iterchildren()] n = 0 if children[1].tag", "= '' continue unit = ingredient.split()[1].lower() if unit == 'cl':", "pass recipes[name]['style'] = style recipes[name]['ingredients'] = OrderedDict() if not children[n+2].tag", "children[n+1].text if style is None: try: style = children[n+1].find('span').text except:", "open(jsonfile, 'w') as fp: json.dump(recipes, fp, indent=4, separators=(',', ': '))", "line.lstrip() # super hax if line.startswith(r'<p>'): print line if line.startswith(r'<li>'):", "literal: \", ingredient literal = {'1': 'one', '2': 'two', 'A':", "w in ingredient.split()[2:]])] = ' '.join(ingredient.split()[:2]) elif unit == 'dash':", "recipes[name]['ingredients'] = OrderedDict() if not children[n+2].tag == 'ul': print \"adapting", "pprint from collections import OrderedDict import json url = 'http://iba-world.com/new-era-drinks/'", "children[n+2].iterchildren()] for ingredient in ing_list: if len(ingredient.split()) == 1: recipes[name]['ingredients'][ingredient.lower()]", "[i.text for i in children[n+2].iterchildren()] for ingredient in ing_list: if", "'one', '2': 'two', 'A': 'one'} try: recipes[name]['ingredients'][' '.join([w.lower() for w", "import xml.etree.ElementTree as ET from lxml import html import requests", "in ingredient.split()[2:]])] = float(ingredient.split()[0]) elif unit == 'bar' or unit", "'' # Get full description from the link ref_url =", "item.find(\".//a[@class='top_hover_image']\").attrib.get('href') detail_page = requests.get(ref_url) detail_tree = html.fromstring(detail_page.content) use_next = False", "': ')) print \"Wrote out as {}\".format(jsonfile) sys.exit(0) raw =", "pprint import pprint from collections import OrderedDict import json url", "# scrape the IBA pages for cocktail lists import sys", "xml.etree.ElementTree as ET from lxml import html import requests from", "<gh_stars>1-10 #! /usr/bin/env python # scrape the IBA pages for", "in ing_list: if len(ingredient.split()) == 1: recipes[name]['ingredients'][ingredient.lower()] = '' continue", "page = requests.get(url) tree = html.fromstring(page.content) items = tree.findall(\".//div[@class='blog_list_item_lists']\") for", "= ' '.join(ingredient.split()[:3]) elif unit == 'dashes' or unit ==", "False for child in detail_tree.find(\".//div[@class='col-sm-9']\").iterchildren(): if use_next and child.tag ==", "body = item.find(\".//div[@class='blog_text']\") recipes[name] = {'unit': 'cL'} print name children", "ingredient literal = {'1': 'one', '2': 'two', 'A': 'one'} try:", "item in items: name = item.find(\".//h3\").text name = ' '.join([word.capitalize()", "use_next = False for child in detail_tree.find(\".//div[@class='col-sm-9']\").iterchildren(): if use_next and", "detail_page = requests.get(ref_url) detail_tree = html.fromstring(detail_page.content) use_next = False for", "children[n+1].find('span').text except: pass recipes[name]['style'] = style recipes[name]['ingredients'] = OrderedDict() if", "\"Wrote out as {}\".format(jsonfile) sys.exit(0) raw = sys.argv[1] with open(raw)", "= item.find(\".//a[@class='top_hover_image']\").attrib.get('href') detail_page = requests.get(ref_url) detail_tree = html.fromstring(detail_page.content) use_next =", "'bar' or unit == 'to': # bar spoon recipes[name]['ingredients'][' '.join([w.lower()", "in items: name = item.find(\".//h3\").text name = ' '.join([word.capitalize() for", "recipes[name] = {'unit': 'cL'} print name children = [c for", "in ingredient.split()[3:]])] = ' '.join(ingredient.split()[:3]) elif unit == 'dashes' or", "recipes[name]['ingredients'][ingredient.lower()] = '' # Get full description from the link", "'.join([w.lower() for w in ingredient.split()[2:]])] = 'dash' else: print \"using", "unit == 'cl': recipes[name]['ingredients'][' '.join([w.lower() for w in ingredient.split()[2:]])] =", "items = tree.findall(\".//div[@class='blog_list_item_lists']\") for item in items: name = item.find(\".//h3\").text", "= 0 if children[1].tag == 'ul': n = -1 style", "except: recipes[name]['ingredients'][ingredient.lower()] = '' # Get full description from the", "name = ' '.join([word.capitalize() for word in name.split()]) body =", "' '.join(ingredient.split()[:2]) elif unit == 'dash': recipes[name]['ingredients'][' '.join([w.lower() for w", "fp: for line in fp.readlines(): if line.lstrip().startswith(r'<h3>'): print line.lstrip() #", "'IBA_unforgettables.json' url = 'http://iba-world.com/contemporary-classics/' jsonfile = 'IBA_contemporary_classics.json' jsonfile = 'IBA_.json'", "html.fromstring(detail_page.content) use_next = False for child in detail_tree.find(\".//div[@class='col-sm-9']\").iterchildren(): if use_next", "literal = {'1': 'one', '2': 'two', 'A': 'one'} try: recipes[name]['ingredients']['", "link ref_url = item.find(\".//a[@class='top_hover_image']\").attrib.get('href') detail_page = requests.get(ref_url) detail_tree = html.fromstring(detail_page.content)", "recipes[name]['ingredients'][' '.join([w.lower() for w in ingredient.split()[1:]])] = literal[ingredient.split()[0]] except: recipes[name]['ingredients'][ingredient.lower()]", "child.tag =='ul': use_next = True with open(jsonfile, 'w') as fp:", "ingredient.split()[2:]])] = float(ingredient.split()[0]) elif unit == 'bar' or unit ==", "= -1 style = children[n+1].text if style is None: try:", "unit == 'bar' or unit == 'to': # bar spoon", "line.lstrip().startswith(r'<h3>'): print line.lstrip() # super hax if line.startswith(r'<p>'): print line", "{}\".format(jsonfile) sys.exit(0) raw = sys.argv[1] with open(raw) as fp: for", "use_next and child.tag == 'p': recipes[name]['IBA_description'] = child.text break if", "OrderedDict() if not children[n+2].tag == 'ul': print \"adapting <p> ingredients:\",", "'dash': recipes[name]['ingredients'][' '.join([w.lower() for w in ingredient.split()[2:]])] = 'dash' else:", "recipes[name]['style'] = style recipes[name]['ingredients'] = OrderedDict() if not children[n+2].tag ==", "from the link ref_url = item.find(\".//a[@class='top_hover_image']\").attrib.get('href') detail_page = requests.get(ref_url) detail_tree", "= 'IBA_new_era_drinks.json' url = 'http://iba-world.com/iba-cocktails/' jsonfile = 'IBA_unforgettables.json' url =", "description from the link ref_url = item.find(\".//a[@class='top_hover_image']\").attrib.get('href') detail_page = requests.get(ref_url)", "unit == 'dashes' or unit == 'drops' or unit ==", "'.join(ingredient.split()[:2]) elif unit == 'dash': recipes[name]['ingredients'][' '.join([w.lower() for w in", "'two', 'A': 'one'} try: recipes[name]['ingredients'][' '.join([w.lower() for w in ingredient.split()[1:]])]", "in ingredient.split()[2:]])] = ' '.join(ingredient.split()[:2]) elif unit == 'dash': recipes[name]['ingredients']['", "json url = 'http://iba-world.com/new-era-drinks/' jsonfile = 'IBA_new_era_drinks.json' url = 'http://iba-world.com/iba-cocktails/'", "'.join([w.lower() for w in ingredient.split()[3:]])] = ' '.join(ingredient.split()[:3]) elif unit", "if child.tag =='ul': use_next = True with open(jsonfile, 'w') as", "recipes[name]['ingredients'][ingredient.lower()] = '' continue unit = ingredient.split()[1].lower() if unit ==", "if unit == 'cl': recipes[name]['ingredients'][' '.join([w.lower() for w in ingredient.split()[2:]])]", "if line.lstrip().startswith(r'<h3>'): print line.lstrip() # super hax if line.startswith(r'<p>'): print", "html.fromstring(page.content) items = tree.findall(\".//div[@class='blog_list_item_lists']\") for item in items: name =", "= OrderedDict() page = requests.get(url) tree = html.fromstring(page.content) items =", "'2': 'two', 'A': 'one'} try: recipes[name]['ingredients'][' '.join([w.lower() for w in", "'' continue unit = ingredient.split()[1].lower() if unit == 'cl': recipes[name]['ingredients']['", "import sys import xml.etree.ElementTree as ET from lxml import html", "== 'with': recipes[name]['ingredients'][' '.join([w.lower() for w in ingredient.split()[2:]])] = '", "recipes[name]['ingredients'][' '.join([w.lower() for w in ingredient.split()[3:]])] = ' '.join(ingredient.split()[:3]) elif", "'http://iba-world.com/new-era-drinks/' jsonfile = 'IBA_new_era_drinks.json' url = 'http://iba-world.com/iba-cocktails/' jsonfile = 'IBA_unforgettables.json'", "= ET.tostring(children[n+2]).lstrip('<p>').rstrip('</p>\\n').split('<br />\\n') else: ing_list = [i.text for i in", "'A': 'one'} try: recipes[name]['ingredients'][' '.join([w.lower() for w in ingredient.split()[1:]])] =", "use_next = True with open(jsonfile, 'w') as fp: json.dump(recipes, fp,", "w in ingredient.split()[2:]])] = float(ingredient.split()[0]) elif unit == 'bar' or", "unit == 'with': recipes[name]['ingredients'][' '.join([w.lower() for w in ingredient.split()[2:]])] =", "= float(ingredient.split()[0]) elif unit == 'bar' or unit == 'to':", "{'1': 'one', '2': 'two', 'A': 'one'} try: recipes[name]['ingredients'][' '.join([w.lower() for", "for cocktail lists import sys import xml.etree.ElementTree as ET from", "indent=4, separators=(',', ': ')) print \"Wrote out as {}\".format(jsonfile) sys.exit(0)", "break if child.tag =='ul': use_next = True with open(jsonfile, 'w')", "for line in fp.readlines(): if line.lstrip().startswith(r'<h3>'): print line.lstrip() # super", "= child.text break if child.tag =='ul': use_next = True with", "True with open(jsonfile, 'w') as fp: json.dump(recipes, fp, indent=4, separators=(',',", "unit == 'to': # bar spoon recipes[name]['ingredients'][' '.join([w.lower() for w", "json.dump(recipes, fp, indent=4, separators=(',', ': ')) print \"Wrote out as", "== 'p': recipes[name]['IBA_description'] = child.text break if child.tag =='ul': use_next", "requests from pprint import pprint from collections import OrderedDict import", "w in ingredient.split()[3:]])] = ' '.join(ingredient.split()[:3]) elif unit == 'dashes'", "=='ul': use_next = True with open(jsonfile, 'w') as fp: json.dump(recipes,", "jsonfile = 'IBA_new_era_drinks.json' url = 'http://iba-world.com/iba-cocktails/' jsonfile = 'IBA_unforgettables.json' url", "try: recipes[name]['ingredients'][' '.join([w.lower() for w in ingredient.split()[1:]])] = literal[ingredient.split()[0]] except:", "/>\\n') else: ing_list = [i.text for i in children[n+2].iterchildren()] for", "body.iterchildren()] n = 0 if children[1].tag == 'ul': n =", "/usr/bin/env python # scrape the IBA pages for cocktail lists", "= item.find(\".//div[@class='blog_text']\") recipes[name] = {'unit': 'cL'} print name children =", "print \"Wrote out as {}\".format(jsonfile) sys.exit(0) raw = sys.argv[1] with", "-1 style = children[n+1].text if style is None: try: style", "except: pass recipes[name]['style'] = style recipes[name]['ingredients'] = OrderedDict() if not", "raw = sys.argv[1] with open(raw) as fp: for line in", "in ingredient.split()[1:]])] = literal[ingredient.split()[0]] except: recipes[name]['ingredients'][ingredient.lower()] = '' # Get", "for i in children[n+2].iterchildren()] for ingredient in ing_list: if len(ingredient.split())", "detail_tree.find(\".//div[@class='col-sm-9']\").iterchildren(): if use_next and child.tag == 'p': recipes[name]['IBA_description'] = child.text", "tree.findall(\".//div[@class='blog_list_item_lists']\") for item in items: name = item.find(\".//h3\").text name =", "= ' '.join([word.capitalize() for word in name.split()]) body = item.find(\".//div[@class='blog_text']\")", "ing_list = ET.tostring(children[n+2]).lstrip('<p>').rstrip('</p>\\n').split('<br />\\n') else: ing_list = [i.text for i", "try: style = children[n+1].find('span').text except: pass recipes[name]['style'] = style recipes[name]['ingredients']", "= requests.get(ref_url) detail_tree = html.fromstring(detail_page.content) use_next = False for child", "in fp.readlines(): if line.lstrip().startswith(r'<h3>'): print line.lstrip() # super hax if", "tree = html.fromstring(page.content) items = tree.findall(\".//div[@class='blog_list_item_lists']\") for item in items:", "for child in detail_tree.find(\".//div[@class='col-sm-9']\").iterchildren(): if use_next and child.tag == 'p':", "\"adapting <p> ingredients:\", children[n+2].text ing_list = ET.tostring(children[n+2]).lstrip('<p>').rstrip('</p>\\n').split('<br />\\n') else: ing_list", "word in name.split()]) body = item.find(\".//div[@class='blog_text']\") recipes[name] = {'unit': 'cL'}", "cocktail lists import sys import xml.etree.ElementTree as ET from lxml", "= item.find(\".//h3\").text name = ' '.join([word.capitalize() for word in name.split()])", "style recipes[name]['ingredients'] = OrderedDict() if not children[n+2].tag == 'ul': print", "'to': # bar spoon recipes[name]['ingredients'][' '.join([w.lower() for w in ingredient.split()[3:]])]", "out as {}\".format(jsonfile) sys.exit(0) raw = sys.argv[1] with open(raw) as", "for w in ingredient.split()[2:]])] = float(ingredient.split()[0]) elif unit == 'bar'", "c in body.iterchildren()] n = 0 if children[1].tag == 'ul':", "line.startswith(r'<p>'): print line if line.startswith(r'<li>'): print line if not line.lstrip().startswith('<'):", "children[n+2].tag == 'ul': print \"adapting <p> ingredients:\", children[n+2].text ing_list =", "html import requests from pprint import pprint from collections import", "# bar spoon recipes[name]['ingredients'][' '.join([w.lower() for w in ingredient.split()[3:]])] =", "unit == 'dash': recipes[name]['ingredients'][' '.join([w.lower() for w in ingredient.split()[2:]])] =", "'ul': n = -1 style = children[n+1].text if style is", "= ingredient.split()[1].lower() if unit == 'cl': recipes[name]['ingredients'][' '.join([w.lower() for w", "'.join([w.lower() for w in ingredient.split()[2:]])] = ' '.join(ingredient.split()[:2]) elif unit", "ingredient.split()[1].lower() if unit == 'cl': recipes[name]['ingredients'][' '.join([w.lower() for w in", "= tree.findall(\".//div[@class='blog_list_item_lists']\") for item in items: name = item.find(\".//h3\").text name", "i in children[n+2].iterchildren()] for ingredient in ing_list: if len(ingredient.split()) ==", "')) print \"Wrote out as {}\".format(jsonfile) sys.exit(0) raw = sys.argv[1]", "1: recipes[name]['ingredients'][ingredient.lower()] = '' continue unit = ingredient.split()[1].lower() if unit", "w in ingredient.split()[2:]])] = 'dash' else: print \"using literal: \",", "fp, indent=4, separators=(',', ': ')) print \"Wrote out as {}\".format(jsonfile)", "= '' # Get full description from the link ref_url", "requests.get(ref_url) detail_tree = html.fromstring(detail_page.content) use_next = False for child in", "print line.lstrip() # super hax if line.startswith(r'<p>'): print line if", "from lxml import html import requests from pprint import pprint", "OrderedDict import json url = 'http://iba-world.com/new-era-drinks/' jsonfile = 'IBA_new_era_drinks.json' url", "if children[1].tag == 'ul': n = -1 style = children[n+1].text", "\", ingredient literal = {'1': 'one', '2': 'two', 'A': 'one'}", "in body.iterchildren()] n = 0 if children[1].tag == 'ul': n", "ing_list: if len(ingredient.split()) == 1: recipes[name]['ingredients'][ingredient.lower()] = '' continue unit", "= True with open(jsonfile, 'w') as fp: json.dump(recipes, fp, indent=4,", "None: try: style = children[n+1].find('span').text except: pass recipes[name]['style'] = style", "url = 'http://iba-world.com/iba-cocktails/' jsonfile = 'IBA_unforgettables.json' url = 'http://iba-world.com/contemporary-classics/' jsonfile", "else: ing_list = [i.text for i in children[n+2].iterchildren()] for ingredient", "= 'IBA_unforgettables.json' url = 'http://iba-world.com/contemporary-classics/' jsonfile = 'IBA_contemporary_classics.json' jsonfile =", "recipes = OrderedDict() page = requests.get(url) tree = html.fromstring(page.content) items", "collections import OrderedDict import json url = 'http://iba-world.com/new-era-drinks/' jsonfile =", "elif unit == 'bar' or unit == 'to': # bar", "'dashes' or unit == 'drops' or unit == 'with': recipes[name]['ingredients']['", "= 'IBA_contemporary_classics.json' jsonfile = 'IBA_.json' recipes = OrderedDict() page =", "== 'cl': recipes[name]['ingredients'][' '.join([w.lower() for w in ingredient.split()[2:]])] = float(ingredient.split()[0])", "= style recipes[name]['ingredients'] = OrderedDict() if not children[n+2].tag == 'ul':", "= 'http://iba-world.com/contemporary-classics/' jsonfile = 'IBA_contemporary_classics.json' jsonfile = 'IBA_.json' recipes =", "if len(ingredient.split()) == 1: recipes[name]['ingredients'][ingredient.lower()] = '' continue unit =", "= {'unit': 'cL'} print name children = [c for c", "ingredient.split()[3:]])] = ' '.join(ingredient.split()[:3]) elif unit == 'dashes' or unit", "ET from lxml import html import requests from pprint import", "= 'IBA_.json' recipes = OrderedDict() page = requests.get(url) tree =", "name.split()]) body = item.find(\".//div[@class='blog_text']\") recipes[name] = {'unit': 'cL'} print name", "recipes[name]['ingredients'][' '.join([w.lower() for w in ingredient.split()[2:]])] = float(ingredient.split()[0]) elif unit", "ref_url = item.find(\".//a[@class='top_hover_image']\").attrib.get('href') detail_page = requests.get(ref_url) detail_tree = html.fromstring(detail_page.content) use_next", "if not children[n+2].tag == 'ul': print \"adapting <p> ingredients:\", children[n+2].text", "else: print \"using literal: \", ingredient literal = {'1': 'one',", "in ingredient.split()[2:]])] = 'dash' else: print \"using literal: \", ingredient", "print name children = [c for c in body.iterchildren()] n", "python # scrape the IBA pages for cocktail lists import", "'ul': print \"adapting <p> ingredients:\", children[n+2].text ing_list = ET.tostring(children[n+2]).lstrip('<p>').rstrip('</p>\\n').split('<br />\\n')", "for word in name.split()]) body = item.find(\".//div[@class='blog_text']\") recipes[name] = {'unit':", "and child.tag == 'p': recipes[name]['IBA_description'] = child.text break if child.tag", "item.find(\".//div[@class='blog_text']\") recipes[name] = {'unit': 'cL'} print name children = [c", "spoon recipes[name]['ingredients'][' '.join([w.lower() for w in ingredient.split()[3:]])] = ' '.join(ingredient.split()[:3])", "items: name = item.find(\".//h3\").text name = ' '.join([word.capitalize() for word", "with open(raw) as fp: for line in fp.readlines(): if line.lstrip().startswith(r'<h3>'):", "'p': recipes[name]['IBA_description'] = child.text break if child.tag =='ul': use_next =", "'cl': recipes[name]['ingredients'][' '.join([w.lower() for w in ingredient.split()[2:]])] = float(ingredient.split()[0]) elif", "full description from the link ref_url = item.find(\".//a[@class='top_hover_image']\").attrib.get('href') detail_page =", "is None: try: style = children[n+1].find('span').text except: pass recipes[name]['style'] =", "OrderedDict() page = requests.get(url) tree = html.fromstring(page.content) items = tree.findall(\".//div[@class='blog_list_item_lists']\")", "import json url = 'http://iba-world.com/new-era-drinks/' jsonfile = 'IBA_new_era_drinks.json' url =", "recipes[name]['ingredients'][' '.join([w.lower() for w in ingredient.split()[2:]])] = 'dash' else: print", "print \"using literal: \", ingredient literal = {'1': 'one', '2':", "'w') as fp: json.dump(recipes, fp, indent=4, separators=(',', ': ')) print", "ing_list = [i.text for i in children[n+2].iterchildren()] for ingredient in", "line if line.startswith(r'<li>'): print line if not line.lstrip().startswith('<'): print line", "recipes[name]['IBA_description'] = child.text break if child.tag =='ul': use_next = True", "fp: json.dump(recipes, fp, indent=4, separators=(',', ': ')) print \"Wrote out", "float(ingredient.split()[0]) elif unit == 'bar' or unit == 'to': #", "elif unit == 'dashes' or unit == 'drops' or unit", "name children = [c for c in body.iterchildren()] n =", "the link ref_url = item.find(\".//a[@class='top_hover_image']\").attrib.get('href') detail_page = requests.get(ref_url) detail_tree =", "\"using literal: \", ingredient literal = {'1': 'one', '2': 'two',", "name = item.find(\".//h3\").text name = ' '.join([word.capitalize() for word in", "n = -1 style = children[n+1].text if style is None:", "#! /usr/bin/env python # scrape the IBA pages for cocktail", "scrape the IBA pages for cocktail lists import sys import", "== 'dashes' or unit == 'drops' or unit == 'with':", "ingredient in ing_list: if len(ingredient.split()) == 1: recipes[name]['ingredients'][ingredient.lower()] = ''", "child in detail_tree.find(\".//div[@class='col-sm-9']\").iterchildren(): if use_next and child.tag == 'p': recipes[name]['IBA_description']", "'.join([w.lower() for w in ingredient.split()[1:]])] = literal[ingredient.split()[0]] except: recipes[name]['ingredients'][ingredient.lower()] =", "'IBA_.json' recipes = OrderedDict() page = requests.get(url) tree = html.fromstring(page.content)", "recipes[name]['ingredients'][' '.join([w.lower() for w in ingredient.split()[2:]])] = ' '.join(ingredient.split()[:2]) elif", "in name.split()]) body = item.find(\".//div[@class='blog_text']\") recipes[name] = {'unit': 'cL'} print", "open(raw) as fp: for line in fp.readlines(): if line.lstrip().startswith(r'<h3>'): print", "separators=(',', ': ')) print \"Wrote out as {}\".format(jsonfile) sys.exit(0) raw", "style = children[n+1].text if style is None: try: style =", "print \"adapting <p> ingredients:\", children[n+2].text ing_list = ET.tostring(children[n+2]).lstrip('<p>').rstrip('</p>\\n').split('<br />\\n') else:", "== 1: recipes[name]['ingredients'][ingredient.lower()] = '' continue unit = ingredient.split()[1].lower() if", "from pprint import pprint from collections import OrderedDict import json", "= 'http://iba-world.com/new-era-drinks/' jsonfile = 'IBA_new_era_drinks.json' url = 'http://iba-world.com/iba-cocktails/' jsonfile =", "as ET from lxml import html import requests from pprint", "= OrderedDict() if not children[n+2].tag == 'ul': print \"adapting <p>", "if use_next and child.tag == 'p': recipes[name]['IBA_description'] = child.text break", "= children[n+1].find('span').text except: pass recipes[name]['style'] = style recipes[name]['ingredients'] = OrderedDict()", "= html.fromstring(detail_page.content) use_next = False for child in detail_tree.find(\".//div[@class='col-sm-9']\").iterchildren(): if", "for c in body.iterchildren()] n = 0 if children[1].tag ==", "item.find(\".//h3\").text name = ' '.join([word.capitalize() for word in name.split()]) body", "= 'dash' else: print \"using literal: \", ingredient literal =", "sys.argv[1] with open(raw) as fp: for line in fp.readlines(): if", "'one'} try: recipes[name]['ingredients'][' '.join([w.lower() for w in ingredient.split()[1:]])] = literal[ingredient.split()[0]]", "= [c for c in body.iterchildren()] n = 0 if", "IBA pages for cocktail lists import sys import xml.etree.ElementTree as", "url = 'http://iba-world.com/new-era-drinks/' jsonfile = 'IBA_new_era_drinks.json' url = 'http://iba-world.com/iba-cocktails/' jsonfile", "= literal[ingredient.split()[0]] except: recipes[name]['ingredients'][ingredient.lower()] = '' # Get full description", "as fp: json.dump(recipes, fp, indent=4, separators=(',', ': ')) print \"Wrote", "detail_tree = html.fromstring(detail_page.content) use_next = False for child in detail_tree.find(\".//div[@class='col-sm-9']\").iterchildren():", "or unit == 'with': recipes[name]['ingredients'][' '.join([w.lower() for w in ingredient.split()[2:]])]", "super hax if line.startswith(r'<p>'): print line if line.startswith(r'<li>'): print line", "elif unit == 'dash': recipes[name]['ingredients'][' '.join([w.lower() for w in ingredient.split()[2:]])]", "'http://iba-world.com/contemporary-classics/' jsonfile = 'IBA_contemporary_classics.json' jsonfile = 'IBA_.json' recipes = OrderedDict()", "for w in ingredient.split()[1:]])] = literal[ingredient.split()[0]] except: recipes[name]['ingredients'][ingredient.lower()] = ''", "'.join(ingredient.split()[:3]) elif unit == 'dashes' or unit == 'drops' or", "style = children[n+1].find('span').text except: pass recipes[name]['style'] = style recipes[name]['ingredients'] =", "Get full description from the link ref_url = item.find(\".//a[@class='top_hover_image']\").attrib.get('href') detail_page", "import html import requests from pprint import pprint from collections", "{'unit': 'cL'} print name children = [c for c in", "import OrderedDict import json url = 'http://iba-world.com/new-era-drinks/' jsonfile = 'IBA_new_era_drinks.json'", "lists import sys import xml.etree.ElementTree as ET from lxml import", "children = [c for c in body.iterchildren()] n = 0", "= html.fromstring(page.content) items = tree.findall(\".//div[@class='blog_list_item_lists']\") for item in items: name", "in children[n+2].iterchildren()] for ingredient in ing_list: if len(ingredient.split()) == 1:", "jsonfile = 'IBA_unforgettables.json' url = 'http://iba-world.com/contemporary-classics/' jsonfile = 'IBA_contemporary_classics.json' jsonfile", "'cL'} print name children = [c for c in body.iterchildren()]", "= ' '.join(ingredient.split()[:2]) elif unit == 'dash': recipes[name]['ingredients'][' '.join([w.lower() for", "line in fp.readlines(): if line.lstrip().startswith(r'<h3>'): print line.lstrip() # super hax", "as fp: for line in fp.readlines(): if line.lstrip().startswith(r'<h3>'): print line.lstrip()", "url = 'http://iba-world.com/contemporary-classics/' jsonfile = 'IBA_contemporary_classics.json' jsonfile = 'IBA_.json' recipes", "unit == 'drops' or unit == 'with': recipes[name]['ingredients'][' '.join([w.lower() for", "0 if children[1].tag == 'ul': n = -1 style =", "'drops' or unit == 'with': recipes[name]['ingredients'][' '.join([w.lower() for w in", "== 'drops' or unit == 'with': recipes[name]['ingredients'][' '.join([w.lower() for w", "ingredient.split()[1:]])] = literal[ingredient.split()[0]] except: recipes[name]['ingredients'][ingredient.lower()] = '' # Get full", "' '.join(ingredient.split()[:3]) elif unit == 'dashes' or unit == 'drops'", "child.text break if child.tag =='ul': use_next = True with open(jsonfile,", "import requests from pprint import pprint from collections import OrderedDict", "for w in ingredient.split()[2:]])] = 'dash' else: print \"using literal:", "= sys.argv[1] with open(raw) as fp: for line in fp.readlines():", "== 'to': # bar spoon recipes[name]['ingredients'][' '.join([w.lower() for w in", "print line if line.startswith(r'<li>'): print line if not line.lstrip().startswith('<'): print", "literal[ingredient.split()[0]] except: recipes[name]['ingredients'][ingredient.lower()] = '' # Get full description from", "pages for cocktail lists import sys import xml.etree.ElementTree as ET", "'IBA_contemporary_classics.json' jsonfile = 'IBA_.json' recipes = OrderedDict() page = requests.get(url)", "or unit == 'drops' or unit == 'with': recipes[name]['ingredients'][' '.join([w.lower()", "= False for child in detail_tree.find(\".//div[@class='col-sm-9']\").iterchildren(): if use_next and child.tag", "= requests.get(url) tree = html.fromstring(page.content) items = tree.findall(\".//div[@class='blog_list_item_lists']\") for item", "from collections import OrderedDict import json url = 'http://iba-world.com/new-era-drinks/' jsonfile", "unit = ingredient.split()[1].lower() if unit == 'cl': recipes[name]['ingredients'][' '.join([w.lower() for", "style is None: try: style = children[n+1].find('span').text except: pass recipes[name]['style']", "hax if line.startswith(r'<p>'): print line if line.startswith(r'<li>'): print line if", "ingredient.split()[2:]])] = 'dash' else: print \"using literal: \", ingredient literal", "jsonfile = 'IBA_.json' recipes = OrderedDict() page = requests.get(url) tree", "for ingredient in ing_list: if len(ingredient.split()) == 1: recipes[name]['ingredients'][ingredient.lower()] =", "jsonfile = 'IBA_contemporary_classics.json' jsonfile = 'IBA_.json' recipes = OrderedDict() page", "or unit == 'to': # bar spoon recipes[name]['ingredients'][' '.join([w.lower() for", "if line.startswith(r'<p>'): print line if line.startswith(r'<li>'): print line if not", "children[1].tag == 'ul': n = -1 style = children[n+1].text if", "sys.exit(0) raw = sys.argv[1] with open(raw) as fp: for line", "ET.tostring(children[n+2]).lstrip('<p>').rstrip('</p>\\n').split('<br />\\n') else: ing_list = [i.text for i in children[n+2].iterchildren()]", "for w in ingredient.split()[2:]])] = ' '.join(ingredient.split()[:2]) elif unit ==", "children[n+2].text ing_list = ET.tostring(children[n+2]).lstrip('<p>').rstrip('</p>\\n').split('<br />\\n') else: ing_list = [i.text for", "'.join([w.lower() for w in ingredient.split()[2:]])] = float(ingredient.split()[0]) elif unit ==", "== 'dash': recipes[name]['ingredients'][' '.join([w.lower() for w in ingredient.split()[2:]])] = 'dash'", "for item in items: name = item.find(\".//h3\").text name = '" ]
[ "elif name in focus and ansistors_n is None: del focus[name]", "data, parent=None): self.name = name self.parent = parent self.data =", "None,): focus = self.childs while True: if ansistors_n == None", "True: if ansistors_n == None or ansistors_n == self.name: del", "self.childs = {} def add_child(self, name, data): self.childs.update({name:(type(self))(name, data, self)})", "name, data, parent=None): self.name = name self.parent = parent self.data", "print(focus) raise NameError(f\"couldn't find branch {ansistors_n[0]}\") def __getitem__(self, item): return", "value): self.childs[key] = value def __delitem__(self, key, ansistors_n: list =", "focus[name] break else: print(focus) raise NameError(f\"couldn't find branch {ansistors_n[0]}\") def", "= name self.parent = parent self.data = data self.childs =", "del focus[name] break else: print(focus) raise NameError(f\"couldn't find branch {ansistors_n[0]}\")", "def __init__(self, name, data, parent=None): self.name = name self.parent =", "= None,): focus = self.childs while True: if ansistors_n ==", "else: print(focus) raise NameError(f\"couldn't find branch {ansistors_n[0]}\") def __getitem__(self, item):", "{ansistors_n[0]}\") def __getitem__(self, item): return self.childs[item] def __setitem__(self, key, value):", "def rm_branch(self, name, ansistors_n: list = None,): focus = self.childs", "= value def __delitem__(self, key, ansistors_n: list = None): self.rm_branch(key,", "def __getitem__(self, item): return self.childs[item] def __setitem__(self, key, value): self.childs[key]", "name, data): self.childs.update({name:(type(self))(name, data, self)}) def rm_branch(self, name, ansistors_n: list", "= parent self.data = data self.childs = {} def add_child(self,", "elif ansistors_n[0] in focus: focus = (focus[ansistors_n[0]]).childs del ansistors_n[0] elif", "name, ansistors_n: list = None,): focus = self.childs while True:", "is None: del focus[name] break else: print(focus) raise NameError(f\"couldn't find", "__getitem__(self, item): return self.childs[item] def __setitem__(self, key, value): self.childs[key] =", "self.childs[key] = value def __delitem__(self, key, ansistors_n: list = None):", "== None or ansistors_n == self.name: del focus[name] break elif", "raise NameError(f\"couldn't find branch {ansistors_n[0]}\") def __getitem__(self, item): return self.childs[item]", "ansistors_n: list = None,): focus = self.childs while True: if", "ansistors_n is None: del focus[name] break else: print(focus) raise NameError(f\"couldn't", "break elif ansistors_n[0] in focus: focus = (focus[ansistors_n[0]]).childs del ansistors_n[0]", "(focus[ansistors_n[0]]).childs del ansistors_n[0] elif name in focus and ansistors_n is", "None: del focus[name] break else: print(focus) raise NameError(f\"couldn't find branch", "rm_branch(self, name, ansistors_n: list = None,): focus = self.childs while", "data, self)}) def rm_branch(self, name, ansistors_n: list = None,): focus", "focus and ansistors_n is None: del focus[name] break else: print(focus)", "self.childs while True: if ansistors_n == None or ansistors_n ==", "None or ansistors_n == self.name: del focus[name] break elif ansistors_n[0]", "__init__(self, name, data, parent=None): self.name = name self.parent = parent", "TreeNode: def __init__(self, name, data, parent=None): self.name = name self.parent", "while True: if ansistors_n == None or ansistors_n == self.name:", "== self.name: del focus[name] break elif ansistors_n[0] in focus: focus", "focus[name] break elif ansistors_n[0] in focus: focus = (focus[ansistors_n[0]]).childs del", "return self.childs[item] def __setitem__(self, key, value): self.childs[key] = value def", "self.childs[item] def __setitem__(self, key, value): self.childs[key] = value def __delitem__(self,", "ansistors_n[0] in focus: focus = (focus[ansistors_n[0]]).childs del ansistors_n[0] elif name", "list = None,): focus = self.childs while True: if ansistors_n", "break else: print(focus) raise NameError(f\"couldn't find branch {ansistors_n[0]}\") def __getitem__(self,", "branch {ansistors_n[0]}\") def __getitem__(self, item): return self.childs[item] def __setitem__(self, key,", "= (focus[ansistors_n[0]]).childs del ansistors_n[0] elif name in focus and ansistors_n", "ansistors_n == self.name: del focus[name] break elif ansistors_n[0] in focus:", "self.name = name self.parent = parent self.data = data self.childs", "NameError(f\"couldn't find branch {ansistors_n[0]}\") def __getitem__(self, item): return self.childs[item] def", "def add_child(self, name, data): self.childs.update({name:(type(self))(name, data, self)}) def rm_branch(self, name,", "def __setitem__(self, key, value): self.childs[key] = value def __delitem__(self, key,", "self.childs.update({name:(type(self))(name, data, self)}) def rm_branch(self, name, ansistors_n: list = None,):", "data self.childs = {} def add_child(self, name, data): self.childs.update({name:(type(self))(name, data,", "= self.childs while True: if ansistors_n == None or ansistors_n", "name in focus and ansistors_n is None: del focus[name] break", "del ansistors_n[0] elif name in focus and ansistors_n is None:", "find branch {ansistors_n[0]}\") def __getitem__(self, item): return self.childs[item] def __setitem__(self,", "= data self.childs = {} def add_child(self, name, data): self.childs.update({name:(type(self))(name,", "class TreeNode: def __init__(self, name, data, parent=None): self.name = name", "{} def add_child(self, name, data): self.childs.update({name:(type(self))(name, data, self)}) def rm_branch(self,", "item): return self.childs[item] def __setitem__(self, key, value): self.childs[key] = value", "in focus and ansistors_n is None: del focus[name] break else:", "self)}) def rm_branch(self, name, ansistors_n: list = None,): focus =", "if ansistors_n == None or ansistors_n == self.name: del focus[name]", "parent self.data = data self.childs = {} def add_child(self, name,", "data): self.childs.update({name:(type(self))(name, data, self)}) def rm_branch(self, name, ansistors_n: list =", "del focus[name] break elif ansistors_n[0] in focus: focus = (focus[ansistors_n[0]]).childs", "ansistors_n[0] elif name in focus and ansistors_n is None: del", "key, value): self.childs[key] = value def __delitem__(self, key, ansistors_n: list", "self.name: del focus[name] break elif ansistors_n[0] in focus: focus =", "focus = self.childs while True: if ansistors_n == None or", "focus: focus = (focus[ansistors_n[0]]).childs del ansistors_n[0] elif name in focus", "self.parent = parent self.data = data self.childs = {} def", "and ansistors_n is None: del focus[name] break else: print(focus) raise", "in focus: focus = (focus[ansistors_n[0]]).childs del ansistors_n[0] elif name in", "ansistors_n == None or ansistors_n == self.name: del focus[name] break", "parent=None): self.name = name self.parent = parent self.data = data", "self.data = data self.childs = {} def add_child(self, name, data):", "= {} def add_child(self, name, data): self.childs.update({name:(type(self))(name, data, self)}) def", "name self.parent = parent self.data = data self.childs = {}", "__setitem__(self, key, value): self.childs[key] = value def __delitem__(self, key, ansistors_n:", "value def __delitem__(self, key, ansistors_n: list = None): self.rm_branch(key, ansistors_n)", "focus = (focus[ansistors_n[0]]).childs del ansistors_n[0] elif name in focus and", "add_child(self, name, data): self.childs.update({name:(type(self))(name, data, self)}) def rm_branch(self, name, ansistors_n:", "or ansistors_n == self.name: del focus[name] break elif ansistors_n[0] in" ]
[ "= 'CarPopularity' mongo_collections = ['CarSalesByYear', 'PopularCarsByRegion'] years_data = ['2019', '2018',", "'CarPopularity' mongo_collections = ['CarSalesByYear', 'PopularCarsByRegion'] years_data = ['2019', '2018', '2017',", "api_key = \"<KEY>\" mongo_url = 'mongodb://localhost:27017' mongo_db = 'CarPopularity' mongo_collections", "\"<KEY>\" mongo_url = 'mongodb://localhost:27017' mongo_db = 'CarPopularity' mongo_collections = ['CarSalesByYear',", "'PopularCarsByRegion'] years_data = ['2019', '2018', '2017', '2016', '2015'] test_mode =", "'mongodb://localhost:27017' mongo_db = 'CarPopularity' mongo_collections = ['CarSalesByYear', 'PopularCarsByRegion'] years_data =", "years_data = ['2019', '2018', '2017', '2016', '2015'] test_mode = True", "mongo_db = 'CarPopularity' mongo_collections = ['CarSalesByYear', 'PopularCarsByRegion'] years_data = ['2019',", "= \"<KEY>\" mongo_url = 'mongodb://localhost:27017' mongo_db = 'CarPopularity' mongo_collections =", "mongo_collections = ['CarSalesByYear', 'PopularCarsByRegion'] years_data = ['2019', '2018', '2017', '2016',", "= ['CarSalesByYear', 'PopularCarsByRegion'] years_data = ['2019', '2018', '2017', '2016', '2015']", "['CarSalesByYear', 'PopularCarsByRegion'] years_data = ['2019', '2018', '2017', '2016', '2015'] test_mode", "= 'mongodb://localhost:27017' mongo_db = 'CarPopularity' mongo_collections = ['CarSalesByYear', 'PopularCarsByRegion'] years_data", "mongo_url = 'mongodb://localhost:27017' mongo_db = 'CarPopularity' mongo_collections = ['CarSalesByYear', 'PopularCarsByRegion']" ]
[ "image to feasible set if needed delta = advimage-image if", "-1), self.p, 1) mask = normVal<=self.epsilon scaling = self.epsilon/normVal scaling[mask]", "self.decay_factor = decay_factor self.stepsize = stepsize self.target = target self.steps", "= torch.zeros_like(image).detach() # PGD to get adversarial example for i", "device if self.data_name==\"cifar10\" and self.target: raise AssertionError('cifar10 dont support targeted", "= torch.norm(grad.view(batchsize, -1), self.p, 1) updates = grad/normVal.view(batchsize, 1, 1,", "def __init__(self, net, epsilon, p, stepsize, steps, decay_factor, data_name,target, loss,", "from pytorch_ares.attack_torch.utils import loss_adv class MIM(object): '''Projected Gradient Descent''' def", "<gh_stars>100-1000 import imp import torch import torch.nn as nn import", "= torch.clamp(delta, -self.epsilon, self.epsilon) else: normVal = torch.norm(delta.view(batchsize, -1), self.p,", "targeted attack') def forward(self, image, label, target_labels): image, label =", "steps, decay_factor, data_name,target, loss, device): self.epsilon = epsilon self.p =", "device): self.epsilon = epsilon self.p = p self.net = net", "= decay_factor self.stepsize = stepsize self.target = target self.steps =", "target_labels): image, label = image.to(self.device), label.to(self.device) if target_labels is not", "np import torch.nn.functional as F from pytorch_ares.attack_torch.utils import loss_adv class", "forward(self, image, label, target_labels): image, label = image.to(self.device), label.to(self.device) if", "target_labels = target_labels.to(self.device) batchsize = image.shape[0] advimage = image momentum", "get adversarial example for i in range(self.steps): advimage = advimage.clone().detach().requires_grad_(True)", "advimage as the next iteration input netOut = self.net(advimage) loss", "image, label = image.to(self.device), label.to(self.device) if target_labels is not None:", "torch.norm(nn.Flatten()(grad), p=1, dim=1) grad = grad / grad_norm.view([-1]+[1]*(len(grad.shape)-1)) grad =", "self.net(advimage) loss = loss_adv(self.loss, netOut, label, target_labels, self.target, self.device) grad", "import torch.nn as nn import numpy as np import torch.nn.functional", "momentum*self.decay_factor momentum = grad if self.p==np.inf: updates = grad.sign() else:", "1, 1) updates = updates*self.stepsize advimage = advimage+updates # project", "self.target: raise AssertionError('cifar10 dont support targeted attack') def forward(self, image,", "target_labels is not None: target_labels = target_labels.to(self.device) batchsize = image.shape[0]", "# PGD to get adversarial example for i in range(self.steps):", "delta = advimage-image if self.p==np.inf: delta = torch.clamp(delta, -self.epsilon, self.epsilon)", "advimage-image if self.p==np.inf: delta = torch.clamp(delta, -self.epsilon, self.epsilon) else: normVal", "= image.to(self.device), label.to(self.device) if target_labels is not None: target_labels =", "grad if self.p==np.inf: updates = grad.sign() else: normVal = torch.norm(grad.view(batchsize,", "= target_labels.to(self.device) batchsize = image.shape[0] advimage = image momentum =", "PGD to get adversarial example for i in range(self.steps): advimage", "delta = delta*scaling.view(batchsize, 1, 1, 1) advimage = image+delta advimage", "advimage = image momentum = torch.zeros_like(image).detach() # PGD to get", "grad_norm.view([-1]+[1]*(len(grad.shape)-1)) grad = grad + momentum*self.decay_factor momentum = grad if", "updates*self.stepsize advimage = advimage+updates # project the disturbed image to", "raise AssertionError('cifar10 dont support targeted attack') def forward(self, image, label,", "= normVal<=self.epsilon scaling = self.epsilon/normVal scaling[mask] = 1 delta =", "= data_name self.device = device if self.data_name==\"cifar10\" and self.target: raise", "= advimage.clone().detach().requires_grad_(True) # clone the advimage as the next iteration", "-self.epsilon, self.epsilon) else: normVal = torch.norm(delta.view(batchsize, -1), self.p, 1) mask", "torch import torch.nn as nn import numpy as np import", "p, stepsize, steps, decay_factor, data_name,target, loss, device): self.epsilon = epsilon", "= grad.sign() else: normVal = torch.norm(grad.view(batchsize, -1), self.p, 1) updates", "imp import torch import torch.nn as nn import numpy as", "advimage = image+delta advimage = torch.clamp(advimage, 0, 1)#cifar10(-1,1) return advimage", "self.p, 1) updates = grad/normVal.view(batchsize, 1, 1, 1) updates =", "1, 1) advimage = image+delta advimage = torch.clamp(advimage, 0, 1)#cifar10(-1,1)", "as the next iteration input netOut = self.net(advimage) loss =", "the next iteration input netOut = self.net(advimage) loss = loss_adv(self.loss,", "self.loss = loss self.data_name = data_name self.device = device if", "= grad if self.p==np.inf: updates = grad.sign() else: normVal =", "self.device = device if self.data_name==\"cifar10\" and self.target: raise AssertionError('cifar10 dont", "disturbed image to feasible set if needed delta = advimage-image", "self.net = net self.decay_factor = decay_factor self.stepsize = stepsize self.target", "decay_factor self.stepsize = stepsize self.target = target self.steps = steps", "= loss self.data_name = data_name self.device = device if self.data_name==\"cifar10\"", "import numpy as np import torch.nn.functional as F from pytorch_ares.attack_torch.utils", "updates = updates*self.stepsize advimage = advimage+updates # project the disturbed", "= torch.norm(nn.Flatten()(grad), p=1, dim=1) grad = grad / grad_norm.view([-1]+[1]*(len(grad.shape)-1)) grad", "AssertionError('cifar10 dont support targeted attack') def forward(self, image, label, target_labels):", "import loss_adv class MIM(object): '''Projected Gradient Descent''' def __init__(self, net,", "= p self.net = net self.decay_factor = decay_factor self.stepsize =", "# project the disturbed image to feasible set if needed", "i in range(self.steps): advimage = advimage.clone().detach().requires_grad_(True) # clone the advimage", "data_name self.device = device if self.data_name==\"cifar10\" and self.target: raise AssertionError('cifar10", "1) updates = grad/normVal.view(batchsize, 1, 1, 1) updates = updates*self.stepsize", "p=1, dim=1) grad = grad / grad_norm.view([-1]+[1]*(len(grad.shape)-1)) grad = grad", "image, label, target_labels): image, label = image.to(self.device), label.to(self.device) if target_labels", "loss self.data_name = data_name self.device = device if self.data_name==\"cifar10\" and", "= self.epsilon/normVal scaling[mask] = 1 delta = delta*scaling.view(batchsize, 1, 1,", "stepsize self.target = target self.steps = steps self.loss = loss", "F from pytorch_ares.attack_torch.utils import loss_adv class MIM(object): '''Projected Gradient Descent'''", "import imp import torch import torch.nn as nn import numpy", "= torch.autograd.grad(loss, [advimage])[0].detach() grad_norm = torch.norm(nn.Flatten()(grad), p=1, dim=1) grad =", "= epsilon self.p = p self.net = net self.decay_factor =", "in range(self.steps): advimage = advimage.clone().detach().requires_grad_(True) # clone the advimage as", "= updates*self.stepsize advimage = advimage+updates # project the disturbed image", "advimage = advimage.clone().detach().requires_grad_(True) # clone the advimage as the next", "self.epsilon/normVal scaling[mask] = 1 delta = delta*scaling.view(batchsize, 1, 1, 1)", "updates = grad.sign() else: normVal = torch.norm(grad.view(batchsize, -1), self.p, 1)", "-1), self.p, 1) updates = grad/normVal.view(batchsize, 1, 1, 1) updates", "= advimage-image if self.p==np.inf: delta = torch.clamp(delta, -self.epsilon, self.epsilon) else:", "= torch.norm(delta.view(batchsize, -1), self.p, 1) mask = normVal<=self.epsilon scaling =", "= image momentum = torch.zeros_like(image).detach() # PGD to get adversarial", "grad = grad / grad_norm.view([-1]+[1]*(len(grad.shape)-1)) grad = grad + momentum*self.decay_factor", "iteration input netOut = self.net(advimage) loss = loss_adv(self.loss, netOut, label,", "data_name,target, loss, device): self.epsilon = epsilon self.p = p self.net", "MIM(object): '''Projected Gradient Descent''' def __init__(self, net, epsilon, p, stepsize,", "loss = loss_adv(self.loss, netOut, label, target_labels, self.target, self.device) grad =", "image.shape[0] advimage = image momentum = torch.zeros_like(image).detach() # PGD to", "pytorch_ares.attack_torch.utils import loss_adv class MIM(object): '''Projected Gradient Descent''' def __init__(self,", "torch.nn as nn import numpy as np import torch.nn.functional as", "nn import numpy as np import torch.nn.functional as F from", "1, 1, 1) advimage = image+delta advimage = torch.clamp(advimage, 0,", "label, target_labels, self.target, self.device) grad = torch.autograd.grad(loss, [advimage])[0].detach() grad_norm =", "if self.data_name==\"cifar10\" and self.target: raise AssertionError('cifar10 dont support targeted attack')", "project the disturbed image to feasible set if needed delta", "= grad + momentum*self.decay_factor momentum = grad if self.p==np.inf: updates", "advimage+updates # project the disturbed image to feasible set if", "torch.norm(delta.view(batchsize, -1), self.p, 1) mask = normVal<=self.epsilon scaling = self.epsilon/normVal", "example for i in range(self.steps): advimage = advimage.clone().detach().requires_grad_(True) # clone", "__init__(self, net, epsilon, p, stepsize, steps, decay_factor, data_name,target, loss, device):", "grad = torch.autograd.grad(loss, [advimage])[0].detach() grad_norm = torch.norm(nn.Flatten()(grad), p=1, dim=1) grad", "epsilon, p, stepsize, steps, decay_factor, data_name,target, loss, device): self.epsilon =", "grad/normVal.view(batchsize, 1, 1, 1) updates = updates*self.stepsize advimage = advimage+updates", "label = image.to(self.device), label.to(self.device) if target_labels is not None: target_labels", "advimage = advimage+updates # project the disturbed image to feasible", "= grad/normVal.view(batchsize, 1, 1, 1) updates = updates*self.stepsize advimage =", "to feasible set if needed delta = advimage-image if self.p==np.inf:", "as nn import numpy as np import torch.nn.functional as F", "target self.steps = steps self.loss = loss self.data_name = data_name", "mask = normVal<=self.epsilon scaling = self.epsilon/normVal scaling[mask] = 1 delta", "= 1 delta = delta*scaling.view(batchsize, 1, 1, 1) advimage =", "loss, device): self.epsilon = epsilon self.p = p self.net =", "grad + momentum*self.decay_factor momentum = grad if self.p==np.inf: updates =", "self.p = p self.net = net self.decay_factor = decay_factor self.stepsize", "not None: target_labels = target_labels.to(self.device) batchsize = image.shape[0] advimage =", "updates = grad/normVal.view(batchsize, 1, 1, 1) updates = updates*self.stepsize advimage", "if needed delta = advimage-image if self.p==np.inf: delta = torch.clamp(delta,", "decay_factor, data_name,target, loss, device): self.epsilon = epsilon self.p = p", "as F from pytorch_ares.attack_torch.utils import loss_adv class MIM(object): '''Projected Gradient", "= device if self.data_name==\"cifar10\" and self.target: raise AssertionError('cifar10 dont support", "if self.p==np.inf: updates = grad.sign() else: normVal = torch.norm(grad.view(batchsize, -1),", "1) mask = normVal<=self.epsilon scaling = self.epsilon/normVal scaling[mask] = 1", "steps self.loss = loss self.data_name = data_name self.device = device", "torch.norm(grad.view(batchsize, -1), self.p, 1) updates = grad/normVal.view(batchsize, 1, 1, 1)", "target_labels.to(self.device) batchsize = image.shape[0] advimage = image momentum = torch.zeros_like(image).detach()", "[advimage])[0].detach() grad_norm = torch.norm(nn.Flatten()(grad), p=1, dim=1) grad = grad /", "grad = grad + momentum*self.decay_factor momentum = grad if self.p==np.inf:", "Descent''' def __init__(self, net, epsilon, p, stepsize, steps, decay_factor, data_name,target,", "range(self.steps): advimage = advimage.clone().detach().requires_grad_(True) # clone the advimage as the", "epsilon self.p = p self.net = net self.decay_factor = decay_factor", "torch.zeros_like(image).detach() # PGD to get adversarial example for i in", "torch.nn.functional as F from pytorch_ares.attack_torch.utils import loss_adv class MIM(object): '''Projected", "self.data_name = data_name self.device = device if self.data_name==\"cifar10\" and self.target:", "if target_labels is not None: target_labels = target_labels.to(self.device) batchsize =", "# clone the advimage as the next iteration input netOut", "= loss_adv(self.loss, netOut, label, target_labels, self.target, self.device) grad = torch.autograd.grad(loss,", "= self.net(advimage) loss = loss_adv(self.loss, netOut, label, target_labels, self.target, self.device)", "self.stepsize = stepsize self.target = target self.steps = steps self.loss", "net self.decay_factor = decay_factor self.stepsize = stepsize self.target = target", "1) updates = updates*self.stepsize advimage = advimage+updates # project the", "if self.p==np.inf: delta = torch.clamp(delta, -self.epsilon, self.epsilon) else: normVal =", "momentum = torch.zeros_like(image).detach() # PGD to get adversarial example for", "Gradient Descent''' def __init__(self, net, epsilon, p, stepsize, steps, decay_factor,", "clone the advimage as the next iteration input netOut =", "support targeted attack') def forward(self, image, label, target_labels): image, label", "next iteration input netOut = self.net(advimage) loss = loss_adv(self.loss, netOut,", "self.data_name==\"cifar10\" and self.target: raise AssertionError('cifar10 dont support targeted attack') def", "set if needed delta = advimage-image if self.p==np.inf: delta =", "1) advimage = image+delta advimage = torch.clamp(advimage, 0, 1)#cifar10(-1,1) return", "net, epsilon, p, stepsize, steps, decay_factor, data_name,target, loss, device): self.epsilon", "attack') def forward(self, image, label, target_labels): image, label = image.to(self.device),", "torch.clamp(delta, -self.epsilon, self.epsilon) else: normVal = torch.norm(delta.view(batchsize, -1), self.p, 1)", "self.epsilon = epsilon self.p = p self.net = net self.decay_factor", "needed delta = advimage-image if self.p==np.inf: delta = torch.clamp(delta, -self.epsilon,", "dont support targeted attack') def forward(self, image, label, target_labels): image,", "= target self.steps = steps self.loss = loss self.data_name =", "normVal = torch.norm(delta.view(batchsize, -1), self.p, 1) mask = normVal<=self.epsilon scaling", "self.steps = steps self.loss = loss self.data_name = data_name self.device", "= grad / grad_norm.view([-1]+[1]*(len(grad.shape)-1)) grad = grad + momentum*self.decay_factor momentum", "scaling = self.epsilon/normVal scaling[mask] = 1 delta = delta*scaling.view(batchsize, 1,", "= advimage+updates # project the disturbed image to feasible set", "image.to(self.device), label.to(self.device) if target_labels is not None: target_labels = target_labels.to(self.device)", "= steps self.loss = loss self.data_name = data_name self.device =", "adversarial example for i in range(self.steps): advimage = advimage.clone().detach().requires_grad_(True) #", "scaling[mask] = 1 delta = delta*scaling.view(batchsize, 1, 1, 1) advimage", "self.device) grad = torch.autograd.grad(loss, [advimage])[0].detach() grad_norm = torch.norm(nn.Flatten()(grad), p=1, dim=1)", "normVal<=self.epsilon scaling = self.epsilon/normVal scaling[mask] = 1 delta = delta*scaling.view(batchsize,", "import torch import torch.nn as nn import numpy as np", "and self.target: raise AssertionError('cifar10 dont support targeted attack') def forward(self,", "loss_adv class MIM(object): '''Projected Gradient Descent''' def __init__(self, net, epsilon,", "self.p, 1) mask = normVal<=self.epsilon scaling = self.epsilon/normVal scaling[mask] =", "batchsize = image.shape[0] advimage = image momentum = torch.zeros_like(image).detach() #", "else: normVal = torch.norm(delta.view(batchsize, -1), self.p, 1) mask = normVal<=self.epsilon", "p self.net = net self.decay_factor = decay_factor self.stepsize = stepsize", "import torch.nn.functional as F from pytorch_ares.attack_torch.utils import loss_adv class MIM(object):", "= net self.decay_factor = decay_factor self.stepsize = stepsize self.target =", "netOut = self.net(advimage) loss = loss_adv(self.loss, netOut, label, target_labels, self.target,", "netOut, label, target_labels, self.target, self.device) grad = torch.autograd.grad(loss, [advimage])[0].detach() grad_norm", "the advimage as the next iteration input netOut = self.net(advimage)", "self.target = target self.steps = steps self.loss = loss self.data_name", "torch.autograd.grad(loss, [advimage])[0].detach() grad_norm = torch.norm(nn.Flatten()(grad), p=1, dim=1) grad = grad", "grad.sign() else: normVal = torch.norm(grad.view(batchsize, -1), self.p, 1) updates =", "to get adversarial example for i in range(self.steps): advimage =", "1 delta = delta*scaling.view(batchsize, 1, 1, 1) advimage = image+delta", "self.p==np.inf: delta = torch.clamp(delta, -self.epsilon, self.epsilon) else: normVal = torch.norm(delta.view(batchsize,", "else: normVal = torch.norm(grad.view(batchsize, -1), self.p, 1) updates = grad/normVal.view(batchsize,", "input netOut = self.net(advimage) loss = loss_adv(self.loss, netOut, label, target_labels,", "= delta*scaling.view(batchsize, 1, 1, 1) advimage = image+delta advimage =", "as np import torch.nn.functional as F from pytorch_ares.attack_torch.utils import loss_adv", "label, target_labels): image, label = image.to(self.device), label.to(self.device) if target_labels is", "target_labels, self.target, self.device) grad = torch.autograd.grad(loss, [advimage])[0].detach() grad_norm = torch.norm(nn.Flatten()(grad),", "stepsize, steps, decay_factor, data_name,target, loss, device): self.epsilon = epsilon self.p", "advimage.clone().detach().requires_grad_(True) # clone the advimage as the next iteration input", "feasible set if needed delta = advimage-image if self.p==np.inf: delta", "grad_norm = torch.norm(nn.Flatten()(grad), p=1, dim=1) grad = grad / grad_norm.view([-1]+[1]*(len(grad.shape)-1))", "self.target, self.device) grad = torch.autograd.grad(loss, [advimage])[0].detach() grad_norm = torch.norm(nn.Flatten()(grad), p=1,", "loss_adv(self.loss, netOut, label, target_labels, self.target, self.device) grad = torch.autograd.grad(loss, [advimage])[0].detach()", "momentum = grad if self.p==np.inf: updates = grad.sign() else: normVal", "delta*scaling.view(batchsize, 1, 1, 1) advimage = image+delta advimage = torch.clamp(advimage,", "for i in range(self.steps): advimage = advimage.clone().detach().requires_grad_(True) # clone the", "/ grad_norm.view([-1]+[1]*(len(grad.shape)-1)) grad = grad + momentum*self.decay_factor momentum = grad", "= stepsize self.target = target self.steps = steps self.loss =", "class MIM(object): '''Projected Gradient Descent''' def __init__(self, net, epsilon, p,", "normVal = torch.norm(grad.view(batchsize, -1), self.p, 1) updates = grad/normVal.view(batchsize, 1,", "delta = torch.clamp(delta, -self.epsilon, self.epsilon) else: normVal = torch.norm(delta.view(batchsize, -1),", "numpy as np import torch.nn.functional as F from pytorch_ares.attack_torch.utils import", "None: target_labels = target_labels.to(self.device) batchsize = image.shape[0] advimage = image", "'''Projected Gradient Descent''' def __init__(self, net, epsilon, p, stepsize, steps,", "image momentum = torch.zeros_like(image).detach() # PGD to get adversarial example", "the disturbed image to feasible set if needed delta =", "+ momentum*self.decay_factor momentum = grad if self.p==np.inf: updates = grad.sign()", "grad / grad_norm.view([-1]+[1]*(len(grad.shape)-1)) grad = grad + momentum*self.decay_factor momentum =", "is not None: target_labels = target_labels.to(self.device) batchsize = image.shape[0] advimage", "self.p==np.inf: updates = grad.sign() else: normVal = torch.norm(grad.view(batchsize, -1), self.p,", "dim=1) grad = grad / grad_norm.view([-1]+[1]*(len(grad.shape)-1)) grad = grad +", "= image.shape[0] advimage = image momentum = torch.zeros_like(image).detach() # PGD", "1, 1, 1) updates = updates*self.stepsize advimage = advimage+updates #", "def forward(self, image, label, target_labels): image, label = image.to(self.device), label.to(self.device)", "label.to(self.device) if target_labels is not None: target_labels = target_labels.to(self.device) batchsize", "self.epsilon) else: normVal = torch.norm(delta.view(batchsize, -1), self.p, 1) mask =" ]
[ "menubuttonclass(context, appname): if appname == context['request'].resolver_match.func.view_class.__module__.split(\".\")[0]: return \"btn-primary\" else: return", "= template.Library() @register.simple_tag(takes_context=True) def menubuttonclass(context, appname): if appname == context['request'].resolver_match.func.view_class.__module__.split(\".\")[0]:", "django import template register = template.Library() @register.simple_tag(takes_context=True) def menubuttonclass(context, appname):", "appname): if appname == context['request'].resolver_match.func.view_class.__module__.split(\".\")[0]: return \"btn-primary\" else: return \"btn-default\"", "from django import template register = template.Library() @register.simple_tag(takes_context=True) def menubuttonclass(context,", "@register.simple_tag(takes_context=True) def menubuttonclass(context, appname): if appname == context['request'].resolver_match.func.view_class.__module__.split(\".\")[0]: return \"btn-primary\"", "register = template.Library() @register.simple_tag(takes_context=True) def menubuttonclass(context, appname): if appname ==", "template register = template.Library() @register.simple_tag(takes_context=True) def menubuttonclass(context, appname): if appname", "def menubuttonclass(context, appname): if appname == context['request'].resolver_match.func.view_class.__module__.split(\".\")[0]: return \"btn-primary\" else:", "template.Library() @register.simple_tag(takes_context=True) def menubuttonclass(context, appname): if appname == context['request'].resolver_match.func.view_class.__module__.split(\".\")[0]: return", "import template register = template.Library() @register.simple_tag(takes_context=True) def menubuttonclass(context, appname): if" ]
[ "title', 'content': 'testing content' } response = self.client.post('/%s/' %slugify(page.title), edit)", "= Page.objects.create(title=\"My Test Page\", content=\"test\", author=user) page.save() edit = {", "a test 1. Set up your test data 2. Make", "self.client.post('/%s/' %slugify(page.title), edit) updated = Page.objects.get(title = edit['title']) self.assertEqual(response.status_code, 302)", "= self.client.get('/%s/' %slugify(page.title)) self.assertEqual(response.status_code, 200) self.assertContains(response, 'test') def test_create(self): user", "response matches what we expect 3b. Check if database matches", "def test_edit(self): user = User.objects.create_user(username='admin', password='<PASSWORD>') self.client.login(username='admin', password='<PASSWORD>') page =", "Page.objects.get(title = new['title']) self.assertEqual(response.status_code, 302) self.assertEqual(updated.title, new['title']) ''' Steps to", "response = self.client.get('/%s/' %slugify(page.title)) self.assertEqual(response.status_code, 200) self.assertContains(response, 'test') def test_create(self):", "Set up your test data 2. Make a request (GET,", "self.assertEqual(updated.title, edit['title']) def test_page(self): user = User.objects.create_user(username='admin', password='<PASSWORD>') self.client.login(username='admin', password='<PASSWORD>')", "User.objects.create_user(username='admin', password='<PASSWORD>') self.client.login(username='admin', password='<PASSWORD>') new = { 'title': 'testing title',", "edit) updated = Page.objects.get(title = edit['title']) self.assertEqual(response.status_code, 302) self.assertEqual(updated.title, edit['title'])", "Test Page\", content=\"test\", author=user) page.save() response = self.client.get('/%s/' %slugify(page.title)) self.assertEqual(response.status_code,", "self.client.post('/wiki/new/', new) updated = Page.objects.get(title = new['title']) self.assertEqual(response.status_code, 302) self.assertEqual(updated.title,", "django.contrib.auth.models import User from wiki.models import Page from django.utils.text import", "Page from django.utils.text import slugify # Create your tests here.", "edit = { 'title': 'testing title', 'content': 'testing content' }", "} response = self.client.post('/%s/' %slugify(page.title), edit) updated = Page.objects.get(title =", "<reponame>Prones94/Make_Wiki from django.test import TestCase from django.contrib.auth.models import User from", "user = User.objects.create_user(username='admin', password='<PASSWORD>') self.client.login(username='admin', password='<PASSWORD>') page = Page.objects.create(title=\"My Test", "if response matches what we expect 3b. Check if database", "Check if response matches what we expect 3b. Check if", "updated = Page.objects.get(title = edit['title']) self.assertEqual(response.status_code, 302) self.assertEqual(updated.title, edit['title']) def", "password='<PASSWORD>') self.client.login(username='admin', password='<PASSWORD>') new = { 'title': 'testing title', 'content':", "TestCase from django.contrib.auth.models import User from wiki.models import Page from", "from django.contrib.auth.models import User from wiki.models import Page from django.utils.text", "django.test import TestCase from django.contrib.auth.models import User from wiki.models import", "Page\", content=\"test\", author=user) page.save() edit = { 'title': 'testing title',", "def test_create(self): user = User.objects.create_user(username='admin', password='<PASSWORD>') self.client.login(username='admin', password='<PASSWORD>') new =", "password='<PASSWORD>') page = Page.objects.create(title=\"My Test Page\", content=\"test\", author=user) page.save() edit", "302) self.assertEqual(updated.title, edit['title']) def test_page(self): user = User.objects.create_user(username='admin', password='<PASSWORD>') self.client.login(username='admin',", "test_page(self): user = User.objects.create_user(username='admin', password='<PASSWORD>') self.client.login(username='admin', password='<PASSWORD>') page = Page.objects.create(title=\"My", "password='<PASSWORD>') self.client.login(username='admin', password='<PASSWORD>') page = Page.objects.create(title=\"My Test Page\", content=\"test\", author=user)", "up your test data 2. Make a request (GET, POST)", "author=user) page.save() response = self.client.get('/%s/' %slugify(page.title)) self.assertEqual(response.status_code, 200) self.assertContains(response, 'test')", "a request (GET, POST) 3a. Check if response matches what", "Page.objects.get(title = edit['title']) self.assertEqual(response.status_code, 302) self.assertEqual(updated.title, edit['title']) def test_page(self): user", "{ 'title': 'testing title', 'content': 'testing content' } response =", "we expect 3b. Check if database matches what we expect", "updated = Page.objects.get(title = new['title']) self.assertEqual(response.status_code, 302) self.assertEqual(updated.title, new['title']) '''", "= Page.objects.get(title = edit['title']) self.assertEqual(response.status_code, 302) self.assertEqual(updated.title, edit['title']) def test_page(self):", "User.objects.create_user(username='admin', password='<PASSWORD>') self.client.login(username='admin', password='<PASSWORD>') page = Page.objects.create(title=\"My Test Page\", content=\"test\",", "expect 3b. Check if database matches what we expect '''", "self.client.login(username='admin', password='<PASSWORD>') page = Page.objects.create(title=\"My Test Page\", content=\"test\", author=user) page.save()", "self.assertEqual(response.status_code, 302) self.assertEqual(updated.title, new['title']) ''' Steps to writing a test", "response = self.client.post('/%s/' %slugify(page.title), edit) updated = Page.objects.get(title = edit['title'])", "self.assertContains(response, 'test') def test_create(self): user = User.objects.create_user(username='admin', password='<PASSWORD>') self.client.login(username='admin', password='<PASSWORD>')", "test_create(self): user = User.objects.create_user(username='admin', password='<PASSWORD>') self.client.login(username='admin', password='<PASSWORD>') new = {", "new) updated = Page.objects.get(title = new['title']) self.assertEqual(response.status_code, 302) self.assertEqual(updated.title, new['title'])", "writing a test 1. Set up your test data 2.", "matches what we expect 3b. Check if database matches what", "edit['title']) self.assertEqual(response.status_code, 302) self.assertEqual(updated.title, edit['title']) def test_page(self): user = User.objects.create_user(username='admin',", "= new['title']) self.assertEqual(response.status_code, 302) self.assertEqual(updated.title, new['title']) ''' Steps to writing", "here. class WikiPageTest(TestCase): def test_edit(self): user = User.objects.create_user(username='admin', password='<PASSWORD>') self.client.login(username='admin',", "page.save() edit = { 'title': 'testing title', 'content': 'testing content'", "= Page.objects.create(title=\"My Test Page\", content=\"test\", author=user) page.save() response = self.client.get('/%s/'", "= edit['title']) self.assertEqual(response.status_code, 302) self.assertEqual(updated.title, edit['title']) def test_page(self): user =", "= User.objects.create_user(username='admin', password='<PASSWORD>') self.client.login(username='admin', password='<PASSWORD>') new = { 'title': 'testing", "what we expect 3b. Check if database matches what we", "''' Steps to writing a test 1. Set up your", "your tests here. class WikiPageTest(TestCase): def test_edit(self): user = User.objects.create_user(username='admin',", "class WikiPageTest(TestCase): def test_edit(self): user = User.objects.create_user(username='admin', password='<PASSWORD>') self.client.login(username='admin', password='<PASSWORD>')", "'testing title', 'content': 'testing content' } response = self.client.post('/%s/' %slugify(page.title),", "import Page from django.utils.text import slugify # Create your tests", "data 2. Make a request (GET, POST) 3a. Check if", "title', 'content': 'testing content' } response = self.client.post('/wiki/new/', new) updated", "wiki.models import Page from django.utils.text import slugify # Create your", "Test Page\", content=\"test\", author=user) page.save() edit = { 'title': 'testing", "self.client.login(username='admin', password='<PASSWORD>') new = { 'title': 'testing title', 'content': 'testing", "%slugify(page.title), edit) updated = Page.objects.get(title = edit['title']) self.assertEqual(response.status_code, 302) self.assertEqual(updated.title,", "= Page.objects.get(title = new['title']) self.assertEqual(response.status_code, 302) self.assertEqual(updated.title, new['title']) ''' Steps", "3a. Check if response matches what we expect 3b. Check", "'title': 'testing title', 'content': 'testing content' } response = self.client.post('/%s/'", "'content': 'testing content' } response = self.client.post('/%s/' %slugify(page.title), edit) updated", "POST) 3a. Check if response matches what we expect 3b.", "200) self.assertContains(response, 'test') def test_create(self): user = User.objects.create_user(username='admin', password='<PASSWORD>') self.client.login(username='admin',", "from wiki.models import Page from django.utils.text import slugify # Create", "import slugify # Create your tests here. class WikiPageTest(TestCase): def", "Make a request (GET, POST) 3a. Check if response matches", "slugify # Create your tests here. class WikiPageTest(TestCase): def test_edit(self):", "(GET, POST) 3a. Check if response matches what we expect", "content=\"test\", author=user) page.save() response = self.client.get('/%s/' %slugify(page.title)) self.assertEqual(response.status_code, 200) self.assertContains(response,", "import User from wiki.models import Page from django.utils.text import slugify", "WikiPageTest(TestCase): def test_edit(self): user = User.objects.create_user(username='admin', password='<PASSWORD>') self.client.login(username='admin', password='<PASSWORD>') page", "Page.objects.create(title=\"My Test Page\", content=\"test\", author=user) page.save() edit = { 'title':", "self.client.get('/%s/' %slugify(page.title)) self.assertEqual(response.status_code, 200) self.assertContains(response, 'test') def test_create(self): user =", "} response = self.client.post('/wiki/new/', new) updated = Page.objects.get(title = new['title'])", "Steps to writing a test 1. Set up your test", "Page\", content=\"test\", author=user) page.save() response = self.client.get('/%s/' %slugify(page.title)) self.assertEqual(response.status_code, 200)", "'testing title', 'content': 'testing content' } response = self.client.post('/wiki/new/', new)", "to writing a test 1. Set up your test data", "test data 2. Make a request (GET, POST) 3a. Check", "# Create your tests here. class WikiPageTest(TestCase): def test_edit(self): user", "= User.objects.create_user(username='admin', password='<PASSWORD>') self.client.login(username='admin', password='<PASSWORD>') page = Page.objects.create(title=\"My Test Page\",", "content=\"test\", author=user) page.save() edit = { 'title': 'testing title', 'content':", "your test data 2. Make a request (GET, POST) 3a.", "tests here. class WikiPageTest(TestCase): def test_edit(self): user = User.objects.create_user(username='admin', password='<PASSWORD>')", "author=user) page.save() edit = { 'title': 'testing title', 'content': 'testing", "password='<PASSWORD>') new = { 'title': 'testing title', 'content': 'testing content'", "302) self.assertEqual(updated.title, new['title']) ''' Steps to writing a test 1.", "2. Make a request (GET, POST) 3a. Check if response", "self.assertEqual(updated.title, new['title']) ''' Steps to writing a test 1. Set", "request (GET, POST) 3a. Check if response matches what we", "self.assertEqual(response.status_code, 302) self.assertEqual(updated.title, edit['title']) def test_page(self): user = User.objects.create_user(username='admin', password='<PASSWORD>')", "Page.objects.create(title=\"My Test Page\", content=\"test\", author=user) page.save() response = self.client.get('/%s/' %slugify(page.title))", "= self.client.post('/wiki/new/', new) updated = Page.objects.get(title = new['title']) self.assertEqual(response.status_code, 302)", "User from wiki.models import Page from django.utils.text import slugify #", "new = { 'title': 'testing title', 'content': 'testing content' }", "%slugify(page.title)) self.assertEqual(response.status_code, 200) self.assertContains(response, 'test') def test_create(self): user = User.objects.create_user(username='admin',", "password='<PASSWORD>') page = Page.objects.create(title=\"My Test Page\", content=\"test\", author=user) page.save() response", "test_edit(self): user = User.objects.create_user(username='admin', password='<PASSWORD>') self.client.login(username='admin', password='<PASSWORD>') page = Page.objects.create(title=\"My", "page = Page.objects.create(title=\"My Test Page\", content=\"test\", author=user) page.save() response =", "import TestCase from django.contrib.auth.models import User from wiki.models import Page", "content' } response = self.client.post('/%s/' %slugify(page.title), edit) updated = Page.objects.get(title", "'title': 'testing title', 'content': 'testing content' } response = self.client.post('/wiki/new/',", "= { 'title': 'testing title', 'content': 'testing content' } response", "response = self.client.post('/wiki/new/', new) updated = Page.objects.get(title = new['title']) self.assertEqual(response.status_code,", "user = User.objects.create_user(username='admin', password='<PASSWORD>') self.client.login(username='admin', password='<PASSWORD>') new = { 'title':", "'testing content' } response = self.client.post('/%s/' %slugify(page.title), edit) updated =", "new['title']) self.assertEqual(response.status_code, 302) self.assertEqual(updated.title, new['title']) ''' Steps to writing a", "= self.client.post('/%s/' %slugify(page.title), edit) updated = Page.objects.get(title = edit['title']) self.assertEqual(response.status_code,", "new['title']) ''' Steps to writing a test 1. Set up", "'test') def test_create(self): user = User.objects.create_user(username='admin', password='<PASSWORD>') self.client.login(username='admin', password='<PASSWORD>') new", "def test_page(self): user = User.objects.create_user(username='admin', password='<PASSWORD>') self.client.login(username='admin', password='<PASSWORD>') page =", "page = Page.objects.create(title=\"My Test Page\", content=\"test\", author=user) page.save() edit =", "Create your tests here. class WikiPageTest(TestCase): def test_edit(self): user =", "from django.utils.text import slugify # Create your tests here. class", "1. Set up your test data 2. Make a request", "test 1. Set up your test data 2. Make a", "edit['title']) def test_page(self): user = User.objects.create_user(username='admin', password='<PASSWORD>') self.client.login(username='admin', password='<PASSWORD>') page", "django.utils.text import slugify # Create your tests here. class WikiPageTest(TestCase):", "'content': 'testing content' } response = self.client.post('/wiki/new/', new) updated =", "'testing content' } response = self.client.post('/wiki/new/', new) updated = Page.objects.get(title", "from django.test import TestCase from django.contrib.auth.models import User from wiki.models", "self.assertEqual(response.status_code, 200) self.assertContains(response, 'test') def test_create(self): user = User.objects.create_user(username='admin', password='<PASSWORD>')", "content' } response = self.client.post('/wiki/new/', new) updated = Page.objects.get(title =", "page.save() response = self.client.get('/%s/' %slugify(page.title)) self.assertEqual(response.status_code, 200) self.assertContains(response, 'test') def" ]
[]
[ "batch of inputs for some classifier. :param scale_min: The random", "rescaling and padding to xs. :param xs: A batch of", "rate would be chosen between ``scale_min`` and 1.0. :param pad_value:", "and dtype as xs. ''' ratio = tf.random.uniform((), minval=scale_min, maxval=1.0)", "pad_top = tf.random_uniform((), 0, height_rem, dtype=tf.int32) pad_bottom = height_rem -", "[[0, 0], [pad_top, pad_bottom], [pad_left, pad_right], [0, 0]], constant_values=pad_value) xs_padded.set_shape(xs.shape)", "= tf.random_uniform((), 0, height_rem, dtype=tf.int32) pad_bottom = height_rem - pad_top", "``constant_values`` parameter for the ``tf.pad`` method. ''' def args_fn(_): return", "pad_value=0.0): ''' Apply random rescaling and padding to xs. :param", "from ares.defense.input_transformation import input_transformation def randomize(xs, scale_min=0.875, pad_value=0.0): ''' Apply", "tf.cast(xs.shape[1].value * ratio, tf.int32), tf.cast(xs.shape[2].value * ratio, tf.int32) xs_rescaled =", "0]], constant_values=pad_value) xs_padded.set_shape(xs.shape) return xs_padded def randomization(scale_min=0.875, pad_value=0.0): ''' A", "def args_fn(_): return (scale_min, pad_value) def kwargs_fn(_): return {} return", "of inputs for some classifier. :param scale_min: The random rescaling", "width_rem = xs.shape[1].value - height, xs.shape[2].value - width pad_left =", "kwargs_fn(_): return {} return lambda rs_class: input_transformation(rs_class, randomize, args_fn, kwargs_fn)", "pad_left = tf.random_uniform((), 0, width_rem, dtype=tf.int32) pad_right = width_rem -", "maxval=1.0) height, width = tf.cast(xs.shape[1].value * ratio, tf.int32), tf.cast(xs.shape[2].value *", "= tf.random_uniform((), 0, width_rem, dtype=tf.int32) pad_right = width_rem - pad_left", "inputs for some classifier. :param scale_min: The random rescaling rate", "0, width_rem, dtype=tf.int32) pad_right = width_rem - pad_left pad_top =", "width), method=tf.image.ResizeMethod.NEAREST_NEIGHBOR, align_corners=True, preserve_aspect_ratio=False) height_rem, width_rem = xs.shape[1].value - height,", "applies random . ''' import tensorflow as tf from ares.defense.input_transformation", "width pad_left = tf.random_uniform((), 0, width_rem, dtype=tf.int32) pad_right = width_rem", ":return: A new tensor with same shape and dtype as", "pad_bottom = height_rem - pad_top xs_padded = tf.pad(xs_rescaled, [[0, 0],", "as xs. ''' ratio = tf.random.uniform((), minval=scale_min, maxval=1.0) height, width", "(scale_min, pad_value) def kwargs_fn(_): return {} return lambda rs_class: input_transformation(rs_class,", "parameter for the ``tf.pad`` method. :return: A new tensor with", "tf.image.resize(xs, (height, width), method=tf.image.ResizeMethod.NEAREST_NEIGHBOR, align_corners=True, preserve_aspect_ratio=False) height_rem, width_rem = xs.shape[1].value", "chosen between ``scale_min`` and 1.0. :param pad_value: ``constant_values`` parameter for", "randomize rescaling and padding to input of the classifier. :param", "height_rem - pad_top xs_padded = tf.pad(xs_rescaled, [[0, 0], [pad_top, pad_bottom],", "randomization defense method, which applies random . ''' import tensorflow", "xs_rescaled = tf.image.resize(xs, (height, width), method=tf.image.ResizeMethod.NEAREST_NEIGHBOR, align_corners=True, preserve_aspect_ratio=False) height_rem, width_rem", "the ``tf.pad`` method. :return: A new tensor with same shape", "dtype=tf.int32) pad_bottom = height_rem - pad_top xs_padded = tf.pad(xs_rescaled, [[0,", "pad_right = width_rem - pad_left pad_top = tf.random_uniform((), 0, height_rem,", "tf.int32) xs_rescaled = tf.image.resize(xs, (height, width), method=tf.image.ResizeMethod.NEAREST_NEIGHBOR, align_corners=True, preserve_aspect_ratio=False) height_rem,", "as tf from ares.defense.input_transformation import input_transformation def randomize(xs, scale_min=0.875, pad_value=0.0):", "A new tensor with same shape and dtype as xs.", "which applies random . ''' import tensorflow as tf from", "and padding to input of the classifier. :param scale_min: The", "method. :return: A new tensor with same shape and dtype", "tf.random_uniform((), 0, width_rem, dtype=tf.int32) pad_right = width_rem - pad_left pad_top", "= height_rem - pad_top xs_padded = tf.pad(xs_rescaled, [[0, 0], [pad_top,", "A batch of inputs for some classifier. :param scale_min: The", "method, which applies random . ''' import tensorflow as tf", "between ``scale_min`` and 1.0. :param pad_value: ``constant_values`` parameter for the", "be chosen between ``scale_min`` and 1.0. :param pad_value: ``constant_values`` parameter", "pad_value=0.0): ''' A decorator to apply randomize rescaling and padding", "* ratio, tf.int32), tf.cast(xs.shape[2].value * ratio, tf.int32) xs_rescaled = tf.image.resize(xs,", "xs. :param xs: A batch of inputs for some classifier.", "random . ''' import tensorflow as tf from ares.defense.input_transformation import", "return xs_padded def randomization(scale_min=0.875, pad_value=0.0): ''' A decorator to apply", "import tensorflow as tf from ares.defense.input_transformation import input_transformation def randomize(xs,", "= width_rem - pad_left pad_top = tf.random_uniform((), 0, height_rem, dtype=tf.int32)", "width_rem - pad_left pad_top = tf.random_uniform((), 0, height_rem, dtype=tf.int32) pad_bottom", "xs.shape[1].value - height, xs.shape[2].value - width pad_left = tf.random_uniform((), 0,", "randomization(scale_min=0.875, pad_value=0.0): ''' A decorator to apply randomize rescaling and", "rescaling rate would be chosen between ``scale_min`` and 1.0. :param", ":param pad_value: ``constant_values`` parameter for the ``tf.pad`` method. ''' def", "pad_value: ``constant_values`` parameter for the ``tf.pad`` method. ''' def args_fn(_):", "pad_value: ``constant_values`` parameter for the ``tf.pad`` method. :return: A new", "def randomization(scale_min=0.875, pad_value=0.0): ''' A decorator to apply randomize rescaling", "= tf.cast(xs.shape[1].value * ratio, tf.int32), tf.cast(xs.shape[2].value * ratio, tf.int32) xs_rescaled", "pad_bottom], [pad_left, pad_right], [0, 0]], constant_values=pad_value) xs_padded.set_shape(xs.shape) return xs_padded def", "to xs. :param xs: A batch of inputs for some", "[pad_top, pad_bottom], [pad_left, pad_right], [0, 0]], constant_values=pad_value) xs_padded.set_shape(xs.shape) return xs_padded", "``tf.pad`` method. ''' def args_fn(_): return (scale_min, pad_value) def kwargs_fn(_):", "ratio = tf.random.uniform((), minval=scale_min, maxval=1.0) height, width = tf.cast(xs.shape[1].value *", "pad_top xs_padded = tf.pad(xs_rescaled, [[0, 0], [pad_top, pad_bottom], [pad_left, pad_right],", "for the ``tf.pad`` method. :return: A new tensor with same", "with same shape and dtype as xs. ''' ratio =", "1.0. :param pad_value: ``constant_values`` parameter for the ``tf.pad`` method. :return:", "(height, width), method=tf.image.ResizeMethod.NEAREST_NEIGHBOR, align_corners=True, preserve_aspect_ratio=False) height_rem, width_rem = xs.shape[1].value -", "minval=scale_min, maxval=1.0) height, width = tf.cast(xs.shape[1].value * ratio, tf.int32), tf.cast(xs.shape[2].value", "randomize(xs, scale_min=0.875, pad_value=0.0): ''' Apply random rescaling and padding to", "tf.random.uniform((), minval=scale_min, maxval=1.0) height, width = tf.cast(xs.shape[1].value * ratio, tf.int32),", "decorator to apply randomize rescaling and padding to input of", "xs.shape[2].value - width pad_left = tf.random_uniform((), 0, width_rem, dtype=tf.int32) pad_right", "random rescaling and padding to xs. :param xs: A batch", "def kwargs_fn(_): return {} return lambda rs_class: input_transformation(rs_class, randomize, args_fn,", "def randomize(xs, scale_min=0.875, pad_value=0.0): ''' Apply random rescaling and padding", "input_transformation def randomize(xs, scale_min=0.875, pad_value=0.0): ''' Apply random rescaling and", "xs: A batch of inputs for some classifier. :param scale_min:", "padding to xs. :param xs: A batch of inputs for", "0], [pad_top, pad_bottom], [pad_left, pad_right], [0, 0]], constant_values=pad_value) xs_padded.set_shape(xs.shape) return", "The randomization defense method, which applies random . ''' import", "The random rescaling rate would be chosen between ``scale_min`` and", "= tf.image.resize(xs, (height, width), method=tf.image.ResizeMethod.NEAREST_NEIGHBOR, align_corners=True, preserve_aspect_ratio=False) height_rem, width_rem =", "''' def args_fn(_): return (scale_min, pad_value) def kwargs_fn(_): return {}", "method=tf.image.ResizeMethod.NEAREST_NEIGHBOR, align_corners=True, preserve_aspect_ratio=False) height_rem, width_rem = xs.shape[1].value - height, xs.shape[2].value", "1.0. :param pad_value: ``constant_values`` parameter for the ``tf.pad`` method. '''", "ratio, tf.int32) xs_rescaled = tf.image.resize(xs, (height, width), method=tf.image.ResizeMethod.NEAREST_NEIGHBOR, align_corners=True, preserve_aspect_ratio=False)", "import input_transformation def randomize(xs, scale_min=0.875, pad_value=0.0): ''' Apply random rescaling", "return (scale_min, pad_value) def kwargs_fn(_): return {} return lambda rs_class:", "= tf.random.uniform((), minval=scale_min, maxval=1.0) height, width = tf.cast(xs.shape[1].value * ratio,", "preserve_aspect_ratio=False) height_rem, width_rem = xs.shape[1].value - height, xs.shape[2].value - width", "input of the classifier. :param scale_min: The random rescaling rate", "A decorator to apply randomize rescaling and padding to input", "''' Apply random rescaling and padding to xs. :param xs:", "scale_min=0.875, pad_value=0.0): ''' Apply random rescaling and padding to xs.", "classifier. :param scale_min: The random rescaling rate would be chosen", ":param scale_min: The random rescaling rate would be chosen between", "args_fn(_): return (scale_min, pad_value) def kwargs_fn(_): return {} return lambda", "= xs.shape[1].value - height, xs.shape[2].value - width pad_left = tf.random_uniform((),", "- pad_left pad_top = tf.random_uniform((), 0, height_rem, dtype=tf.int32) pad_bottom =", "dtype=tf.int32) pad_right = width_rem - pad_left pad_top = tf.random_uniform((), 0,", "some classifier. :param scale_min: The random rescaling rate would be", "``scale_min`` and 1.0. :param pad_value: ``constant_values`` parameter for the ``tf.pad``", "new tensor with same shape and dtype as xs. '''", "xs. ''' ratio = tf.random.uniform((), minval=scale_min, maxval=1.0) height, width =", "defense method, which applies random . ''' import tensorflow as", "pad_value) def kwargs_fn(_): return {} return lambda rs_class: input_transformation(rs_class, randomize,", "tf.int32), tf.cast(xs.shape[2].value * ratio, tf.int32) xs_rescaled = tf.image.resize(xs, (height, width),", "tf from ares.defense.input_transformation import input_transformation def randomize(xs, scale_min=0.875, pad_value=0.0): '''", "* ratio, tf.int32) xs_rescaled = tf.image.resize(xs, (height, width), method=tf.image.ResizeMethod.NEAREST_NEIGHBOR, align_corners=True,", "- width pad_left = tf.random_uniform((), 0, width_rem, dtype=tf.int32) pad_right =", "rescaling and padding to input of the classifier. :param scale_min:", "width = tf.cast(xs.shape[1].value * ratio, tf.int32), tf.cast(xs.shape[2].value * ratio, tf.int32)", "parameter for the ``tf.pad`` method. ''' def args_fn(_): return (scale_min,", "to apply randomize rescaling and padding to input of the", "ares.defense.input_transformation import input_transformation def randomize(xs, scale_min=0.875, pad_value=0.0): ''' Apply random", "``constant_values`` parameter for the ``tf.pad`` method. :return: A new tensor", "''' ratio = tf.random.uniform((), minval=scale_min, maxval=1.0) height, width = tf.cast(xs.shape[1].value", "= tf.pad(xs_rescaled, [[0, 0], [pad_top, pad_bottom], [pad_left, pad_right], [0, 0]],", "tf.pad(xs_rescaled, [[0, 0], [pad_top, pad_bottom], [pad_left, pad_right], [0, 0]], constant_values=pad_value)", "xs_padded def randomization(scale_min=0.875, pad_value=0.0): ''' A decorator to apply randomize", "would be chosen between ``scale_min`` and 1.0. :param pad_value: ``constant_values``", "Apply random rescaling and padding to xs. :param xs: A", "dtype as xs. ''' ratio = tf.random.uniform((), minval=scale_min, maxval=1.0) height,", "of the classifier. :param scale_min: The random rescaling rate would", "<reponame>KuanKuanQAQ/ares<gh_stars>100-1000 ''' The randomization defense method, which applies random .", "height, width = tf.cast(xs.shape[1].value * ratio, tf.int32), tf.cast(xs.shape[2].value * ratio,", "align_corners=True, preserve_aspect_ratio=False) height_rem, width_rem = xs.shape[1].value - height, xs.shape[2].value -", "tf.cast(xs.shape[2].value * ratio, tf.int32) xs_rescaled = tf.image.resize(xs, (height, width), method=tf.image.ResizeMethod.NEAREST_NEIGHBOR,", "tensorflow as tf from ares.defense.input_transformation import input_transformation def randomize(xs, scale_min=0.875,", "0, height_rem, dtype=tf.int32) pad_bottom = height_rem - pad_top xs_padded =", "height_rem, dtype=tf.int32) pad_bottom = height_rem - pad_top xs_padded = tf.pad(xs_rescaled,", "shape and dtype as xs. ''' ratio = tf.random.uniform((), minval=scale_min,", "for some classifier. :param scale_min: The random rescaling rate would", "random rescaling rate would be chosen between ``scale_min`` and 1.0.", "''' The randomization defense method, which applies random . '''", "''' A decorator to apply randomize rescaling and padding to", "and 1.0. :param pad_value: ``constant_values`` parameter for the ``tf.pad`` method.", "pad_right], [0, 0]], constant_values=pad_value) xs_padded.set_shape(xs.shape) return xs_padded def randomization(scale_min=0.875, pad_value=0.0):", "apply randomize rescaling and padding to input of the classifier.", "tf.random_uniform((), 0, height_rem, dtype=tf.int32) pad_bottom = height_rem - pad_top xs_padded", "- height, xs.shape[2].value - width pad_left = tf.random_uniform((), 0, width_rem,", "''' import tensorflow as tf from ares.defense.input_transformation import input_transformation def", "scale_min: The random rescaling rate would be chosen between ``scale_min``", "same shape and dtype as xs. ''' ratio = tf.random.uniform((),", "ratio, tf.int32), tf.cast(xs.shape[2].value * ratio, tf.int32) xs_rescaled = tf.image.resize(xs, (height,", "the ``tf.pad`` method. ''' def args_fn(_): return (scale_min, pad_value) def", "the classifier. :param scale_min: The random rescaling rate would be", ". ''' import tensorflow as tf from ares.defense.input_transformation import input_transformation", "tensor with same shape and dtype as xs. ''' ratio", "pad_left pad_top = tf.random_uniform((), 0, height_rem, dtype=tf.int32) pad_bottom = height_rem", "for the ``tf.pad`` method. ''' def args_fn(_): return (scale_min, pad_value)", "[pad_left, pad_right], [0, 0]], constant_values=pad_value) xs_padded.set_shape(xs.shape) return xs_padded def randomization(scale_min=0.875,", "and padding to xs. :param xs: A batch of inputs", "height, xs.shape[2].value - width pad_left = tf.random_uniform((), 0, width_rem, dtype=tf.int32)", ":param xs: A batch of inputs for some classifier. :param", ":param pad_value: ``constant_values`` parameter for the ``tf.pad`` method. :return: A", "xs_padded = tf.pad(xs_rescaled, [[0, 0], [pad_top, pad_bottom], [pad_left, pad_right], [0,", "method. ''' def args_fn(_): return (scale_min, pad_value) def kwargs_fn(_): return", "height_rem, width_rem = xs.shape[1].value - height, xs.shape[2].value - width pad_left", "to input of the classifier. :param scale_min: The random rescaling", "padding to input of the classifier. :param scale_min: The random", "width_rem, dtype=tf.int32) pad_right = width_rem - pad_left pad_top = tf.random_uniform((),", "constant_values=pad_value) xs_padded.set_shape(xs.shape) return xs_padded def randomization(scale_min=0.875, pad_value=0.0): ''' A decorator", "[0, 0]], constant_values=pad_value) xs_padded.set_shape(xs.shape) return xs_padded def randomization(scale_min=0.875, pad_value=0.0): '''", "``tf.pad`` method. :return: A new tensor with same shape and", "xs_padded.set_shape(xs.shape) return xs_padded def randomization(scale_min=0.875, pad_value=0.0): ''' A decorator to", "- pad_top xs_padded = tf.pad(xs_rescaled, [[0, 0], [pad_top, pad_bottom], [pad_left," ]
[ "django.contrib import admin from annotate.backend.models import Image, Annotation admin.site.register(Image) admin.site.register(Annotation)", "<gh_stars>0 from django.contrib import admin from annotate.backend.models import Image, Annotation", "from django.contrib import admin from annotate.backend.models import Image, Annotation admin.site.register(Image)" ]
[ "i-1 while j<len(nums)-1 and nums[j+1] == target: j = j+1", "= 0 while low<=high: mid = (low+high)//2 if nums[mid] ==", "1 i, j = mid, mid while i>=1 and nums[i-1]", "high = mid - 1 i, j = mid, mid", "= mid + 1 elif nums[mid] > target: high =", "1 elif nums[mid] > target: high = mid - 1", "if f == 1: return [i, j] else: return [-1,", "mid while i>=1 and nums[i-1] == target: i = i-1", ":type nums: List[int] :type target: int :rtype: List[int] \"\"\" if", "< target: low = mid + 1 elif nums[mid] >", "while i>=1 and nums[i-1] == target: i = i-1 while", "nums[mid] == target: f = 1 break elif nums[mid] <", "(low+high)//2 if nums[mid] == target: f = 1 break elif", "f == 1: return [i, j] else: return [-1, -1]", "f = 1 break elif nums[mid] < target: low =", "i>=1 and nums[i-1] == target: i = i-1 while j<len(nums)-1", "0 high = len(nums) - 1 f = 0 while", "nums[j+1] == target: j = j+1 if f == 1:", "low = mid + 1 elif nums[mid] > target: high", "nums[mid] < target: low = mid + 1 elif nums[mid]", ":type target: int :rtype: List[int] \"\"\" if not nums: return", "break elif nums[mid] < target: low = mid + 1", "= mid - 1 i, j = mid, mid while", "[-1, -1] low = 0 high = len(nums) - 1", "nums[mid] > target: high = mid - 1 i, j", "> target: high = mid - 1 i, j =", "def searchRange(self, nums, target): \"\"\" :type nums: List[int] :type target:", "= i-1 while j<len(nums)-1 and nums[j+1] == target: j =", "- 1 f = 0 while low<=high: mid = (low+high)//2", "mid, mid while i>=1 and nums[i-1] == target: i =", "target: f = 1 break elif nums[mid] < target: low", "int :rtype: List[int] \"\"\" if not nums: return [-1, -1]", "= 1 break elif nums[mid] < target: low = mid", ":rtype: List[int] \"\"\" if not nums: return [-1, -1] low", "target: j = j+1 if f == 1: return [i,", "\"\"\" if not nums: return [-1, -1] low = 0", "if nums[mid] == target: f = 1 break elif nums[mid]", "and nums[j+1] == target: j = j+1 if f ==", "while j<len(nums)-1 and nums[j+1] == target: j = j+1 if", "= j+1 if f == 1: return [i, j] else:", "j<len(nums)-1 and nums[j+1] == target: j = j+1 if f", "f = 0 while low<=high: mid = (low+high)//2 if nums[mid]", "= 0 high = len(nums) - 1 f = 0", "i, j = mid, mid while i>=1 and nums[i-1] ==", "mid = (low+high)//2 if nums[mid] == target: f = 1", "0 while low<=high: mid = (low+high)//2 if nums[mid] == target:", "if not nums: return [-1, -1] low = 0 high", "== target: i = i-1 while j<len(nums)-1 and nums[j+1] ==", "low<=high: mid = (low+high)//2 if nums[mid] == target: f =", "1 f = 0 while low<=high: mid = (low+high)//2 if", "mid - 1 i, j = mid, mid while i>=1", "target: low = mid + 1 elif nums[mid] > target:", "j+1 if f == 1: return [i, j] else: return", "nums: return [-1, -1] low = 0 high = len(nums)", "low = 0 high = len(nums) - 1 f =", "= mid, mid while i>=1 and nums[i-1] == target: i", "\"\"\" :type nums: List[int] :type target: int :rtype: List[int] \"\"\"", "j = mid, mid while i>=1 and nums[i-1] == target:", "j = j+1 if f == 1: return [i, j]", "searchRange(self, nums, target): \"\"\" :type nums: List[int] :type target: int", "target): \"\"\" :type nums: List[int] :type target: int :rtype: List[int]", "= (low+high)//2 if nums[mid] == target: f = 1 break", "and nums[i-1] == target: i = i-1 while j<len(nums)-1 and", "-1] low = 0 high = len(nums) - 1 f", "len(nums) - 1 f = 0 while low<=high: mid =", "return [-1, -1] low = 0 high = len(nums) -", "nums, target): \"\"\" :type nums: List[int] :type target: int :rtype:", "1 break elif nums[mid] < target: low = mid +", "== target: f = 1 break elif nums[mid] < target:", "- 1 i, j = mid, mid while i>=1 and", "target: i = i-1 while j<len(nums)-1 and nums[j+1] == target:", "target: high = mid - 1 i, j = mid,", "= len(nums) - 1 f = 0 while low<=high: mid", "elif nums[mid] > target: high = mid - 1 i,", "i = i-1 while j<len(nums)-1 and nums[j+1] == target: j", "List[int] :type target: int :rtype: List[int] \"\"\" if not nums:", "target: int :rtype: List[int] \"\"\" if not nums: return [-1,", "+ 1 elif nums[mid] > target: high = mid -", "List[int] \"\"\" if not nums: return [-1, -1] low =", "elif nums[mid] < target: low = mid + 1 elif", "mid + 1 elif nums[mid] > target: high = mid", "== target: j = j+1 if f == 1: return", "not nums: return [-1, -1] low = 0 high =", "Solution: def searchRange(self, nums, target): \"\"\" :type nums: List[int] :type", "nums: List[int] :type target: int :rtype: List[int] \"\"\" if not", "nums[i-1] == target: i = i-1 while j<len(nums)-1 and nums[j+1]", "class Solution: def searchRange(self, nums, target): \"\"\" :type nums: List[int]", "while low<=high: mid = (low+high)//2 if nums[mid] == target: f", "high = len(nums) - 1 f = 0 while low<=high:" ]
[ "referenced: if x not in declared: final.append(x) print \"\" for", "= 0 for x in alphabet: if x in tmp:", "if '%%' == x: start = 1 continue elif start", "= 0 current = \"\" space = \"<space>\" declared =", "current = x[0] declared.append(item(x[0])) print \"\" else: x = x[1:]", "y in range(len(x)): referenced.append(item(x[y])) tmp += item(x[y]) if y !=", "<gh_stars>0 data = open('./original').readlines() alphabet = { \"<\":\"lt\", \">\":\"gt\", \"=\":\"=\",", "\"*\":\"*\", \"(\":\"(\", \")\":\"right_paran\", \"[\":\"[\", \"]\":\"]\", \"{\":\"{\", \"}\":\"}\", \"[\":\"[\", \"]\":\"]\", \"|\":\"|\",", "tmp: final += item(alphabet[x]) return final else: return item(tmp) else:", "\"<space>\" declared = [] referenced = [] for x in", "in data: x = x.strip() if x == \"\": continue", "declared: final.append(x) print \"\" for x in final: tmp =", "x == \"\": continue if '%%' == x: start =", "for x in final: tmp = x+'\\t=\\t' x = x[1:-1]", "y != len(x)-1 and \"'\" not in x[y+1] and \"'\"", "final = [] for x in referenced: if x not", "referenced = [] for x in data: x = x.strip()", "item(alphabet[x]) return final else: return item(tmp) else: return \"<\"+y+\">\" start", "[] for x in referenced: if x not in declared:", "declared = [] referenced = [] for x in data:", "in declared: final.append(x) print \"\" for x in final: tmp", "\"'\" not in x[y]: tmp+=space print tmp referenced = set(referenced)", "final: tmp = x+'\\t=\\t' x = x[1:-1] print tmp +", "start = 1 continue elif start != 1: continue if", "tmp referenced = set(referenced) final = [] for x in", "in alphabet: if x in tmp: test = 1 if", "= x.split(' ') if len(x) == 1:#item declaration or end", "space = \"<space>\" declared = [] referenced = [] for", "in x[y]: tmp+=space print tmp referenced = set(referenced) final =", "= \"\" space = \"<space>\" declared = [] referenced =", "') if len(x) == 1:#item declaration or end if x[0]", "tmp += item(x[y]) if y != len(x)-1 and \"'\" not", "test: final = '' for x in tmp: final +=", "else: return \"<\"+y+\">\" start = 0 current = \"\" space", "= '' for x in tmp: final += item(alphabet[x]) return", "'%%' == x: start = 1 continue elif start !=", "x[0] declared.append(item(x[0])) print \"\" else: x = x[1:] tmp =", "in tmp: test = 1 if test: final = ''", "\"}\":\"}\", \"[\":\"[\", \"]\":\"]\", \"|\":\"|\", \";\":\";\", \":\":\":\", \",\":\",\", \".\":\".\", \"?\":\"?\", \"/\":\"/\",", "not in x[y+1] and \"'\" not in x[y]: tmp+=space print", "x[y+1] and \"'\" not in x[y]: tmp+=space print tmp referenced", "== x: start = 1 continue elif start != 1:", "in tmp: final += item(alphabet[x]) return final else: return item(tmp)", "\"test\": break; x = x.split(' ') if len(x) == 1:#item", "if y != len(x)-1 and \"'\" not in x[y+1] and", "'' for x in tmp: final += item(alphabet[x]) return final", "\"+\":\"+\", \"-\":\"-\", \"~\":\"~\", \"!\":\"ex\", \"%\":\"%\", \"^\":\"^\", \"&\":\"&\", \"*\":\"*\", \"(\":\"(\", \")\":\"right_paran\",", "if x not in declared: final.append(x) print \"\" for x", "!= len(x)-1 and \"'\" not in x[y+1] and \"'\" not", "\"[\":\"[\", \"]\":\"]\", \"|\":\"|\", \";\":\";\", \":\":\":\", \",\":\",\", \".\":\".\", \"?\":\"?\", \"/\":\"/\", }", "range(len(x)): referenced.append(item(x[y])) tmp += item(x[y]) if y != len(x)-1 and", "if x == \"test\": break; x = x.split(' ') if", "1:#item declaration or end if x[0] == ';': current =", "declaration or end if x[0] == ';': current = \"\"", "\"\": continue if '%%' == x: start = 1 continue", "and \"'\" not in x[y]: tmp+=space print tmp referenced =", "\",\":\",\", \".\":\".\", \"?\":\"?\", \"/\":\"/\", } def item(y): if \"'\" in", "final += item(alphabet[x]) return final else: return item(tmp) else: return", "= item(current)+'\\t=\\t' for y in range(len(x)): referenced.append(item(x[y])) tmp += item(x[y])", "= open('./original').readlines() alphabet = { \"<\":\"lt\", \">\":\"gt\", \"=\":\"=\", \"-\":'-', \"+\":\"+\",", "x = x.strip() if x == \"\": continue if '%%'", "\"{\":\"{\", \"}\":\"}\", \"[\":\"[\", \"]\":\"]\", \"|\":\"|\", \";\":\";\", \":\":\":\", \",\":\",\", \".\":\".\", \"?\":\"?\",", "x in data: x = x.strip() if x == \"\":", "if x in tmp: test = 1 if test: final", "= set(referenced) final = [] for x in referenced: if", "x[0] == ';': current = \"\" else: current = x[0]", "{ \"<\":\"lt\", \">\":\"gt\", \"=\":\"=\", \"-\":'-', \"+\":\"+\", \"-\":\"-\", \"~\":\"~\", \"!\":\"ex\", \"%\":\"%\",", "if len(x) == 1:#item declaration or end if x[0] ==", "final = '' for x in tmp: final += item(alphabet[x])", "\"\" for x in final: tmp = x+'\\t=\\t' x =", "final else: return item(tmp) else: return \"<\"+y+\">\" start = 0", "0 for x in alphabet: if x in tmp: test", "\"\" else: current = x[0] declared.append(item(x[0])) print \"\" else: x", "for x in referenced: if x not in declared: final.append(x)", "\"?\":\"?\", \"/\":\"/\", } def item(y): if \"'\" in y: tmp", "y: tmp = y.split(\"'\")[1] test = 0 for x in", "\"<\"+y+\">\" start = 0 current = \"\" space = \"<space>\"", "in x[y+1] and \"'\" not in x[y]: tmp+=space print tmp", "= y.split(\"'\")[1] test = 0 for x in alphabet: if", "if \"'\" in y: tmp = y.split(\"'\")[1] test = 0", "def item(y): if \"'\" in y: tmp = y.split(\"'\")[1] test", "\"\" space = \"<space>\" declared = [] referenced = []", "== \"\": continue if '%%' == x: start = 1", "for x in data: x = x.strip() if x ==", "else: return item(tmp) else: return \"<\"+y+\">\" start = 0 current", "print \"\" for x in final: tmp = x+'\\t=\\t' x", "= [] for x in data: x = x.strip() if", "= [] for x in referenced: if x not in", "tmp = y.split(\"'\")[1] test = 0 for x in alphabet:", "final.append(x) print \"\" for x in final: tmp = x+'\\t=\\t'", "\"\" else: x = x[1:] tmp = item(current)+'\\t=\\t' for y", "current = \"\" space = \"<space>\" declared = [] referenced", "in range(len(x)): referenced.append(item(x[y])) tmp += item(x[y]) if y != len(x)-1", "x == \"test\": break; x = x.split(' ') if len(x)", "x not in declared: final.append(x) print \"\" for x in", "1: continue if x == \"test\": break; x = x.split('", "1 if test: final = '' for x in tmp:", "x.strip() if x == \"\": continue if '%%' == x:", "and \"'\" not in x[y+1] and \"'\" not in x[y]:", "test = 0 for x in alphabet: if x in", "!= 1: continue if x == \"test\": break; x =", "x in final: tmp = x+'\\t=\\t' x = x[1:-1] print", "tmp = x+'\\t=\\t' x = x[1:-1] print tmp + x.lower()", "not in declared: final.append(x) print \"\" for x in final:", "continue elif start != 1: continue if x == \"test\":", "if x == \"\": continue if '%%' == x: start", "in referenced: if x not in declared: final.append(x) print \"\"", "== 1:#item declaration or end if x[0] == ';': current", "return item(tmp) else: return \"<\"+y+\">\" start = 0 current =", "\"<\":\"lt\", \">\":\"gt\", \"=\":\"=\", \"-\":'-', \"+\":\"+\", \"-\":\"-\", \"~\":\"~\", \"!\":\"ex\", \"%\":\"%\", \"^\":\"^\",", "x[y]: tmp+=space print tmp referenced = set(referenced) final = []", "\"!\":\"ex\", \"%\":\"%\", \"^\":\"^\", \"&\":\"&\", \"*\":\"*\", \"(\":\"(\", \")\":\"right_paran\", \"[\":\"[\", \"]\":\"]\", \"{\":\"{\",", "= x[1:] tmp = item(current)+'\\t=\\t' for y in range(len(x)): referenced.append(item(x[y]))", "else: x = x[1:] tmp = item(current)+'\\t=\\t' for y in", "continue if '%%' == x: start = 1 continue elif", "tmp+=space print tmp referenced = set(referenced) final = [] for", "break; x = x.split(' ') if len(x) == 1:#item declaration", "} def item(y): if \"'\" in y: tmp = y.split(\"'\")[1]", "data = open('./original').readlines() alphabet = { \"<\":\"lt\", \">\":\"gt\", \"=\":\"=\", \"-\":'-',", "\"]\":\"]\", \"{\":\"{\", \"}\":\"}\", \"[\":\"[\", \"]\":\"]\", \"|\":\"|\", \";\":\";\", \":\":\":\", \",\":\",\", \".\":\".\",", "alphabet: if x in tmp: test = 1 if test:", "y.split(\"'\")[1] test = 0 for x in alphabet: if x", "\"=\":\"=\", \"-\":'-', \"+\":\"+\", \"-\":\"-\", \"~\":\"~\", \"!\":\"ex\", \"%\":\"%\", \"^\":\"^\", \"&\":\"&\", \"*\":\"*\",", "= \"<space>\" declared = [] referenced = [] for x", "set(referenced) final = [] for x in referenced: if x", "\":\":\":\", \",\":\",\", \".\":\".\", \"?\":\"?\", \"/\":\"/\", } def item(y): if \"'\"", "start = 0 current = \"\" space = \"<space>\" declared", "for x in tmp: final += item(alphabet[x]) return final else:", "1 continue elif start != 1: continue if x ==", "x = x[1:] tmp = item(current)+'\\t=\\t' for y in range(len(x)):", "\"'\" not in x[y+1] and \"'\" not in x[y]: tmp+=space", "open('./original').readlines() alphabet = { \"<\":\"lt\", \">\":\"gt\", \"=\":\"=\", \"-\":'-', \"+\":\"+\", \"-\":\"-\",", "\"|\":\"|\", \";\":\";\", \":\":\":\", \",\":\",\", \".\":\".\", \"?\":\"?\", \"/\":\"/\", } def item(y):", "\"'\" in y: tmp = y.split(\"'\")[1] test = 0 for", "else: current = x[0] declared.append(item(x[0])) print \"\" else: x =", "start != 1: continue if x == \"test\": break; x", "in y: tmp = y.split(\"'\")[1] test = 0 for x", "alphabet = { \"<\":\"lt\", \">\":\"gt\", \"=\":\"=\", \"-\":'-', \"+\":\"+\", \"-\":\"-\", \"~\":\"~\",", "= x[0] declared.append(item(x[0])) print \"\" else: x = x[1:] tmp", "= [] referenced = [] for x in data: x", "\"&\":\"&\", \"*\":\"*\", \"(\":\"(\", \")\":\"right_paran\", \"[\":\"[\", \"]\":\"]\", \"{\":\"{\", \"}\":\"}\", \"[\":\"[\", \"]\":\"]\",", "+= item(x[y]) if y != len(x)-1 and \"'\" not in", "tmp: test = 1 if test: final = '' for", "[] for x in data: x = x.strip() if x", "\">\":\"gt\", \"=\":\"=\", \"-\":'-', \"+\":\"+\", \"-\":\"-\", \"~\":\"~\", \"!\":\"ex\", \"%\":\"%\", \"^\":\"^\", \"&\":\"&\",", "\")\":\"right_paran\", \"[\":\"[\", \"]\":\"]\", \"{\":\"{\", \"}\":\"}\", \"[\":\"[\", \"]\":\"]\", \"|\":\"|\", \";\":\";\", \":\":\":\",", "[] referenced = [] for x in data: x =", "x.split(' ') if len(x) == 1:#item declaration or end if", "current = \"\" else: current = x[0] declared.append(item(x[0])) print \"\"", "if x[0] == ';': current = \"\" else: current =", "\"%\":\"%\", \"^\":\"^\", \"&\":\"&\", \"*\":\"*\", \"(\":\"(\", \")\":\"right_paran\", \"[\":\"[\", \"]\":\"]\", \"{\":\"{\", \"}\":\"}\",", "+= item(alphabet[x]) return final else: return item(tmp) else: return \"<\"+y+\">\"", "return \"<\"+y+\">\" start = 0 current = \"\" space =", "continue if x == \"test\": break; x = x.split(' ')", "= 1 if test: final = '' for x in", "= x.strip() if x == \"\": continue if '%%' ==", "tmp = item(current)+'\\t=\\t' for y in range(len(x)): referenced.append(item(x[y])) tmp +=", "\"[\":\"[\", \"]\":\"]\", \"{\":\"{\", \"}\":\"}\", \"[\":\"[\", \"]\":\"]\", \"|\":\"|\", \";\":\";\", \":\":\":\", \",\":\",\",", "item(x[y]) if y != len(x)-1 and \"'\" not in x[y+1]", "x = x.split(' ') if len(x) == 1:#item declaration or", "for x in alphabet: if x in tmp: test =", "x in referenced: if x not in declared: final.append(x) print", "in final: tmp = x+'\\t=\\t' x = x[1:-1] print tmp", "x in alphabet: if x in tmp: test = 1", "if test: final = '' for x in tmp: final", "x: start = 1 continue elif start != 1: continue", "x[1:] tmp = item(current)+'\\t=\\t' for y in range(len(x)): referenced.append(item(x[y])) tmp", "\"^\":\"^\", \"&\":\"&\", \"*\":\"*\", \"(\":\"(\", \")\":\"right_paran\", \"[\":\"[\", \"]\":\"]\", \"{\":\"{\", \"}\":\"}\", \"[\":\"[\",", "\"-\":\"-\", \"~\":\"~\", \"!\":\"ex\", \"%\":\"%\", \"^\":\"^\", \"&\":\"&\", \"*\":\"*\", \"(\":\"(\", \")\":\"right_paran\", \"[\":\"[\",", "return final else: return item(tmp) else: return \"<\"+y+\">\" start =", "end if x[0] == ';': current = \"\" else: current", "print \"\" else: x = x[1:] tmp = item(current)+'\\t=\\t' for", "0 current = \"\" space = \"<space>\" declared = []", "referenced = set(referenced) final = [] for x in referenced:", "len(x) == 1:#item declaration or end if x[0] == ';':", "= 1 continue elif start != 1: continue if x", "item(current)+'\\t=\\t' for y in range(len(x)): referenced.append(item(x[y])) tmp += item(x[y]) if", "or end if x[0] == ';': current = \"\" else:", "\"]\":\"]\", \"|\":\"|\", \";\":\";\", \":\":\":\", \",\":\",\", \".\":\".\", \"?\":\"?\", \"/\":\"/\", } def", "x in tmp: final += item(alphabet[x]) return final else: return", "referenced.append(item(x[y])) tmp += item(x[y]) if y != len(x)-1 and \"'\"", "declared.append(item(x[0])) print \"\" else: x = x[1:] tmp = item(current)+'\\t=\\t'", "elif start != 1: continue if x == \"test\": break;", "\".\":\".\", \"?\":\"?\", \"/\":\"/\", } def item(y): if \"'\" in y:", "data: x = x.strip() if x == \"\": continue if", "len(x)-1 and \"'\" not in x[y+1] and \"'\" not in", "item(tmp) else: return \"<\"+y+\">\" start = 0 current = \"\"", "\"/\":\"/\", } def item(y): if \"'\" in y: tmp =", "';': current = \"\" else: current = x[0] declared.append(item(x[0])) print", "\";\":\";\", \":\":\":\", \",\":\",\", \".\":\".\", \"?\":\"?\", \"/\":\"/\", } def item(y): if", "for y in range(len(x)): referenced.append(item(x[y])) tmp += item(x[y]) if y", "= \"\" else: current = x[0] declared.append(item(x[0])) print \"\" else:", "\"-\":'-', \"+\":\"+\", \"-\":\"-\", \"~\":\"~\", \"!\":\"ex\", \"%\":\"%\", \"^\":\"^\", \"&\":\"&\", \"*\":\"*\", \"(\":\"(\",", "x in tmp: test = 1 if test: final =", "== ';': current = \"\" else: current = x[0] declared.append(item(x[0]))", "\"~\":\"~\", \"!\":\"ex\", \"%\":\"%\", \"^\":\"^\", \"&\":\"&\", \"*\":\"*\", \"(\":\"(\", \")\":\"right_paran\", \"[\":\"[\", \"]\":\"]\",", "item(y): if \"'\" in y: tmp = y.split(\"'\")[1] test =", "== \"test\": break; x = x.split(' ') if len(x) ==", "print tmp referenced = set(referenced) final = [] for x", "test = 1 if test: final = '' for x", "\"(\":\"(\", \")\":\"right_paran\", \"[\":\"[\", \"]\":\"]\", \"{\":\"{\", \"}\":\"}\", \"[\":\"[\", \"]\":\"]\", \"|\":\"|\", \";\":\";\",", "not in x[y]: tmp+=space print tmp referenced = set(referenced) final", "= { \"<\":\"lt\", \">\":\"gt\", \"=\":\"=\", \"-\":'-', \"+\":\"+\", \"-\":\"-\", \"~\":\"~\", \"!\":\"ex\"," ]
[ "AppScale file which has a list of IPs running memcached.", "item in request.item_list(): key = self._GetKey(request.name_space(), item.key()) set_policy = item.set_policy()", "= \"/etc/appscale/memcache_ips\" # The minimum frequency by which memcache clients", "old_entry is not None)): if (old_entry is None or set_policy", "response): \"\"\"Implementation of sets for memcache. Args: request: A MemcacheSetRequest.", "self._GetKey(namespace, request.key()) value = self._memcache.get(key) if value is None: if", "request.direction() == MemcacheIncrementRequest.INCREMENT: new_value += request.delta() elif request.direction() == MemcacheIncrementRequest.DECREMENT:", "name expected for all calls. \"\"\" super(MemcacheService, self).__init__(service_name) self._gettime =", "logging.error(str(e)) return None return new_value def _Dynamic_Increment(self, request, response): \"\"\"Implementation", "response: A MemcacheBatchIncrementResponse protocol buffer. \"\"\" namespace = request.name_space() for", "!= item.cas_id(): set_status = MemcacheSetResponse.EXISTS else: set_status = MemcacheSetResponse.STORED if", "2.0 (the \"License\"); # you may not use this file", "MemcacheIncrementRequest instance. Returns: An integer or long if the offset", "MemcacheIncrementRequest protocol buffer. response: A MemcacheIncrementResponse protocol buffer. \"\"\" new_value", "None: continue flags = 0 stored_flags, cas_id, stored_value = cPickle.loads(value)", "and item.for_cas() and item.has_cas_id()): if old_entry is None: set_status =", "memcache_file.read().split(\"\\n\") memcache_file.close() else: all_ips = ['localhost'] memcaches = [ip +", "get_stats_value(stats_dict, key, _type=int): \"\"\" Gets statisical values and makes sure", "key: The key as provided by the application. Returns: A", "MemcacheSetResponse.NOT_STORED if ((set_policy == MemcacheSetRequest.SET) or (set_policy == MemcacheSetRequest.ADD and", "only memcache service. This service keeps all data in any", "get the Memcache key. It is encoded because the sdk", "+= get_stats_value(server_stats, 'bytes') time_total += get_stats_value(server_stats, 'time', float) stats.set_hits(hits_total) stats.set_misses(misses_total)", "key. It is encoded because the sdk allows special characters", "== MemcacheSetRequest.SET) or (set_policy == MemcacheSetRequest.ADD and old_entry is None)", "0 byte_hits_total = 0 items_total = 0 bytes_total = 0", "memcache_service_pb.MemcacheIncrementRequest MemcacheIncrementResponse = memcache_service_pb.MemcacheIncrementResponse MemcacheDeleteResponse = memcache_service_pb.MemcacheDeleteResponse from google.appengine.api.memcache import", "num_servers += 1 hits_total += get_stats_value(server_stats, 'get_hits') misses_total += get_stats_value(server_stats,", "appname = os.environ['APPNAME'] internal_key = appname + \"__\" + namespace", "from a MemcacheIncrementRequest. Args: namespace: A string containing the namespace", "cas_id + 1, str(new_value)]) try: self._memcache.cas(key, new_stored_value) except Exception, e:", "'time', float) stats.set_hits(hits_total) stats.set_misses(misses_total) stats.set_byte_hits(byte_hits_total) stats.set_items(items_total) stats.set_bytes(bytes_total) # With the", "return None return new_value def _Dynamic_Increment(self, request, response): \"\"\"Implementation of", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "and old_entry is None) or (set_policy == MemcacheSetRequest.REPLACE and old_entry", "= 0 bytes_total = 0 time_total = 0 def get_stats_value(stats_dict,", "\"\"\" if os.path.exists(self.APPSCALE_MEMCACHE_FILE): memcache_file = open(self.APPSCALE_MEMCACHE_FILE, \"r\") all_ips = memcache_file.read().split(\"\\n\")", "memcached default port. MEMCACHE_PORT = \"11211\" # An AppScale file", "a list of IPs running memcached. APPSCALE_MEMCACHE_FILE = \"/etc/appscale/memcache_ips\" #", "request_item in request.item_list(): new_value = self._Increment(namespace, request_item) item = response.add_item()", "but the Memcache client does not. Args: namespace: The namespace", "time from google.appengine.api import apiproxy_stub from google.appengine.api.memcache import memcache_service_pb from", "A MemcacheSetResponse. \"\"\" for item in request.item_list(): key = self._GetKey(request.name_space(),", "= item.set_policy() old_entry = self._memcache.get(key) cas_id = 0 if old_entry:", "the sdk allows special characters but the Memcache client does", "for memcache. Args: request: A MemcacheGetRequest protocol buffer. response: A", "A MemcacheDeleteRequest protocol buffer. response: A MemcacheDeleteResponse protocol buffer. \"\"\"", "in memcached. Uses the python-memcached library to interface with memcached.", "TYPE_INT: new_value = int(stored_value) elif flags == TYPE_LONG: new_value =", "namespace as provided by the application. key: The key as", "if request.direction() == MemcacheIncrementRequest.INCREMENT: new_value += request.delta() elif request.direction() ==", "request, response): \"\"\"Implementation of MemcacheService::Stats(). Args: request: A MemcacheStatsRequest. response:", "stored_value = cPickle.loads(value) flags |= stored_flags item = response.add_item() item.set_key(key)", "set_policy == MemcacheSetRequest.REPLACE: self._memcache.replace(key, set_value) else: self._memcache.set(key, set_value, item.expiration_time()) response.add_set_status(set_status)", "None)): if (old_entry is None or set_policy == MemcacheSetRequest.SET): set_status", "if old_entry is None: set_status = MemcacheSetResponse.NOT_STORED elif cas_id !=", "(set_policy == MemcacheSetRequest.REPLACE and old_entry is not None)): if (old_entry", "\"\"\"Implementation of MemcacheService::FlushAll(). Args: request: A MemcacheFlushRequest. response: A MemcacheFlushResponse.", "string __{appname}__{namespace}__{key} \"\"\" appname = os.environ['APPNAME'] internal_key = appname +", "function for incrementing from a MemcacheIncrementRequest. Args: namespace: A string", "get_stats_value(server_stats, 'bytes_read') items_total += get_stats_value(server_stats, 'curr_items') bytes_total += get_stats_value(server_stats, 'bytes')", "This service keeps all data in any external servers running", "use this file except in compliance with the License. #", "== MemcacheIncrementRequest.DECREMENT: new_value -= request.delta() new_stored_value = cPickle.dumps([flags, cas_id +", "def get_stats_value(stats_dict, key, _type=int): \"\"\" Gets statisical values and makes", "self._memcache.set(key, set_value, item.expiration_time()) response.add_set_status(set_status) def _Dynamic_Delete(self, request, response): \"\"\"Implementation of", "buffer. response: A MemcacheDeleteResponse protocol buffer. \"\"\" for item in", "= self._memcache.get(internal_key) if value is None: continue flags = 0", "'get_hits') misses_total += get_stats_value(server_stats, 'get_misses') byte_hits_total += get_stats_value(server_stats, 'bytes_read') items_total", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "License. # \"\"\" Non-stub version of the memcache API, keeping", "in set(request.key_list()): internal_key = self._GetKey(request.name_space(), key) value = self._memcache.get(internal_key) if", "== MemcacheSetRequest.ADD and old_entry is None) or (set_policy == MemcacheSetRequest.REPLACE", "gets for memcache. Args: request: A MemcacheGetRequest protocol buffer. response:", "if not request.delta(): return None cas_id = 0 key =", "License. # You may obtain a copy of the License", "self._Increment(request.name_space(), request) if new_value is None: raise apiproxy_errors.ApplicationError( memcache_service_pb.MemcacheServiceError.UNSPECIFIED_ERROR) response.set_new_value(new_value)", "\"\"\" self._memcache.flush_all() def _Dynamic_Stats(self, request, response): \"\"\"Implementation of MemcacheService::Stats(). Args:", "MemcacheSetRequest.SET) or (set_policy == MemcacheSetRequest.ADD and old_entry is None) or", "cPickle.dumps( [item.flags(), cas_id + 1, item.value()]) if set_policy == MemcacheSetRequest.REPLACE:", "response.add_delete_status(delete_status) def _Increment(self, namespace, request): \"\"\"Internal function for incrementing from", "elif (set_policy == MemcacheSetRequest.CAS and item.for_cas() and item.has_cas_id()): if old_entry", "under the License is distributed on an \"AS IS\" BASIS,", "buffer. response: A MemcacheBatchIncrementResponse protocol buffer. \"\"\" namespace = request.name_space()", "protocol buffer. \"\"\" for key in set(request.key_list()): internal_key = self._GetKey(request.name_space(),", "License for the specific language governing permissions and # limitations", "for server, server_stats in self._memcache.get_stats(): num_servers += 1 hits_total +=", "raise apiproxy_errors.ApplicationError( memcache_service_pb.MemcacheServiceError.UNSPECIFIED_ERROR) response.set_new_value(new_value) def _Dynamic_BatchIncrement(self, request, response): \"\"\"Implementation of", "= [ip + \":\" + self.MEMCACHE_PORT for ip in all_ips", "# Python 2.5 was fine with this being a float,", "MemcacheIncrementResponse protocol buffer. \"\"\" new_value = self._Increment(request.name_space(), request) if new_value", "MemcacheBatchIncrementRequest protocol buffer. response: A MemcacheBatchIncrementResponse protocol buffer. \"\"\" namespace", "import memcache_service_pb from google.appengine.runtime import apiproxy_errors MemcacheSetResponse = memcache_service_pb.MemcacheSetResponse MemcacheSetRequest", "= \"11211\" # An AppScale file which has a list", "new_value def _Dynamic_Increment(self, request, response): \"\"\"Implementation of increment for memcache.", "return new_value def _Dynamic_Increment(self, request, response): \"\"\"Implementation of increment for", "\"\"\"Internal function for incrementing from a MemcacheIncrementRequest. Args: namespace: A", "cas_id, stored_value = cPickle.loads(value) if flags == TYPE_INT: new_value =", "containing the namespace for the request, if any. Pass an", "instance. Returns: An integer or long if the offset was", "sure the key is in the dict. \"\"\" if key", "stats.set_byte_hits(byte_hits_total) stats.set_items(items_total) stats.set_bytes(bytes_total) # With the Python 2.7 GAE runtime,", "hits_total += get_stats_value(server_stats, 'get_hits') misses_total += get_stats_value(server_stats, 'get_misses') byte_hits_total +=", "gettime self._memcache = None self.setupMemcacheClient() def setupMemcacheClient(self): \"\"\" Sets up", "else: item.set_increment_status(MemcacheIncrementResponse.OK) item.set_new_value(new_value) def _Dynamic_FlushAll(self, request, response): \"\"\"Implementation of MemcacheService::FlushAll().", "new_value = int(stored_value) elif flags == TYPE_LONG: new_value = long(stored_value)", "is in the dict. \"\"\" if key not in stats_dict:", "response: A MemcacheDeleteResponse protocol buffer. \"\"\" for item in request.item_list():", "request.item_list(): key = self._GetKey(request.name_space(), item.key()) set_policy = item.set_policy() old_entry =", "+= get_stats_value(server_stats, 'time', float) stats.set_hits(hits_total) stats.set_misses(misses_total) stats.set_byte_hits(byte_hits_total) stats.set_items(items_total) stats.set_bytes(bytes_total) #", "float) stats.set_hits(hits_total) stats.set_misses(misses_total) stats.set_byte_hits(byte_hits_total) stats.set_items(items_total) stats.set_bytes(bytes_total) # With the Python", "A MemcacheDeleteResponse protocol buffer. \"\"\" for item in request.item_list(): key", "import logging import memcache import os import time from google.appengine.api", "application. Returns: A base64 string __{appname}__{namespace}__{key} \"\"\" appname = os.environ['APPNAME']", "in compliance with the License. # You may obtain a", "software # distributed under the License is distributed on an", "= None self.setupMemcacheClient() def setupMemcacheClient(self): \"\"\" Sets up the memcache", "MemcacheService::FlushAll(). Args: request: A MemcacheFlushRequest. response: A MemcacheFlushResponse. \"\"\" self._memcache.flush_all()", "server, server_stats in self._memcache.get_stats(): num_servers += 1 hits_total += get_stats_value(server_stats,", "GAE runtime, it expects all fields here to be ints.", "or set_policy == MemcacheSetRequest.REPLACE): set_value = cPickle.dumps( [item.flags(), cas_id +", "being a float, so callers in that runtime # may", "sets for memcache. Args: request: A MemcacheSetRequest. response: A MemcacheSetResponse.", "does not. Args: namespace: The namespace as provided by the", "in any external servers running memcached. \"\"\" # The memcached", "self._memcache.get(key) if value is None: if not request.has_initial_value(): return None", "A MemcacheSetRequest. response: A MemcacheSetResponse. \"\"\" for item in request.item_list():", "A MemcacheBatchIncrementRequest protocol buffer. response: A MemcacheBatchIncrementResponse protocol buffer. \"\"\"", "= 0 time_total = 0 def get_stats_value(stats_dict, key, _type=int): \"\"\"", "import apiproxy_stub from google.appengine.api.memcache import memcache_service_pb from google.appengine.runtime import apiproxy_errors", "ints. # Python 2.5 was fine with this being a", "MemcacheDeleteResponse protocol buffer. \"\"\" for item in request.item_list(): key =", "'bytes_read') items_total += get_stats_value(server_stats, 'curr_items') bytes_total += get_stats_value(server_stats, 'bytes') time_total", "TYPE_LONG class MemcacheService(apiproxy_stub.APIProxyStub): \"\"\"Python only memcache service. This service keeps", "= memcache.Client(memcaches, debug=0) def _Dynamic_Get(self, request, response): \"\"\"Implementation of gets", "= 0 byte_hits_total = 0 items_total = 0 bytes_total =", "The minimum frequency by which memcache clients will update their", "response: A MemcacheFlushResponse. \"\"\" self._memcache.flush_all() def _Dynamic_Stats(self, request, response): \"\"\"Implementation", "Args: request: A MemcacheSetRequest. response: A MemcacheSetResponse. \"\"\" for item", "MemcacheStatsResponse. \"\"\" stats = response.mutable_stats() num_servers = 0 hits_total =", "string if there is no namespace. request: A MemcacheIncrementRequest instance.", "for key '%s'.\" % key) return _type(stats_dict.get(key, '0')) for server,", "def _Dynamic_Delete(self, request, response): \"\"\"Implementation of delete in memcache. Args:", "list of # clients that they connect to (which can", "Args: namespace: The namespace as provided by the application. key:", "as provided by the application. key: The key as provided", "= cPickle.loads(old_entry) set_status = MemcacheSetResponse.NOT_STORED if ((set_policy == MemcacheSetRequest.SET) or", "TYPE_INT, cas_id, str(request.initial_value())) else: flags, cas_id, stored_value = cPickle.loads(value) if", "may not be expecting an int. stats.set_oldest_item_age(int(time.time() - time_total /", "data in any external servers running memcached. \"\"\" # The", "service_name='memcache'): \"\"\"Initializer. Args: gettime: time.time()-like function used for testing. service_name:", "time_total / num_servers)) def _GetKey(self, namespace, key): \"\"\"Used to get", "response.add_set_status(set_status) def _Dynamic_Delete(self, request, response): \"\"\"Implementation of delete in memcache.", "A MemcacheFlushResponse. \"\"\" self._memcache.flush_all() def _Dynamic_Stats(self, request, response): \"\"\"Implementation of", "if (old_entry is None or set_policy == MemcacheSetRequest.SET): set_status =", "__init__(self, gettime=time.time, service_name='memcache'): \"\"\"Initializer. Args: gettime: time.time()-like function used for", "str(new_value)]) try: self._memcache.cas(key, new_stored_value) except Exception, e: logging.error(str(e)) return None", "A MemcacheIncrementRequest instance. Returns: An integer or long if the", "== MemcacheSetRequest.REPLACE and old_entry is not None)): if (old_entry is", "old_entry is None: set_status = MemcacheSetResponse.NOT_STORED elif cas_id != item.cas_id():", "bytes_total = 0 time_total = 0 def get_stats_value(stats_dict, key, _type=int):", "e: logging.error(str(e)) return None return new_value def _Dynamic_Increment(self, request, response):", "successful, None on error. \"\"\" if not request.delta(): return None", "num_servers)) def _GetKey(self, namespace, key): \"\"\"Used to get the Memcache", "list of IPs running memcached. APPSCALE_MEMCACHE_FILE = \"/etc/appscale/memcache_ips\" # The", "item.key()) set_policy = item.set_policy() old_entry = self._memcache.get(key) cas_id = 0", "MemcacheIncrementRequest.DECREMENT: new_value -= request.delta() new_stored_value = cPickle.dumps([flags, cas_id + 1,", "old_entry = self._memcache.get(key) cas_id = 0 if old_entry: _, cas_id,", "hits_total = 0 misses_total = 0 byte_hits_total = 0 items_total", "MemcacheSetResponse = memcache_service_pb.MemcacheSetResponse MemcacheSetRequest = memcache_service_pb.MemcacheSetRequest MemcacheIncrementRequest = memcache_service_pb.MemcacheIncrementRequest MemcacheIncrementResponse", "else: self._memcache.set(key, set_value, item.expiration_time()) response.add_set_status(set_status) def _Dynamic_Delete(self, request, response): \"\"\"Implementation", "OF ANY KIND, either express or implied. # See the", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "# \"\"\" Non-stub version of the memcache API, keeping all", "set_policy == MemcacheSetRequest.SET): set_status = MemcacheSetResponse.STORED elif (set_policy == MemcacheSetRequest.CAS", "ANY KIND, either express or implied. # See the License", "See the License for the specific language governing permissions and", "that they connect to (which can change if AppScale scales", "set_status = MemcacheSetResponse.NOT_STORED elif cas_id != item.cas_id(): set_status = MemcacheSetResponse.EXISTS", "response: A MemcacheSetResponse. \"\"\" for item in request.item_list(): key =", "interface with memcached. \"\"\" import base64 import cPickle import logging", "the License. # You may obtain a copy of the", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "for the specific language governing permissions and # limitations under", "of # clients that they connect to (which can change", "None return new_value def _Dynamic_Increment(self, request, response): \"\"\"Implementation of increment", "self._GetKey(request.name_space(), key) value = self._memcache.get(internal_key) if value is None: continue", "= 0 hits_total = 0 misses_total = 0 byte_hits_total =", "self._memcache.get_stats(): num_servers += 1 hits_total += get_stats_value(server_stats, 'get_hits') misses_total +=", "to in writing, software # distributed under the License is", "_, cas_id, _ = cPickle.loads(old_entry) set_status = MemcacheSetResponse.NOT_STORED if ((set_policy", "None or set_policy == MemcacheSetRequest.SET): set_status = MemcacheSetResponse.STORED elif (set_policy", "was fine with this being a float, so callers in", "# See the License for the specific language governing permissions", "new_value = long(stored_value) if request.direction() == MemcacheIncrementRequest.INCREMENT: new_value += request.delta()", "their list of # clients that they connect to (which", "_Dynamic_Stats(self, request, response): \"\"\"Implementation of MemcacheService::Stats(). Args: request: A MemcacheStatsRequest.", "memcache_service_pb.MemcacheSetRequest MemcacheIncrementRequest = memcache_service_pb.MemcacheIncrementRequest MemcacheIncrementResponse = memcache_service_pb.MemcacheIncrementResponse MemcacheDeleteResponse = memcache_service_pb.MemcacheDeleteResponse", "cPickle.dumps([flags, cas_id + 1, str(new_value)]) try: self._memcache.cas(key, new_stored_value) except Exception,", "response.mutable_stats() num_servers = 0 hits_total = 0 misses_total = 0", "language governing permissions and # limitations under the License. #", "protocol buffer. response: A MemcacheDeleteResponse protocol buffer. \"\"\" for item", "or agreed to in writing, software # distributed under the", "or # down). UPDATE_WINDOW = 60 # seconds def __init__(self,", "request, response): \"\"\"Implementation of delete in memcache. Args: request: A", "+ self.MEMCACHE_PORT for ip in all_ips if ip != '']", "required by applicable law or agreed to in writing, software", "Returns: An integer or long if the offset was successful,", "if entry is None: delete_status = MemcacheDeleteResponse.NOT_FOUND else: self._memcache.delete(key) response.add_delete_status(delete_status)", "Exception, e: logging.error(str(e)) return None return new_value def _Dynamic_Increment(self, request,", "0 def get_stats_value(stats_dict, key, _type=int): \"\"\" Gets statisical values and", "response): \"\"\"Implementation of gets for memcache. Args: request: A MemcacheGetRequest", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "frequency by which memcache clients will update their list of", "offset was successful, None on error. \"\"\" if not request.delta():", "with the License. # You may obtain a copy of", "= self._GetKey(request.name_space(), key) value = self._memcache.get(internal_key) if value is None:", "by the application. Returns: A base64 string __{appname}__{namespace}__{key} \"\"\" appname", "= 0 misses_total = 0 byte_hits_total = 0 items_total =", "((set_policy == MemcacheSetRequest.SET) or (set_policy == MemcacheSetRequest.ADD and old_entry is", "(set_policy == MemcacheSetRequest.ADD and old_entry is None) or (set_policy ==", "It is encoded because the sdk allows special characters but", "long(stored_value) if request.direction() == MemcacheIncrementRequest.INCREMENT: new_value += request.delta() elif request.direction()", "MemcacheDeleteResponse.NOT_FOUND else: self._memcache.delete(key) response.add_delete_status(delete_status) def _Increment(self, namespace, request): \"\"\"Internal function", "new_value = self._Increment(request.name_space(), request) if new_value is None: raise apiproxy_errors.ApplicationError(", "+= get_stats_value(server_stats, 'get_hits') misses_total += get_stats_value(server_stats, 'get_misses') byte_hits_total += get_stats_value(server_stats,", "with memcached. \"\"\" import base64 import cPickle import logging import", "compliance with the License. # You may obtain a copy", "appname + \"__\" + namespace + \"__\" + key return", "agreed to in writing, software # distributed under the License", "Args: request: A MemcacheStatsRequest. response: A MemcacheStatsResponse. \"\"\" stats =", "memcache. Args: request: A MemcacheDeleteRequest protocol buffer. response: A MemcacheDeleteResponse", "distributed under the License is distributed on an \"AS IS\"", "0 key = self._GetKey(namespace, request.key()) value = self._memcache.get(key) if value", "def _GetKey(self, namespace, key): \"\"\"Used to get the Memcache key.", "Memcache client does not. Args: namespace: The namespace as provided", "buffer. \"\"\" new_value = self._Increment(request.name_space(), request) if new_value is None:", "'0')) for server, server_stats in self._memcache.get_stats(): num_servers += 1 hits_total", "not be expecting an int. stats.set_oldest_item_age(int(time.time() - time_total / num_servers))", "self._GetKey(request.name_space(), item.key()) set_policy = item.set_policy() old_entry = self._memcache.get(key) cas_id =", "stats for key '%s'.\" % key) return _type(stats_dict.get(key, '0')) for", "0 bytes_total = 0 time_total = 0 def get_stats_value(stats_dict, key,", "request, response): \"\"\"Implementation of increment for memcache. Args: request: A", "application. key: The key as provided by the application. Returns:", "API, keeping all data in memcached. Uses the python-memcached library", "express or implied. # See the License for the specific", "is None: item.set_increment_status(MemcacheIncrementResponse.NOT_CHANGED) else: item.set_increment_status(MemcacheIncrementResponse.OK) item.set_new_value(new_value) def _Dynamic_FlushAll(self, request, response):", "the Memcache client does not. Args: namespace: The namespace as", "memcache_service_pb.MemcacheIncrementResponse MemcacheDeleteResponse = memcache_service_pb.MemcacheDeleteResponse from google.appengine.api.memcache import TYPE_INT from google.appengine.api.memcache", "except in compliance with the License. # You may obtain", "apiproxy_errors MemcacheSetResponse = memcache_service_pb.MemcacheSetResponse MemcacheSetRequest = memcache_service_pb.MemcacheSetRequest MemcacheIncrementRequest = memcache_service_pb.MemcacheIncrementRequest", "= memcache_service_pb.MemcacheIncrementResponse MemcacheDeleteResponse = memcache_service_pb.MemcacheDeleteResponse from google.appengine.api.memcache import TYPE_INT from", "_Dynamic_BatchIncrement(self, request, response): \"\"\"Implementation of batch increment for memcache. Args:", "if flags == TYPE_INT: new_value = int(stored_value) elif flags ==", "1, item.value()]) if set_policy == MemcacheSetRequest.REPLACE: self._memcache.replace(key, set_value) else: self._memcache.set(key,", "if key not in stats_dict: logging.warn(\"No stats for key '%s'.\"", "# may not be expecting an int. stats.set_oldest_item_age(int(time.time() - time_total", "Licensed under the Apache License, Version 2.0 (the \"License\"); #", "on error. \"\"\" if not request.delta(): return None cas_id =", "request.item_list(): new_value = self._Increment(namespace, request_item) item = response.add_item() if new_value", "delete_status = MemcacheDeleteResponse.NOT_FOUND else: self._memcache.delete(key) response.add_delete_status(delete_status) def _Increment(self, namespace, request):", "not. Args: namespace: The namespace as provided by the application.", "not use this file except in compliance with the License.", "# Copyright 2007 Google Inc. # # Licensed under the", "== MemcacheSetRequest.SET): set_status = MemcacheSetResponse.STORED elif (set_policy == MemcacheSetRequest.CAS and", "Python 2.5 was fine with this being a float, so", "in all_ips if ip != ''] memcaches.sort() self._memcache = memcache.Client(memcaches,", "byte_hits_total += get_stats_value(server_stats, 'bytes_read') items_total += get_stats_value(server_stats, 'curr_items') bytes_total +=", "Copyright 2007 Google Inc. # # Licensed under the Apache", "request: A MemcacheGetRequest protocol buffer. response: A MemcacheGetResponse protocol buffer.", "entry = self._memcache.get(key) delete_status = MemcacheDeleteResponse.DELETED if entry is None:", "get_stats_value(server_stats, 'time', float) stats.set_hits(hits_total) stats.set_misses(misses_total) stats.set_byte_hits(byte_hits_total) stats.set_items(items_total) stats.set_bytes(bytes_total) # With", "writing, software # distributed under the License is distributed on", "by the application. key: The key as provided by the", "0 items_total = 0 bytes_total = 0 time_total = 0", "you may not use this file except in compliance with", "0 hits_total = 0 misses_total = 0 byte_hits_total = 0", "gettime=time.time, service_name='memcache'): \"\"\"Initializer. Args: gettime: time.time()-like function used for testing.", "buffer. \"\"\" namespace = request.name_space() for request_item in request.item_list(): new_value", "is no namespace. request: A MemcacheIncrementRequest instance. Returns: An integer", "self._memcache.get(internal_key) if value is None: continue flags = 0 stored_flags,", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "memcached. \"\"\" # The memcached default port. MEMCACHE_PORT = \"11211\"", "runtime, it expects all fields here to be ints. #", "namespace: The namespace as provided by the application. key: The", "self.setupMemcacheClient() def setupMemcacheClient(self): \"\"\" Sets up the memcache client. \"\"\"", "for the request, if any. Pass an empty string if", "\"\"\" super(MemcacheService, self).__init__(service_name) self._gettime = gettime self._memcache = None self.setupMemcacheClient()", "any external servers running memcached. \"\"\" # The memcached default", "namespace, request): \"\"\"Internal function for incrementing from a MemcacheIncrementRequest. Args:", "time_total = 0 def get_stats_value(stats_dict, key, _type=int): \"\"\" Gets statisical", "if not request.has_initial_value(): return None flags, cas_id, stored_value = (", "MemcacheSetResponse.STORED elif (set_policy == MemcacheSetRequest.CAS and item.for_cas() and item.has_cas_id()): if", "clients that they connect to (which can change if AppScale", "from google.appengine.runtime import apiproxy_errors MemcacheSetResponse = memcache_service_pb.MemcacheSetResponse MemcacheSetRequest = memcache_service_pb.MemcacheSetRequest", "old_entry: _, cas_id, _ = cPickle.loads(old_entry) set_status = MemcacheSetResponse.NOT_STORED if", "Sets up the memcache client. \"\"\" if os.path.exists(self.APPSCALE_MEMCACHE_FILE): memcache_file =", "seconds def __init__(self, gettime=time.time, service_name='memcache'): \"\"\"Initializer. Args: gettime: time.time()-like function", "Args: request: A MemcacheBatchIncrementRequest protocol buffer. response: A MemcacheBatchIncrementResponse protocol", "stats.set_oldest_item_age(int(time.time() - time_total / num_servers)) def _GetKey(self, namespace, key): \"\"\"Used", "testing. service_name: Service name expected for all calls. \"\"\" super(MemcacheService,", "/ num_servers)) def _GetKey(self, namespace, key): \"\"\"Used to get the", "MemcacheGetRequest protocol buffer. response: A MemcacheGetResponse protocol buffer. \"\"\" for", "CONDITIONS OF ANY KIND, either express or implied. # See", "for memcache. Args: request: A MemcacheBatchIncrementRequest protocol buffer. response: A", "os import time from google.appengine.api import apiproxy_stub from google.appengine.api.memcache import", "= MemcacheSetResponse.NOT_STORED if ((set_policy == MemcacheSetRequest.SET) or (set_policy == MemcacheSetRequest.ADD", "of increment for memcache. Args: request: A MemcacheIncrementRequest protocol buffer.", "AppScale scales up or # down). UPDATE_WINDOW = 60 #", "not in stats_dict: logging.warn(\"No stats for key '%s'.\" % key)", "The key as provided by the application. Returns: A base64", "= gettime self._memcache = None self.setupMemcacheClient() def setupMemcacheClient(self): \"\"\" Sets", "MemcacheIncrementResponse = memcache_service_pb.MemcacheIncrementResponse MemcacheDeleteResponse = memcache_service_pb.MemcacheDeleteResponse from google.appengine.api.memcache import TYPE_INT", "\"\"\"Implementation of sets for memcache. Args: request: A MemcacheSetRequest. response:", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "cas_id != item.cas_id(): set_status = MemcacheSetResponse.EXISTS else: set_status = MemcacheSetResponse.STORED", "stored_value = cPickle.loads(value) if flags == TYPE_INT: new_value = int(stored_value)", "key): \"\"\"Used to get the Memcache key. It is encoded", "_Increment(self, namespace, request): \"\"\"Internal function for incrementing from a MemcacheIncrementRequest.", "memcache. Args: request: A MemcacheGetRequest protocol buffer. response: A MemcacheGetResponse", "request: A MemcacheFlushRequest. response: A MemcacheFlushResponse. \"\"\" self._memcache.flush_all() def _Dynamic_Stats(self,", "port. MEMCACHE_PORT = \"11211\" # An AppScale file which has", "= os.environ['APPNAME'] internal_key = appname + \"__\" + namespace +", "protocol buffer. \"\"\" for item in request.item_list(): key = self._GetKey(request.name_space(),", "= self._GetKey(namespace, request.key()) value = self._memcache.get(key) if value is None:", "all_ips = ['localhost'] memcaches = [ip + \":\" + self.MEMCACHE_PORT", "request.item_list(): key = self._GetKey(request.name_space(), item.key()) entry = self._memcache.get(key) delete_status =", "values and makes sure the key is in the dict.", "= request.name_space() for request_item in request.item_list(): new_value = self._Increment(namespace, request_item)", "Args: request: A MemcacheIncrementRequest protocol buffer. response: A MemcacheIncrementResponse protocol", "MemcacheDeleteRequest protocol buffer. response: A MemcacheDeleteResponse protocol buffer. \"\"\" for", "def _Dynamic_Get(self, request, response): \"\"\"Implementation of gets for memcache. Args:", "item.set_flags(flags) if request.for_cas(): item.set_cas_id(cas_id) def _Dynamic_Set(self, request, response): \"\"\"Implementation of", "bytes_total += get_stats_value(server_stats, 'bytes') time_total += get_stats_value(server_stats, 'time', float) stats.set_hits(hits_total)", "MemcacheService(apiproxy_stub.APIProxyStub): \"\"\"Python only memcache service. This service keeps all data", "\"\"\" if not request.delta(): return None cas_id = 0 key", "set_status = MemcacheSetResponse.EXISTS else: set_status = MemcacheSetResponse.STORED if (set_status ==", "cas_id = 0 key = self._GetKey(namespace, request.key()) value = self._memcache.get(key)", "try: self._memcache.cas(key, new_stored_value) except Exception, e: logging.error(str(e)) return None return", "\"\"\"Implementation of batch increment for memcache. Args: request: A MemcacheBatchIncrementRequest", "memcache client. \"\"\" if os.path.exists(self.APPSCALE_MEMCACHE_FILE): memcache_file = open(self.APPSCALE_MEMCACHE_FILE, \"r\") all_ips", "response: A MemcacheGetResponse protocol buffer. \"\"\" for key in set(request.key_list()):", "empty string if there is no namespace. request: A MemcacheIncrementRequest", "the offset was successful, None on error. \"\"\" if not", "dict. \"\"\" if key not in stats_dict: logging.warn(\"No stats for", "new_value is None: item.set_increment_status(MemcacheIncrementResponse.NOT_CHANGED) else: item.set_increment_status(MemcacheIncrementResponse.OK) item.set_new_value(new_value) def _Dynamic_FlushAll(self, request,", "OR CONDITIONS OF ANY KIND, either express or implied. #", "for all calls. \"\"\" super(MemcacheService, self).__init__(service_name) self._gettime = gettime self._memcache", "memcache. Args: request: A MemcacheIncrementRequest protocol buffer. response: A MemcacheIncrementResponse", "request.key()) value = self._memcache.get(key) if value is None: if not", "MEMCACHE_PORT = \"11211\" # An AppScale file which has a", "google.appengine.api.memcache import TYPE_INT from google.appengine.api.memcache import TYPE_LONG class MemcacheService(apiproxy_stub.APIProxyStub): \"\"\"Python", "\"\"\" # The memcached default port. MEMCACHE_PORT = \"11211\" #", "client. \"\"\" if os.path.exists(self.APPSCALE_MEMCACHE_FILE): memcache_file = open(self.APPSCALE_MEMCACHE_FILE, \"r\") all_ips =", "MemcacheSetRequest.REPLACE and old_entry is not None)): if (old_entry is None", "key is in the dict. \"\"\" if key not in", "stats.set_hits(hits_total) stats.set_misses(misses_total) stats.set_byte_hits(byte_hits_total) stats.set_items(items_total) stats.set_bytes(bytes_total) # With the Python 2.7", "the License is distributed on an \"AS IS\" BASIS, #", "= cPickle.loads(value) flags |= stored_flags item = response.add_item() item.set_key(key) item.set_value(stored_value)", "def setupMemcacheClient(self): \"\"\" Sets up the memcache client. \"\"\" if", "default port. MEMCACHE_PORT = \"11211\" # An AppScale file which", "item.expiration_time()) response.add_set_status(set_status) def _Dynamic_Delete(self, request, response): \"\"\"Implementation of delete in", "if any. Pass an empty string if there is no", "\"\"\" appname = os.environ['APPNAME'] internal_key = appname + \"__\" +", "request: A MemcacheBatchIncrementRequest protocol buffer. response: A MemcacheBatchIncrementResponse protocol buffer.", "update their list of # clients that they connect to", "import os import time from google.appengine.api import apiproxy_stub from google.appengine.api.memcache", "import TYPE_INT from google.appengine.api.memcache import TYPE_LONG class MemcacheService(apiproxy_stub.APIProxyStub): \"\"\"Python only", "num_servers = 0 hits_total = 0 misses_total = 0 byte_hits_total", "all fields here to be ints. # Python 2.5 was", "None: item.set_increment_status(MemcacheIncrementResponse.NOT_CHANGED) else: item.set_increment_status(MemcacheIncrementResponse.OK) item.set_new_value(new_value) def _Dynamic_FlushAll(self, request, response): \"\"\"Implementation", "to get the Memcache key. It is encoded because the", "= self._memcache.get(key) cas_id = 0 if old_entry: _, cas_id, _", "governing permissions and # limitations under the License. # \"\"\"", "import time from google.appengine.api import apiproxy_stub from google.appengine.api.memcache import memcache_service_pb", "response.add_item() item.set_key(key) item.set_value(stored_value) item.set_flags(flags) if request.for_cas(): item.set_cas_id(cas_id) def _Dynamic_Set(self, request,", "None: delete_status = MemcacheDeleteResponse.NOT_FOUND else: self._memcache.delete(key) response.add_delete_status(delete_status) def _Increment(self, namespace,", "makes sure the key is in the dict. \"\"\" if", "if old_entry: _, cas_id, _ = cPickle.loads(old_entry) set_status = MemcacheSetResponse.NOT_STORED", "in that runtime # may not be expecting an int.", "value is None: if not request.has_initial_value(): return None flags, cas_id,", "self._memcache.flush_all() def _Dynamic_Stats(self, request, response): \"\"\"Implementation of MemcacheService::Stats(). Args: request:", "request, response): \"\"\"Implementation of sets for memcache. Args: request: A", "MemcacheSetRequest. response: A MemcacheSetResponse. \"\"\" for item in request.item_list(): key", "\"\"\" if key not in stats_dict: logging.warn(\"No stats for key", "An AppScale file which has a list of IPs running", "% key) return _type(stats_dict.get(key, '0')) for server, server_stats in self._memcache.get_stats():", "= memcache_file.read().split(\"\\n\") memcache_file.close() else: all_ips = ['localhost'] memcaches = [ip", "item.for_cas() and item.has_cas_id()): if old_entry is None: set_status = MemcacheSetResponse.NOT_STORED", "client does not. Args: namespace: The namespace as provided by", "if new_value is None: item.set_increment_status(MemcacheIncrementResponse.NOT_CHANGED) else: item.set_increment_status(MemcacheIncrementResponse.OK) item.set_new_value(new_value) def _Dynamic_FlushAll(self,", "from google.appengine.api import apiproxy_stub from google.appengine.api.memcache import memcache_service_pb from google.appengine.runtime", "used for testing. service_name: Service name expected for all calls.", "= ( TYPE_INT, cas_id, str(request.initial_value())) else: flags, cas_id, stored_value =", "buffer. response: A MemcacheIncrementResponse protocol buffer. \"\"\" new_value = self._Increment(request.name_space(),", "Args: request: A MemcacheFlushRequest. response: A MemcacheFlushResponse. \"\"\" self._memcache.flush_all() def", "def _Dynamic_Stats(self, request, response): \"\"\"Implementation of MemcacheService::Stats(). Args: request: A", "items_total = 0 bytes_total = 0 time_total = 0 def", "get_stats_value(server_stats, 'get_misses') byte_hits_total += get_stats_value(server_stats, 'bytes_read') items_total += get_stats_value(server_stats, 'curr_items')", "item = response.add_item() if new_value is None: item.set_increment_status(MemcacheIncrementResponse.NOT_CHANGED) else: item.set_increment_status(MemcacheIncrementResponse.OK)", "law or agreed to in writing, software # distributed under", "None: set_status = MemcacheSetResponse.NOT_STORED elif cas_id != item.cas_id(): set_status =", "if value is None: if not request.has_initial_value(): return None flags,", "MemcacheGetResponse protocol buffer. \"\"\" for key in set(request.key_list()): internal_key =", "\"r\") all_ips = memcache_file.read().split(\"\\n\") memcache_file.close() else: all_ips = ['localhost'] memcaches", "None: if not request.has_initial_value(): return None flags, cas_id, stored_value =", "Memcache key. It is encoded because the sdk allows special", "== MemcacheSetRequest.REPLACE: self._memcache.replace(key, set_value) else: self._memcache.set(key, set_value, item.expiration_time()) response.add_set_status(set_status) def", "IPs running memcached. APPSCALE_MEMCACHE_FILE = \"/etc/appscale/memcache_ips\" # The minimum frequency", "import TYPE_LONG class MemcacheService(apiproxy_stub.APIProxyStub): \"\"\"Python only memcache service. This service", "all_ips if ip != ''] memcaches.sort() self._memcache = memcache.Client(memcaches, debug=0)", "2.5 was fine with this being a float, so callers", "_Dynamic_Delete(self, request, response): \"\"\"Implementation of delete in memcache. Args: request:", "= MemcacheSetResponse.STORED elif (set_policy == MemcacheSetRequest.CAS and item.for_cas() and item.has_cas_id()):", "# An AppScale file which has a list of IPs", "value is None: continue flags = 0 stored_flags, cas_id, stored_value", "request, response): \"\"\"Implementation of gets for memcache. Args: request: A", "self._gettime = gettime self._memcache = None self.setupMemcacheClient() def setupMemcacheClient(self): \"\"\"", "Args: gettime: time.time()-like function used for testing. service_name: Service name", "= self._memcache.get(key) if value is None: if not request.has_initial_value(): return", "0 time_total = 0 def get_stats_value(stats_dict, key, _type=int): \"\"\" Gets", "server_stats in self._memcache.get_stats(): num_servers += 1 hits_total += get_stats_value(server_stats, 'get_hits')", "class MemcacheService(apiproxy_stub.APIProxyStub): \"\"\"Python only memcache service. This service keeps all", "runtime # may not be expecting an int. stats.set_oldest_item_age(int(time.time() -", "MemcacheSetRequest.SET): set_status = MemcacheSetResponse.STORED elif (set_policy == MemcacheSetRequest.CAS and item.for_cas()", "to interface with memcached. \"\"\" import base64 import cPickle import", "in self._memcache.get_stats(): num_servers += 1 hits_total += get_stats_value(server_stats, 'get_hits') misses_total", "for ip in all_ips if ip != ''] memcaches.sort() self._memcache", "item.set_policy() old_entry = self._memcache.get(key) cas_id = 0 if old_entry: _,", "servers running memcached. \"\"\" # The memcached default port. MEMCACHE_PORT", "A MemcacheGetResponse protocol buffer. \"\"\" for key in set(request.key_list()): internal_key", "cas_id, stored_value = cPickle.loads(value) flags |= stored_flags item = response.add_item()", "may obtain a copy of the License at # #", "_Dynamic_Get(self, request, response): \"\"\"Implementation of gets for memcache. Args: request:", "up the memcache client. \"\"\" if os.path.exists(self.APPSCALE_MEMCACHE_FILE): memcache_file = open(self.APPSCALE_MEMCACHE_FILE,", "(old_entry is None or set_policy == MemcacheSetRequest.SET): set_status = MemcacheSetResponse.STORED", "None flags, cas_id, stored_value = ( TYPE_INT, cas_id, str(request.initial_value())) else:", "of gets for memcache. Args: request: A MemcacheGetRequest protocol buffer.", "is None: set_status = MemcacheSetResponse.NOT_STORED elif cas_id != item.cas_id(): set_status", "None self.setupMemcacheClient() def setupMemcacheClient(self): \"\"\" Sets up the memcache client.", "An integer or long if the offset was successful, None", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "Inc. # # Licensed under the Apache License, Version 2.0", "of batch increment for memcache. Args: request: A MemcacheBatchIncrementRequest protocol", "allows special characters but the Memcache client does not. Args:", "by which memcache clients will update their list of #", "( TYPE_INT, cas_id, str(request.initial_value())) else: flags, cas_id, stored_value = cPickle.loads(value)", "Uses the python-memcached library to interface with memcached. \"\"\" import", "may not use this file except in compliance with the", "else: flags, cas_id, stored_value = cPickle.loads(value) if flags == TYPE_INT:", "memcache_file = open(self.APPSCALE_MEMCACHE_FILE, \"r\") all_ips = memcache_file.read().split(\"\\n\") memcache_file.close() else: all_ips", "MemcacheFlushResponse. \"\"\" self._memcache.flush_all() def _Dynamic_Stats(self, request, response): \"\"\"Implementation of MemcacheService::Stats().", "# With the Python 2.7 GAE runtime, it expects all", "ip in all_ips if ip != ''] memcaches.sort() self._memcache =", "request.delta(): return None cas_id = 0 key = self._GetKey(namespace, request.key())", "= memcache_service_pb.MemcacheSetRequest MemcacheIncrementRequest = memcache_service_pb.MemcacheIncrementRequest MemcacheIncrementResponse = memcache_service_pb.MemcacheIncrementResponse MemcacheDeleteResponse =", "they connect to (which can change if AppScale scales up", "== TYPE_INT: new_value = int(stored_value) elif flags == TYPE_LONG: new_value", "MemcacheSetResponse.STORED if (set_status == MemcacheSetResponse.STORED or set_policy == MemcacheSetRequest.REPLACE): set_value", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "TYPE_LONG: new_value = long(stored_value) if request.direction() == MemcacheIncrementRequest.INCREMENT: new_value +=", "= response.add_item() item.set_key(key) item.set_value(stored_value) item.set_flags(flags) if request.for_cas(): item.set_cas_id(cas_id) def _Dynamic_Set(self,", "from google.appengine.api.memcache import TYPE_LONG class MemcacheService(apiproxy_stub.APIProxyStub): \"\"\"Python only memcache service.", "memcache clients will update their list of # clients that", "this file except in compliance with the License. # You", "external servers running memcached. \"\"\" # The memcached default port.", "memcache_service_pb.MemcacheDeleteResponse from google.appengine.api.memcache import TYPE_INT from google.appengine.api.memcache import TYPE_LONG class", "request: A MemcacheSetRequest. response: A MemcacheSetResponse. \"\"\" for item in", "Non-stub version of the memcache API, keeping all data in", "entry is None: delete_status = MemcacheDeleteResponse.NOT_FOUND else: self._memcache.delete(key) response.add_delete_status(delete_status) def", "namespace: A string containing the namespace for the request, if", "float, so callers in that runtime # may not be", "memcached. APPSCALE_MEMCACHE_FILE = \"/etc/appscale/memcache_ips\" # The minimum frequency by which", "\"\"\" import base64 import cPickle import logging import memcache import", "if new_value is None: raise apiproxy_errors.ApplicationError( memcache_service_pb.MemcacheServiceError.UNSPECIFIED_ERROR) response.set_new_value(new_value) def _Dynamic_BatchIncrement(self,", "memcache. Args: request: A MemcacheSetRequest. response: A MemcacheSetResponse. \"\"\" for", "None on error. \"\"\" if not request.delta(): return None cas_id", "key) return _type(stats_dict.get(key, '0')) for server, server_stats in self._memcache.get_stats(): num_servers", "The memcached default port. MEMCACHE_PORT = \"11211\" # An AppScale", "service keeps all data in any external servers running memcached.", "item = response.add_item() item.set_key(key) item.set_value(stored_value) item.set_flags(flags) if request.for_cas(): item.set_cas_id(cas_id) def", "elif flags == TYPE_LONG: new_value = long(stored_value) if request.direction() ==", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "memcache.Client(memcaches, debug=0) def _Dynamic_Get(self, request, response): \"\"\"Implementation of gets for", "Args: namespace: A string containing the namespace for the request,", "be ints. # Python 2.5 was fine with this being", "protocol buffer. \"\"\" new_value = self._Increment(request.name_space(), request) if new_value is", "# # Licensed under the Apache License, Version 2.0 (the", "down). UPDATE_WINDOW = 60 # seconds def __init__(self, gettime=time.time, service_name='memcache'):", "the request, if any. Pass an empty string if there", "file except in compliance with the License. # You may", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "has a list of IPs running memcached. APPSCALE_MEMCACHE_FILE = \"/etc/appscale/memcache_ips\"", "cas_id = 0 if old_entry: _, cas_id, _ = cPickle.loads(old_entry)", "long if the offset was successful, None on error. \"\"\"", "= 0 key = self._GetKey(namespace, request.key()) value = self._memcache.get(key) if", "= long(stored_value) if request.direction() == MemcacheIncrementRequest.INCREMENT: new_value += request.delta() elif", "and item.has_cas_id()): if old_entry is None: set_status = MemcacheSetResponse.NOT_STORED elif", "item.set_key(key) item.set_value(stored_value) item.set_flags(flags) if request.for_cas(): item.set_cas_id(cas_id) def _Dynamic_Set(self, request, response):", "in stats_dict: logging.warn(\"No stats for key '%s'.\" % key) return", "item.cas_id(): set_status = MemcacheSetResponse.EXISTS else: set_status = MemcacheSetResponse.STORED if (set_status", "'bytes') time_total += get_stats_value(server_stats, 'time', float) stats.set_hits(hits_total) stats.set_misses(misses_total) stats.set_byte_hits(byte_hits_total) stats.set_items(items_total)", "key, _type=int): \"\"\" Gets statisical values and makes sure the", "self._memcache.replace(key, set_value) else: self._memcache.set(key, set_value, item.expiration_time()) response.add_set_status(set_status) def _Dynamic_Delete(self, request,", "no namespace. request: A MemcacheIncrementRequest instance. Returns: An integer or", "import apiproxy_errors MemcacheSetResponse = memcache_service_pb.MemcacheSetResponse MemcacheSetRequest = memcache_service_pb.MemcacheSetRequest MemcacheIncrementRequest =", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "buffer. \"\"\" for item in request.item_list(): key = self._GetKey(request.name_space(), item.key())", "= 0 stored_flags, cas_id, stored_value = cPickle.loads(value) flags |= stored_flags", "for item in request.item_list(): key = self._GetKey(request.name_space(), item.key()) entry =", "A MemcacheStatsResponse. \"\"\" stats = response.mutable_stats() num_servers = 0 hits_total", "memcaches.sort() self._memcache = memcache.Client(memcaches, debug=0) def _Dynamic_Get(self, request, response): \"\"\"Implementation", "flags = 0 stored_flags, cas_id, stored_value = cPickle.loads(value) flags |=", "logging.warn(\"No stats for key '%s'.\" % key) return _type(stats_dict.get(key, '0'))", "delete in memcache. Args: request: A MemcacheDeleteRequest protocol buffer. response:", "\"\"\" new_value = self._Increment(request.name_space(), request) if new_value is None: raise", "memcache_service_pb.MemcacheServiceError.UNSPECIFIED_ERROR) response.set_new_value(new_value) def _Dynamic_BatchIncrement(self, request, response): \"\"\"Implementation of batch increment", "2.7 GAE runtime, it expects all fields here to be", "def _Dynamic_Set(self, request, response): \"\"\"Implementation of sets for memcache. Args:", "else: set_status = MemcacheSetResponse.STORED if (set_status == MemcacheSetResponse.STORED or set_policy", "key in set(request.key_list()): internal_key = self._GetKey(request.name_space(), key) value = self._memcache.get(internal_key)", "flags, cas_id, stored_value = cPickle.loads(value) if flags == TYPE_INT: new_value", "1, str(new_value)]) try: self._memcache.cas(key, new_stored_value) except Exception, e: logging.error(str(e)) return", "response): \"\"\"Implementation of increment for memcache. Args: request: A MemcacheIncrementRequest", "'%s'.\" % key) return _type(stats_dict.get(key, '0')) for server, server_stats in", "-= request.delta() new_stored_value = cPickle.dumps([flags, cas_id + 1, str(new_value)]) try:", "is not None)): if (old_entry is None or set_policy ==", "\"\"\"Python only memcache service. This service keeps all data in", "batch increment for memcache. Args: request: A MemcacheBatchIncrementRequest protocol buffer.", "new_stored_value = cPickle.dumps([flags, cas_id + 1, str(new_value)]) try: self._memcache.cas(key, new_stored_value)", "memcache service. This service keeps all data in any external", "if request.for_cas(): item.set_cas_id(cas_id) def _Dynamic_Set(self, request, response): \"\"\"Implementation of sets", "os.path.exists(self.APPSCALE_MEMCACHE_FILE): memcache_file = open(self.APPSCALE_MEMCACHE_FILE, \"r\") all_ips = memcache_file.read().split(\"\\n\") memcache_file.close() else:", "key not in stats_dict: logging.warn(\"No stats for key '%s'.\" %", "provided by the application. key: The key as provided by", "MemcacheSetResponse.STORED or set_policy == MemcacheSetRequest.REPLACE): set_value = cPickle.dumps( [item.flags(), cas_id", "return None flags, cas_id, stored_value = ( TYPE_INT, cas_id, str(request.initial_value()))", "error. \"\"\" if not request.delta(): return None cas_id = 0", "set_value, item.expiration_time()) response.add_set_status(set_status) def _Dynamic_Delete(self, request, response): \"\"\"Implementation of delete", "for key in set(request.key_list()): internal_key = self._GetKey(request.name_space(), key) value =", "memcache. Args: request: A MemcacheBatchIncrementRequest protocol buffer. response: A MemcacheBatchIncrementResponse", "0 misses_total = 0 byte_hits_total = 0 items_total = 0", "= 0 def get_stats_value(stats_dict, key, _type=int): \"\"\" Gets statisical values", "['localhost'] memcaches = [ip + \":\" + self.MEMCACHE_PORT for ip", "ip != ''] memcaches.sort() self._memcache = memcache.Client(memcaches, debug=0) def _Dynamic_Get(self,", "new_value = self._Increment(namespace, request_item) item = response.add_item() if new_value is", "= ['localhost'] memcaches = [ip + \":\" + self.MEMCACHE_PORT for", "= self._GetKey(request.name_space(), item.key()) set_policy = item.set_policy() old_entry = self._memcache.get(key) cas_id", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "== MemcacheSetRequest.CAS and item.for_cas() and item.has_cas_id()): if old_entry is None:", "A MemcacheStatsRequest. response: A MemcacheStatsResponse. \"\"\" stats = response.mutable_stats() num_servers", "the key is in the dict. \"\"\" if key not", "_type=int): \"\"\" Gets statisical values and makes sure the key", "return None cas_id = 0 key = self._GetKey(namespace, request.key()) value", "will update their list of # clients that they connect", "fields here to be ints. # Python 2.5 was fine", "Args: request: A MemcacheGetRequest protocol buffer. response: A MemcacheGetResponse protocol", "A base64 string __{appname}__{namespace}__{key} \"\"\" appname = os.environ['APPNAME'] internal_key =", "self._GetKey(request.name_space(), item.key()) entry = self._memcache.get(key) delete_status = MemcacheDeleteResponse.DELETED if entry", "key = self._GetKey(request.name_space(), item.key()) set_policy = item.set_policy() old_entry = self._memcache.get(key)", "flags, cas_id, stored_value = ( TYPE_INT, cas_id, str(request.initial_value())) else: flags,", "buffer. response: A MemcacheGetResponse protocol buffer. \"\"\" for key in", "google.appengine.api import apiproxy_stub from google.appengine.api.memcache import memcache_service_pb from google.appengine.runtime import", "or implied. # See the License for the specific language", "== MemcacheSetRequest.REPLACE): set_value = cPickle.dumps( [item.flags(), cas_id + 1, item.value()])", "MemcacheSetResponse.EXISTS else: set_status = MemcacheSetResponse.STORED if (set_status == MemcacheSetResponse.STORED or", "version of the memcache API, keeping all data in memcached.", "\"\"\"Implementation of increment for memcache. Args: request: A MemcacheIncrementRequest protocol", "as provided by the application. Returns: A base64 string __{appname}__{namespace}__{key}", "set_status = MemcacheSetResponse.STORED elif (set_policy == MemcacheSetRequest.CAS and item.for_cas() and", "a float, so callers in that runtime # may not", "provided by the application. Returns: A base64 string __{appname}__{namespace}__{key} \"\"\"", "KIND, either express or implied. # See the License for", "specific language governing permissions and # limitations under the License.", "protocol buffer. response: A MemcacheGetResponse protocol buffer. \"\"\" for key", "scales up or # down). UPDATE_WINDOW = 60 # seconds", "0 stored_flags, cas_id, stored_value = cPickle.loads(value) flags |= stored_flags item", "\"\"\"Implementation of gets for memcache. Args: request: A MemcacheGetRequest protocol", "stored_flags item = response.add_item() item.set_key(key) item.set_value(stored_value) item.set_flags(flags) if request.for_cas(): item.set_cas_id(cas_id)", "The namespace as provided by the application. key: The key", "None: raise apiproxy_errors.ApplicationError( memcache_service_pb.MemcacheServiceError.UNSPECIFIED_ERROR) response.set_new_value(new_value) def _Dynamic_BatchIncrement(self, request, response): \"\"\"Implementation", "Pass an empty string if there is no namespace. request:", "memcached. Uses the python-memcached library to interface with memcached. \"\"\"", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "set_value = cPickle.dumps( [item.flags(), cas_id + 1, item.value()]) if set_policy", "set_value) else: self._memcache.set(key, set_value, item.expiration_time()) response.add_set_status(set_status) def _Dynamic_Delete(self, request, response):", "stored_flags, cas_id, stored_value = cPickle.loads(value) flags |= stored_flags item =", "string containing the namespace for the request, if any. Pass", "= cPickle.dumps( [item.flags(), cas_id + 1, item.value()]) if set_policy ==", "+= request.delta() elif request.direction() == MemcacheIncrementRequest.DECREMENT: new_value -= request.delta() new_stored_value", "+= get_stats_value(server_stats, 'curr_items') bytes_total += get_stats_value(server_stats, 'bytes') time_total += get_stats_value(server_stats,", "int. stats.set_oldest_item_age(int(time.time() - time_total / num_servers)) def _GetKey(self, namespace, key):", "def __init__(self, gettime=time.time, service_name='memcache'): \"\"\"Initializer. Args: gettime: time.time()-like function used", "Google Inc. # # Licensed under the Apache License, Version", "running memcached. \"\"\" # The memcached default port. MEMCACHE_PORT =", "= int(stored_value) elif flags == TYPE_LONG: new_value = long(stored_value) if", "# limitations under the License. # \"\"\" Non-stub version of", "= self._Increment(request.name_space(), request) if new_value is None: raise apiproxy_errors.ApplicationError( memcache_service_pb.MemcacheServiceError.UNSPECIFIED_ERROR)", "def _Dynamic_Increment(self, request, response): \"\"\"Implementation of increment for memcache. Args:", "the License. # \"\"\" Non-stub version of the memcache API,", "request.for_cas(): item.set_cas_id(cas_id) def _Dynamic_Set(self, request, response): \"\"\"Implementation of sets for", "(the \"License\"); # you may not use this file except", "= MemcacheDeleteResponse.NOT_FOUND else: self._memcache.delete(key) response.add_delete_status(delete_status) def _Increment(self, namespace, request): \"\"\"Internal", "= memcache_service_pb.MemcacheIncrementRequest MemcacheIncrementResponse = memcache_service_pb.MemcacheIncrementResponse MemcacheDeleteResponse = memcache_service_pb.MemcacheDeleteResponse from google.appengine.api.memcache", "memcache import os import time from google.appengine.api import apiproxy_stub from", "clients will update their list of # clients that they", "# you may not use this file except in compliance", "the Python 2.7 GAE runtime, it expects all fields here", "the application. Returns: A base64 string __{appname}__{namespace}__{key} \"\"\" appname =", "all data in any external servers running memcached. \"\"\" #", "request: A MemcacheIncrementRequest instance. Returns: An integer or long if", "MemcacheBatchIncrementResponse protocol buffer. \"\"\" namespace = request.name_space() for request_item in", "self._memcache = None self.setupMemcacheClient() def setupMemcacheClient(self): \"\"\" Sets up the", "new_value is None: raise apiproxy_errors.ApplicationError( memcache_service_pb.MemcacheServiceError.UNSPECIFIED_ERROR) response.set_new_value(new_value) def _Dynamic_BatchIncrement(self, request,", "calls. \"\"\" super(MemcacheService, self).__init__(service_name) self._gettime = gettime self._memcache = None", "because the sdk allows special characters but the Memcache client", "is encoded because the sdk allows special characters but the", "cas_id + 1, item.value()]) if set_policy == MemcacheSetRequest.REPLACE: self._memcache.replace(key, set_value)", "\"\"\" for item in request.item_list(): key = self._GetKey(request.name_space(), item.key()) entry", "item.has_cas_id()): if old_entry is None: set_status = MemcacheSetResponse.NOT_STORED elif cas_id", "+= get_stats_value(server_stats, 'bytes_read') items_total += get_stats_value(server_stats, 'curr_items') bytes_total += get_stats_value(server_stats,", "response): \"\"\"Implementation of MemcacheService::Stats(). Args: request: A MemcacheStatsRequest. response: A", "old_entry is None) or (set_policy == MemcacheSetRequest.REPLACE and old_entry is", "item.key()) entry = self._memcache.get(key) delete_status = MemcacheDeleteResponse.DELETED if entry is", "stats.set_items(items_total) stats.set_bytes(bytes_total) # With the Python 2.7 GAE runtime, it", "key '%s'.\" % key) return _type(stats_dict.get(key, '0')) for server, server_stats", "MemcacheSetRequest.CAS and item.for_cas() and item.has_cas_id()): if old_entry is None: set_status", "None cas_id = 0 key = self._GetKey(namespace, request.key()) value =", "# # Unless required by applicable law or agreed to", "cPickle.loads(value) if flags == TYPE_INT: new_value = int(stored_value) elif flags", "here to be ints. # Python 2.5 was fine with", "key = self._GetKey(request.name_space(), item.key()) entry = self._memcache.get(key) delete_status = MemcacheDeleteResponse.DELETED", "MemcacheIncrementRequest.INCREMENT: new_value += request.delta() elif request.direction() == MemcacheIncrementRequest.DECREMENT: new_value -=", "misses_total += get_stats_value(server_stats, 'get_misses') byte_hits_total += get_stats_value(server_stats, 'bytes_read') items_total +=", "request): \"\"\"Internal function for incrementing from a MemcacheIncrementRequest. Args: namespace:", "special characters but the Memcache client does not. Args: namespace:", "# seconds def __init__(self, gettime=time.time, service_name='memcache'): \"\"\"Initializer. Args: gettime: time.time()-like", "delete_status = MemcacheDeleteResponse.DELETED if entry is None: delete_status = MemcacheDeleteResponse.NOT_FOUND", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "_Dynamic_Set(self, request, response): \"\"\"Implementation of sets for memcache. Args: request:", "Version 2.0 (the \"License\"); # you may not use this", "is None: continue flags = 0 stored_flags, cas_id, stored_value =", "for memcache. Args: request: A MemcacheSetRequest. response: A MemcacheSetResponse. \"\"\"", "set_status = MemcacheSetResponse.STORED if (set_status == MemcacheSetResponse.STORED or set_policy ==", "MemcacheDeleteResponse.DELETED if entry is None: delete_status = MemcacheDeleteResponse.NOT_FOUND else: self._memcache.delete(key)", "MemcacheIncrementRequest. Args: namespace: A string containing the namespace for the", "protocol buffer. \"\"\" namespace = request.name_space() for request_item in request.item_list():", "request_item) item = response.add_item() if new_value is None: item.set_increment_status(MemcacheIncrementResponse.NOT_CHANGED) else:", "stored_value = ( TYPE_INT, cas_id, str(request.initial_value())) else: flags, cas_id, stored_value", "memcache API, keeping all data in memcached. Uses the python-memcached", "\"\"\"Used to get the Memcache key. It is encoded because", "self._memcache.get(key) cas_id = 0 if old_entry: _, cas_id, _ =", "(set_policy == MemcacheSetRequest.CAS and item.for_cas() and item.has_cas_id()): if old_entry is", "# The minimum frequency by which memcache clients will update", "A string containing the namespace for the request, if any.", "a MemcacheIncrementRequest. Args: namespace: A string containing the namespace for", "except Exception, e: logging.error(str(e)) return None return new_value def _Dynamic_Increment(self,", "minimum frequency by which memcache clients will update their list", "response.add_item() if new_value is None: item.set_increment_status(MemcacheIncrementResponse.NOT_CHANGED) else: item.set_increment_status(MemcacheIncrementResponse.OK) item.set_new_value(new_value) def", "= MemcacheSetResponse.EXISTS else: set_status = MemcacheSetResponse.STORED if (set_status == MemcacheSetResponse.STORED", "stats.set_misses(misses_total) stats.set_byte_hits(byte_hits_total) stats.set_items(items_total) stats.set_bytes(bytes_total) # With the Python 2.7 GAE", "Service name expected for all calls. \"\"\" super(MemcacheService, self).__init__(service_name) self._gettime", "self._memcache = memcache.Client(memcaches, debug=0) def _Dynamic_Get(self, request, response): \"\"\"Implementation of", "request) if new_value is None: raise apiproxy_errors.ApplicationError( memcache_service_pb.MemcacheServiceError.UNSPECIFIED_ERROR) response.set_new_value(new_value) def", "response): \"\"\"Implementation of batch increment for memcache. Args: request: A", "= MemcacheDeleteResponse.DELETED if entry is None: delete_status = MemcacheDeleteResponse.NOT_FOUND else:", "stats_dict: logging.warn(\"No stats for key '%s'.\" % key) return _type(stats_dict.get(key,", "MemcacheSetRequest = memcache_service_pb.MemcacheSetRequest MemcacheIncrementRequest = memcache_service_pb.MemcacheIncrementRequest MemcacheIncrementResponse = memcache_service_pb.MemcacheIncrementResponse MemcacheDeleteResponse", "or long if the offset was successful, None on error.", "flags |= stored_flags item = response.add_item() item.set_key(key) item.set_value(stored_value) item.set_flags(flags) if", "response.set_new_value(new_value) def _Dynamic_BatchIncrement(self, request, response): \"\"\"Implementation of batch increment for", "\"\"\" Gets statisical values and makes sure the key is", "\"\"\"Implementation of MemcacheService::Stats(). Args: request: A MemcacheStatsRequest. response: A MemcacheStatsResponse.", "request, if any. Pass an empty string if there is", "implied. # See the License for the specific language governing", "or (set_policy == MemcacheSetRequest.REPLACE and old_entry is not None)): if", "if ip != ''] memcaches.sort() self._memcache = memcache.Client(memcaches, debug=0) def", "google.appengine.api.memcache import memcache_service_pb from google.appengine.runtime import apiproxy_errors MemcacheSetResponse = memcache_service_pb.MemcacheSetResponse", "Args: request: A MemcacheDeleteRequest protocol buffer. response: A MemcacheDeleteResponse protocol", "under the Apache License, Version 2.0 (the \"License\"); # you", "0 if old_entry: _, cas_id, _ = cPickle.loads(old_entry) set_status =", "[item.flags(), cas_id + 1, item.value()]) if set_policy == MemcacheSetRequest.REPLACE: self._memcache.replace(key,", "increment for memcache. Args: request: A MemcacheBatchIncrementRequest protocol buffer. response:", "key as provided by the application. Returns: A base64 string", "base64 import cPickle import logging import memcache import os import", "request: A MemcacheIncrementRequest protocol buffer. response: A MemcacheIncrementResponse protocol buffer.", "in request.item_list(): new_value = self._Increment(namespace, request_item) item = response.add_item() if", "!= ''] memcaches.sort() self._memcache = memcache.Client(memcaches, debug=0) def _Dynamic_Get(self, request,", "item.value()]) if set_policy == MemcacheSetRequest.REPLACE: self._memcache.replace(key, set_value) else: self._memcache.set(key, set_value,", "internal_key = appname + \"__\" + namespace + \"__\" +", "import memcache import os import time from google.appengine.api import apiproxy_stub", "+ 1, str(new_value)]) try: self._memcache.cas(key, new_stored_value) except Exception, e: logging.error(str(e))", "by applicable law or agreed to in writing, software #", "else: self._memcache.delete(key) response.add_delete_status(delete_status) def _Increment(self, namespace, request): \"\"\"Internal function for", "response): \"\"\"Implementation of MemcacheService::FlushAll(). Args: request: A MemcacheFlushRequest. response: A", "the memcache client. \"\"\" if os.path.exists(self.APPSCALE_MEMCACHE_FILE): memcache_file = open(self.APPSCALE_MEMCACHE_FILE, \"r\")", "_GetKey(self, namespace, key): \"\"\"Used to get the Memcache key. It", "if value is None: continue flags = 0 stored_flags, cas_id,", "== TYPE_LONG: new_value = long(stored_value) if request.direction() == MemcacheIncrementRequest.INCREMENT: new_value", "all_ips = memcache_file.read().split(\"\\n\") memcache_file.close() else: all_ips = ['localhost'] memcaches =", "up or # down). UPDATE_WINDOW = 60 # seconds def", "the application. key: The key as provided by the application.", "item.set_increment_status(MemcacheIncrementResponse.NOT_CHANGED) else: item.set_increment_status(MemcacheIncrementResponse.OK) item.set_new_value(new_value) def _Dynamic_FlushAll(self, request, response): \"\"\"Implementation of", "= memcache_service_pb.MemcacheDeleteResponse from google.appengine.api.memcache import TYPE_INT from google.appengine.api.memcache import TYPE_LONG", "get_stats_value(server_stats, 'curr_items') bytes_total += get_stats_value(server_stats, 'bytes') time_total += get_stats_value(server_stats, 'time',", "an empty string if there is no namespace. request: A", "cPickle.loads(value) flags |= stored_flags item = response.add_item() item.set_key(key) item.set_value(stored_value) item.set_flags(flags)", "namespace. request: A MemcacheIncrementRequest instance. Returns: An integer or long", "expecting an int. stats.set_oldest_item_age(int(time.time() - time_total / num_servers)) def _GetKey(self,", "sdk allows special characters but the Memcache client does not.", "was successful, None on error. \"\"\" if not request.delta(): return", "apiproxy_errors.ApplicationError( memcache_service_pb.MemcacheServiceError.UNSPECIFIED_ERROR) response.set_new_value(new_value) def _Dynamic_BatchIncrement(self, request, response): \"\"\"Implementation of batch", "key) value = self._memcache.get(internal_key) if value is None: continue flags", "_Dynamic_Increment(self, request, response): \"\"\"Implementation of increment for memcache. Args: request:", "\"\"\" Sets up the memcache client. \"\"\" if os.path.exists(self.APPSCALE_MEMCACHE_FILE): memcache_file", "permissions and # limitations under the License. # \"\"\" Non-stub", "cPickle import logging import memcache import os import time from", "for testing. service_name: Service name expected for all calls. \"\"\"", "if (set_status == MemcacheSetResponse.STORED or set_policy == MemcacheSetRequest.REPLACE): set_value =", "request.has_initial_value(): return None flags, cas_id, stored_value = ( TYPE_INT, cas_id,", "from google.appengine.api.memcache import memcache_service_pb from google.appengine.runtime import apiproxy_errors MemcacheSetResponse =", "integer or long if the offset was successful, None on", "setupMemcacheClient(self): \"\"\" Sets up the memcache client. \"\"\" if os.path.exists(self.APPSCALE_MEMCACHE_FILE):", "MemcacheService::Stats(). Args: request: A MemcacheStatsRequest. response: A MemcacheStatsResponse. \"\"\" stats", "item.set_cas_id(cas_id) def _Dynamic_Set(self, request, response): \"\"\"Implementation of sets for memcache.", "google.appengine.api.memcache import TYPE_LONG class MemcacheService(apiproxy_stub.APIProxyStub): \"\"\"Python only memcache service. This", "change if AppScale scales up or # down). UPDATE_WINDOW =", "protocol buffer. response: A MemcacheIncrementResponse protocol buffer. \"\"\" new_value =", "for memcache. Args: request: A MemcacheIncrementRequest protocol buffer. response: A", "memcaches = [ip + \":\" + self.MEMCACHE_PORT for ip in", "value = self._memcache.get(internal_key) if value is None: continue flags =", "# down). UPDATE_WINDOW = 60 # seconds def __init__(self, gettime=time.time,", "the python-memcached library to interface with memcached. \"\"\" import base64", "not request.has_initial_value(): return None flags, cas_id, stored_value = ( TYPE_INT,", "'curr_items') bytes_total += get_stats_value(server_stats, 'bytes') time_total += get_stats_value(server_stats, 'time', float)", "not None)): if (old_entry is None or set_policy == MemcacheSetRequest.SET):", "namespace, key): \"\"\"Used to get the Memcache key. It is", "or set_policy == MemcacheSetRequest.SET): set_status = MemcacheSetResponse.STORED elif (set_policy ==", "response: A MemcacheStatsResponse. \"\"\" stats = response.mutable_stats() num_servers = 0", "service. This service keeps all data in any external servers", "for item in request.item_list(): key = self._GetKey(request.name_space(), item.key()) set_policy =", "encoded because the sdk allows special characters but the Memcache", "cPickle.loads(old_entry) set_status = MemcacheSetResponse.NOT_STORED if ((set_policy == MemcacheSetRequest.SET) or (set_policy", "byte_hits_total = 0 items_total = 0 bytes_total = 0 time_total", "item.set_value(stored_value) item.set_flags(flags) if request.for_cas(): item.set_cas_id(cas_id) def _Dynamic_Set(self, request, response): \"\"\"Implementation", "the namespace for the request, if any. Pass an empty", "an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "and old_entry is not None)): if (old_entry is None or", "item in request.item_list(): key = self._GetKey(request.name_space(), item.key()) entry = self._memcache.get(key)", "and makes sure the key is in the dict. \"\"\"", "super(MemcacheService, self).__init__(service_name) self._gettime = gettime self._memcache = None self.setupMemcacheClient() def", "Unless required by applicable law or agreed to in writing,", "MemcacheSetRequest.REPLACE: self._memcache.replace(key, set_value) else: self._memcache.set(key, set_value, item.expiration_time()) response.add_set_status(set_status) def _Dynamic_Delete(self,", "an int. stats.set_oldest_item_age(int(time.time() - time_total / num_servers)) def _GetKey(self, namespace,", "new_stored_value) except Exception, e: logging.error(str(e)) return None return new_value def", "\"/etc/appscale/memcache_ips\" # The minimum frequency by which memcache clients will", "get_stats_value(server_stats, 'get_hits') misses_total += get_stats_value(server_stats, 'get_misses') byte_hits_total += get_stats_value(server_stats, 'bytes_read')", "continue flags = 0 stored_flags, cas_id, stored_value = cPickle.loads(value) flags", "|= stored_flags item = response.add_item() item.set_key(key) item.set_value(stored_value) item.set_flags(flags) if request.for_cas():", "in the dict. \"\"\" if key not in stats_dict: logging.warn(\"No", "A MemcacheFlushRequest. response: A MemcacheFlushResponse. \"\"\" self._memcache.flush_all() def _Dynamic_Stats(self, request,", "flags == TYPE_LONG: new_value = long(stored_value) if request.direction() == MemcacheIncrementRequest.INCREMENT:", "request, response): \"\"\"Implementation of MemcacheService::FlushAll(). Args: request: A MemcacheFlushRequest. response:", "in memcache. Args: request: A MemcacheDeleteRequest protocol buffer. response: A", "the specific language governing permissions and # limitations under the", "int(stored_value) elif flags == TYPE_LONG: new_value = long(stored_value) if request.direction()", "request, response): \"\"\"Implementation of batch increment for memcache. Args: request:", "Returns: A base64 string __{appname}__{namespace}__{key} \"\"\" appname = os.environ['APPNAME'] internal_key", "os.environ['APPNAME'] internal_key = appname + \"__\" + namespace + \"__\"", "be expecting an int. stats.set_oldest_item_age(int(time.time() - time_total / num_servers)) def", "applicable law or agreed to in writing, software # distributed", "keeps all data in any external servers running memcached. \"\"\"", "of delete in memcache. Args: request: A MemcacheDeleteRequest protocol buffer.", "of the memcache API, keeping all data in memcached. Uses", "'get_misses') byte_hits_total += get_stats_value(server_stats, 'bytes_read') items_total += get_stats_value(server_stats, 'curr_items') bytes_total", "= cPickle.loads(value) if flags == TYPE_INT: new_value = int(stored_value) elif", "debug=0) def _Dynamic_Get(self, request, response): \"\"\"Implementation of gets for memcache.", "set_status = MemcacheSetResponse.NOT_STORED if ((set_policy == MemcacheSetRequest.SET) or (set_policy ==", "the dict. \"\"\" if key not in stats_dict: logging.warn(\"No stats", "item.set_new_value(new_value) def _Dynamic_FlushAll(self, request, response): \"\"\"Implementation of MemcacheService::FlushAll(). Args: request:", "elif request.direction() == MemcacheIncrementRequest.DECREMENT: new_value -= request.delta() new_stored_value = cPickle.dumps([flags,", "base64 string __{appname}__{namespace}__{key} \"\"\" appname = os.environ['APPNAME'] internal_key = appname", "in writing, software # distributed under the License is distributed", "file which has a list of IPs running memcached. APPSCALE_MEMCACHE_FILE", "(set_status == MemcacheSetResponse.STORED or set_policy == MemcacheSetRequest.REPLACE): set_value = cPickle.dumps(", "\"\"\" stats = response.mutable_stats() num_servers = 0 hits_total = 0", "set_policy = item.set_policy() old_entry = self._memcache.get(key) cas_id = 0 if", "request.name_space() for request_item in request.item_list(): new_value = self._Increment(namespace, request_item) item", "_type(stats_dict.get(key, '0')) for server, server_stats in self._memcache.get_stats(): num_servers += 1", "python-memcached library to interface with memcached. \"\"\" import base64 import", "\"\"\" Non-stub version of the memcache API, keeping all data", "== MemcacheIncrementRequest.INCREMENT: new_value += request.delta() elif request.direction() == MemcacheIncrementRequest.DECREMENT: new_value", "or (set_policy == MemcacheSetRequest.ADD and old_entry is None) or (set_policy", "fine with this being a float, so callers in that", "request: A MemcacheDeleteRequest protocol buffer. response: A MemcacheDeleteResponse protocol buffer.", "A MemcacheGetRequest protocol buffer. response: A MemcacheGetResponse protocol buffer. \"\"\"", "response): \"\"\"Implementation of delete in memcache. Args: request: A MemcacheDeleteRequest", "Python 2.7 GAE runtime, it expects all fields here to", "stats = response.mutable_stats() num_servers = 0 hits_total = 0 misses_total", "incrementing from a MemcacheIncrementRequest. Args: namespace: A string containing the", "if ((set_policy == MemcacheSetRequest.SET) or (set_policy == MemcacheSetRequest.ADD and old_entry", "open(self.APPSCALE_MEMCACHE_FILE, \"r\") all_ips = memcache_file.read().split(\"\\n\") memcache_file.close() else: all_ips = ['localhost']", "str(request.initial_value())) else: flags, cas_id, stored_value = cPickle.loads(value) if flags ==", "= cPickle.dumps([flags, cas_id + 1, str(new_value)]) try: self._memcache.cas(key, new_stored_value) except", "MemcacheFlushRequest. response: A MemcacheFlushResponse. \"\"\" self._memcache.flush_all() def _Dynamic_Stats(self, request, response):", "python # # Copyright 2007 Google Inc. # # Licensed", "with this being a float, so callers in that runtime", "\"\"\"Initializer. Args: gettime: time.time()-like function used for testing. service_name: Service", "None) or (set_policy == MemcacheSetRequest.REPLACE and old_entry is not None)):", "get_stats_value(server_stats, 'bytes') time_total += get_stats_value(server_stats, 'time', float) stats.set_hits(hits_total) stats.set_misses(misses_total) stats.set_byte_hits(byte_hits_total)", "is None: raise apiproxy_errors.ApplicationError( memcache_service_pb.MemcacheServiceError.UNSPECIFIED_ERROR) response.set_new_value(new_value) def _Dynamic_BatchIncrement(self, request, response):", "= open(self.APPSCALE_MEMCACHE_FILE, \"r\") all_ips = memcache_file.read().split(\"\\n\") memcache_file.close() else: all_ips =", "self._memcache.delete(key) response.add_delete_status(delete_status) def _Increment(self, namespace, request): \"\"\"Internal function for incrementing", "for request_item in request.item_list(): new_value = self._Increment(namespace, request_item) item =", "License is distributed on an \"AS IS\" BASIS, # WITHOUT", "not request.delta(): return None cas_id = 0 key = self._GetKey(namespace,", "cas_id, str(request.initial_value())) else: flags, cas_id, stored_value = cPickle.loads(value) if flags", "of MemcacheService::Stats(). Args: request: A MemcacheStatsRequest. response: A MemcacheStatsResponse. \"\"\"", "MemcacheStatsRequest. response: A MemcacheStatsResponse. \"\"\" stats = response.mutable_stats() num_servers =", "License, Version 2.0 (the \"License\"); # you may not use", "namespace = request.name_space() for request_item in request.item_list(): new_value = self._Increment(namespace,", "self).__init__(service_name) self._gettime = gettime self._memcache = None self.setupMemcacheClient() def setupMemcacheClient(self):", "memcache_service_pb.MemcacheSetResponse MemcacheSetRequest = memcache_service_pb.MemcacheSetRequest MemcacheIncrementRequest = memcache_service_pb.MemcacheIncrementRequest MemcacheIncrementResponse = memcache_service_pb.MemcacheIncrementResponse", "self._memcache.get(key) delete_status = MemcacheDeleteResponse.DELETED if entry is None: delete_status =", "new_value += request.delta() elif request.direction() == MemcacheIncrementRequest.DECREMENT: new_value -= request.delta()", "# You may obtain a copy of the License at", "keeping all data in memcached. Uses the python-memcached library to", "_Dynamic_FlushAll(self, request, response): \"\"\"Implementation of MemcacheService::FlushAll(). Args: request: A MemcacheFlushRequest.", "item.set_increment_status(MemcacheIncrementResponse.OK) item.set_new_value(new_value) def _Dynamic_FlushAll(self, request, response): \"\"\"Implementation of MemcacheService::FlushAll(). Args:", "60 # seconds def __init__(self, gettime=time.time, service_name='memcache'): \"\"\"Initializer. Args: gettime:", "MemcacheSetResponse. \"\"\" for item in request.item_list(): key = self._GetKey(request.name_space(), item.key())", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "def _Increment(self, namespace, request): \"\"\"Internal function for incrementing from a", "if set_policy == MemcacheSetRequest.REPLACE: self._memcache.replace(key, set_value) else: self._memcache.set(key, set_value, item.expiration_time())", "limitations under the License. # \"\"\" Non-stub version of the", "stats.set_bytes(bytes_total) # With the Python 2.7 GAE runtime, it expects", "can change if AppScale scales up or # down). UPDATE_WINDOW", "\"\"\" for key in set(request.key_list()): internal_key = self._GetKey(request.name_space(), key) value", "request.direction() == MemcacheIncrementRequest.DECREMENT: new_value -= request.delta() new_stored_value = cPickle.dumps([flags, cas_id", "MemcacheSetResponse.NOT_STORED elif cas_id != item.cas_id(): set_status = MemcacheSetResponse.EXISTS else: set_status", "of IPs running memcached. APPSCALE_MEMCACHE_FILE = \"/etc/appscale/memcache_ips\" # The minimum", "else: all_ips = ['localhost'] memcaches = [ip + \":\" +", "the memcache API, keeping all data in memcached. Uses the", "for incrementing from a MemcacheIncrementRequest. Args: namespace: A string containing", "+= 1 hits_total += get_stats_value(server_stats, 'get_hits') misses_total += get_stats_value(server_stats, 'get_misses')", "memcached. \"\"\" import base64 import cPickle import logging import memcache", "expects all fields here to be ints. # Python 2.5", "apiproxy_stub from google.appengine.api.memcache import memcache_service_pb from google.appengine.runtime import apiproxy_errors MemcacheSetResponse", "the License for the specific language governing permissions and #", "is None or set_policy == MemcacheSetRequest.SET): set_status = MemcacheSetResponse.STORED elif", "of MemcacheService::FlushAll(). Args: request: A MemcacheFlushRequest. response: A MemcacheFlushResponse. \"\"\"", "Gets statisical values and makes sure the key is in", "Apache License, Version 2.0 (the \"License\"); # you may not", "service_name: Service name expected for all calls. \"\"\" super(MemcacheService, self).__init__(service_name)", "MemcacheSetRequest.REPLACE): set_value = cPickle.dumps( [item.flags(), cas_id + 1, item.value()]) if", "def _Dynamic_BatchIncrement(self, request, response): \"\"\"Implementation of batch increment for memcache.", "to be ints. # Python 2.5 was fine with this", "either express or implied. # See the License for the", "is None) or (set_policy == MemcacheSetRequest.REPLACE and old_entry is not", "in request.item_list(): key = self._GetKey(request.name_space(), item.key()) entry = self._memcache.get(key) delete_status", "so callers in that runtime # may not be expecting", "items_total += get_stats_value(server_stats, 'curr_items') bytes_total += get_stats_value(server_stats, 'bytes') time_total +=", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "time.time()-like function used for testing. service_name: Service name expected for", "= self._Increment(namespace, request_item) item = response.add_item() if new_value is None:", "self.MEMCACHE_PORT for ip in all_ips if ip != ''] memcaches.sort()", "= self._GetKey(request.name_space(), item.key()) entry = self._memcache.get(key) delete_status = MemcacheDeleteResponse.DELETED if", "+ \":\" + self.MEMCACHE_PORT for ip in all_ips if ip", "elif cas_id != item.cas_id(): set_status = MemcacheSetResponse.EXISTS else: set_status =", "if there is no namespace. request: A MemcacheIncrementRequest instance. Returns:", "cas_id, stored_value = ( TYPE_INT, cas_id, str(request.initial_value())) else: flags, cas_id,", "= 0 if old_entry: _, cas_id, _ = cPickle.loads(old_entry) set_status", "all calls. \"\"\" super(MemcacheService, self).__init__(service_name) self._gettime = gettime self._memcache =", "namespace for the request, if any. Pass an empty string", "statisical values and makes sure the key is in the", "+ 1, item.value()]) if set_policy == MemcacheSetRequest.REPLACE: self._memcache.replace(key, set_value) else:", "is None: delete_status = MemcacheDeleteResponse.NOT_FOUND else: self._memcache.delete(key) response.add_delete_status(delete_status) def _Increment(self,", "protocol buffer. response: A MemcacheBatchIncrementResponse protocol buffer. \"\"\" namespace =", "A MemcacheIncrementResponse protocol buffer. \"\"\" new_value = self._Increment(request.name_space(), request) if", "key = self._GetKey(namespace, request.key()) value = self._memcache.get(key) if value is", "\"\"\" namespace = request.name_space() for request_item in request.item_list(): new_value =", "= response.add_item() if new_value is None: item.set_increment_status(MemcacheIncrementResponse.NOT_CHANGED) else: item.set_increment_status(MemcacheIncrementResponse.OK) item.set_new_value(new_value)", "request.delta() elif request.direction() == MemcacheIncrementRequest.DECREMENT: new_value -= request.delta() new_stored_value =", "= MemcacheSetResponse.STORED if (set_status == MemcacheSetResponse.STORED or set_policy == MemcacheSetRequest.REPLACE):", "self._Increment(namespace, request_item) item = response.add_item() if new_value is None: item.set_increment_status(MemcacheIncrementResponse.NOT_CHANGED)", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "if the offset was successful, None on error. \"\"\" if", "import base64 import cPickle import logging import memcache import os", "+= get_stats_value(server_stats, 'get_misses') byte_hits_total += get_stats_value(server_stats, 'bytes_read') items_total += get_stats_value(server_stats,", "it expects all fields here to be ints. # Python", "under the License. # \"\"\" Non-stub version of the memcache", "response: A MemcacheIncrementResponse protocol buffer. \"\"\" new_value = self._Increment(request.name_space(), request)", "set(request.key_list()): internal_key = self._GetKey(request.name_space(), key) value = self._memcache.get(internal_key) if value", "logging import memcache import os import time from google.appengine.api import", "library to interface with memcached. \"\"\" import base64 import cPickle", "UPDATE_WINDOW = 60 # seconds def __init__(self, gettime=time.time, service_name='memcache'): \"\"\"Initializer.", "\":\" + self.MEMCACHE_PORT for ip in all_ips if ip !=", "of sets for memcache. Args: request: A MemcacheSetRequest. response: A", "all data in memcached. Uses the python-memcached library to interface", "function used for testing. service_name: Service name expected for all", "return _type(stats_dict.get(key, '0')) for server, server_stats in self._memcache.get_stats(): num_servers +=", "new_value -= request.delta() new_stored_value = cPickle.dumps([flags, cas_id + 1, str(new_value)])", "misses_total = 0 byte_hits_total = 0 items_total = 0 bytes_total", "value = self._memcache.get(key) if value is None: if not request.has_initial_value():", "memcache_file.close() else: all_ips = ['localhost'] memcaches = [ip + \":\"", "characters but the Memcache client does not. Args: namespace: The", "APPSCALE_MEMCACHE_FILE = \"/etc/appscale/memcache_ips\" # The minimum frequency by which memcache", "which memcache clients will update their list of # clients", "# clients that they connect to (which can change if", "self._memcache.cas(key, new_stored_value) except Exception, e: logging.error(str(e)) return None return new_value", "increment for memcache. Args: request: A MemcacheIncrementRequest protocol buffer. response:", "\"License\"); # you may not use this file except in", "if AppScale scales up or # down). UPDATE_WINDOW = 60", "MemcacheSetRequest.ADD and old_entry is None) or (set_policy == MemcacheSetRequest.REPLACE and", "= 0 items_total = 0 bytes_total = 0 time_total =", "set_policy == MemcacheSetRequest.REPLACE): set_value = cPickle.dumps( [item.flags(), cas_id + 1,", "_ = cPickle.loads(old_entry) set_status = MemcacheSetResponse.NOT_STORED if ((set_policy == MemcacheSetRequest.SET)", "\"11211\" # An AppScale file which has a list of", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "the Memcache key. It is encoded because the sdk allows", "is None: if not request.has_initial_value(): return None flags, cas_id, stored_value", "= response.mutable_stats() num_servers = 0 hits_total = 0 misses_total =", "(which can change if AppScale scales up or # down).", "# distributed under the License is distributed on an \"AS", "__{appname}__{namespace}__{key} \"\"\" appname = os.environ['APPNAME'] internal_key = appname + \"__\"", "which has a list of IPs running memcached. APPSCALE_MEMCACHE_FILE =", "= memcache_service_pb.MemcacheSetResponse MemcacheSetRequest = memcache_service_pb.MemcacheSetRequest MemcacheIncrementRequest = memcache_service_pb.MemcacheIncrementRequest MemcacheIncrementResponse =", "# Unless required by applicable law or agreed to in", "there is no namespace. request: A MemcacheIncrementRequest instance. Returns: An", "def _Dynamic_FlushAll(self, request, response): \"\"\"Implementation of MemcacheService::FlushAll(). Args: request: A", "any. Pass an empty string if there is no namespace.", "from google.appengine.api.memcache import TYPE_INT from google.appengine.api.memcache import TYPE_LONG class MemcacheService(apiproxy_stub.APIProxyStub):", "A MemcacheIncrementRequest protocol buffer. response: A MemcacheIncrementResponse protocol buffer. \"\"\"", "buffer. \"\"\" for key in set(request.key_list()): internal_key = self._GetKey(request.name_space(), key)", "With the Python 2.7 GAE runtime, it expects all fields", "callers in that runtime # may not be expecting an", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "internal_key = self._GetKey(request.name_space(), key) value = self._memcache.get(internal_key) if value is", "[ip + \":\" + self.MEMCACHE_PORT for ip in all_ips if", "running memcached. APPSCALE_MEMCACHE_FILE = \"/etc/appscale/memcache_ips\" # The minimum frequency by", "google.appengine.runtime import apiproxy_errors MemcacheSetResponse = memcache_service_pb.MemcacheSetResponse MemcacheSetRequest = memcache_service_pb.MemcacheSetRequest MemcacheIncrementRequest", "1 hits_total += get_stats_value(server_stats, 'get_hits') misses_total += get_stats_value(server_stats, 'get_misses') byte_hits_total", "== MemcacheSetResponse.STORED or set_policy == MemcacheSetRequest.REPLACE): set_value = cPickle.dumps( [item.flags(),", "gettime: time.time()-like function used for testing. service_name: Service name expected", "= MemcacheSetResponse.NOT_STORED elif cas_id != item.cas_id(): set_status = MemcacheSetResponse.EXISTS else:", "to (which can change if AppScale scales up or #", "time_total += get_stats_value(server_stats, 'time', float) stats.set_hits(hits_total) stats.set_misses(misses_total) stats.set_byte_hits(byte_hits_total) stats.set_items(items_total) stats.set_bytes(bytes_total)", "MemcacheDeleteResponse = memcache_service_pb.MemcacheDeleteResponse from google.appengine.api.memcache import TYPE_INT from google.appengine.api.memcache import", "You may obtain a copy of the License at #", "# # Copyright 2007 Google Inc. # # Licensed under", "expected for all calls. \"\"\" super(MemcacheService, self).__init__(service_name) self._gettime = gettime", "request.delta() new_stored_value = cPickle.dumps([flags, cas_id + 1, str(new_value)]) try: self._memcache.cas(key,", "and # limitations under the License. # \"\"\" Non-stub version", "\"\"\"Implementation of delete in memcache. Args: request: A MemcacheDeleteRequest protocol", "= self._memcache.get(key) delete_status = MemcacheDeleteResponse.DELETED if entry is None: delete_status", "2007 Google Inc. # # Licensed under the Apache License,", "this being a float, so callers in that runtime #", "+ \"__\" + namespace + \"__\" + key return base64.b64encode(internal_key)", "cas_id, _ = cPickle.loads(old_entry) set_status = MemcacheSetResponse.NOT_STORED if ((set_policy ==", "TYPE_INT from google.appengine.api.memcache import TYPE_LONG class MemcacheService(apiproxy_stub.APIProxyStub): \"\"\"Python only memcache", "- time_total / num_servers)) def _GetKey(self, namespace, key): \"\"\"Used to", "memcache_service_pb from google.appengine.runtime import apiproxy_errors MemcacheSetResponse = memcache_service_pb.MemcacheSetResponse MemcacheSetRequest =", "that runtime # may not be expecting an int. stats.set_oldest_item_age(int(time.time()", "\"\"\" for item in request.item_list(): key = self._GetKey(request.name_space(), item.key()) set_policy", "request: A MemcacheStatsRequest. response: A MemcacheStatsResponse. \"\"\" stats = response.mutable_stats()", "= appname + \"__\" + namespace + \"__\" + key", "the Apache License, Version 2.0 (the \"License\"); # you may", "connect to (which can change if AppScale scales up or", "import cPickle import logging import memcache import os import time", "# The memcached default port. MEMCACHE_PORT = \"11211\" # An", "if os.path.exists(self.APPSCALE_MEMCACHE_FILE): memcache_file = open(self.APPSCALE_MEMCACHE_FILE, \"r\") all_ips = memcache_file.read().split(\"\\n\") memcache_file.close()", "''] memcaches.sort() self._memcache = memcache.Client(memcaches, debug=0) def _Dynamic_Get(self, request, response):", "in request.item_list(): key = self._GetKey(request.name_space(), item.key()) set_policy = item.set_policy() old_entry", "A MemcacheBatchIncrementResponse protocol buffer. \"\"\" namespace = request.name_space() for request_item", "= 60 # seconds def __init__(self, gettime=time.time, service_name='memcache'): \"\"\"Initializer. Args:", "#!/usr/bin/env python # # Copyright 2007 Google Inc. # #", "data in memcached. Uses the python-memcached library to interface with", "flags == TYPE_INT: new_value = int(stored_value) elif flags == TYPE_LONG:", "MemcacheIncrementRequest = memcache_service_pb.MemcacheIncrementRequest MemcacheIncrementResponse = memcache_service_pb.MemcacheIncrementResponse MemcacheDeleteResponse = memcache_service_pb.MemcacheDeleteResponse from" ]
[ "\"]\" line += \");\" scad.append(line) scad.append(\"}\\n\") return \"\\n\".join(scad) def saveSCAD(filename,", "rgb,polyhedron in polys: for face in polyhedron: output.append((rgb,face)) return output", "polys \"\"\" polys = toPolyhedra(polys) scad = [] scad.append(\"module \"", "status message if set \"\"\" if not quiet: sys.stderr.write(\"Saving %s\\n\"", "* from .formatdecimal import decimal from numbers import Number import", "+ \"();\\n\") def saveSTL(filename, mesh, swapYZ=False, quiet=False): \"\"\" filename: filename", "status message if set \"\"\" mesh = toMesh(mesh) if not", "0x8000 | ( (rgb[0] >> 3) << 10 ) |", "to write OpenSCAD file polys: list of (color,polyhedra) pairs (counterclockwise", "save STL file mesh: list of (color,triangle) pairs (counterclockwise) swapYZ:", "face in polyhedron: output.append((rgb,face)) return output def describeColor(c): if c", "for all in latter case) moduleName: OpenSCAD module name OUTPUT:", "open(filename, \"w\") as f: f.write(toSCADModule(polys, moduleName)) f.write(\"\\n\" + moduleName +", "Vector(min(minVector[i], vertex[i]) for i in range(3)) minVector -= Vector(0.001,0.001,0.001) #", "polys def toMesh(polys): if isColorTriangleList(polys): return polys else: output =", "pairs (counterclockwise triangles) moduleName: OpenSCAD module name quiet: give no", "color)) if filename: with open(filename, \"wb\") as f: writeSTL(f.write) else:", "sys try: basestring except: basestring = str def isColorTriangleList(polys): return", "as f: writeSTL(f.write) else: if sys.platform == \"win32\": import msvcrt", "describeColor(colorOverride if colorOverride else tuple(min(max(c,0.),1.0) for c in rgb)) else:", "5 ) | ( (rgb[2] >> 3) << 0 )", "basestring except: basestring = str def isColorTriangleList(polys): return isinstance(polys[0][1][0][0], Number)", "from numbers import Number import os import sys try: basestring", "colorOverride != \"\" and (colorOverride or rgb): line = \"", "in reversed(face): if tuple(v) not in pointsDict: pointsDict[tuple(v)] = i", "polyhedron: output.append((rgb,face)) return output def describeColor(c): if c is None:", "in poly: for v in reversed(face): if tuple(v) not in", "write(pack(\"<3f\", *(matrix*normal))) for vertex in tri: write(pack(\"<3f\", *(matrix*(vertex-minVector)))) write(pack(\"<H\", color))", "+ \",\".join(str(pointsDict[tuple(v)]) for v in reversed(face)) + \"]\" for face", "= i points.append( (\"[%s,%s,%s]\") % tuple(decimal(x,digitsAfterDecimal) for x in v)", "\",\".join( \"[\" + \",\".join(str(pointsDict[tuple(v)]) for v in reversed(face)) + \"]\"", "= toPolyhedra(polys) scad = [] scad.append(\"module \" +moduleName+ \"() {\")", "for rgb,tri in mesh: if mono: color = 0 else:", "for x in v) ) i += 1 line +=", "rgb = (255,255,255) else: rgb = tuple(min(255,max(0,int(0.5 + 255 *", "currently uses first color for all in latter case) moduleName:", "+= 1 for vertex in triangle: vertex = matrix*vertex minVector", "f.write(toSCADModule(polys, moduleName)) f.write(\"\\n\" + moduleName + \"();\\n\") else: sys.stdout.write(toSCADModule(polys, moduleName))", "INPUT: polys: list of (color,polyhedra) pairs (counterclockwise triangles), or a", "swapYZ: matrix = Matrix( (1,0,0), (0,0,-1), (0,1,0) ) else: matrix", "moduleName: OpenSCAD module name OUTPUT: string with OpenSCAD code implementing", "[] for face in poly: for v in reversed(face): if", "% filename) if filename: with open(filename, \"w\") as f: f.write(toSCADModule(polys,", "writeSTL(f.write) else: if sys.platform == \"win32\": import msvcrt msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)", "write(pack(\"<3f\", *(matrix*(vertex-minVector)))) write(pack(\"<H\", color)) if filename: with open(filename, \"wb\") as", "= matrix*vertex minVector = Vector(min(minVector[i], vertex[i]) for i in range(3))", "\" color(%s) \" % describeColor(colorOverride if colorOverride else tuple(min(max(c,0.),1.0) for", "for rgb,face in polys)) ] else: return polys def toMesh(polys):", "all STL coordinates are strictly positive as per Wikipedia def", "in c) def toSCADModule(polys, moduleName, digitsAfterDecimal=9, colorOverride=None): \"\"\" INPUT: polys:", "color for all in latter case) moduleName: OpenSCAD module name", "if set \"\"\" if not quiet: sys.stderr.write(\"Saving %s\\n\" % filename)", "isColorTriangleList(polys): return polys else: output = [] for rgb,polyhedron in", "= True for rgb,triangle in mesh: if rgb is not", "vertex[i]) for i in range(3)) minVector -= Vector(0.001,0.001,0.001) # make", "positive as per Wikipedia def writeSTL(write): write(pack(\"80s\",b'')) write(pack(\"<I\",numTriangles)) for rgb,tri", "\"[%s,%s,%s]\" % tuple(decimal(component) for component in c) def toSCADModule(polys, moduleName,", "give no status message if set \"\"\" if not quiet:", "points.append( (\"[%s,%s,%s]\") % tuple(decimal(x,digitsAfterDecimal) for x in v) ) i", "if colorOverride != \"\" and (colorOverride or rgb): line =", "(color,triangle) pairs (counterclockwise) swapYZ: should Y/Z axes be swapped? quiet:", "mono = True for rgb,triangle in mesh: if rgb is", "+= \"], faces=[\" line += \",\".join( \"[\" + \",\".join(str(pointsDict[tuple(v)]) for", "name quiet: give no status message if set \"\"\" if", "= (255,255,255) else: rgb = tuple(min(255,max(0,int(0.5 + 255 * comp)))", "line = \" \" pointsDict = {} i = 0", "if c is None: return \"undef\"; elif isinstance(c, str): return", "polys: list of (color,polyhedra) pairs (counterclockwise triangles), or a list", "filename) if filename: with open(filename, \"w\") as f: f.write(toSCADModule(polys, moduleName))", "file polys: list of (color,polyhedra) pairs (counterclockwise triangles) moduleName: OpenSCAD", "+ moduleName + \"();\\n\") else: sys.stdout.write(toSCADModule(polys, moduleName)) sys.stdout.write(\"\\n\" + moduleName", "\"[\" + \",\".join(str(pointsDict[tuple(v)]) for v in reversed(face)) + \"]\" for", "def toMesh(polys): if isColorTriangleList(polys): return polys else: output = []", "\"() {\") for rgb,poly in polys: if colorOverride != \"\"", "in polys: for face in polyhedron: output.append((rgb,face)) return output def", "pack from .vector import * from .formatdecimal import decimal from", "color = 0x8000 | ( (rgb[0] >> 3) << 10", "return [ (polys[0][0], list(face for rgb,face in polys)) ] else:", "list of (color,polyhedra) pairs (counterclockwise triangles) moduleName: OpenSCAD module name", "(color,triangle) pairs (TODO: currently uses first color for all in", "def saveSTL(filename, mesh, swapYZ=False, quiet=False): \"\"\" filename: filename to save", "matrix*vertex minVector = Vector(min(minVector[i], vertex[i]) for i in range(3)) minVector", "if colorOverride else tuple(min(max(c,0.),1.0) for c in rgb)) else: line", "\",\".join(points) line += \"], faces=[\" line += \",\".join( \"[\" +", "(0,1,0) ) else: matrix = Matrix.identity(3) mono = True for", "in poly ) + \"]\" line += \");\" scad.append(line) scad.append(\"}\\n\")", "= [] scad.append(\"module \" +moduleName+ \"() {\") for rgb,poly in", "triangles), or a list of (color,triangle) pairs (TODO: currently uses", "for c in rgb)) else: line = \" \" pointsDict", "set \"\"\" mesh = toMesh(mesh) if not quiet: sys.stderr.write(\"Saving %s\\n\"", "numTriangles += 1 for vertex in triangle: vertex = matrix*vertex", "toMesh(polys): if isColorTriangleList(polys): return polys else: output = [] for", "OpenSCAD module name OUTPUT: string with OpenSCAD code implementing the", "for v in reversed(face)) + \"]\" for face in poly", "file mesh: list of (color,triangle) pairs (counterclockwise) swapYZ: should Y/Z", "no status message if set \"\"\" mesh = toMesh(mesh) if", "+= \");\" scad.append(line) scad.append(\"}\\n\") return \"\\n\".join(scad) def saveSCAD(filename, polys, moduleName=\"object1\",", ">> 3) << 10 ) | ( (rgb[1] >> 3)", "moduleName + \"();\\n\") def saveSTL(filename, mesh, swapYZ=False, quiet=False): \"\"\" filename:", "quiet=False): \"\"\" filename: filename to save STL file mesh: list", ">> 3) << 0 ) normal = (Vector(tri[1])-Vector(tri[0])).cross(Vector(tri[2])-Vector(tri[0])).normalize() write(pack(\"<3f\", *(matrix*normal)))", "else: sys.stdout.write(toSCADModule(polys, moduleName)) sys.stdout.write(\"\\n\" + moduleName + \"();\\n\") def saveSTL(filename,", "str def isColorTriangleList(polys): return isinstance(polys[0][1][0][0], Number) def toPolyhedra(polys): if isColorTriangleList(polys):", "sys.platform == \"win32\": import msvcrt msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY) writeSTL(lambda data :", "swapYZ=False, quiet=False): \"\"\" filename: filename to save STL file mesh:", "else: return polys def toMesh(polys): if isColorTriangleList(polys): return polys else:", "filename: with open(filename, \"wb\") as f: writeSTL(f.write) else: if sys.platform", "quiet: give no status message if set \"\"\" mesh =", "sure all STL coordinates are strictly positive as per Wikipedia", "\" +moduleName+ \"() {\") for rgb,poly in polys: if colorOverride", "c else: return \"[%s,%s,%s]\" % tuple(decimal(component) for component in c)", "f: f.write(toSCADModule(polys, moduleName)) f.write(\"\\n\" + moduleName + \"();\\n\") else: sys.stdout.write(toSCADModule(polys,", "in tri: write(pack(\"<3f\", *(matrix*(vertex-minVector)))) write(pack(\"<H\", color)) if filename: with open(filename,", "Matrix.identity(3) mono = True for rgb,triangle in mesh: if rgb", "\",\".join(str(pointsDict[tuple(v)]) for v in reversed(face)) + \"]\" for face in", ".vector import * from .formatdecimal import decimal from numbers import", "3) << 10 ) | ( (rgb[1] >> 3) <<", "not quiet: sys.stderr.write(\"Saving %s\\n\" % filename) minY = float(\"inf\") minVector", "and (colorOverride or rgb): line = \" color(%s) \" %", "return output def describeColor(c): if c is None: return \"undef\";", "line += \",\".join(points) line += \"], faces=[\" line += \",\".join(", "Matrix( (1,0,0), (0,0,-1), (0,1,0) ) else: matrix = Matrix.identity(3) mono", "= float(\"inf\") minVector = Vector(float(\"inf\"),float(\"inf\"),float(\"inf\")) numTriangles = 0 if swapYZ:", "with OpenSCAD code implementing the polys \"\"\" polys = toPolyhedra(polys)", "triangle: vertex = matrix*vertex minVector = Vector(min(minVector[i], vertex[i]) for i", "polys: list of (color,polyhedra) pairs (counterclockwise triangles) moduleName: OpenSCAD module", "*(matrix*normal))) for vertex in tri: write(pack(\"<3f\", *(matrix*(vertex-minVector)))) write(pack(\"<H\", color)) if", "tri: write(pack(\"<3f\", *(matrix*(vertex-minVector)))) write(pack(\"<H\", color)) if filename: with open(filename, \"wb\")", "uses first color for all in latter case) moduleName: OpenSCAD", "minVector = Vector(min(minVector[i], vertex[i]) for i in range(3)) minVector -=", "Wikipedia def writeSTL(write): write(pack(\"80s\",b'')) write(pack(\"<I\",numTriangles)) for rgb,tri in mesh: if", "for face in poly ) + \"]\" line += \");\"", "rgb is None: rgb = (255,255,255) else: rgb = tuple(min(255,max(0,int(0.5", "message if set \"\"\" mesh = toMesh(mesh) if not quiet:", "tuple(min(max(c,0.),1.0) for c in rgb)) else: line = \" \"", "if filename: with open(filename, \"w\") as f: f.write(toSCADModule(polys, moduleName)) f.write(\"\\n\"", "rgb,triangle in mesh: if rgb is not None: mono =", "OpenSCAD file polys: list of (color,polyhedra) pairs (counterclockwise triangles) moduleName:", "scad = [] scad.append(\"module \" +moduleName+ \"() {\") for rgb,poly", "if tuple(v) not in pointsDict: pointsDict[tuple(v)] = i points.append( (\"[%s,%s,%s]\")", "%s\\n\" % filename) if filename: with open(filename, \"w\") as f:", "to save STL file mesh: list of (color,triangle) pairs (counterclockwise)", "rgb)) else: line = \" \" pointsDict = {} i", "numTriangles = 0 if swapYZ: matrix = Matrix( (1,0,0), (0,0,-1),", "latter case) moduleName: OpenSCAD module name OUTPUT: string with OpenSCAD", "False numTriangles += 1 for vertex in triangle: vertex =", "scad.append(\"}\\n\") return \"\\n\".join(scad) def saveSCAD(filename, polys, moduleName=\"object1\", quiet=False): \"\"\" filename:", "face in poly ) + \"]\" line += \");\" scad.append(line)", "poly ) + \"]\" line += \");\" scad.append(line) scad.append(\"}\\n\") return", "the polys \"\"\" polys = toPolyhedra(polys) scad = [] scad.append(\"module", "[ (polys[0][0], list(face for rgb,face in polys)) ] else: return", "pairs (counterclockwise triangles), or a list of (color,triangle) pairs (TODO:", "all in latter case) moduleName: OpenSCAD module name OUTPUT: string", "+ moduleName + \"();\\n\") def saveSTL(filename, mesh, swapYZ=False, quiet=False): \"\"\"", "mesh: list of (color,triangle) pairs (counterclockwise) swapYZ: should Y/Z axes", "no status message if set \"\"\" if not quiet: sys.stderr.write(\"Saving", "= 0x8000 | ( (rgb[0] >> 3) << 10 )", "import os import sys try: basestring except: basestring = str", "str): return c else: return \"[%s,%s,%s]\" % tuple(decimal(component) for component", "= \" color(%s) \" % describeColor(colorOverride if colorOverride else tuple(min(max(c,0.),1.0)", "# make sure all STL coordinates are strictly positive as", "rgb) color = 0x8000 | ( (rgb[0] >> 3) <<", "return \"[%s,%s,%s]\" % tuple(decimal(component) for component in c) def toSCADModule(polys,", "\" \" pointsDict = {} i = 0 line +=", "= Vector(min(minVector[i], vertex[i]) for i in range(3)) minVector -= Vector(0.001,0.001,0.001)", "import Number import os import sys try: basestring except: basestring", "toPolyhedra(polys) scad = [] scad.append(\"module \" +moduleName+ \"() {\") for", "return \"undef\"; elif isinstance(c, str): return c else: return \"[%s,%s,%s]\"", "in latter case) moduleName: OpenSCAD module name OUTPUT: string with", "\"\"\" polys = toPolyhedra(polys) scad = [] scad.append(\"module \" +moduleName+", "\"();\\n\") def saveSTL(filename, mesh, swapYZ=False, quiet=False): \"\"\" filename: filename to", "(TODO: currently uses first color for all in latter case)", "i = 0 line += \"polyhedron(points=[\" points = [] for", "saveSCAD(filename, polys, moduleName=\"object1\", quiet=False): \"\"\" filename: filename to write OpenSCAD", "implementing the polys \"\"\" polys = toPolyhedra(polys) scad = []", "write(pack(\"<H\", color)) if filename: with open(filename, \"wb\") as f: writeSTL(f.write)", "3) << 5 ) | ( (rgb[2] >> 3) <<", "line += \"polyhedron(points=[\" points = [] for face in poly:", "mesh: if mono: color = 0 else: if rgb is", "+= \",\".join( \"[\" + \",\".join(str(pointsDict[tuple(v)]) for v in reversed(face)) +", "face in poly: for v in reversed(face): if tuple(v) not", "\"polyhedron(points=[\" points = [] for face in poly: for v", "% tuple(decimal(x,digitsAfterDecimal) for x in v) ) i += 1", "moduleName + \"();\\n\") else: sys.stdout.write(toSCADModule(polys, moduleName)) sys.stdout.write(\"\\n\" + moduleName +", "polys)) ] else: return polys def toMesh(polys): if isColorTriangleList(polys): return", "digitsAfterDecimal=9, colorOverride=None): \"\"\" INPUT: polys: list of (color,polyhedra) pairs (counterclockwise", "= [] for face in poly: for v in reversed(face):", "(Vector(tri[1])-Vector(tri[0])).cross(Vector(tri[2])-Vector(tri[0])).normalize() write(pack(\"<3f\", *(matrix*normal))) for vertex in tri: write(pack(\"<3f\", *(matrix*(vertex-minVector)))) write(pack(\"<H\",", "c) def toSCADModule(polys, moduleName, digitsAfterDecimal=9, colorOverride=None): \"\"\" INPUT: polys: list", "import * from .formatdecimal import decimal from numbers import Number", "isColorTriangleList(polys): return isinstance(polys[0][1][0][0], Number) def toPolyhedra(polys): if isColorTriangleList(polys): return [", "\" % describeColor(colorOverride if colorOverride else tuple(min(max(c,0.),1.0) for c in", "(color,polyhedra) pairs (counterclockwise triangles), or a list of (color,triangle) pairs", "OpenSCAD module name quiet: give no status message if set", "else: rgb = tuple(min(255,max(0,int(0.5 + 255 * comp))) for comp", "None: return \"undef\"; elif isinstance(c, str): return c else: return", "os import sys try: basestring except: basestring = str def", ") i += 1 line += \",\".join(points) line += \"],", "% filename) minY = float(\"inf\") minVector = Vector(float(\"inf\"),float(\"inf\"),float(\"inf\")) numTriangles =", "i in range(3)) minVector -= Vector(0.001,0.001,0.001) # make sure all", "\"\\n\".join(scad) def saveSCAD(filename, polys, moduleName=\"object1\", quiet=False): \"\"\" filename: filename to", "= 0 if swapYZ: matrix = Matrix( (1,0,0), (0,0,-1), (0,1,0)", "\"undef\"; elif isinstance(c, str): return c else: return \"[%s,%s,%s]\" %", "scad.append(line) scad.append(\"}\\n\") return \"\\n\".join(scad) def saveSCAD(filename, polys, moduleName=\"object1\", quiet=False): \"\"\"", "isColorTriangleList(polys): return [ (polys[0][0], list(face for rgb,face in polys)) ]", "reversed(face): if tuple(v) not in pointsDict: pointsDict[tuple(v)] = i points.append(", "rgb,tri in mesh: if mono: color = 0 else: if", "is None: return \"undef\"; elif isinstance(c, str): return c else:", "* comp))) for comp in rgb) color = 0x8000 |", "[] scad.append(\"module \" +moduleName+ \"() {\") for rgb,poly in polys:", "sys.stdout.write(toSCADModule(polys, moduleName)) sys.stdout.write(\"\\n\" + moduleName + \"();\\n\") def saveSTL(filename, mesh,", "toMesh(mesh) if not quiet: sys.stderr.write(\"Saving %s\\n\" % filename) minY =", "\"], faces=[\" line += \",\".join( \"[\" + \",\".join(str(pointsDict[tuple(v)]) for v", "swapYZ: should Y/Z axes be swapped? quiet: give no status", "(color,polyhedra) pairs (counterclockwise triangles) moduleName: OpenSCAD module name quiet: give", "c is None: return \"undef\"; elif isinstance(c, str): return c", "comp))) for comp in rgb) color = 0x8000 | (", "elif isinstance(c, str): return c else: return \"[%s,%s,%s]\" % tuple(decimal(component)", "0 line += \"polyhedron(points=[\" points = [] for face in", "x in v) ) i += 1 line += \",\".join(points)", "points = [] for face in poly: for v in", "if rgb is None: rgb = (255,255,255) else: rgb =", "c in rgb)) else: line = \" \" pointsDict =", "return isinstance(polys[0][1][0][0], Number) def toPolyhedra(polys): if isColorTriangleList(polys): return [ (polys[0][0],", "moduleName=\"object1\", quiet=False): \"\"\" filename: filename to write OpenSCAD file polys:", "\"();\\n\") else: sys.stdout.write(toSCADModule(polys, moduleName)) sys.stdout.write(\"\\n\" + moduleName + \"();\\n\") def", "for rgb,poly in polys: if colorOverride != \"\" and (colorOverride", "name OUTPUT: string with OpenSCAD code implementing the polys \"\"\"", "case) moduleName: OpenSCAD module name OUTPUT: string with OpenSCAD code", "pointsDict = {} i = 0 line += \"polyhedron(points=[\" points", "+= 1 line += \",\".join(points) line += \"], faces=[\" line", "sys.stdout.write(\"\\n\" + moduleName + \"();\\n\") def saveSTL(filename, mesh, swapYZ=False, quiet=False):", "for rgb,polyhedron in polys: for face in polyhedron: output.append((rgb,face)) return", "pointsDict[tuple(v)] = i points.append( (\"[%s,%s,%s]\") % tuple(decimal(x,digitsAfterDecimal) for x in", "\"wb\") as f: writeSTL(f.write) else: if sys.platform == \"win32\": import", "pointsDict: pointsDict[tuple(v)] = i points.append( (\"[%s,%s,%s]\") % tuple(decimal(x,digitsAfterDecimal) for x", "for face in poly: for v in reversed(face): if tuple(v)", "is not None: mono = False numTriangles += 1 for", "== \"win32\": import msvcrt msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY) writeSTL(lambda data : os.write(sys.stdout.fileno(),", "-= Vector(0.001,0.001,0.001) # make sure all STL coordinates are strictly", "def saveSCAD(filename, polys, moduleName=\"object1\", quiet=False): \"\"\" filename: filename to write", "rgb = tuple(min(255,max(0,int(0.5 + 255 * comp))) for comp in", "string with OpenSCAD code implementing the polys \"\"\" polys =", "tuple(v) not in pointsDict: pointsDict[tuple(v)] = i points.append( (\"[%s,%s,%s]\") %", ") normal = (Vector(tri[1])-Vector(tri[0])).cross(Vector(tri[2])-Vector(tri[0])).normalize() write(pack(\"<3f\", *(matrix*normal))) for vertex in tri:", "mesh: if rgb is not None: mono = False numTriangles", "{\") for rgb,poly in polys: if colorOverride != \"\" and", "color(%s) \" % describeColor(colorOverride if colorOverride else tuple(min(max(c,0.),1.0) for c", "message if set \"\"\" if not quiet: sys.stderr.write(\"Saving %s\\n\" %", "tuple(min(255,max(0,int(0.5 + 255 * comp))) for comp in rgb) color", "= str def isColorTriangleList(polys): return isinstance(polys[0][1][0][0], Number) def toPolyhedra(polys): if", "in mesh: if rgb is not None: mono = False", "i points.append( (\"[%s,%s,%s]\") % tuple(decimal(x,digitsAfterDecimal) for x in v) )", "import decimal from numbers import Number import os import sys", "list of (color,triangle) pairs (TODO: currently uses first color for", "def isColorTriangleList(polys): return isinstance(polys[0][1][0][0], Number) def toPolyhedra(polys): if isColorTriangleList(polys): return", "decimal from numbers import Number import os import sys try:", "in polyhedron: output.append((rgb,face)) return output def describeColor(c): if c is", "else: output = [] for rgb,polyhedron in polys: for face", "filename: filename to write OpenSCAD file polys: list of (color,polyhedra)", "colorOverride else tuple(min(max(c,0.),1.0) for c in rgb)) else: line =", "<< 10 ) | ( (rgb[1] >> 3) << 5", "describeColor(c): if c is None: return \"undef\"; elif isinstance(c, str):", "def writeSTL(write): write(pack(\"80s\",b'')) write(pack(\"<I\",numTriangles)) for rgb,tri in mesh: if mono:", "f: writeSTL(f.write) else: if sys.platform == \"win32\": import msvcrt msvcrt.setmode(sys.stdout.fileno(),", "from .formatdecimal import decimal from numbers import Number import os", "rgb): line = \" color(%s) \" % describeColor(colorOverride if colorOverride", "(counterclockwise) swapYZ: should Y/Z axes be swapped? quiet: give no", "struct import pack from .vector import * from .formatdecimal import", "def toSCADModule(polys, moduleName, digitsAfterDecimal=9, colorOverride=None): \"\"\" INPUT: polys: list of", "import pack from .vector import * from .formatdecimal import decimal", "moduleName, digitsAfterDecimal=9, colorOverride=None): \"\"\" INPUT: polys: list of (color,polyhedra) pairs", "] else: return polys def toMesh(polys): if isColorTriangleList(polys): return polys", "for rgb,triangle in mesh: if rgb is not None: mono", "(255,255,255) else: rgb = tuple(min(255,max(0,int(0.5 + 255 * comp))) for", "line += \",\".join( \"[\" + \",\".join(str(pointsDict[tuple(v)]) for v in reversed(face))", "+ 255 * comp))) for comp in rgb) color =", ") | ( (rgb[2] >> 3) << 0 ) normal", "\"w\") as f: f.write(toSCADModule(polys, moduleName)) f.write(\"\\n\" + moduleName + \"();\\n\")", "STL file mesh: list of (color,triangle) pairs (counterclockwise) swapYZ: should", "in range(3)) minVector -= Vector(0.001,0.001,0.001) # make sure all STL", "as f: f.write(toSCADModule(polys, moduleName)) f.write(\"\\n\" + moduleName + \"();\\n\") else:", "from .vector import * from .formatdecimal import decimal from numbers", "pairs (TODO: currently uses first color for all in latter", "toSCADModule(polys, moduleName, digitsAfterDecimal=9, colorOverride=None): \"\"\" INPUT: polys: list of (color,polyhedra)", "write(pack(\"80s\",b'')) write(pack(\"<I\",numTriangles)) for rgb,tri in mesh: if mono: color =", ") + \"]\" line += \");\" scad.append(line) scad.append(\"}\\n\") return \"\\n\".join(scad)", "OUTPUT: string with OpenSCAD code implementing the polys \"\"\" polys", "None: rgb = (255,255,255) else: rgb = tuple(min(255,max(0,int(0.5 + 255", "not None: mono = False numTriangles += 1 for vertex", "else: matrix = Matrix.identity(3) mono = True for rgb,triangle in", "v) ) i += 1 line += \",\".join(points) line +=", "+= \"polyhedron(points=[\" points = [] for face in poly: for", "if not quiet: sys.stderr.write(\"Saving %s\\n\" % filename) if filename: with", "list of (color,polyhedra) pairs (counterclockwise triangles), or a list of", "module name OUTPUT: string with OpenSCAD code implementing the polys", "quiet: give no status message if set \"\"\" if not", "+ \"]\" for face in poly ) + \"]\" line", "| ( (rgb[1] >> 3) << 5 ) | (", "reversed(face)) + \"]\" for face in poly ) + \"]\"", "1 line += \",\".join(points) line += \"], faces=[\" line +=", "| ( (rgb[0] >> 3) << 10 ) | (", "line += \");\" scad.append(line) scad.append(\"}\\n\") return \"\\n\".join(scad) def saveSCAD(filename, polys,", "axes be swapped? quiet: give no status message if set", "in triangle: vertex = matrix*vertex minVector = Vector(min(minVector[i], vertex[i]) for", "return polys else: output = [] for rgb,polyhedron in polys:", "quiet: sys.stderr.write(\"Saving %s\\n\" % filename) if filename: with open(filename, \"w\")", "poly: for v in reversed(face): if tuple(v) not in pointsDict:", "module name quiet: give no status message if set \"\"\"", "v in reversed(face): if tuple(v) not in pointsDict: pointsDict[tuple(v)] =", "list(face for rgb,face in polys)) ] else: return polys def", "write(pack(\"<I\",numTriangles)) for rgb,tri in mesh: if mono: color = 0", "OpenSCAD code implementing the polys \"\"\" polys = toPolyhedra(polys) scad", "*(matrix*(vertex-minVector)))) write(pack(\"<H\", color)) if filename: with open(filename, \"wb\") as f:", "<< 0 ) normal = (Vector(tri[1])-Vector(tri[0])).cross(Vector(tri[2])-Vector(tri[0])).normalize() write(pack(\"<3f\", *(matrix*normal))) for vertex", "first color for all in latter case) moduleName: OpenSCAD module", "<< 5 ) | ( (rgb[2] >> 3) << 0", "in reversed(face)) + \"]\" for face in poly ) +", "% describeColor(colorOverride if colorOverride else tuple(min(max(c,0.),1.0) for c in rgb))", "( (rgb[0] >> 3) << 10 ) | ( (rgb[1]", "for vertex in tri: write(pack(\"<3f\", *(matrix*(vertex-minVector)))) write(pack(\"<H\", color)) if filename:", "3) << 0 ) normal = (Vector(tri[1])-Vector(tri[0])).cross(Vector(tri[2])-Vector(tri[0])).normalize() write(pack(\"<3f\", *(matrix*normal))) for", "a list of (color,triangle) pairs (TODO: currently uses first color", "Y/Z axes be swapped? quiet: give no status message if", "for v in reversed(face): if tuple(v) not in pointsDict: pointsDict[tuple(v)]", "1 for vertex in triangle: vertex = matrix*vertex minVector =", "filename: filename to save STL file mesh: list of (color,triangle)", "filename to write OpenSCAD file polys: list of (color,polyhedra) pairs", "if filename: with open(filename, \"wb\") as f: writeSTL(f.write) else: if", "in rgb)) else: line = \" \" pointsDict = {}", "= Matrix( (1,0,0), (0,0,-1), (0,1,0) ) else: matrix = Matrix.identity(3)", "minVector -= Vector(0.001,0.001,0.001) # make sure all STL coordinates are", "Number import os import sys try: basestring except: basestring =", "else: if sys.platform == \"win32\": import msvcrt msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY) writeSTL(lambda", "from struct import pack from .vector import * from .formatdecimal", "if isColorTriangleList(polys): return polys else: output = [] for rgb,polyhedron", "= Vector(float(\"inf\"),float(\"inf\"),float(\"inf\")) numTriangles = 0 if swapYZ: matrix = Matrix(", "f.write(\"\\n\" + moduleName + \"();\\n\") else: sys.stdout.write(toSCADModule(polys, moduleName)) sys.stdout.write(\"\\n\" +", "+ \"();\\n\") else: sys.stdout.write(toSCADModule(polys, moduleName)) sys.stdout.write(\"\\n\" + moduleName + \"();\\n\")", "range(3)) minVector -= Vector(0.001,0.001,0.001) # make sure all STL coordinates", "basestring = str def isColorTriangleList(polys): return isinstance(polys[0][1][0][0], Number) def toPolyhedra(polys):", "= 0 line += \"polyhedron(points=[\" points = [] for face", "for comp in rgb) color = 0x8000 | ( (rgb[0]", "of (color,triangle) pairs (counterclockwise) swapYZ: should Y/Z axes be swapped?", "10 ) | ( (rgb[1] >> 3) << 5 )", "strictly positive as per Wikipedia def writeSTL(write): write(pack(\"80s\",b'')) write(pack(\"<I\",numTriangles)) for", "with open(filename, \"wb\") as f: writeSTL(f.write) else: if sys.platform ==", "rgb is not None: mono = False numTriangles += 1", "mono: color = 0 else: if rgb is None: rgb", "comp in rgb) color = 0x8000 | ( (rgb[0] >>", "255 * comp))) for comp in rgb) color = 0x8000", "\"win32\": import msvcrt msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY) writeSTL(lambda data : os.write(sys.stdout.fileno(), data))", "if mono: color = 0 else: if rgb is None:", "per Wikipedia def writeSTL(write): write(pack(\"80s\",b'')) write(pack(\"<I\",numTriangles)) for rgb,tri in mesh:", "vertex in triangle: vertex = matrix*vertex minVector = Vector(min(minVector[i], vertex[i])", "<filename>inflateutils/exportmesh.py from struct import pack from .vector import * from", "filename) minY = float(\"inf\") minVector = Vector(float(\"inf\"),float(\"inf\"),float(\"inf\")) numTriangles = 0", "vertex in tri: write(pack(\"<3f\", *(matrix*(vertex-minVector)))) write(pack(\"<H\", color)) if filename: with", "polys, moduleName=\"object1\", quiet=False): \"\"\" filename: filename to write OpenSCAD file", "True for rgb,triangle in mesh: if rgb is not None:", "component in c) def toSCADModule(polys, moduleName, digitsAfterDecimal=9, colorOverride=None): \"\"\" INPUT:", "Number) def toPolyhedra(polys): if isColorTriangleList(polys): return [ (polys[0][0], list(face for", "\"\"\" if not quiet: sys.stderr.write(\"Saving %s\\n\" % filename) if filename:", "make sure all STL coordinates are strictly positive as per", "(rgb[1] >> 3) << 5 ) | ( (rgb[2] >>", "colorOverride=None): \"\"\" INPUT: polys: list of (color,polyhedra) pairs (counterclockwise triangles),", "STL coordinates are strictly positive as per Wikipedia def writeSTL(write):", "for component in c) def toSCADModule(polys, moduleName, digitsAfterDecimal=9, colorOverride=None): \"\"\"", "\"]\" for face in poly ) + \"]\" line +=", "{} i = 0 line += \"polyhedron(points=[\" points = []", "( (rgb[2] >> 3) << 0 ) normal = (Vector(tri[1])-Vector(tri[0])).cross(Vector(tri[2])-Vector(tri[0])).normalize()", "polys: for face in polyhedron: output.append((rgb,face)) return output def describeColor(c):", "sys.stderr.write(\"Saving %s\\n\" % filename) minY = float(\"inf\") minVector = Vector(float(\"inf\"),float(\"inf\"),float(\"inf\"))", "output.append((rgb,face)) return output def describeColor(c): if c is None: return", "toPolyhedra(polys): if isColorTriangleList(polys): return [ (polys[0][0], list(face for rgb,face in", "= tuple(min(255,max(0,int(0.5 + 255 * comp))) for comp in rgb)", "= [] for rgb,polyhedron in polys: for face in polyhedron:", "None: mono = False numTriangles += 1 for vertex in", "of (color,polyhedra) pairs (counterclockwise triangles) moduleName: OpenSCAD module name quiet:", "(1,0,0), (0,0,-1), (0,1,0) ) else: matrix = Matrix.identity(3) mono =", "normal = (Vector(tri[1])-Vector(tri[0])).cross(Vector(tri[2])-Vector(tri[0])).normalize() write(pack(\"<3f\", *(matrix*normal))) for vertex in tri: write(pack(\"<3f\",", "of (color,polyhedra) pairs (counterclockwise triangles), or a list of (color,triangle)", "moduleName)) f.write(\"\\n\" + moduleName + \"();\\n\") else: sys.stdout.write(toSCADModule(polys, moduleName)) sys.stdout.write(\"\\n\"", "numbers import Number import os import sys try: basestring except:", "in polys)) ] else: return polys def toMesh(polys): if isColorTriangleList(polys):", "minY = float(\"inf\") minVector = Vector(float(\"inf\"),float(\"inf\"),float(\"inf\")) numTriangles = 0 if", "Vector(float(\"inf\"),float(\"inf\"),float(\"inf\")) numTriangles = 0 if swapYZ: matrix = Matrix( (1,0,0),", "tuple(decimal(x,digitsAfterDecimal) for x in v) ) i += 1 line", "+= \",\".join(points) line += \"], faces=[\" line += \",\".join( \"[\"", "vertex = matrix*vertex minVector = Vector(min(minVector[i], vertex[i]) for i in", "polys: if colorOverride != \"\" and (colorOverride or rgb): line", "or a list of (color,triangle) pairs (TODO: currently uses first", "(\"[%s,%s,%s]\") % tuple(decimal(x,digitsAfterDecimal) for x in v) ) i +=", "swapped? quiet: give no status message if set \"\"\" mesh", "in v) ) i += 1 line += \",\".join(points) line", "mesh, swapYZ=False, quiet=False): \"\"\" filename: filename to save STL file", "(rgb[0] >> 3) << 10 ) | ( (rgb[1] >>", "set \"\"\" if not quiet: sys.stderr.write(\"Saving %s\\n\" % filename) if", "sys.stderr.write(\"Saving %s\\n\" % filename) if filename: with open(filename, \"w\") as", "\"\"\" filename: filename to save STL file mesh: list of", "0 if swapYZ: matrix = Matrix( (1,0,0), (0,0,-1), (0,1,0) )", "if rgb is not None: mono = False numTriangles +=", "import sys try: basestring except: basestring = str def isColorTriangleList(polys):", "\" pointsDict = {} i = 0 line += \"polyhedron(points=[\"", "color = 0 else: if rgb is None: rgb =", "in polys: if colorOverride != \"\" and (colorOverride or rgb):", "= 0 else: if rgb is None: rgb = (255,255,255)", "( (rgb[1] >> 3) << 5 ) | ( (rgb[2]", "list of (color,triangle) pairs (counterclockwise) swapYZ: should Y/Z axes be", "!= \"\" and (colorOverride or rgb): line = \" color(%s)", "else: line = \" \" pointsDict = {} i =", "(rgb[2] >> 3) << 0 ) normal = (Vector(tri[1])-Vector(tri[0])).cross(Vector(tri[2])-Vector(tri[0])).normalize() write(pack(\"<3f\",", "[] for rgb,polyhedron in polys: for face in polyhedron: output.append((rgb,face))", "= False numTriangles += 1 for vertex in triangle: vertex", "for face in polyhedron: output.append((rgb,face)) return output def describeColor(c): if", "else: if rgb is None: rgb = (255,255,255) else: rgb", "open(filename, \"wb\") as f: writeSTL(f.write) else: if sys.platform == \"win32\":", "mono = False numTriangles += 1 for vertex in triangle:", "Vector(0.001,0.001,0.001) # make sure all STL coordinates are strictly positive", "\");\" scad.append(line) scad.append(\"}\\n\") return \"\\n\".join(scad) def saveSCAD(filename, polys, moduleName=\"object1\", quiet=False):", ">> 3) << 5 ) | ( (rgb[2] >> 3)", "float(\"inf\") minVector = Vector(float(\"inf\"),float(\"inf\"),float(\"inf\")) numTriangles = 0 if swapYZ: matrix", "write OpenSCAD file polys: list of (color,polyhedra) pairs (counterclockwise triangles)", "code implementing the polys \"\"\" polys = toPolyhedra(polys) scad =", "(counterclockwise triangles) moduleName: OpenSCAD module name quiet: give no status", "not in pointsDict: pointsDict[tuple(v)] = i points.append( (\"[%s,%s,%s]\") % tuple(decimal(x,digitsAfterDecimal)", "quiet=False): \"\"\" filename: filename to write OpenSCAD file polys: list", "v in reversed(face)) + \"]\" for face in poly )", "try: basestring except: basestring = str def isColorTriangleList(polys): return isinstance(polys[0][1][0][0],", "if sys.platform == \"win32\": import msvcrt msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY) writeSTL(lambda data", "if isColorTriangleList(polys): return [ (polys[0][0], list(face for rgb,face in polys))", "matrix = Matrix( (1,0,0), (0,0,-1), (0,1,0) ) else: matrix =", "0 else: if rgb is None: rgb = (255,255,255) else:", "output def describeColor(c): if c is None: return \"undef\"; elif", "polys = toPolyhedra(polys) scad = [] scad.append(\"module \" +moduleName+ \"()", "% tuple(decimal(component) for component in c) def toSCADModule(polys, moduleName, digitsAfterDecimal=9,", "give no status message if set \"\"\" mesh = toMesh(mesh)", "output = [] for rgb,polyhedron in polys: for face in", "in rgb) color = 0x8000 | ( (rgb[0] >> 3)", "matrix = Matrix.identity(3) mono = True for rgb,triangle in mesh:", ") | ( (rgb[1] >> 3) << 5 ) |", "coordinates are strictly positive as per Wikipedia def writeSTL(write): write(pack(\"80s\",b''))", "def toPolyhedra(polys): if isColorTriangleList(polys): return [ (polys[0][0], list(face for rgb,face", "for vertex in triangle: vertex = matrix*vertex minVector = Vector(min(minVector[i],", "def describeColor(c): if c is None: return \"undef\"; elif isinstance(c,", "\"\"\" filename: filename to write OpenSCAD file polys: list of", "%s\\n\" % filename) minY = float(\"inf\") minVector = Vector(float(\"inf\"),float(\"inf\"),float(\"inf\")) numTriangles", "isinstance(polys[0][1][0][0], Number) def toPolyhedra(polys): if isColorTriangleList(polys): return [ (polys[0][0], list(face", "for i in range(3)) minVector -= Vector(0.001,0.001,0.001) # make sure", "else tuple(min(max(c,0.),1.0) for c in rgb)) else: line = \"", "\"\" and (colorOverride or rgb): line = \" color(%s) \"", "in pointsDict: pointsDict[tuple(v)] = i points.append( (\"[%s,%s,%s]\") % tuple(decimal(x,digitsAfterDecimal) for", "mesh = toMesh(mesh) if not quiet: sys.stderr.write(\"Saving %s\\n\" % filename)", "else: return \"[%s,%s,%s]\" % tuple(decimal(component) for component in c) def", "scad.append(\"module \" +moduleName+ \"() {\") for rgb,poly in polys: if", "return c else: return \"[%s,%s,%s]\" % tuple(decimal(component) for component in", "= toMesh(mesh) if not quiet: sys.stderr.write(\"Saving %s\\n\" % filename) minY", "(counterclockwise triangles), or a list of (color,triangle) pairs (TODO: currently", "(colorOverride or rgb): line = \" color(%s) \" % describeColor(colorOverride", "= {} i = 0 line += \"polyhedron(points=[\" points =", "= \" \" pointsDict = {} i = 0 line", "if set \"\"\" mesh = toMesh(mesh) if not quiet: sys.stderr.write(\"Saving", ".formatdecimal import decimal from numbers import Number import os import", "moduleName: OpenSCAD module name quiet: give no status message if", "if swapYZ: matrix = Matrix( (1,0,0), (0,0,-1), (0,1,0) ) else:", "return polys def toMesh(polys): if isColorTriangleList(polys): return polys else: output", "(polys[0][0], list(face for rgb,face in polys)) ] else: return polys", "of (color,triangle) pairs (TODO: currently uses first color for all", "= Matrix.identity(3) mono = True for rgb,triangle in mesh: if", "return \"\\n\".join(scad) def saveSCAD(filename, polys, moduleName=\"object1\", quiet=False): \"\"\" filename: filename", "\"\"\" INPUT: polys: list of (color,polyhedra) pairs (counterclockwise triangles), or", "not quiet: sys.stderr.write(\"Saving %s\\n\" % filename) if filename: with open(filename,", "+moduleName+ \"() {\") for rgb,poly in polys: if colorOverride !=", "is None: rgb = (255,255,255) else: rgb = tuple(min(255,max(0,int(0.5 +", "| ( (rgb[2] >> 3) << 0 ) normal =", "polys else: output = [] for rgb,polyhedron in polys: for", "rgb,poly in polys: if colorOverride != \"\" and (colorOverride or", "except: basestring = str def isColorTriangleList(polys): return isinstance(polys[0][1][0][0], Number) def", "be swapped? quiet: give no status message if set \"\"\"", "minVector = Vector(float(\"inf\"),float(\"inf\"),float(\"inf\")) numTriangles = 0 if swapYZ: matrix =", "saveSTL(filename, mesh, swapYZ=False, quiet=False): \"\"\" filename: filename to save STL", "\"\"\" mesh = toMesh(mesh) if not quiet: sys.stderr.write(\"Saving %s\\n\" %", "+ \"]\" line += \");\" scad.append(line) scad.append(\"}\\n\") return \"\\n\".join(scad) def", "line = \" color(%s) \" % describeColor(colorOverride if colorOverride else", "pairs (counterclockwise) swapYZ: should Y/Z axes be swapped? quiet: give", "filename: with open(filename, \"w\") as f: f.write(toSCADModule(polys, moduleName)) f.write(\"\\n\" +", "as per Wikipedia def writeSTL(write): write(pack(\"80s\",b'')) write(pack(\"<I\",numTriangles)) for rgb,tri in", "filename to save STL file mesh: list of (color,triangle) pairs", "should Y/Z axes be swapped? quiet: give no status message", "line += \"], faces=[\" line += \",\".join( \"[\" + \",\".join(str(pointsDict[tuple(v)])", ") else: matrix = Matrix.identity(3) mono = True for rgb,triangle", "= (Vector(tri[1])-Vector(tri[0])).cross(Vector(tri[2])-Vector(tri[0])).normalize() write(pack(\"<3f\", *(matrix*normal))) for vertex in tri: write(pack(\"<3f\", *(matrix*(vertex-minVector))))", "with open(filename, \"w\") as f: f.write(toSCADModule(polys, moduleName)) f.write(\"\\n\" + moduleName", "rgb,face in polys)) ] else: return polys def toMesh(polys): if", "tuple(decimal(component) for component in c) def toSCADModule(polys, moduleName, digitsAfterDecimal=9, colorOverride=None):", "0 ) normal = (Vector(tri[1])-Vector(tri[0])).cross(Vector(tri[2])-Vector(tri[0])).normalize() write(pack(\"<3f\", *(matrix*normal))) for vertex in", "writeSTL(write): write(pack(\"80s\",b'')) write(pack(\"<I\",numTriangles)) for rgb,tri in mesh: if mono: color", "if not quiet: sys.stderr.write(\"Saving %s\\n\" % filename) minY = float(\"inf\")", "(0,0,-1), (0,1,0) ) else: matrix = Matrix.identity(3) mono = True", "moduleName)) sys.stdout.write(\"\\n\" + moduleName + \"();\\n\") def saveSTL(filename, mesh, swapYZ=False,", "triangles) moduleName: OpenSCAD module name quiet: give no status message", "are strictly positive as per Wikipedia def writeSTL(write): write(pack(\"80s\",b'')) write(pack(\"<I\",numTriangles))", "in mesh: if mono: color = 0 else: if rgb", "i += 1 line += \",\".join(points) line += \"], faces=[\"", "faces=[\" line += \",\".join( \"[\" + \",\".join(str(pointsDict[tuple(v)]) for v in", "or rgb): line = \" color(%s) \" % describeColor(colorOverride if", "isinstance(c, str): return c else: return \"[%s,%s,%s]\" % tuple(decimal(component) for", "quiet: sys.stderr.write(\"Saving %s\\n\" % filename) minY = float(\"inf\") minVector =" ]
[ "= best_args[ind] model_img = model_images[model_ind] plt.subplot(Q, 6, pos); plt.imshow(np.array(Image.open(model_img)), vmin=0,", "save index for query best_match = np.array(best_match) # array of", "type: 'grayvalue', 'dxdy', 'rgb', 'rg' # # note: use functions", "= rgb2gray(img_color) if hist_isgray else img_color.astype('double') # We compute histogram", "to find out whether histogram function # expects grayvalue or", "distance best_match.append(argmin) # save index for query best_match = np.array(best_match)", "# compute distance for each couple of query - image", "in enumerate(query_hists): for i, model in enumerate(model_hists): D[i, j] =", "Compute hisgoram for each image and add it at the", "j] best_args = np.argsort(query_matches)[:num_nearest] query_img = query_images[j] pos += 1", "query in enumerate(query_hists): for i, model in enumerate(model_hists): D[i, j]", "string which specifies histogram type: 'grayvalue', 'dxdy', 'rgb', 'rg' #", "the top-5 neighbors # ... (your code here) _, D", "hist_type, num_bins): hist_isgray = histogram_module.is_grayvalue_hist(hist_type) model_hists = compute_histograms(model_images, hist_type, hist_isgray,", "5 # show the top-5 neighbors # ... (your code", "in image_list: img_color = np.array(Image.open(img)) # if hist is gray", "for j in range(len(query_images)): query_matches = D[:, j] # get", "dist_module def rgb2gray(rgb): r, g, b = rgb[:, :, 0],", "at the bottom of image_hist # ... (your code here)", "D def compute_histograms(image_list, hist_type, hist_isgray, num_bins): image_hist = [] #", "best_args = np.argsort(query_matches)[:num_nearest] query_img = query_images[j] pos += 1 plt.subplot(Q,", "for img in image_list: img_color = np.array(Image.open(img)) # if hist", "compute_histograms(query_images, hist_type, hist_isgray, num_bins) D = np.zeros((len(model_images), len(query_images))) # compute", "'dxdy', 'rgb', 'rg' # # note: use functions 'get_dist_by_name', 'get_hist_by_name'", "num_bins_gray=num_bins, hist_name=hist_type ) image_hist.append(hist) return image_hist # For each image", "For each image file from 'query_images' find and visualize the", "def rgb2gray(rgb): r, g, b = rgb[:, :, 0], rgb[:,", "query_images, dist_type, hist_type, num_bins): hist_isgray = histogram_module.is_grayvalue_hist(hist_type) model_hists = compute_histograms(model_images,", "- list of file names of query images # #", "range(len(query_images)): query_matches = D[:, j] # get query columns from", "and 'is_grayvalue_hist' to obtain # handles to distance and histogram", "file names of query images # # dist_type - string", "plt import histogram_module import dist_module def rgb2gray(rgb): r, g, b", "j, query in enumerate(query_hists): for i, model in enumerate(model_hists): D[i,", "img in image_list: img_color = np.array(Image.open(img)) # if hist is", "import dist_module def rgb2gray(rgb): r, g, b = rgb[:, :,", "histogram_module.get_hist_by_name(img=img_to_process, num_bins_gray=num_bins, hist_name=hist_type ) image_hist.append(hist) return image_hist # For each", "list of file names of query images # # dist_type", "'get_dist_by_name', 'get_hist_by_name' and 'is_grayvalue_hist' to obtain # handles to distance", "num_nearest = 5 # show the top-5 neighbors # ...", "num_bins): hist_isgray = histogram_module.is_grayvalue_hist(hist_type) model_hists = compute_histograms(model_images, hist_type, hist_isgray, num_bins)", "of best match for each query return best_match, D def", "type we use gray image # othewise rgb image img_to_process", "query_hists = compute_histograms(query_images, hist_type, hist_isgray, num_bins) D = np.zeros((len(model_images), len(query_images)))", "# array of best match for each query return best_match,", "find and visualize the 5 nearest images from 'model_image'. #", "histogram functions, and to find out whether histogram function #", "= compute_histograms(model_images, hist_type, hist_isgray, num_bins) query_hists = compute_histograms(query_images, hist_type, hist_isgray,", "query_images[j] pos += 1 plt.subplot(Q, 6, pos); plt.imshow(np.array(Image.open(query_img)), vmin=0, vmax=255);", "D[:, j] # get query columns from matrix argmin =", "each image file from 'query_images' find and visualize the 5", "the same Python figure, one row per query image def", "(your code here) for img in image_list: img_color = np.array(Image.open(img))", "compute_histograms(model_images, hist_type, hist_isgray, num_bins) query_hists = compute_histograms(query_images, hist_type, hist_isgray, num_bins)", "# query_images - list of file names of query images", "range(Q): query_matches = D[:, j] best_args = np.argsort(query_matches)[:num_nearest] query_img =", "dist_type - string which specifies distance type: 'chi2', 'l2', 'intersect'", "and add it at the bottom of image_hist # ...", "'l2', 'intersect' # hist_type - string which specifies histogram type:", "g + 0.1140 * b return gray # model_images -", "# Note: use subplot command to show all the images", "r + 0.5870 * g + 0.1140 * b return", "'rg' # # note: use functions 'get_dist_by_name', 'get_hist_by_name' and 'is_grayvalue_hist'", "for j in range(Q): query_matches = D[:, j] best_args =", "j] # get query columns from matrix argmin = np.argmin(query_matches)", "j] = dist_module.get_dist_by_name(model, query, dist_type) best_match = [] # to", "return best_match, D def compute_histograms(image_list, hist_type, hist_isgray, num_bins): image_hist =", "0 for j in range(Q): query_matches = D[:, j] best_args", "images # # dist_type - string which specifies distance type:", "# if hist is gray type we use gray image", "pos = 0 for j in range(Q): query_matches = D[:,", "query_images - list of file names of query images #", "plt.figure() num_nearest = 5 # show the top-5 neighbors #", "+ 0.1140 * b return gray # model_images - list", "'find_best_match' # Note: use subplot command to show all the", "model for j in range(len(query_images)): query_matches = D[:, j] #", "the bottom of image_hist # ... (your code here) for", "with minimum distance best_match.append(argmin) # save index for query best_match", "one row per query image def show_neighbors(model_images, query_images, dist_type, hist_type,", "'intersect' # hist_type - string which specifies histogram type: 'grayvalue',", "'model_image'. # # Note: use the previously implemented function 'find_best_match'", "in range(len(best_args)): pos += 1 model_ind = best_args[ind] model_img =", "hist = histogram_module.get_hist_by_name(img=img_to_process, num_bins_gray=num_bins, hist_name=hist_type ) image_hist.append(hist) return image_hist #", "= dist_module.get_dist_by_name(model, query, dist_type) best_match = [] # to save", "in range(len(query_images)): query_matches = D[:, j] # get query columns", "of image_hist # ... (your code here) for img in", "# for each query , find best model for j", "g, b = rgb[:, :, 0], rgb[:, :, 1], rgb[:,", "find_best_match(model_images, query_images, dist_type, hist_type, num_bins): hist_isgray = histogram_module.is_grayvalue_hist(hist_type) model_hists =", "from 'query_images' find and visualize the 5 nearest images from", "'grayvalue', 'dxdy', 'rgb', 'rg' # # note: use functions 'get_dist_by_name',", "D[i, j] = dist_module.get_dist_by_name(model, query, dist_type) best_match = [] #", "to distance and histogram functions, and to find out whether", "np.array(best_match) # array of best match for each query return", "query, dist_type) best_match = [] # to save best matches", "find_best_match(model_images=model_images, query_images=query_images, dist_type=dist_type, hist_type=hist_type, num_bins=num_bins ) Q = len(query_images) pos", "i, model in enumerate(model_hists): D[i, j] = dist_module.get_dist_by_name(model, query, dist_type)", "= np.zeros((len(model_images), len(query_images))) # compute distance for each couple of", "use the previously implemented function 'find_best_match' # Note: use subplot", ":, 1], rgb[:, :, 2] gray = 0.2989 * r", "functions, and to find out whether histogram function # expects", "functions 'get_dist_by_name', 'get_hist_by_name' and 'is_grayvalue_hist' to obtain # handles to", "function # expects grayvalue or color image def find_best_match(model_images, query_images,", "best_match, D def compute_histograms(image_list, hist_type, hist_isgray, num_bins): image_hist = []", "image_hist = [] # Compute hisgoram for each image and", "for image hist = histogram_module.get_hist_by_name(img=img_to_process, num_bins_gray=num_bins, hist_name=hist_type ) image_hist.append(hist) return", "subplot command to show all the images in the same", "np.argsort(query_matches)[:num_nearest] query_img = query_images[j] pos += 1 plt.subplot(Q, 6, pos);", "+ 0.5870 * g + 0.1140 * b return gray", "num_bins) D = np.zeros((len(model_images), len(query_images))) # compute distance for each", "find out whether histogram function # expects grayvalue or color", "matplotlib.pyplot as plt import histogram_module import dist_module def rgb2gray(rgb): r,", "obtain # handles to distance and histogram functions, and to", "for each query , find best model for j in", "np.array(Image.open(img)) # if hist is gray type we use gray", "in the same Python figure, one row per query image", "nearest images from 'model_image'. # # Note: use the previously", "show all the images in the same Python figure, one", "img_to_process = rgb2gray(img_color) if hist_isgray else img_color.astype('double') # We compute", "for ind in range(len(best_args)): pos += 1 model_ind = best_args[ind]", "- string which specifies distance type: 'chi2', 'l2', 'intersect' #", "j in range(len(query_images)): query_matches = D[:, j] # get query", "or color image def find_best_match(model_images, query_images, dist_type, hist_type, num_bins): hist_isgray", "0.5870 * g + 0.1140 * b return gray #", "in range(Q): query_matches = D[:, j] best_args = np.argsort(query_matches)[:num_nearest] query_img", "gray # model_images - list of file names of model", ":, 0], rgb[:, :, 1], rgb[:, :, 2] gray =", "each image and add it at the bottom of image_hist", "query image def show_neighbors(model_images, query_images, dist_type, hist_type, num_bins): plt.figure() num_nearest", "from matrix argmin = np.argmin(query_matches) # get index with minimum", "argmin = np.argmin(query_matches) # get index with minimum distance best_match.append(argmin)", "2] gray = 0.2989 * r + 0.5870 * g", "# We compute histogram for image hist = histogram_module.get_hist_by_name(img=img_to_process, num_bins_gray=num_bins,", "'rgb', 'rg' # # note: use functions 'get_dist_by_name', 'get_hist_by_name' and", "D = find_best_match(model_images=model_images, query_images=query_images, dist_type=dist_type, hist_type=hist_type, num_bins=num_bins ) Q =", "show_neighbors(model_images, query_images, dist_type, hist_type, num_bins): plt.figure() num_nearest = 5 #", "which specifies histogram type: 'grayvalue', 'dxdy', 'rgb', 'rg' # #", "image_hist # For each image file from 'query_images' find and", "model_img = model_images[model_ind] plt.subplot(Q, 6, pos); plt.imshow(np.array(Image.open(model_img)), vmin=0, vmax=255); plt.title(f'MO.{model_ind}')", "of file names of model images # query_images - list", "hist_type, hist_isgray, num_bins) query_hists = compute_histograms(query_images, hist_type, hist_isgray, num_bins) D", "row per query image def show_neighbors(model_images, query_images, dist_type, hist_type, num_bins):", "query_matches = D[:, j] best_args = np.argsort(query_matches)[:num_nearest] query_img = query_images[j]", "of query images # # dist_type - string which specifies", "type: 'chi2', 'l2', 'intersect' # hist_type - string which specifies", "histogram function # expects grayvalue or color image def find_best_match(model_images,", "dist_module.get_dist_by_name(model, query, dist_type) best_match = [] # to save best", "best match for each query return best_match, D def compute_histograms(image_list,", "names of model images # query_images - list of file", "# get index with minimum distance best_match.append(argmin) # save index", "histogram_module import dist_module def rgb2gray(rgb): r, g, b = rgb[:,", "vmin=0, vmax=255); plt.title(f'Q{j}') for ind in range(len(best_args)): pos += 1", "ind in range(len(best_args)): pos += 1 model_ind = best_args[ind] model_img", "# For each image file from 'query_images' find and visualize", "# Compute hisgoram for each image and add it at", "[] # Compute hisgoram for each image and add it", "len(query_images) pos = 0 for j in range(Q): query_matches =", "distance for each couple of query - image for j,", "- string which specifies histogram type: 'grayvalue', 'dxdy', 'rgb', 'rg'", "num_bins): plt.figure() num_nearest = 5 # show the top-5 neighbors", "model_ind = best_args[ind] model_img = model_images[model_ind] plt.subplot(Q, 6, pos); plt.imshow(np.array(Image.open(model_img)),", "compute_histograms(image_list, hist_type, hist_isgray, num_bins): image_hist = [] # Compute hisgoram", "_, D = find_best_match(model_images=model_images, query_images=query_images, dist_type=dist_type, hist_type=hist_type, num_bins=num_bins ) Q", "# ... (your code here) for img in image_list: img_color", "= 5 # show the top-5 neighbors # ... (your", "histogram_module.is_grayvalue_hist(hist_type) model_hists = compute_histograms(model_images, hist_type, hist_isgray, num_bins) query_hists = compute_histograms(query_images,", "is gray type we use gray image # othewise rgb", "find best model for j in range(len(query_images)): query_matches = D[:,", "function 'find_best_match' # Note: use subplot command to show all", "= D[:, j] best_args = np.argsort(query_matches)[:num_nearest] query_img = query_images[j] pos", ") image_hist.append(hist) return image_hist # For each image file from", "Python figure, one row per query image def show_neighbors(model_images, query_images,", "hist_type=hist_type, num_bins=num_bins ) Q = len(query_images) pos = 0 for", "+= 1 plt.subplot(Q, 6, pos); plt.imshow(np.array(Image.open(query_img)), vmin=0, vmax=255); plt.title(f'Q{j}') for", "= find_best_match(model_images=model_images, query_images=query_images, dist_type=dist_type, hist_type=hist_type, num_bins=num_bins ) Q = len(query_images)", "bottom of image_hist # ... (your code here) for img", "'chi2', 'l2', 'intersect' # hist_type - string which specifies histogram", "# to save best matches # for each query ,", "previously implemented function 'find_best_match' # Note: use subplot command to", "minimum distance best_match.append(argmin) # save index for query best_match =", "query return best_match, D def compute_histograms(image_list, hist_type, hist_isgray, num_bins): image_hist", "# handles to distance and histogram functions, and to find", "r, g, b = rgb[:, :, 0], rgb[:, :, 1],", "per query image def show_neighbors(model_images, query_images, dist_type, hist_type, num_bins): plt.figure()", "best_match = np.array(best_match) # array of best match for each", "if hist_isgray else img_color.astype('double') # We compute histogram for image", "+= 1 model_ind = best_args[ind] model_img = model_images[model_ind] plt.subplot(Q, 6,", "images from 'model_image'. # # Note: use the previously implemented", "compute distance for each couple of query - image for", "enumerate(model_hists): D[i, j] = dist_module.get_dist_by_name(model, query, dist_type) best_match = []", "as plt import histogram_module import dist_module def rgb2gray(rgb): r, g,", "b return gray # model_images - list of file names", "for each couple of query - image for j, query", "for j, query in enumerate(query_hists): for i, model in enumerate(model_hists):", "numpy as np from PIL import Image import matplotlib.pyplot as", "* r + 0.5870 * g + 0.1140 * b", "match for each query return best_match, D def compute_histograms(image_list, hist_type,", "1 model_ind = best_args[ind] model_img = model_images[model_ind] plt.subplot(Q, 6, pos);", "index for query best_match = np.array(best_match) # array of best", "# show the top-5 neighbors # ... (your code here)", "= np.argsort(query_matches)[:num_nearest] query_img = query_images[j] pos += 1 plt.subplot(Q, 6,", "(your code here) _, D = find_best_match(model_images=model_images, query_images=query_images, dist_type=dist_type, hist_type=hist_type,", "query_matches = D[:, j] # get query columns from matrix", "import matplotlib.pyplot as plt import histogram_module import dist_module def rgb2gray(rgb):", "image for j, query in enumerate(query_hists): for i, model in", "# Note: use the previously implemented function 'find_best_match' # Note:", "images in the same Python figure, one row per query", "query - image for j, query in enumerate(query_hists): for i,", "len(query_images))) # compute distance for each couple of query -", "note: use functions 'get_dist_by_name', 'get_hist_by_name' and 'is_grayvalue_hist' to obtain #", "import Image import matplotlib.pyplot as plt import histogram_module import dist_module", "query , find best model for j in range(len(query_images)): query_matches", "for each image and add it at the bottom of", "# note: use functions 'get_dist_by_name', 'get_hist_by_name' and 'is_grayvalue_hist' to obtain", "whether histogram function # expects grayvalue or color image def", "color image def find_best_match(model_images, query_images, dist_type, hist_type, num_bins): hist_isgray =", "to obtain # handles to distance and histogram functions, and", "vmax=255); plt.title(f'Q{j}') for ind in range(len(best_args)): pos += 1 model_ind", "np from PIL import Image import matplotlib.pyplot as plt import", "image img_to_process = rgb2gray(img_color) if hist_isgray else img_color.astype('double') # We", "= len(query_images) pos = 0 for j in range(Q): query_matches", "couple of query - image for j, query in enumerate(query_hists):", "each query return best_match, D def compute_histograms(image_list, hist_type, hist_isgray, num_bins):", "the images in the same Python figure, one row per", "histogram type: 'grayvalue', 'dxdy', 'rgb', 'rg' # # note: use", "hist_isgray, num_bins) query_hists = compute_histograms(query_images, hist_type, hist_isgray, num_bins) D =", "PIL import Image import matplotlib.pyplot as plt import histogram_module import", "img_color.astype('double') # We compute histogram for image hist = histogram_module.get_hist_by_name(img=img_to_process,", "here) _, D = find_best_match(model_images=model_images, query_images=query_images, dist_type=dist_type, hist_type=hist_type, num_bins=num_bins )", "hist is gray type we use gray image # othewise", "image_hist.append(hist) return image_hist # For each image file from 'query_images'", "to save best matches # for each query , find", "compute histogram for image hist = histogram_module.get_hist_by_name(img=img_to_process, num_bins_gray=num_bins, hist_name=hist_type )", "the 5 nearest images from 'model_image'. # # Note: use", "hisgoram for each image and add it at the bottom", "specifies histogram type: 'grayvalue', 'dxdy', 'rgb', 'rg' # # note:", ", find best model for j in range(len(query_images)): query_matches =", "of model images # query_images - list of file names", "specifies distance type: 'chi2', 'l2', 'intersect' # hist_type - string", "matches # for each query , find best model for", "= [] # to save best matches # for each", "query_img = query_images[j] pos += 1 plt.subplot(Q, 6, pos); plt.imshow(np.array(Image.open(query_img)),", "# model_images - list of file names of model images", "of query - image for j, query in enumerate(query_hists): for", "1 plt.subplot(Q, 6, pos); plt.imshow(np.array(Image.open(query_img)), vmin=0, vmax=255); plt.title(f'Q{j}') for ind", "[] # to save best matches # for each query", "pos += 1 plt.subplot(Q, 6, pos); plt.imshow(np.array(Image.open(query_img)), vmin=0, vmax=255); plt.title(f'Q{j}')", "figure, one row per query image def show_neighbors(model_images, query_images, dist_type,", ") Q = len(query_images) pos = 0 for j in", "D[:, j] best_args = np.argsort(query_matches)[:num_nearest] query_img = query_images[j] pos +=", "return image_hist # For each image file from 'query_images' find", "... (your code here) _, D = find_best_match(model_images=model_images, query_images=query_images, dist_type=dist_type,", "query images # # dist_type - string which specifies distance", "plt.title(f'Q{j}') for ind in range(len(best_args)): pos += 1 model_ind =", "hist_type - string which specifies histogram type: 'grayvalue', 'dxdy', 'rgb',", "import numpy as np from PIL import Image import matplotlib.pyplot", "for each query return best_match, D def compute_histograms(image_list, hist_type, hist_isgray,", "use subplot command to show all the images in the", "to show all the images in the same Python figure,", "and histogram functions, and to find out whether histogram function", "rgb[:, :, 2] gray = 0.2989 * r + 0.5870", "0.2989 * r + 0.5870 * g + 0.1140 *", "if hist is gray type we use gray image #", "for query best_match = np.array(best_match) # array of best match", "Note: use subplot command to show all the images in", "query columns from matrix argmin = np.argmin(query_matches) # get index", "= rgb[:, :, 0], rgb[:, :, 1], rgb[:, :, 2]", "array of best match for each query return best_match, D", "= D[:, j] # get query columns from matrix argmin", "= 0 for j in range(Q): query_matches = D[:, j]", "image hist = histogram_module.get_hist_by_name(img=img_to_process, num_bins_gray=num_bins, hist_name=hist_type ) image_hist.append(hist) return image_hist", "# expects grayvalue or color image def find_best_match(model_images, query_images, dist_type,", "hist_isgray else img_color.astype('double') # We compute histogram for image hist", "pos += 1 model_ind = best_args[ind] model_img = model_images[model_ind] plt.subplot(Q,", "0], rgb[:, :, 1], rgb[:, :, 2] gray = 0.2989", "np.argmin(query_matches) # get index with minimum distance best_match.append(argmin) # save", "# othewise rgb image img_to_process = rgb2gray(img_color) if hist_isgray else", "'query_images' find and visualize the 5 nearest images from 'model_image'.", "and to find out whether histogram function # expects grayvalue", "here) for img in image_list: img_color = np.array(Image.open(img)) # if", "dist_type, hist_type, num_bins): hist_isgray = histogram_module.is_grayvalue_hist(hist_type) model_hists = compute_histograms(model_images, hist_type,", "each couple of query - image for j, query in", "each query , find best model for j in range(len(query_images)):", "D = np.zeros((len(model_images), len(query_images))) # compute distance for each couple", "hist_type, hist_isgray, num_bins): image_hist = [] # Compute hisgoram for", "hist_isgray, num_bins): image_hist = [] # Compute hisgoram for each", "distance and histogram functions, and to find out whether histogram", "'is_grayvalue_hist' to obtain # handles to distance and histogram functions,", "enumerate(query_hists): for i, model in enumerate(model_hists): D[i, j] = dist_module.get_dist_by_name(model,", "hist_name=hist_type ) image_hist.append(hist) return image_hist # For each image file", "string which specifies distance type: 'chi2', 'l2', 'intersect' # hist_type", "def find_best_match(model_images, query_images, dist_type, hist_type, num_bins): hist_isgray = histogram_module.is_grayvalue_hist(hist_type) model_hists", "model images # query_images - list of file names of", "= histogram_module.is_grayvalue_hist(hist_type) model_hists = compute_histograms(model_images, hist_type, hist_isgray, num_bins) query_hists =", "image def find_best_match(model_images, query_images, dist_type, hist_type, num_bins): hist_isgray = histogram_module.is_grayvalue_hist(hist_type)", "neighbors # ... (your code here) _, D = find_best_match(model_images=model_images,", "range(len(best_args)): pos += 1 model_ind = best_args[ind] model_img = model_images[model_ind]", "show the top-5 neighbors # ... (your code here) _,", "Image import matplotlib.pyplot as plt import histogram_module import dist_module def", "import histogram_module import dist_module def rgb2gray(rgb): r, g, b =", "add it at the bottom of image_hist # ... (your", "query_images, dist_type, hist_type, num_bins): plt.figure() num_nearest = 5 # show", "hist_type, num_bins): plt.figure() num_nearest = 5 # show the top-5", "get index with minimum distance best_match.append(argmin) # save index for", "rgb2gray(rgb): r, g, b = rgb[:, :, 0], rgb[:, :,", "list of file names of model images # query_images -", ":, 2] gray = 0.2989 * r + 0.5870 *", "from PIL import Image import matplotlib.pyplot as plt import histogram_module", "gray image # othewise rgb image img_to_process = rgb2gray(img_color) if", "image_hist # ... (your code here) for img in image_list:", "plt.subplot(Q, 6, pos); plt.imshow(np.array(Image.open(query_img)), vmin=0, vmax=255); plt.title(f'Q{j}') for ind in", "out whether histogram function # expects grayvalue or color image", "# ... (your code here) _, D = find_best_match(model_images=model_images, query_images=query_images,", "best_match = [] # to save best matches # for", "image def show_neighbors(model_images, query_images, dist_type, hist_type, num_bins): plt.figure() num_nearest =", "use functions 'get_dist_by_name', 'get_hist_by_name' and 'is_grayvalue_hist' to obtain # handles", "columns from matrix argmin = np.argmin(query_matches) # get index with", "command to show all the images in the same Python", "expects grayvalue or color image def find_best_match(model_images, query_images, dist_type, hist_type,", "we use gray image # othewise rgb image img_to_process =", "which specifies distance type: 'chi2', 'l2', 'intersect' # hist_type -", "= np.argmin(query_matches) # get index with minimum distance best_match.append(argmin) #", "all the images in the same Python figure, one row", "img_color = np.array(Image.open(img)) # if hist is gray type we", "= model_images[model_ind] plt.subplot(Q, 6, pos); plt.imshow(np.array(Image.open(model_img)), vmin=0, vmax=255); plt.title(f'MO.{model_ind}') plt.show()", "= np.array(best_match) # array of best match for each query", "= query_images[j] pos += 1 plt.subplot(Q, 6, pos); plt.imshow(np.array(Image.open(query_img)), vmin=0,", "rgb[:, :, 1], rgb[:, :, 2] gray = 0.2989 *", "np.zeros((len(model_images), len(query_images))) # compute distance for each couple of query", "model_images - list of file names of model images #", "= [] # Compute hisgoram for each image and add", "matrix argmin = np.argmin(query_matches) # get index with minimum distance", "image_list: img_color = np.array(Image.open(img)) # if hist is gray type", "# # dist_type - string which specifies distance type: 'chi2',", "model_hists = compute_histograms(model_images, hist_type, hist_isgray, num_bins) query_hists = compute_histograms(query_images, hist_type,", "def show_neighbors(model_images, query_images, dist_type, hist_type, num_bins): plt.figure() num_nearest = 5", "5 nearest images from 'model_image'. # # Note: use the", "... (your code here) for img in image_list: img_color =", "rgb image img_to_process = rgb2gray(img_color) if hist_isgray else img_color.astype('double') #", "num_bins) query_hists = compute_histograms(query_images, hist_type, hist_isgray, num_bins) D = np.zeros((len(model_images),", "rgb2gray(img_color) if hist_isgray else img_color.astype('double') # We compute histogram for", "file from 'query_images' find and visualize the 5 nearest images", "= compute_histograms(query_images, hist_type, hist_isgray, num_bins) D = np.zeros((len(model_images), len(query_images))) #", "query_images=query_images, dist_type=dist_type, hist_type=hist_type, num_bins=num_bins ) Q = len(query_images) pos =", "dist_type=dist_type, hist_type=hist_type, num_bins=num_bins ) Q = len(query_images) pos = 0", "images # query_images - list of file names of query", "1], rgb[:, :, 2] gray = 0.2989 * r +", "code here) for img in image_list: img_color = np.array(Image.open(img)) #", "get query columns from matrix argmin = np.argmin(query_matches) # get", "gray = 0.2989 * r + 0.5870 * g +", "it at the bottom of image_hist # ... (your code", "query best_match = np.array(best_match) # array of best match for", "othewise rgb image img_to_process = rgb2gray(img_color) if hist_isgray else img_color.astype('double')", "implemented function 'find_best_match' # Note: use subplot command to show", "best_args[ind] model_img = model_images[model_ind] plt.subplot(Q, 6, pos); plt.imshow(np.array(Image.open(model_img)), vmin=0, vmax=255);", "the previously implemented function 'find_best_match' # Note: use subplot command", "# hist_type - string which specifies histogram type: 'grayvalue', 'dxdy',", "hist_isgray = histogram_module.is_grayvalue_hist(hist_type) model_hists = compute_histograms(model_images, hist_type, hist_isgray, num_bins) query_hists", "pos); plt.imshow(np.array(Image.open(query_img)), vmin=0, vmax=255); plt.title(f'Q{j}') for ind in range(len(best_args)): pos", "hist_type, hist_isgray, num_bins) D = np.zeros((len(model_images), len(query_images))) # compute distance", "of file names of query images # # dist_type -", "- list of file names of model images # query_images", "from 'model_image'. # # Note: use the previously implemented function", "save best matches # for each query , find best", "for i, model in enumerate(model_hists): D[i, j] = dist_module.get_dist_by_name(model, query,", "We compute histogram for image hist = histogram_module.get_hist_by_name(img=img_to_process, num_bins_gray=num_bins, hist_name=hist_type", "top-5 neighbors # ... (your code here) _, D =", "'get_hist_by_name' and 'is_grayvalue_hist' to obtain # handles to distance and", "0.1140 * b return gray # model_images - list of", "# # Note: use the previously implemented function 'find_best_match' #", "same Python figure, one row per query image def show_neighbors(model_images,", "j in range(Q): query_matches = D[:, j] best_args = np.argsort(query_matches)[:num_nearest]", "image file from 'query_images' find and visualize the 5 nearest", "histogram for image hist = histogram_module.get_hist_by_name(img=img_to_process, num_bins_gray=num_bins, hist_name=hist_type ) image_hist.append(hist)", "and visualize the 5 nearest images from 'model_image'. # #", "plt.imshow(np.array(Image.open(query_img)), vmin=0, vmax=255); plt.title(f'Q{j}') for ind in range(len(best_args)): pos +=", "* b return gray # model_images - list of file", "hist_isgray, num_bins) D = np.zeros((len(model_images), len(query_images))) # compute distance for", "index with minimum distance best_match.append(argmin) # save index for query", "dist_type) best_match = [] # to save best matches #", "# # note: use functions 'get_dist_by_name', 'get_hist_by_name' and 'is_grayvalue_hist' to", "return gray # model_images - list of file names of", "in enumerate(model_hists): D[i, j] = dist_module.get_dist_by_name(model, query, dist_type) best_match =", "as np from PIL import Image import matplotlib.pyplot as plt", "best matches # for each query , find best model", "num_bins): image_hist = [] # Compute hisgoram for each image", "image and add it at the bottom of image_hist #", "grayvalue or color image def find_best_match(model_images, query_images, dist_type, hist_type, num_bins):", "image # othewise rgb image img_to_process = rgb2gray(img_color) if hist_isgray", "- image for j, query in enumerate(query_hists): for i, model", "Note: use the previously implemented function 'find_best_match' # Note: use", "handles to distance and histogram functions, and to find out", "* g + 0.1140 * b return gray # model_images", "visualize the 5 nearest images from 'model_image'. # # Note:", "def compute_histograms(image_list, hist_type, hist_isgray, num_bins): image_hist = [] # Compute", "= np.array(Image.open(img)) # if hist is gray type we use", "rgb[:, :, 0], rgb[:, :, 1], rgb[:, :, 2] gray", "Q = len(query_images) pos = 0 for j in range(Q):", "best_match.append(argmin) # save index for query best_match = np.array(best_match) #", "# get query columns from matrix argmin = np.argmin(query_matches) #", "file names of model images # query_images - list of", "names of query images # # dist_type - string which", "gray type we use gray image # othewise rgb image", "= 0.2989 * r + 0.5870 * g + 0.1140", "best model for j in range(len(query_images)): query_matches = D[:, j]", "num_bins=num_bins ) Q = len(query_images) pos = 0 for j", "b = rgb[:, :, 0], rgb[:, :, 1], rgb[:, :,", "distance type: 'chi2', 'l2', 'intersect' # hist_type - string which", "model in enumerate(model_hists): D[i, j] = dist_module.get_dist_by_name(model, query, dist_type) best_match", "dist_type, hist_type, num_bins): plt.figure() num_nearest = 5 # show the", "# save index for query best_match = np.array(best_match) # array", "use gray image # othewise rgb image img_to_process = rgb2gray(img_color)", "else img_color.astype('double') # We compute histogram for image hist =", "# dist_type - string which specifies distance type: 'chi2', 'l2',", "code here) _, D = find_best_match(model_images=model_images, query_images=query_images, dist_type=dist_type, hist_type=hist_type, num_bins=num_bins", "= histogram_module.get_hist_by_name(img=img_to_process, num_bins_gray=num_bins, hist_name=hist_type ) image_hist.append(hist) return image_hist # For", "6, pos); plt.imshow(np.array(Image.open(query_img)), vmin=0, vmax=255); plt.title(f'Q{j}') for ind in range(len(best_args)):" ]
[ "produce a .md or .adoc file in single-column to be", "will have to install asciidoc3, of course)') arg_parser.add_argument('-e', '--escape-html', action='store_true',", "processed externally') args = arg_parser.parse_args() sys.exit(main(args.source_file, args.output_dir, args.use_ascii, args.escape_html, args.single_file))", "main(paths, output_dir, use_ascii:bool, escape_html:bool, single_file:bool): try: document(paths, output_dir, use_ascii, escape_html,", "'--single-file', action='store_true', default=False, dest='single_file', help='Just produce a .md or .adoc", "if necessary)') arg_parser.add_argument('-a', '--asciidoc3', action='store_true', default=False, dest='use_ascii', help='Process with asciidoc3", "arg_parser.add_argument('-e', '--escape-html', action='store_true', default=False, dest='escape_html', help='Run the documentation through html.escape()", "action='store_true', default=False, dest='use_ascii', help='Process with asciidoc3 instead of markdown (you", "or asciidoc3') arg_parser.add_argument('-f', '--single-file', action='store_true', default=False, dest='single_file', help='Just produce a", "except IOError as e: logging.error('Unable to open file: %s', e)", "dest='escape_html', help='Run the documentation through html.escape() before markdown or asciidoc3')", "use_ascii, escape_html, single_file) except IOError as e: logging.error('Unable to open", "have to install asciidoc3, of course)') arg_parser.add_argument('-e', '--escape-html', action='store_true', default=False,", "instead of markdown (you will have to install asciidoc3, of", "(you will have to install asciidoc3, of course)') arg_parser.add_argument('-e', '--escape-html',", "occurred: %s', e) return 1 else: return 0 if __name__", "html.escape() before markdown or asciidoc3') arg_parser.add_argument('-f', '--single-file', action='store_true', default=False, dest='single_file',", "in single-column to be processed externally') args = arg_parser.parse_args() sys.exit(main(args.source_file,", "if __name__ == '__main__': arg_parser = argparse.ArgumentParser(prog='dycco', description='Literate-style documentation generator.')", "arg_parser.add_argument('-o', '--output-dir', default='docs', help='Output directory (will be created if necessary)')", "through html.escape() before markdown or asciidoc3') arg_parser.add_argument('-f', '--single-file', action='store_true', default=False,", "necessary)') arg_parser.add_argument('-a', '--asciidoc3', action='store_true', default=False, dest='use_ascii', help='Process with asciidoc3 instead", "to install asciidoc3, of course)') arg_parser.add_argument('-e', '--escape-html', action='store_true', default=False, dest='escape_html',", "to be processed externally') args = arg_parser.parse_args() sys.exit(main(args.source_file, args.output_dir, args.use_ascii,", "action='store_true', default=False, dest='single_file', help='Just produce a .md or .adoc file", "default=False, dest='use_ascii', help='Process with asciidoc3 instead of markdown (you will", "error occurred: %s', e) return 1 else: return 0 if", "1 else: return 0 if __name__ == '__main__': arg_parser =", "of markdown (you will have to install asciidoc3, of course)')", "install asciidoc3, of course)') arg_parser.add_argument('-e', '--escape-html', action='store_true', default=False, dest='escape_html', help='Run", "e: logging.error('An error occurred: %s', e) return 1 else: return", "single-column to be processed externally') args = arg_parser.parse_args() sys.exit(main(args.source_file, args.output_dir,", "as e: logging.error('Unable to open file: %s', e) return 1", "sys from .dycco import document def main(paths, output_dir, use_ascii:bool, escape_html:bool,", "__name__ == '__main__': arg_parser = argparse.ArgumentParser(prog='dycco', description='Literate-style documentation generator.') arg_parser.add_argument('source_file',", "documentation generator.') arg_parser.add_argument('source_file', nargs='+', default=sys.stdin, help='Source files to document') arg_parser.add_argument('-o',", "import document def main(paths, output_dir, use_ascii:bool, escape_html:bool, single_file:bool): try: document(paths,", "return 1 except Exception as e: logging.error('An error occurred: %s',", "def main(paths, output_dir, use_ascii:bool, escape_html:bool, single_file:bool): try: document(paths, output_dir, use_ascii,", "== '__main__': arg_parser = argparse.ArgumentParser(prog='dycco', description='Literate-style documentation generator.') arg_parser.add_argument('source_file', nargs='+',", "of course)') arg_parser.add_argument('-e', '--escape-html', action='store_true', default=False, dest='escape_html', help='Run the documentation", "single_file) except IOError as e: logging.error('Unable to open file: %s',", "'--output-dir', default='docs', help='Output directory (will be created if necessary)') arg_parser.add_argument('-a',", "be created if necessary)') arg_parser.add_argument('-a', '--asciidoc3', action='store_true', default=False, dest='use_ascii', help='Process", "asciidoc3') arg_parser.add_argument('-f', '--single-file', action='store_true', default=False, dest='single_file', help='Just produce a .md", "default=False, dest='escape_html', help='Run the documentation through html.escape() before markdown or", "default='docs', help='Output directory (will be created if necessary)') arg_parser.add_argument('-a', '--asciidoc3',", "single_file:bool): try: document(paths, output_dir, use_ascii, escape_html, single_file) except IOError as", "output_dir, use_ascii, escape_html, single_file) except IOError as e: logging.error('Unable to", "to document') arg_parser.add_argument('-o', '--output-dir', default='docs', help='Output directory (will be created", "directory (will be created if necessary)') arg_parser.add_argument('-a', '--asciidoc3', action='store_true', default=False,", "dest='single_file', help='Just produce a .md or .adoc file in single-column", "document(paths, output_dir, use_ascii, escape_html, single_file) except IOError as e: logging.error('Unable", "'--escape-html', action='store_true', default=False, dest='escape_html', help='Run the documentation through html.escape() before", ".adoc file in single-column to be processed externally') args =", "open file: %s', e) return 1 except Exception as e:", "escape_html, single_file) except IOError as e: logging.error('Unable to open file:", "markdown or asciidoc3') arg_parser.add_argument('-f', '--single-file', action='store_true', default=False, dest='single_file', help='Just produce", "return 0 if __name__ == '__main__': arg_parser = argparse.ArgumentParser(prog='dycco', description='Literate-style", "be processed externally') args = arg_parser.parse_args() sys.exit(main(args.source_file, args.output_dir, args.use_ascii, args.escape_html,", "help='Output directory (will be created if necessary)') arg_parser.add_argument('-a', '--asciidoc3', action='store_true',", "nargs='+', default=sys.stdin, help='Source files to document') arg_parser.add_argument('-o', '--output-dir', default='docs', help='Output", "0 if __name__ == '__main__': arg_parser = argparse.ArgumentParser(prog='dycco', description='Literate-style documentation", "arg_parser = argparse.ArgumentParser(prog='dycco', description='Literate-style documentation generator.') arg_parser.add_argument('source_file', nargs='+', default=sys.stdin, help='Source", "the documentation through html.escape() before markdown or asciidoc3') arg_parser.add_argument('-f', '--single-file',", "help='Process with asciidoc3 instead of markdown (you will have to", "'__main__': arg_parser = argparse.ArgumentParser(prog='dycco', description='Literate-style documentation generator.') arg_parser.add_argument('source_file', nargs='+', default=sys.stdin,", "import logging import sys from .dycco import document def main(paths,", "except Exception as e: logging.error('An error occurred: %s', e) return", "file in single-column to be processed externally') args = arg_parser.parse_args()", "1 except Exception as e: logging.error('An error occurred: %s', e)", "asciidoc3, of course)') arg_parser.add_argument('-e', '--escape-html', action='store_true', default=False, dest='escape_html', help='Run the", "arg_parser.add_argument('source_file', nargs='+', default=sys.stdin, help='Source files to document') arg_parser.add_argument('-o', '--output-dir', default='docs',", "with asciidoc3 instead of markdown (you will have to install", "generator.') arg_parser.add_argument('source_file', nargs='+', default=sys.stdin, help='Source files to document') arg_parser.add_argument('-o', '--output-dir',", "created if necessary)') arg_parser.add_argument('-a', '--asciidoc3', action='store_true', default=False, dest='use_ascii', help='Process with", "or .adoc file in single-column to be processed externally') args", ".md or .adoc file in single-column to be processed externally')", "logging.error('Unable to open file: %s', e) return 1 except Exception", "to open file: %s', e) return 1 except Exception as", "description='Literate-style documentation generator.') arg_parser.add_argument('source_file', nargs='+', default=sys.stdin, help='Source files to document')", "default=sys.stdin, help='Source files to document') arg_parser.add_argument('-o', '--output-dir', default='docs', help='Output directory", "course)') arg_parser.add_argument('-e', '--escape-html', action='store_true', default=False, dest='escape_html', help='Run the documentation through", "asciidoc3 instead of markdown (you will have to install asciidoc3,", "argparse.ArgumentParser(prog='dycco', description='Literate-style documentation generator.') arg_parser.add_argument('source_file', nargs='+', default=sys.stdin, help='Source files to", "argparse import logging import sys from .dycco import document def", "escape_html:bool, single_file:bool): try: document(paths, output_dir, use_ascii, escape_html, single_file) except IOError", "action='store_true', default=False, dest='escape_html', help='Run the documentation through html.escape() before markdown", "file: %s', e) return 1 except Exception as e: logging.error('An", "default=False, dest='single_file', help='Just produce a .md or .adoc file in", "e) return 1 else: return 0 if __name__ == '__main__':", "files to document') arg_parser.add_argument('-o', '--output-dir', default='docs', help='Output directory (will be", "else: return 0 if __name__ == '__main__': arg_parser = argparse.ArgumentParser(prog='dycco',", "document def main(paths, output_dir, use_ascii:bool, escape_html:bool, single_file:bool): try: document(paths, output_dir,", "try: document(paths, output_dir, use_ascii, escape_html, single_file) except IOError as e:", "output_dir, use_ascii:bool, escape_html:bool, single_file:bool): try: document(paths, output_dir, use_ascii, escape_html, single_file)", "= argparse.ArgumentParser(prog='dycco', description='Literate-style documentation generator.') arg_parser.add_argument('source_file', nargs='+', default=sys.stdin, help='Source files", "use_ascii:bool, escape_html:bool, single_file:bool): try: document(paths, output_dir, use_ascii, escape_html, single_file) except", "e: logging.error('Unable to open file: %s', e) return 1 except", "%s', e) return 1 except Exception as e: logging.error('An error", "arg_parser.add_argument('-a', '--asciidoc3', action='store_true', default=False, dest='use_ascii', help='Process with asciidoc3 instead of", "'--asciidoc3', action='store_true', default=False, dest='use_ascii', help='Process with asciidoc3 instead of markdown", "import argparse import logging import sys from .dycco import document", "<reponame>rojalator/dycco<filename>dycco/__main__.py import argparse import logging import sys from .dycco import", "return 1 else: return 0 if __name__ == '__main__': arg_parser", "document') arg_parser.add_argument('-o', '--output-dir', default='docs', help='Output directory (will be created if", ".dycco import document def main(paths, output_dir, use_ascii:bool, escape_html:bool, single_file:bool): try:", "markdown (you will have to install asciidoc3, of course)') arg_parser.add_argument('-e',", "help='Run the documentation through html.escape() before markdown or asciidoc3') arg_parser.add_argument('-f',", "from .dycco import document def main(paths, output_dir, use_ascii:bool, escape_html:bool, single_file:bool):", "help='Source files to document') arg_parser.add_argument('-o', '--output-dir', default='docs', help='Output directory (will", "import sys from .dycco import document def main(paths, output_dir, use_ascii:bool,", "logging.error('An error occurred: %s', e) return 1 else: return 0", "logging import sys from .dycco import document def main(paths, output_dir,", "(will be created if necessary)') arg_parser.add_argument('-a', '--asciidoc3', action='store_true', default=False, dest='use_ascii',", "Exception as e: logging.error('An error occurred: %s', e) return 1", "%s', e) return 1 else: return 0 if __name__ ==", "IOError as e: logging.error('Unable to open file: %s', e) return", "arg_parser.add_argument('-f', '--single-file', action='store_true', default=False, dest='single_file', help='Just produce a .md or", "documentation through html.escape() before markdown or asciidoc3') arg_parser.add_argument('-f', '--single-file', action='store_true',", "help='Just produce a .md or .adoc file in single-column to", "as e: logging.error('An error occurred: %s', e) return 1 else:", "e) return 1 except Exception as e: logging.error('An error occurred:", "before markdown or asciidoc3') arg_parser.add_argument('-f', '--single-file', action='store_true', default=False, dest='single_file', help='Just", "a .md or .adoc file in single-column to be processed", "dest='use_ascii', help='Process with asciidoc3 instead of markdown (you will have" ]
[ "= np.dtype(dtype).type elif isinstance(dtype, np.dtype): dtype = dtype.type jtype =", "xd, yd in zip(xs, ys): if xd == yd: yt.append(1)", "Nd4j.tile(x, *xt) if rep_y: try: y = Nd4j.tile(y, *yt) except:", "y): xs = x.shape() ys = y.shape() if xs ==", "def __getitem__(self, key): return ndarray(self.numpy()[key]) if type(key) is int: return", "' + str(_ys)) if rep_y: y = y.repmat(*yt) return y", "== np_array.dtype.itemsize strides = np_array.strides strides = [dim / elem_size", "import numpy as np import ctypes import warnings native_ops =", "'Sorry, this type of indexing is not supported yet.') return", "not supported yet.') if type(key) is tuple: key = list(key)", "rep_y: y = y.repmat(*yt) return y def broadcast(x, y): xs", "numpy as np import ctypes import warnings native_ops = NativeOpsHolder.getInstance().getDeviceNativeOps()", "import ops f = getattr(ops, attr) setattr(ndarray, attr, f) return", "pointer = ctypes.cast(address, Pointer) np_array = np.ctypeslib.as_array(pointer, tuple(nd4j_array.shape())) return np_array", "raise NotImplementedError( 'Sorry, this type of indexing is not supported", "= broadcast(self.array, other) return ndarray(x.mul(y)) def __div__(self, other): return ndarray(self.numpy()", "other): return ndarray(self.numpy() ** _nparray(other)) other = _indarray(other) x, y", "return pytype def set_context_dtype(dtype): ''' Sets the dtype for nd4j", "and ' + str(_ys)) if rep_x: x = Nd4j.tile(x, *xt)", "np_array def _indarray(x): typ = type(x) if typ is INDArray:", "DATA TYPE MANAGEMENT DOUBLE = DataType.DOUBLE FLOAT = DataType.FLOAT HALF", "_indarray(other) x, y = broadcast(self.array, other) return ndarray(Transforms.pow(x, y)) def", "in range(len(SUPPORTED_JAVA_DTYPES))} _J2PY = {SUPPORTED_JAVA_DTYPES[i] : SUPPORTED_PYTHON_DTYPES[i] for i in", "yt = [] rep_y = False for xd, yd in", "def __imul__(self, other): self.numpy().__imul__(_nparray(other)) return self other = _indarray(other) if", "[] def _from_numpy(np_array): ''' Convert numpy array to nd4j array", "are made available under the # terms of the Apache", "raise Exception('Data type not understood :' + str(typ)) def broadcast_like(y,", "is tuple: key = list(key) shape = self.array.shape() ndim =", "'double' ''' dtype_map = { 'float32': 'float', 'float64': 'double' }", "INT, SHORT, BOOL #UTF8 ] SUPPORTED_PYTHON_DTYPES = [ np.float64, np.float32,", "nx: raise Exception('Unable to broadcast shapes ' + str(_xs) +", "try: y = Nd4j.tile(y, *yt) except: y = Nd4j.tile(y, *yt)", "ny > nx: raise Exception('Unable to broadcast shapes ' +", "' + str(_xs) + '' ' and ' + str(_ys))", "slice(None): args.append(NDArrayIndex.all()) else: start = dim.start stop = dim.stop step", "is ndarray: self.array = data.array.dup() else: if typ is not", "+ _nparray(other)) other = _indarray(other) x, y = broadcast(self.array, other)", "= _nparray(other) return other = _indarray(other) view = self[key] if", "= DataType.SHORT UBYTE = DataType.UBYTE BYTE = DataType.BYTE BOOL =", "native_ops = NativeOpsHolder.getInstance().getDeviceNativeOps() # DATA TYPE MANAGEMENT DOUBLE = DataType.DOUBLE", "is None or step == 1: args.append(NDArrayIndex.interval(start, stop)) else: args.append(NDArrayIndex.interval(", "array to nd4j array ''' pointer_address, _ = np_array.__array_interface__['data'] _refs.append(np_array)", "HALF, LONG, INT, SHORT, BOOL #UTF8 ] SUPPORTED_PYTHON_DTYPES = [", "now typ = type(data) if 'nd4j' in typ.__name__: # Note", "x elif typ in (list, tuple): return np.array(x) elif typ", "= _indarray(other) x, y = broadcast(self.array, other) return ndarray(x.sub(y)) def", "ndarray(self.numpy() / _nparray(other)) other = _indarray(other) x, y = broadcast(self.array,", "DataTypeUtil.getDTypeForName(dtype) _refs = [] def _from_numpy(np_array): ''' Convert numpy array", "dtype_map = { 'float32': 'float', 'float64': 'double' } dtype =", "_ys = tuple(ys) nx = len(xs) ny = len(ys) if", "in str(typ): return x elif typ in (list, tuple): return", "''' Convert numpy array to nd4j array ''' pointer_address, _", "= dtype_map.get(dtype, dtype) if dtype not in ['float', 'double']: raise", "view) view.assign(other) def __add__(self, other): return ndarray(self.numpy() + _nparray(other)) other", "to broadcast shapes ' + str(_xs) + '' ' and", "attr, f) return getattr(self, attr) def __int__(self): if self.array.length() ==", "self.array.shape() if shape[0] == 1: stop = shape[1] else: stop", "xt.append(1) yt.append(1) elif xd == 1: xt.append(yd) yt.append(1) rep_x =", "np.ndarray: data = np.array(data) self.array = _from_numpy(data) def numpy(self): try:", "'float' and 'double'.\".format(dtype)) dtype_ = DataTypeUtil.getDtypeFromContext(dtype) DataTypeUtil.setDTypeForContext(dtype_) if get_context_dtype() !=", "self.array = x.add(y) return self def __isub__(self, other): self.numpy().__isub__(_nparray(other)) return", "xs = x.shape() ys = y.shape() if xs == ys:", "yt.append(1) elif xd == 1: raise Exception('Unable to broadcast shapes", "y = Nd4j.tile(y, *yt) return x, y class ndarray(object): def", "Nd4j.tile(y, *yt) except: y = Nd4j.tile(y, *yt) return x, y", "''' pointer_address, _ = np_array.__array_interface__['data'] _refs.append(np_array) pointer = native_ops.pointerForAddress(pointer_address) size", "stop)) elif type(dim) in (list, tuple): raise NotImplementedError( 'Sorry, this", "return ndarray(self.numpy() / _nparray(other)) other = _indarray(other) x, y =", "__iadd__(self, other): self.numpy().__iadd__(_nparray(other)) return self other = _indarray(other) if self.array.shape()", "broadcast(self.array, other) self.array = x.add(y) return self def __isub__(self, other):", "UBYTE = DataType.UBYTE BYTE = DataType.BYTE BOOL = DataType.BOOL UTF8", ": SUPPORTED_PYTHON_DTYPES[i] for i in range(len(SUPPORTED_JAVA_DTYPES))} def _dtype_py2j(dtype): if isinstance(dtype,", "the beginning of your program.\") def get_context_dtype(): ''' Returns the", "DOUBLE: DoublePointer, FLOAT: FloatPointer, HALF: HalfPointer, LONG: LongPointer, INT: IntPointer,", "if self.array.shape() == other.shape(): self.array = self.array.divi(other) else: x, y", "Exception('Unable to broadcast shapes ' + str(_xs) + '' '", "= [] rep_y = False for xd, yd in zip(xs,", "to in writing, software # distributed under the License is", "dim.stop step = dim.step if start is None: start =", "elif typ is ndarray: return x.array elif 'numpy' in str(typ):", "arr = self.reshape(value) self.array = arr.array @property def ndim(self): return", "return _from_numpy(np.array(x)) elif typ in (int, float): return Nd4j.scalar(x) else:", "and ' + str(_ys)) yt = [] rep_y = False", "import warnings native_ops = NativeOpsHolder.getInstance().getDeviceNativeOps() # DATA TYPE MANAGEMENT DOUBLE", "or agreed to in writing, software # distributed under the", "shape(self, value): arr = self.reshape(value) self.array = arr.array @property def", "import * import numpy as np import ctypes import warnings", "scalars') @property def T(self): return self.transpose() def array(*args, **kwargs): return", "(int, float): return Nd4j.scalar(x) else: raise Exception('Data type not understood", "= x.shape() ys = y.shape() if xs == ys: return", "= broadcast(self.array, other) self.array = x.sub(y) return self def __imul__(self,", "Returns the nd4j dtype ''' dtype = DataTypeUtil.getDtypeFromContext() return DataTypeUtil.getDTypeForName(dtype)", "'{}'. Available dtypes are 'float' and 'double'.\".format(dtype)) dtype_ = DataTypeUtil.getDtypeFromContext(dtype)", "str(_ys)) yt = [] rep_y = False for xd, yd", "if step is None or step == 1: args.append(NDArrayIndex.interval(start, stop))", "np.array(x) else: raise Exception('Data type not understood :' + str(typ))", "xs == ys: return y _xs = tuple(xs) _ys =", "None: stop = shape[i] if stop - start <= 0:", "len(xs) ny = len(ys) if nx > ny: diff =", "dtype.type jtype = _PY2J.get(dtype) if jtype is None: raise NotImplementedError(\"Unsupported", "= nd4j_array.data() address = buff.pointer().address() dtype = nd4j_array.dataType().toString() mapping =", "np_array.size pointer.limit(size) jdtype = _dtype_py2j(np_array.dtype) ''' mapping = { DOUBLE:", "'float32': 'float', 'float64': 'double' } dtype = dtype_map.get(dtype, dtype) if", "which is available at # https://www.apache.org/licenses/LICENSE-2.0. # # Unless required", "tuple): return _from_numpy(np.array(x)) elif typ in (int, float): return Nd4j.scalar(x)", "= { 'float32': 'float', 'float64': 'double' } dtype = dtype_map.get(dtype,", "rep_x = True elif yd == 1: xt.append(1) yt.append(xd) rep_y", "now. Set it at the beginning of your program.\") def", "ndarray(object): def __init__(self, data, dtype=None): # we ignore dtype for", "BoolPointer } pc = mapping[jdtype] #pointer = pc(pointer) ''' buff", "def _from_numpy(np_array): ''' Convert numpy array to nd4j array '''", "nd4j dtype ''' dtype = DataTypeUtil.getDtypeFromContext() return DataTypeUtil.getDTypeForName(dtype) _refs =", "+ str(_xs) + '' ' and ' + str(_ys)) if", "x.numpy() elif 'numpy' in str(typ): return x elif typ in", "xd, yd in zip(xs, ys): if xd == yd: xt.append(1)", "float): return np.array(x) else: raise Exception('Data type not understood :'", "dtype = np.dtype(dtype).type elif isinstance(dtype, np.dtype): dtype = dtype.type jtype", "np_array.dtype.itemsize strides = np_array.strides strides = [dim / elem_size for", "1: raise Exception('Unable to broadcast shapes ' + str(_xs) +", "x.reshape(*xs) nx = ny xt = [] yt = []", "Convert numpy array to nd4j array ''' pointer_address, _ =", "_dtype_j2py(dtype): pytype = _J2PY.get(dtype) if pytype is None: raise NotImplementedError(\"Unsupported", "np.ctypeslib.as_array(pointer, tuple(nd4j_array.shape())) return np_array def _indarray(x): typ = type(x) if", "\" + dtype.name) return jtype def _dtype_j2py(dtype): pytype = _J2PY.get(dtype)", "indexing is not supported yet.') return ndarray(self.array.get(*args)) def __setitem__(self, key,", "ndarray(x.add(y)) def __sub__(self, other): return ndarray(self.numpy() - _nparray(other)) other =", "it at the beginning of your program.\") def get_context_dtype(): '''", "Skymind, Inc. # # This program and the accompanying materials", "other): self.numpy().__ipow__(_nparray(other)) return self other = _indarray(other) if self.array.shape() ==", "= _indarray(other) x, y = broadcast(self.array, other) return ndarray(Transforms.pow(x, y))", "_indarray(other) if self.array.shape() == other.shape(): self.array = self.array.addi(other) else: x,", "INT = DataType.INT SHORT = DataType.SHORT UBYTE = DataType.UBYTE BYTE", "COMPRESSED = DataType.COMPRESSED UNKNOWN = DataType.UNKNOWN SUPPORTED_JAVA_DTYPES = [ DOUBLE,", "+ str(typ)) def _nparray(x): typ = type(x) if typ is", "def __float__(self): if self.array.length() == 1: return self.array.getDouble(0) raise Exception('Applicable", "+ '' ' and ' + str(_ys)) elif yd ==", "+= [slice(None)] * (ndim - nk) args = [] for", "License is distributed on an \"AS IS\" BASIS, WITHOUT #", "raise ValueError(\"Invalid dtype '{}'. Available dtypes are 'float' and 'double'.\".format(dtype))", "_J2PY.get(dtype) if pytype is None: raise NotImplementedError(\"Unsupported type: \" +", "stop))) if type(key) is list: raise NotImplementedError( 'Sorry, this type", "buff = nd4j_array.data() address = buff.pointer().address() dtype = nd4j_array.dataType().toString() mapping", "is int: return ndarray(self.array.get(NDArrayIndex.point(key))) if type(key) is slice: start =", "stop = dim.stop step = dim.step if start is None:", "= _indarray(other) if self.array.shape() == other.shape(): self.array = self.array.muli(other) else:", "is None: return view = view.array other = broadcast_like(other, view)", "self.reshape(value) self.array = arr.array @property def ndim(self): return len(self.array.shape()) def", "we ignore dtype for now typ = type(data) if 'nd4j'", "y = broadcast(self.array, other) self.array = x.div(y) return self def", "ndim(self): return len(self.array.shape()) def __getitem__(self, key): return ndarray(self.numpy()[key]) if type(key)", "__ipow__(self, other): self.numpy().__ipow__(_nparray(other)) return self other = _indarray(other) if self.array.shape()", "(c) 2015-2018 Skymind, Inc. # # This program and the", "buff.address() == pointer_address _refs.append(buff) elem_size = buff.getElementSize() assert elem_size ==", "nd4j_array def _to_numpy(nd4j_array): ''' Convert nd4j array to numpy array", "view.array other = broadcast_like(other, view) view.assign(other) def __add__(self, other): return", "NotImplementedError(\"Unsupported type: \" + (str(dtype))) return pytype def set_context_dtype(dtype): '''", "_nparray(other) return other = _indarray(other) view = self[key] if view", "= np.ctypeslib.as_array(pointer, tuple(nd4j_array.shape())) return np_array def _indarray(x): typ = type(x)", "'float64': 'double' } dtype = dtype_map.get(dtype, dtype) if dtype not", "' and ' + str(_ys)) if rep_x: x = Nd4j.tile(x,", "return len(self.array.shape()) def __getitem__(self, key): return ndarray(self.numpy()[key]) if type(key) is", "= broadcast(self.array, other) return ndarray(Transforms.pow(x, y)) def __iadd__(self, other): self.numpy().__iadd__(_nparray(other))", "the # terms of the Apache License, Version 2.0 which", "def __setitem__(self, key, other): self.numpy()[key] = _nparray(other) return other =", "return self.array.getInt(0) raise Exception('Applicable only for scalars') def __float__(self): if", "2015-2018 Skymind, Inc. # # This program and the accompanying", "return ndarray(self.numpy()[key]) if type(key) is int: return ndarray(self.array.get(NDArrayIndex.point(key))) if type(key)", "permissions and limitations # under the License. # # SPDX-License-Identifier:", "ndarray(self.numpy() - _nparray(other)) other = _indarray(other) x, y = broadcast(self.array,", "' and ' + str(_ys)) elif yd == 1: yt.append(xd)", "list(key) shape = self.array.shape() ndim = len(shape) nk = len(key)", "ndarray(self.numpy() + _nparray(other)) other = _indarray(other) x, y = broadcast(self.array,", "[] rep_y = False for xd, yd in zip(xs, ys):", "= np_array.shape nd4j_array = Nd4j.create(buff, shape, strides, 0) assert buff.address()", "key): return ndarray(self.numpy()[key]) if type(key) is int: return ndarray(self.array.get(NDArrayIndex.point(key))) if", "# under the License. # # SPDX-License-Identifier: Apache-2.0 ################################################################################ from", "nd4j_array.dataType().toString() mapping = { 'DOUBLE': ctypes.c_double, 'FLOAT': ctypes.c_float, 'HALF': ctypes.c_short,", "= ([1] * diff) + xs x = x.reshape(*xs) nx", "None: start = 0 if stop is None: shape =", "LONG = DataType.LONG INT = DataType.INT SHORT = DataType.SHORT UBYTE", "return other = _indarray(other) view = self[key] if view is", "start = key.start stop = key.stop step = key.step if", "self.array = self.array.addi(other) else: x, y = broadcast(self.array, other) self.array", "zip(xs, ys): if xd == yd: yt.append(1) elif xd ==", "def _indarray(x): typ = type(x) if typ is INDArray: return", "if xs == ys: return x, y _xs = tuple(xs)", "xt.append(1) yt.append(xd) rep_y = True else: raise Exception('Unable to broadcast", "return ndarray(self.array.get(*args)) def __setitem__(self, key, other): self.numpy()[key] = _nparray(other) return", "y.reshape(*ys) ny = nx elif ny > nx: diff =", "distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR", "pointer.limit(size) jdtype = _dtype_py2j(np_array.dtype) ''' mapping = { DOUBLE: DoublePointer,", "ctypes.c_double, 'FLOAT': ctypes.c_float, 'HALF': ctypes.c_short, 'LONG': ctypes.c_long, 'INT': ctypes.c_int, 'SHORT':", "getattr(ops, attr) setattr(ndarray, attr, f) return getattr(self, attr) def __int__(self):", "_ = np_array.__array_interface__['data'] _refs.append(np_array) pointer = native_ops.pointerForAddress(pointer_address) size = np_array.size", "(ndim - nk) args = [] for i, dim in", "'double']: raise ValueError(\"Invalid dtype '{}'. Available dtypes are 'float' and", "int: args.append(NDArrayIndex.point(dim)) elif type(dim) is slice: if dim == slice(None):", "ValueError(\"Invalid dtype '{}'. Available dtypes are 'float' and 'double'.\".format(dtype)) dtype_", "strides = np_array.strides strides = [dim / elem_size for dim", "nd4j # Arguments dtype: 'float' or 'double' ''' dtype_map =", "ndarray: return x.numpy() elif 'numpy' in str(typ): return x elif", "' + str(_ys)) elif yd == 1: yt.append(xd) rep_y =", "return y def broadcast(x, y): xs = x.shape() ys =", "is not supported yet.') return ndarray(self.array.get(*args)) def __setitem__(self, key, other):", "= list(key) shape = self.array.shape() ndim = len(shape) nk =", "key += [slice(None)] * (ndim - nk) args = []", "diff = nx - ny ys = ([1] * diff)", "as np import ctypes import warnings native_ops = NativeOpsHolder.getInstance().getDeviceNativeOps() #", "program.\") def get_context_dtype(): ''' Returns the nd4j dtype ''' dtype", "xs x = x.reshape(*xs) nx = ny xt = []", "typ is INDArray: return ndarray(x).numpy() elif typ is ndarray: return", "elif xd == 1: xt.append(yd) yt.append(1) rep_x = True elif", "dtype = dtype_map.get(dtype, dtype) if dtype not in ['float', 'double']:", "type(key) is slice: start = key.start stop = key.stop step", "MANAGEMENT DOUBLE = DataType.DOUBLE FLOAT = DataType.FLOAT HALF = DataType.HALF", "understood :' + str(typ)) def _nparray(x): typ = type(x) if", "= y.reshape(*ys) ny = nx elif ny > nx: diff", "dtype: warnings.warn(\"Can not set context dtype now. Set it at", "'' ' and ' + str(_ys)) if rep_x: x =", "self.array.shape() == other.shape(): self.array = self.array.addi(other) else: x, y =", "= _indarray(other) if self.array.shape() == other.shape(): self.array = self.array.divi(other) else:", "if stop is None: shape = self.array.shape() if shape[0] ==", "the dtype for nd4j # Arguments dtype: 'float' or 'double'", "= broadcast(self.array, other) return ndarray(x.add(y)) def __sub__(self, other): return ndarray(self.numpy()", "Arguments dtype: 'float' or 'double' ''' dtype_map = { 'float32':", "= x.div(y) return self def __ipow__(self, other): self.numpy().__ipow__(_nparray(other)) return self", "def get_context_dtype(): ''' Returns the nd4j dtype ''' dtype =", "step is None or step == 1: return ndarray(self.array.get(NDArrayIndex.interval(start, stop)))", "= ([1] * diff) + ys y = y.reshape(ys) ny", "str): dtype = np.dtype(dtype).type elif isinstance(dtype, np.dtype): dtype = dtype.type", "[slice(None)] * (ndim - nk) args = [] for i,", "None or step == 1: args.append(NDArrayIndex.interval(start, stop)) else: args.append(NDArrayIndex.interval( start,", "is None: start = 0 if stop is None: shape", "# This program and the accompanying materials are made available", "tuple(nd4j_array.shape())) return np_array def _indarray(x): typ = type(x) if typ", "self.array.divi(other) else: x, y = broadcast(self.array, other) self.array = x.div(y)", "# # Unless required by applicable law or agreed to", "ignore dtype for now typ = type(data) if 'nd4j' in", "DataType.UTF8 COMPRESSED = DataType.COMPRESSED UNKNOWN = DataType.UNKNOWN SUPPORTED_JAVA_DTYPES = [", "= self.array.shape() if shape[0] == 1: stop = shape[1] else:", "= Nd4j.createBuffer(pointer, size, jdtype) assert buff.address() == pointer_address _refs.append(buff) elem_size", "or step == 1: args.append(NDArrayIndex.interval(start, stop)) else: args.append(NDArrayIndex.interval( start, step,", "size, jdtype) assert buff.address() == pointer_address _refs.append(buff) elem_size = buff.getElementSize()", "ctypes.c_int, 'SHORT': ctypes.c_short, 'BOOL': ctypes.c_bool } Pointer = ctypes.POINTER(mapping[dtype]) pointer", "mapping = { 'DOUBLE': ctypes.c_double, 'FLOAT': ctypes.c_float, 'HALF': ctypes.c_short, 'LONG':", "ops f = getattr(ops, attr) setattr(ndarray, attr, f) return getattr(self,", "class ndarray(object): def __init__(self, data, dtype=None): # we ignore dtype", "= {SUPPORTED_JAVA_DTYPES[i] : SUPPORTED_PYTHON_DTYPES[i] for i in range(len(SUPPORTED_JAVA_DTYPES))} def _dtype_py2j(dtype):", "self.array = self.array.divi(other) else: x, y = broadcast(self.array, other) self.array", "True elif yd == 1: xt.append(1) yt.append(xd) rep_y = True", "are 'float' and 'double'.\".format(dtype)) dtype_ = DataTypeUtil.getDtypeFromContext(dtype) DataTypeUtil.setDTypeForContext(dtype_) if get_context_dtype()", "== other.shape(): self.array = self.array.divi(other) else: x, y = broadcast(self.array,", "other): self.numpy().__iadd__(_nparray(other)) return self other = _indarray(other) if self.array.shape() ==", "shape[1] else: stop = shape[0] if stop - start <=", "BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either", "args = [] for i, dim in enumerate(key): if type(dim)", "len(ys) if nx > ny: diff = nx - ny", "get_context_dtype(): ''' Returns the nd4j dtype ''' dtype = DataTypeUtil.getDtypeFromContext()", "x.div(y) return self def __ipow__(self, other): self.numpy().__ipow__(_nparray(other)) return self other", "DataType.DOUBLE FLOAT = DataType.FLOAT HALF = DataType.HALF LONG = DataType.LONG", "'' ' and ' + str(_ys)) if rep_y: y =", "shape[0] if stop - start <= 0: return None if", "- ny ys = ([1] * diff) + ys y", "data = np.array(data) self.array = _from_numpy(data) def numpy(self): try: return", "self.array = self.array.subi(other) else: x, y = broadcast(self.array, other) self.array", "Unless required by applicable law or agreed to in writing,", "_PY2J = {SUPPORTED_PYTHON_DTYPES[i] : SUPPORTED_JAVA_DTYPES[i] for i in range(len(SUPPORTED_JAVA_DTYPES))} _J2PY", "= type(data) if 'nd4j' in typ.__name__: # Note that we", "if rep_y: y = y.repmat(*yt) return y def broadcast(x, y):", "None if step is None or step == 1: args.append(NDArrayIndex.interval(start,", "== 1: return self.array.getInt(0) raise Exception('Applicable only for scalars') def", "+ '' ' and ' + str(_ys)) yt = []", "self.np_array except AttributeError: self.np_array = _to_numpy(self.array) return self.np_array @property def", "stop))) else: return ndarray(self.array.get(NDArrayIndex.interval(start, step, stop))) if type(key) is list:", "= key.stop step = key.step if start is None: start", "None: start = 0 if stop is None: stop =", "def __sub__(self, other): return ndarray(self.numpy() - _nparray(other)) other = _indarray(other)", "1: xt.append(1) yt.append(xd) rep_y = True else: raise Exception('Unable to", "xt = [] yt = [] rep_x = False rep_y", "SUPPORTED_PYTHON_DTYPES = [ np.float64, np.float32, np.float16, np.int64, np.int32, np.int16, np.bool_", "return ndarray(x.sub(y)) def __mul__(self, other): return ndarray(self.numpy() * _nparray(other)) other", "self.array.getDouble(0) raise Exception('Applicable only for scalars') @property def T(self): return", "elif typ in (list, tuple): return _from_numpy(np.array(x)) elif typ in", "dtypes are 'float' and 'double'.\".format(dtype)) dtype_ = DataTypeUtil.getDtypeFromContext(dtype) DataTypeUtil.setDTypeForContext(dtype_) if", "def __mul__(self, other): return ndarray(self.numpy() * _nparray(other)) other = _indarray(other)", "#UTF8 ] SUPPORTED_PYTHON_DTYPES = [ np.float64, np.float32, np.float16, np.int64, np.int32,", "ndarray(Transforms.pow(x, y)) def __iadd__(self, other): self.numpy().__iadd__(_nparray(other)) return self other =", "= shape[0] if stop - start <= 0: return None", "0: return None if step is None or step ==", "ys = y.shape() if xs == ys: return y _xs", "__idiv__(self, other): self.numpy().__idiv__(_nparray(other)) return self other = _indarray(other) if self.array.shape()", "Nd4j.tile(y, *yt) return x, y class ndarray(object): def __init__(self, data,", "set_context_dtype(dtype): ''' Sets the dtype for nd4j # Arguments dtype:", "either express or implied. See the # License for the", "*xt) if rep_y: try: y = Nd4j.tile(y, *yt) except: y", "a copy here self.array = data elif typ is ndarray:", "self.array.subi(other) else: x, y = broadcast(self.array, other) self.array = x.sub(y)", "= view.array other = broadcast_like(other, view) view.assign(other) def __add__(self, other):", "+ str(_ys)) elif yd == 1: yt.append(xd) rep_y = True", "def _dtype_j2py(dtype): pytype = _J2PY.get(dtype) if pytype is None: raise", "not understood :' + str(typ)) def broadcast_like(y, x): xs =", "FloatPointer, HALF: HalfPointer, LONG: LongPointer, INT: IntPointer, SHORT: ShortPointer, BOOL:", "type(key) is list: raise NotImplementedError( 'Sorry, this type of indexing", "= { 'DOUBLE': ctypes.c_double, 'FLOAT': ctypes.c_float, 'HALF': ctypes.c_short, 'LONG': ctypes.c_long,", "* _nparray(other)) other = _indarray(other) x, y = broadcast(self.array, other)", "Convert nd4j array to numpy array ''' buff = nd4j_array.data()", "return _from_numpy(x) elif typ in (list, tuple): return _from_numpy(np.array(x)) elif", "_indarray(other) x, y = broadcast(self.array, other) return ndarray(x.mul(y)) def __div__(self,", "def __pow__(self, other): return ndarray(self.numpy() ** _nparray(other)) other = _indarray(other)", "return ndarray(x.add(y)) def __sub__(self, other): return ndarray(self.numpy() - _nparray(other)) other", "= tuple(xs) _ys = tuple(ys) nx = len(xs) ny =", "start = dim.start stop = dim.stop step = dim.step if", "we don't make a copy here self.array = data elif", "key.step if start is None: start = 0 if stop", "else: stop = shape[0] if stop - start <= 0:", "} pc = mapping[jdtype] #pointer = pc(pointer) ''' buff =", "return ndarray(self.numpy() * _nparray(other)) other = _indarray(other) x, y =", "= broadcast(self.array, other) self.array = x.div(y) return self def __ipow__(self,", "the License is distributed on an \"AS IS\" BASIS, WITHOUT", "other): return ndarray(self.numpy() - _nparray(other)) other = _indarray(other) x, y", "= np_array.__array_interface__['data'] _refs.append(np_array) pointer = native_ops.pointerForAddress(pointer_address) size = np_array.size pointer.limit(size)", "self.numpy().__iadd__(_nparray(other)) return self other = _indarray(other) if self.array.shape() == other.shape():", "= Transforms.pow(x, y) return self def __getattr__(self, attr): import ops", "type(dim) in (list, tuple): raise NotImplementedError( 'Sorry, this type of", "array ''' buff = nd4j_array.data() address = buff.pointer().address() dtype =", "+ str(_ys)) yt = [] rep_y = False for xd,", "jtype is None: raise NotImplementedError(\"Unsupported type: \" + dtype.name) return", "Apache-2.0 ################################################################################ from .java_classes import * import numpy as np", "to numpy array ''' buff = nd4j_array.data() address = buff.pointer().address()", "dim in enumerate(key): if type(dim) is int: args.append(NDArrayIndex.point(dim)) elif type(dim)", "type(key) is tuple: key = list(key) shape = self.array.shape() ndim", "indexing is not supported yet.') if type(key) is tuple: key", "def shape(self): return tuple(self.array.shape()) @shape.setter def shape(self, value): arr =", "start, step, stop)) elif type(dim) in (list, tuple): raise NotImplementedError(", "if type(key) is tuple: key = list(key) shape = self.array.shape()", "np.float32, np.float16, np.int64, np.int32, np.int16, np.bool_ #np.str_ ] _PY2J =", "type(x) if typ is INDArray: return ndarray(x).numpy() elif typ is", "shape[i] if stop - start <= 0: return None if", "Exception('Applicable only for scalars') @property def T(self): return self.transpose() def", "start is None: start = 0 if stop is None:", "return ndarray(self.numpy() - _nparray(other)) other = _indarray(other) x, y =", "isinstance(dtype, np.dtype): dtype = dtype.type jtype = _PY2J.get(dtype) if jtype", "str(_xs) + '' ' and ' + str(_ys)) yt =", "__mul__(self, other): return ndarray(self.numpy() * _nparray(other)) other = _indarray(other) x,", "warnings.warn(\"Can not set context dtype now. Set it at the", "step is None or step == 1: args.append(NDArrayIndex.interval(start, stop)) else:", "DataType.SHORT UBYTE = DataType.UBYTE BYTE = DataType.BYTE BOOL = DataType.BOOL", "yt.append(1) rep_x = True elif yd == 1: xt.append(1) yt.append(xd)", "native_ops.pointerForAddress(pointer_address) size = np_array.size pointer.limit(size) jdtype = _dtype_py2j(np_array.dtype) ''' mapping", "else: args.append(NDArrayIndex.interval( start, step, stop)) elif type(dim) in (list, tuple):", "understood :' + str(typ)) def broadcast_like(y, x): xs = x.shape()", "([1] * diff) + ys y = y.reshape(ys) ny =", "return ndarray(x.div(y)) def __pow__(self, other): return ndarray(self.numpy() ** _nparray(other)) other", "pytype def set_context_dtype(dtype): ''' Sets the dtype for nd4j #", "type of indexing is not supported yet.') return ndarray(self.array.get(*args)) def", "buff.address() == nd4j_array.data().address() return nd4j_array def _to_numpy(nd4j_array): ''' Convert nd4j", "] SUPPORTED_PYTHON_DTYPES = [ np.float64, np.float32, np.float16, np.int64, np.int32, np.int16,", "array to numpy array ''' buff = nd4j_array.data() address =", "broadcast(self.array, other) return ndarray(Transforms.pow(x, y)) def __iadd__(self, other): self.numpy().__iadd__(_nparray(other)) return", "ny = len(ys) if nx > ny: diff = nx", "= True elif yd == 1: xt.append(1) yt.append(xd) rep_y =", "args.append(NDArrayIndex.interval( start, step, stop)) elif type(dim) in (list, tuple): raise", "is None: start = 0 if stop is None: stop", "stop is None: shape = self.array.shape() if shape[0] == 1:", "{SUPPORTED_JAVA_DTYPES[i] : SUPPORTED_PYTHON_DTYPES[i] for i in range(len(SUPPORTED_JAVA_DTYPES))} def _dtype_py2j(dtype): if", "* diff) + ys y = y.reshape(*ys) ny = nx", "return ndarray(x.mul(y)) def __div__(self, other): return ndarray(self.numpy() / _nparray(other)) other", "dtype.name) return jtype def _dtype_j2py(dtype): pytype = _J2PY.get(dtype) if pytype", "if shape[0] == 1: stop = shape[1] else: stop =", "broadcast_like(other, view) view.assign(other) def __add__(self, other): return ndarray(self.numpy() + _nparray(other))", "(list, tuple): return np.array(x) elif typ in (int, float): return", "'nd4j' in typ.__name__: # Note that we don't make a", "nx elif ny > nx: raise Exception('Unable to broadcast shapes", "dtype_map.get(dtype, dtype) if dtype not in ['float', 'double']: raise ValueError(\"Invalid", "x, y _xs = tuple(xs) _ys = tuple(ys) nx =", "typ is ndarray: self.array = data.array.dup() else: if typ is", "# SPDX-License-Identifier: Apache-2.0 ################################################################################ from .java_classes import * import numpy", "is list: raise NotImplementedError( 'Sorry, this type of indexing is", "# DATA TYPE MANAGEMENT DOUBLE = DataType.DOUBLE FLOAT = DataType.FLOAT", "def set_context_dtype(dtype): ''' Sets the dtype for nd4j # Arguments", "x, y = broadcast(self.array, other) self.array = x.div(y) return self", "1: stop = shape[1] else: stop = shape[0] if stop", "other) return ndarray(x.div(y)) def __pow__(self, other): return ndarray(self.numpy() ** _nparray(other))", "1: xt.append(yd) yt.append(1) rep_x = True elif yd == 1:", "None if step is None or step == 1: return", "@property def shape(self): return tuple(self.array.shape()) @shape.setter def shape(self, value): arr", "_from_numpy(x) elif typ in (list, tuple): return _from_numpy(np.array(x)) elif typ", "shape = self.array.shape() ndim = len(shape) nk = len(key) key", "jdtype = _dtype_py2j(np_array.dtype) ''' mapping = { DOUBLE: DoublePointer, FLOAT:", "ys = ([1] * diff) + ys y = y.reshape(*ys)", "diff) + xs x = x.reshape(*xs) nx = ny xt", "'LONG': ctypes.c_long, 'INT': ctypes.c_int, 'SHORT': ctypes.c_short, 'BOOL': ctypes.c_bool } Pointer", "value): arr = self.reshape(value) self.array = arr.array @property def ndim(self):", "other): self.numpy().__idiv__(_nparray(other)) return self other = _indarray(other) if self.array.shape() ==", "Nd4j.createBuffer(pointer, size, jdtype) assert buff.address() == pointer_address _refs.append(buff) elem_size =", "[] yt = [] rep_x = False rep_y = False", "yd in zip(xs, ys): if xd == yd: xt.append(1) yt.append(1)", "the specific language governing permissions and limitations # under the", "# Copyright (c) 2015-2018 Skymind, Inc. # # This program", "np.float64, np.float32, np.float16, np.int64, np.int32, np.int16, np.bool_ #np.str_ ] _PY2J", "nk = len(key) key += [slice(None)] * (ndim - nk)", "INDArray: return ndarray(x).numpy() elif typ is ndarray: return x.numpy() elif", "for i in range(len(SUPPORTED_JAVA_DTYPES))} def _dtype_py2j(dtype): if isinstance(dtype, str): dtype", "_xs = tuple(xs) _ys = tuple(ys) nx = len(xs) ny", "y = broadcast(self.array, other) return ndarray(x.div(y)) def __pow__(self, other): return", "dtype_ = DataTypeUtil.getDtypeFromContext(dtype) DataTypeUtil.setDTypeForContext(dtype_) if get_context_dtype() != dtype: warnings.warn(\"Can not", "return DataTypeUtil.getDTypeForName(dtype) _refs = [] def _from_numpy(np_array): ''' Convert numpy", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "} dtype = dtype_map.get(dtype, dtype) if dtype not in ['float',", "i in range(len(SUPPORTED_JAVA_DTYPES))} _J2PY = {SUPPORTED_JAVA_DTYPES[i] : SUPPORTED_PYTHON_DTYPES[i] for i", "LONG, INT, SHORT, BOOL #UTF8 ] SUPPORTED_PYTHON_DTYPES = [ np.float64,", "def __idiv__(self, other): self.numpy().__idiv__(_nparray(other)) return self other = _indarray(other) if", "- nk) args = [] for i, dim in enumerate(key):", "INDArray: return x elif typ is ndarray: return x.array elif", "ys y = y.reshape(ys) ny = nx elif ny >", "== yd: xt.append(1) yt.append(1) elif xd == 1: xt.append(yd) yt.append(1)", "DataType.BOOL UTF8 = DataType.UTF8 COMPRESSED = DataType.COMPRESSED UNKNOWN = DataType.UNKNOWN", "[ DOUBLE, FLOAT, HALF, LONG, INT, SHORT, BOOL #UTF8 ]", "'double' } dtype = dtype_map.get(dtype, dtype) if dtype not in", "= np_array.strides strides = [dim / elem_size for dim in", "elif ny > nx: diff = ny - nx xs", "= Nd4j.tile(y, *yt) return x, y class ndarray(object): def __init__(self,", "ndim = len(shape) nk = len(key) key += [slice(None)] *", "ys = y.shape() if xs == ys: return x, y", "required by applicable law or agreed to in writing, software", "pytype is None: raise NotImplementedError(\"Unsupported type: \" + (str(dtype))) return", "return np_array def _indarray(x): typ = type(x) if typ is", "broadcast(self.array, other) return ndarray(x.mul(y)) def __div__(self, other): return ndarray(self.numpy() /", "nx > ny: diff = nx - ny ys =", "x.shape() ys = y.shape() if xs == ys: return x,", "x elif typ is ndarray: return x.array elif 'numpy' in", "+ str(_xs) + '' ' and ' + str(_ys)) yt", "Nd4j.scalar(x) else: raise Exception('Data type not understood :' + str(typ))", "agreed to in writing, software # distributed under the License", "= [ np.float64, np.float32, np.float16, np.int64, np.int32, np.int16, np.bool_ #np.str_", "stop = key.stop step = key.step if start is None:", "distributed under the License is distributed on an \"AS IS\"", "CONDITIONS OF ANY KIND, either express or implied. See the", "= self[key] if view is None: return view = view.array", "= key.start stop = key.stop step = key.step if start", "raise Exception('Applicable only for scalars') @property def T(self): return self.transpose()", "nd4j_array = Nd4j.create(buff, shape, strides, 0) assert buff.address() == nd4j_array.data().address()", "if self.array.length() == 1: return self.array.getDouble(0) raise Exception('Applicable only for", "xd == yd: xt.append(1) yt.append(1) elif xd == 1: xt.append(yd)", "str(typ)) def _nparray(x): typ = type(x) if typ is INDArray:", "== 1: yt.append(xd) rep_y = True else: raise Exception('Unable to", "return tuple(self.array.shape()) @shape.setter def shape(self, value): arr = self.reshape(value) self.array", "= [] yt = [] rep_x = False rep_y =", "self.np_array @property def size(self): return self.array.length() @property def shape(self): return", "SHORT = DataType.SHORT UBYTE = DataType.UBYTE BYTE = DataType.BYTE BOOL", "== nd4j_array.data().address() return nd4j_array def _to_numpy(nd4j_array): ''' Convert nd4j array", "type(x) if typ is INDArray: return x elif typ is", "'' ' and ' + str(_ys)) elif yd == 1:", "available under the # terms of the Apache License, Version", "@property def ndim(self): return len(self.array.shape()) def __getitem__(self, key): return ndarray(self.numpy()[key])", "AttributeError: self.np_array = _to_numpy(self.array) return self.np_array @property def size(self): return", "return y _xs = tuple(xs) _ys = tuple(ys) nx =", "y = broadcast(self.array, other) return ndarray(x.sub(y)) def __mul__(self, other): return", "dtype for now typ = type(data) if 'nd4j' in typ.__name__:", "x, y = broadcast(self.array, other) return ndarray(x.mul(y)) def __div__(self, other):", "step = dim.step if start is None: start = 0", "= _dtype_py2j(np_array.dtype) ''' mapping = { DOUBLE: DoublePointer, FLOAT: FloatPointer,", "is ndarray: return x.numpy() elif 'numpy' in str(typ): return x", "= buff.pointer().address() dtype = nd4j_array.dataType().toString() mapping = { 'DOUBLE': ctypes.c_double,", "IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND,", "#np.str_ ] _PY2J = {SUPPORTED_PYTHON_DTYPES[i] : SUPPORTED_JAVA_DTYPES[i] for i in", "/ _nparray(other)) other = _indarray(other) x, y = broadcast(self.array, other)", "rep_y = False for xd, yd in zip(xs, ys): if", "elem_size = buff.getElementSize() assert elem_size == np_array.dtype.itemsize strides = np_array.strides", "- start <= 0: return None if step is None", "SUPPORTED_JAVA_DTYPES[i] for i in range(len(SUPPORTED_JAVA_DTYPES))} _J2PY = {SUPPORTED_JAVA_DTYPES[i] : SUPPORTED_PYTHON_DTYPES[i]", "for nd4j # Arguments dtype: 'float' or 'double' ''' dtype_map", "dtype = nd4j_array.dataType().toString() mapping = { 'DOUBLE': ctypes.c_double, 'FLOAT': ctypes.c_float,", "jtype = _PY2J.get(dtype) if jtype is None: raise NotImplementedError(\"Unsupported type:", "== 1: raise Exception('Unable to broadcast shapes ' + str(_xs)", "+ str(typ)) def broadcast_like(y, x): xs = x.shape() ys =", "Pointer) np_array = np.ctypeslib.as_array(pointer, tuple(nd4j_array.shape())) return np_array def _indarray(x): typ", "See the # License for the specific language governing permissions", "_nparray(x): typ = type(x) if typ is INDArray: return ndarray(x).numpy()", "ndarray(self.array.get(NDArrayIndex.point(key))) if type(key) is slice: start = key.start stop =", "else: start = dim.start stop = dim.stop step = dim.step", "stop)) else: args.append(NDArrayIndex.interval( start, step, stop)) elif type(dim) in (list,", "elif typ in (list, tuple): return np.array(x) elif typ in", "self.array = data elif typ is ndarray: self.array = data.array.dup()", "assert elem_size == np_array.dtype.itemsize strides = np_array.strides strides = [dim", "# https://www.apache.org/licenses/LICENSE-2.0. # # Unless required by applicable law or", "NativeOpsHolder.getInstance().getDeviceNativeOps() # DATA TYPE MANAGEMENT DOUBLE = DataType.DOUBLE FLOAT =", "== 1: stop = shape[1] else: stop = shape[0] if", "elif ny > nx: raise Exception('Unable to broadcast shapes '", "[ np.float64, np.float32, np.float16, np.int64, np.int32, np.int16, np.bool_ #np.str_ ]", "= 0 if stop is None: stop = shape[i] if", "law or agreed to in writing, software # distributed under", "[dim / elem_size for dim in strides] shape = np_array.shape", "x.add(y) return self def __isub__(self, other): self.numpy().__isub__(_nparray(other)) return self other", "# terms of the Apache License, Version 2.0 which is", "= x.mul(y) return self def __idiv__(self, other): self.numpy().__idiv__(_nparray(other)) return self", "FLOAT, HALF, LONG, INT, SHORT, BOOL #UTF8 ] SUPPORTED_PYTHON_DTYPES =", "is ndarray: return x.array elif 'numpy' in str(typ): return _from_numpy(x)", "if self.array.shape() == other.shape(): self.array = self.array.addi(other) else: x, y", "dtype=None): # we ignore dtype for now typ = type(data)", "ny - nx xs = ([1] * diff) + xs", "= broadcast(self.array, other) self.array = x.add(y) return self def __isub__(self,", "the accompanying materials are made available under the # terms", "[] rep_x = False rep_y = False for xd, yd", "Inc. # # This program and the accompanying materials are", "for i in range(len(SUPPORTED_JAVA_DTYPES))} _J2PY = {SUPPORTED_JAVA_DTYPES[i] : SUPPORTED_PYTHON_DTYPES[i] for", "_to_numpy(nd4j_array): ''' Convert nd4j array to numpy array ''' buff", "= key.step if start is None: start = 0 if", "if pytype is None: raise NotImplementedError(\"Unsupported type: \" + (str(dtype)))", "data, dtype=None): # we ignore dtype for now typ =", "your program.\") def get_context_dtype(): ''' Returns the nd4j dtype '''", "Note that we don't make a copy here self.array =", "args.append(NDArrayIndex.all()) else: start = dim.start stop = dim.stop step =", "other): return ndarray(self.numpy() + _nparray(other)) other = _indarray(other) x, y", "self.array = data.array.dup() else: if typ is not np.ndarray: data", "= x.add(y) return self def __isub__(self, other): self.numpy().__isub__(_nparray(other)) return self", "+ str(_ys)) if rep_x: x = Nd4j.tile(x, *xt) if rep_y:", "*yt) return x, y class ndarray(object): def __init__(self, data, dtype=None):", "([1] * diff) + xs x = x.reshape(*xs) nx =", "''' Sets the dtype for nd4j # Arguments dtype: 'float'", "LongPointer, INT: IntPointer, SHORT: ShortPointer, BOOL: BoolPointer } pc =", "elif typ is ndarray: return x.numpy() elif 'numpy' in str(typ):", "= y.reshape(ys) ny = nx elif ny > nx: raise", "yd == 1: yt.append(xd) rep_y = True else: raise Exception('Unable", "self.array.shape() == other.shape(): self.array = self.array.subi(other) else: x, y =", "typ is INDArray: return x elif typ is ndarray: return", "and 'double'.\".format(dtype)) dtype_ = DataTypeUtil.getDtypeFromContext(dtype) DataTypeUtil.setDTypeForContext(dtype_) if get_context_dtype() != dtype:", "= type(x) if typ is INDArray: return x elif typ", "rep_x: x = Nd4j.tile(x, *xt) if rep_y: try: y =", "return None if step is None or step == 1:", "typ in (list, tuple): return _from_numpy(np.array(x)) elif typ in (int,", "np.int16, np.bool_ #np.str_ ] _PY2J = {SUPPORTED_PYTHON_DTYPES[i] : SUPPORTED_JAVA_DTYPES[i] for", "the Apache License, Version 2.0 which is available at #", "supported yet.') if type(key) is tuple: key = list(key) shape", "= np.array(data) self.array = _from_numpy(data) def numpy(self): try: return self.np_array", "elif typ is ndarray: self.array = data.array.dup() else: if typ", "raise Exception('Applicable only for scalars') def __float__(self): if self.array.length() ==", "ndarray(self.numpy()[key]) if type(key) is int: return ndarray(self.array.get(NDArrayIndex.point(key))) if type(key) is", "and ' + str(_ys)) if rep_y: y = y.repmat(*yt) return", "on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS", "return x elif typ is ndarray: return x.array elif 'numpy'", "broadcast(self.array, other) return ndarray(x.div(y)) def __pow__(self, other): return ndarray(self.numpy() **", "Exception('Data type not understood :' + str(typ)) def _nparray(x): typ", "== 1: xt.append(1) yt.append(xd) rep_y = True else: raise Exception('Unable", "@shape.setter def shape(self, value): arr = self.reshape(value) self.array = arr.array", "None: shape = self.array.shape() if shape[0] == 1: stop =", "None: return view = view.array other = broadcast_like(other, view) view.assign(other)", "typ.__name__: # Note that we don't make a copy here", "* diff) + ys y = y.reshape(ys) ny = nx", "if rep_y: try: y = Nd4j.tile(y, *yt) except: y =", "yd == 1: xt.append(1) yt.append(xd) rep_y = True else: raise", "nx elif ny > nx: diff = ny - nx", "self.array = Transforms.pow(x, y) return self def __getattr__(self, attr): import", "def __int__(self): if self.array.length() == 1: return self.array.getInt(0) raise Exception('Applicable", "here self.array = data elif typ is ndarray: self.array =", "if xd == yd: xt.append(1) yt.append(1) elif xd == 1:", "at # https://www.apache.org/licenses/LICENSE-2.0. # # Unless required by applicable law", "y.shape() if xs == ys: return x, y _xs =", "if step is None or step == 1: return ndarray(self.array.get(NDArrayIndex.interval(start,", "None: raise NotImplementedError(\"Unsupported type: \" + dtype.name) return jtype def", "ndarray: self.array = data.array.dup() else: if typ is not np.ndarray:", "ctypes.c_short, 'LONG': ctypes.c_long, 'INT': ctypes.c_int, 'SHORT': ctypes.c_short, 'BOOL': ctypes.c_bool }", "BOOL: BoolPointer } pc = mapping[jdtype] #pointer = pc(pointer) '''", "__div__(self, other): return ndarray(self.numpy() / _nparray(other)) other = _indarray(other) x,", "is INDArray: return ndarray(x).numpy() elif typ is ndarray: return x.numpy()", "other) self.array = x.sub(y) return self def __imul__(self, other): self.numpy().__imul__(_nparray(other))", "view = view.array other = broadcast_like(other, view) view.assign(other) def __add__(self,", "= y.shape() if xs == ys: return y _xs =", "in (int, float): return np.array(x) else: raise Exception('Data type not", "set context dtype now. Set it at the beginning of", "y = broadcast(self.array, other) self.array = Transforms.pow(x, y) return self", "= dim.step if start is None: start = 0 if", "if get_context_dtype() != dtype: warnings.warn(\"Can not set context dtype now.", "return ndarray(self.numpy() + _nparray(other)) other = _indarray(other) x, y =", "other): self.numpy().__imul__(_nparray(other)) return self other = _indarray(other) if self.array.shape() ==", "} Pointer = ctypes.POINTER(mapping[dtype]) pointer = ctypes.cast(address, Pointer) np_array =", "type: \" + (str(dtype))) return pytype def set_context_dtype(dtype): ''' Sets", "yt = [] rep_x = False rep_y = False for", "= self.reshape(value) self.array = arr.array @property def ndim(self): return len(self.array.shape())", "License, Version 2.0 which is available at # https://www.apache.org/licenses/LICENSE-2.0. #", "raise Exception('Unable to broadcast shapes ' + str(_xs) + ''", "broadcast shapes ' + str(_xs) + '' ' and '", "return self def __ipow__(self, other): self.numpy().__ipow__(_nparray(other)) return self other =", "x.sub(y) return self def __imul__(self, other): self.numpy().__imul__(_nparray(other)) return self other", "+ xs x = x.reshape(*xs) nx = ny xt =", "!= dtype: warnings.warn(\"Can not set context dtype now. Set it", "type(dim) is int: args.append(NDArrayIndex.point(dim)) elif type(dim) is slice: if dim", "typ in (int, float): return np.array(x) else: raise Exception('Data type", "OF ANY KIND, either express or implied. See the #", "self.array.length() == 1: return self.array.getDouble(0) raise Exception('Applicable only for scalars')", "' + str(_ys)) yt = [] rep_y = False for", "else: x, y = broadcast(self.array, other) self.array = x.add(y) return", "== 1: return ndarray(self.array.get(NDArrayIndex.interval(start, stop))) else: return ndarray(self.array.get(NDArrayIndex.interval(start, step, stop)))", "for scalars') @property def T(self): return self.transpose() def array(*args, **kwargs):", "in writing, software # distributed under the License is distributed", "setattr(ndarray, attr, f) return getattr(self, attr) def __int__(self): if self.array.length()", "warnings native_ops = NativeOpsHolder.getInstance().getDeviceNativeOps() # DATA TYPE MANAGEMENT DOUBLE =", "is None: raise NotImplementedError(\"Unsupported type: \" + dtype.name) return jtype", "x, y class ndarray(object): def __init__(self, data, dtype=None): # we", "_indarray(x): typ = type(x) if typ is INDArray: return x", "str(typ)) def broadcast_like(y, x): xs = x.shape() ys = y.shape()", "* import numpy as np import ctypes import warnings native_ops", "- _nparray(other)) other = _indarray(other) x, y = broadcast(self.array, other)", "in enumerate(key): if type(dim) is int: args.append(NDArrayIndex.point(dim)) elif type(dim) is", "np_array.shape nd4j_array = Nd4j.create(buff, shape, strides, 0) assert buff.address() ==", "= len(shape) nk = len(key) key += [slice(None)] * (ndim", "= self.array.subi(other) else: x, y = broadcast(self.array, other) self.array =", "''' buff = nd4j_array.data() address = buff.pointer().address() dtype = nd4j_array.dataType().toString()", "nk) args = [] for i, dim in enumerate(key): if", "elem_size for dim in strides] shape = np_array.shape nd4j_array =", "other): self.numpy()[key] = _nparray(other) return other = _indarray(other) view =", "__isub__(self, other): self.numpy().__isub__(_nparray(other)) return self other = _indarray(other) if self.array.shape()", "view is None: return view = view.array other = broadcast_like(other,", "= DataType.DOUBLE FLOAT = DataType.FLOAT HALF = DataType.HALF LONG =", "= DataType.BOOL UTF8 = DataType.UTF8 COMPRESSED = DataType.COMPRESSED UNKNOWN =", "nx: diff = ny - nx xs = ([1] *", "= 0 if stop is None: shape = self.array.shape() if", "if isinstance(dtype, str): dtype = np.dtype(dtype).type elif isinstance(dtype, np.dtype): dtype", "1: yt.append(xd) rep_y = True else: raise Exception('Unable to broadcast", "_dtype_py2j(np_array.dtype) ''' mapping = { DOUBLE: DoublePointer, FLOAT: FloatPointer, HALF:", "ys: return x, y _xs = tuple(xs) _ys = tuple(ys)", "stop is None: stop = shape[i] if stop - start", "HalfPointer, LONG: LongPointer, INT: IntPointer, SHORT: ShortPointer, BOOL: BoolPointer }", "tuple(xs) _ys = tuple(ys) nx = len(xs) ny = len(ys)", "_J2PY = {SUPPORTED_JAVA_DTYPES[i] : SUPPORTED_PYTHON_DTYPES[i] for i in range(len(SUPPORTED_JAVA_DTYPES))} def", "'DOUBLE': ctypes.c_double, 'FLOAT': ctypes.c_float, 'HALF': ctypes.c_short, 'LONG': ctypes.c_long, 'INT': ctypes.c_int,", "other = _indarray(other) if self.array.shape() == other.shape(): self.array = self.array.addi(other)", "x, y = broadcast(self.array, other) self.array = x.add(y) return self", "nd4j array to numpy array ''' buff = nd4j_array.data() address", "is INDArray: return x elif typ is ndarray: return x.array", "1: args.append(NDArrayIndex.interval(start, stop)) else: args.append(NDArrayIndex.interval( start, step, stop)) elif type(dim)", "self.array.getInt(0) raise Exception('Applicable only for scalars') def __float__(self): if self.array.length()", "not understood :' + str(typ)) def _nparray(x): typ = type(x)", "key.stop step = key.step if start is None: start =", "# distributed under the License is distributed on an \"AS", "# Unless required by applicable law or agreed to in", ":' + str(typ)) def broadcast_like(y, x): xs = x.shape() ys", "yt.append(xd) rep_y = True else: raise Exception('Unable to broadcast shapes", "under the # terms of the Apache License, Version 2.0", "is distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES", "strides, 0) assert buff.address() == nd4j_array.data().address() return nd4j_array def _to_numpy(nd4j_array):", "def ndim(self): return len(self.array.shape()) def __getitem__(self, key): return ndarray(self.numpy()[key]) if", "= dim.stop step = dim.step if start is None: start", "tuple(self.array.shape()) @shape.setter def shape(self, value): arr = self.reshape(value) self.array =", "= _J2PY.get(dtype) if pytype is None: raise NotImplementedError(\"Unsupported type: \"", "= _PY2J.get(dtype) if jtype is None: raise NotImplementedError(\"Unsupported type: \"", "elif xd == 1: raise Exception('Unable to broadcast shapes '", "DOUBLE = DataType.DOUBLE FLOAT = DataType.FLOAT HALF = DataType.HALF LONG", "other = _indarray(other) x, y = broadcast(self.array, other) return ndarray(x.mul(y))", "= _indarray(other) x, y = broadcast(self.array, other) return ndarray(x.div(y)) def", "{SUPPORTED_PYTHON_DTYPES[i] : SUPPORTED_JAVA_DTYPES[i] for i in range(len(SUPPORTED_JAVA_DTYPES))} _J2PY = {SUPPORTED_JAVA_DTYPES[i]", "other = broadcast_like(other, view) view.assign(other) def __add__(self, other): return ndarray(self.numpy()", "= DataType.UBYTE BYTE = DataType.BYTE BOOL = DataType.BOOL UTF8 =", "elif typ in (int, float): return Nd4j.scalar(x) else: raise Exception('Data", "if xs == ys: return y _xs = tuple(xs) _ys", "pointer_address, _ = np_array.__array_interface__['data'] _refs.append(np_array) pointer = native_ops.pointerForAddress(pointer_address) size =", "in ['float', 'double']: raise ValueError(\"Invalid dtype '{}'. Available dtypes are", "y = y.repmat(*yt) return y def broadcast(x, y): xs =", "def __ipow__(self, other): self.numpy().__ipow__(_nparray(other)) return self other = _indarray(other) if", "nx = len(xs) ny = len(ys) if nx > ny:", "specific language governing permissions and limitations # under the License.", "shape = self.array.shape() if shape[0] == 1: stop = shape[1]", "= arr.array @property def ndim(self): return len(self.array.shape()) def __getitem__(self, key):", "shape = np_array.shape nd4j_array = Nd4j.create(buff, shape, strides, 0) assert", "self def __ipow__(self, other): self.numpy().__ipow__(_nparray(other)) return self other = _indarray(other)", "for dim in strides] shape = np_array.shape nd4j_array = Nd4j.create(buff,", "ny > nx: diff = ny - nx xs =", "self.array = x.div(y) return self def __ipow__(self, other): self.numpy().__ipow__(_nparray(other)) return", "= DataType.FLOAT HALF = DataType.HALF LONG = DataType.LONG INT =", "if 'nd4j' in typ.__name__: # Note that we don't make", "= Nd4j.tile(x, *xt) if rep_y: try: y = Nd4j.tile(y, *yt)", "# Arguments dtype: 'float' or 'double' ''' dtype_map = {", "this type of indexing is not supported yet.') if type(key)", "nd4j_array.data().address() return nd4j_array def _to_numpy(nd4j_array): ''' Convert nd4j array to", "type: \" + dtype.name) return jtype def _dtype_j2py(dtype): pytype =", "ctypes.c_float, 'HALF': ctypes.c_short, 'LONG': ctypes.c_long, 'INT': ctypes.c_int, 'SHORT': ctypes.c_short, 'BOOL':", "+ str(_xs) + '' ' and ' + str(_ys)) elif", "other = _indarray(other) if self.array.shape() == other.shape(): self.array = self.array.divi(other)", "rep_x = False rep_y = False for xd, yd in", "'float', 'float64': 'double' } dtype = dtype_map.get(dtype, dtype) if dtype", "HALF: HalfPointer, LONG: LongPointer, INT: IntPointer, SHORT: ShortPointer, BOOL: BoolPointer", "under the License is distributed on an \"AS IS\" BASIS,", "x = Nd4j.tile(x, *xt) if rep_y: try: y = Nd4j.tile(y,", "_PY2J.get(dtype) if jtype is None: raise NotImplementedError(\"Unsupported type: \" +", "data elif typ is ndarray: self.array = data.array.dup() else: if", "elem_size == np_array.dtype.itemsize strides = np_array.strides strides = [dim /", "return x elif typ in (list, tuple): return np.array(x) elif", "ys): if xd == yd: xt.append(1) yt.append(1) elif xd ==", "= True else: raise Exception('Unable to broadcast shapes ' +", "== 1: args.append(NDArrayIndex.interval(start, stop)) else: args.append(NDArrayIndex.interval( start, step, stop)) elif", "view = self[key] if view is None: return view =", "else: x, y = broadcast(self.array, other) self.array = x.mul(y) return", "= nx elif ny > nx: raise Exception('Unable to broadcast", "else: x, y = broadcast(self.array, other) self.array = x.div(y) return", "dim.step if start is None: start = 0 if stop", "'' ' and ' + str(_ys)) yt = [] rep_y", "= y.shape() if xs == ys: return x, y _xs", "DataType.INT SHORT = DataType.SHORT UBYTE = DataType.UBYTE BYTE = DataType.BYTE", "= x.sub(y) return self def __imul__(self, other): self.numpy().__imul__(_nparray(other)) return self", "1: return self.array.getDouble(0) raise Exception('Applicable only for scalars') @property def", "def __init__(self, data, dtype=None): # we ignore dtype for now", "= data.array.dup() else: if typ is not np.ndarray: data =", "is None: raise NotImplementedError(\"Unsupported type: \" + (str(dtype))) return pytype", "= data elif typ is ndarray: self.array = data.array.dup() else:", "' and ' + str(_ys)) if rep_y: y = y.repmat(*yt)", "start = 0 if stop is None: stop = shape[i]", "else: raise Exception('Unable to broadcast shapes ' + str(_xs) +", "__add__(self, other): return ndarray(self.numpy() + _nparray(other)) other = _indarray(other) x,", "OR CONDITIONS OF ANY KIND, either express or implied. See", "zip(xs, ys): if xd == yd: xt.append(1) yt.append(1) elif xd", "# Note that we don't make a copy here self.array", "np.int32, np.int16, np.bool_ #np.str_ ] _PY2J = {SUPPORTED_PYTHON_DTYPES[i] : SUPPORTED_JAVA_DTYPES[i]", "except AttributeError: self.np_array = _to_numpy(self.array) return self.np_array @property def size(self):", "data.array.dup() else: if typ is not np.ndarray: data = np.array(data)", "2.0 which is available at # https://www.apache.org/licenses/LICENSE-2.0. # # Unless", "x.mul(y) return self def __idiv__(self, other): self.numpy().__idiv__(_nparray(other)) return self other", "__pow__(self, other): return ndarray(self.numpy() ** _nparray(other)) other = _indarray(other) x,", "'INT': ctypes.c_int, 'SHORT': ctypes.c_short, 'BOOL': ctypes.c_bool } Pointer = ctypes.POINTER(mapping[dtype])", "_indarray(other) view = self[key] if view is None: return view", "attr) setattr(ndarray, attr, f) return getattr(self, attr) def __int__(self): if", "ctypes.cast(address, Pointer) np_array = np.ctypeslib.as_array(pointer, tuple(nd4j_array.shape())) return np_array def _indarray(x):", "step, stop)) elif type(dim) in (list, tuple): raise NotImplementedError( 'Sorry,", "copy here self.array = data elif typ is ndarray: self.array", "= DataType.HALF LONG = DataType.LONG INT = DataType.INT SHORT =", "BOOL = DataType.BOOL UTF8 = DataType.UTF8 COMPRESSED = DataType.COMPRESSED UNKNOWN", "args.append(NDArrayIndex.interval(start, stop)) else: args.append(NDArrayIndex.interval( start, step, stop)) elif type(dim) in", "dtype = dtype.type jtype = _PY2J.get(dtype) if jtype is None:", "= DataTypeUtil.getDtypeFromContext() return DataTypeUtil.getDTypeForName(dtype) _refs = [] def _from_numpy(np_array): '''", "_from_numpy(np_array): ''' Convert numpy array to nd4j array ''' pointer_address,", "* diff) + xs x = x.reshape(*xs) nx = ny", "ny = nx elif ny > nx: diff = ny", "self def __idiv__(self, other): self.numpy().__idiv__(_nparray(other)) return self other = _indarray(other)", "the nd4j dtype ''' dtype = DataTypeUtil.getDtypeFromContext() return DataTypeUtil.getDTypeForName(dtype) _refs", "x.array elif 'numpy' in str(typ): return _from_numpy(x) elif typ in", "broadcast_like(y, x): xs = x.shape() ys = y.shape() if xs", "== 1: return self.array.getDouble(0) raise Exception('Applicable only for scalars') @property", ".java_classes import * import numpy as np import ctypes import", "return x, y _xs = tuple(xs) _ys = tuple(ys) nx", "= _indarray(other) if self.array.shape() == other.shape(): self.array = self.array.subi(other) else:", "return self def __imul__(self, other): self.numpy().__imul__(_nparray(other)) return self other =", "y = y.reshape(ys) ny = nx elif ny > nx:", "start <= 0: return None if step is None or", "writing, software # distributed under the License is distributed on", "BYTE = DataType.BYTE BOOL = DataType.BOOL UTF8 = DataType.UTF8 COMPRESSED", "y class ndarray(object): def __init__(self, data, dtype=None): # we ignore", "__int__(self): if self.array.length() == 1: return self.array.getInt(0) raise Exception('Applicable only", "self other = _indarray(other) if self.array.shape() == other.shape(): self.array =", "Exception('Applicable only for scalars') def __float__(self): if self.array.length() == 1:", "= shape[1] else: stop = shape[0] if stop - start", "= _indarray(other) x, y = broadcast(self.array, other) return ndarray(x.mul(y)) def", "################################################################################ from .java_classes import * import numpy as np import", "ctypes.c_bool } Pointer = ctypes.POINTER(mapping[dtype]) pointer = ctypes.cast(address, Pointer) np_array", "y = broadcast(self.array, other) return ndarray(x.mul(y)) def __div__(self, other): return", "= self.array.addi(other) else: x, y = broadcast(self.array, other) self.array =", "numpy array ''' buff = nd4j_array.data() address = buff.pointer().address() dtype", "DataTypeUtil.setDTypeForContext(dtype_) if get_context_dtype() != dtype: warnings.warn(\"Can not set context dtype", "return self def __idiv__(self, other): self.numpy().__idiv__(_nparray(other)) return self other =", "buff.getElementSize() assert elem_size == np_array.dtype.itemsize strides = np_array.strides strides =", "= DataType.INT SHORT = DataType.SHORT UBYTE = DataType.UBYTE BYTE =", "Copyright (c) 2015-2018 Skymind, Inc. # # This program and", "'BOOL': ctypes.c_bool } Pointer = ctypes.POINTER(mapping[dtype]) pointer = ctypes.cast(address, Pointer)", "in range(len(SUPPORTED_JAVA_DTYPES))} def _dtype_py2j(dtype): if isinstance(dtype, str): dtype = np.dtype(dtype).type", "= broadcast(self.array, other) self.array = Transforms.pow(x, y) return self def", "in (int, float): return Nd4j.scalar(x) else: raise Exception('Data type not", "return self def __isub__(self, other): self.numpy().__isub__(_nparray(other)) return self other =", "or 'double' ''' dtype_map = { 'float32': 'float', 'float64': 'double'", "> nx: raise Exception('Unable to broadcast shapes ' + str(_xs)", "= Nd4j.tile(y, *yt) except: y = Nd4j.tile(y, *yt) return x,", "express or implied. See the # License for the specific", "if dtype not in ['float', 'double']: raise ValueError(\"Invalid dtype '{}'.", "'SHORT': ctypes.c_short, 'BOOL': ctypes.c_bool } Pointer = ctypes.POINTER(mapping[dtype]) pointer =", "DataType.HALF LONG = DataType.LONG INT = DataType.INT SHORT = DataType.SHORT", "yt.append(1) elif xd == 1: xt.append(yd) yt.append(1) rep_x = True", "self def __getattr__(self, attr): import ops f = getattr(ops, attr)", "0 if stop is None: shape = self.array.shape() if shape[0]", "def _dtype_py2j(dtype): if isinstance(dtype, str): dtype = np.dtype(dtype).type elif isinstance(dtype,", "UNKNOWN = DataType.UNKNOWN SUPPORTED_JAVA_DTYPES = [ DOUBLE, FLOAT, HALF, LONG,", "= len(key) key += [slice(None)] * (ndim - nk) args", "is not supported yet.') if type(key) is tuple: key =", "str(_ys)) if rep_x: x = Nd4j.tile(x, *xt) if rep_y: try:", "or step == 1: return ndarray(self.array.get(NDArrayIndex.interval(start, stop))) else: return ndarray(self.array.get(NDArrayIndex.interval(start,", "str(typ): return _from_numpy(x) elif typ in (list, tuple): return _from_numpy(np.array(x))", "self.array.shape() ndim = len(shape) nk = len(key) key += [slice(None)]", "assert buff.address() == pointer_address _refs.append(buff) elem_size = buff.getElementSize() assert elem_size", "return jtype def _dtype_j2py(dtype): pytype = _J2PY.get(dtype) if pytype is", "= broadcast(self.array, other) return ndarray(x.sub(y)) def __mul__(self, other): return ndarray(self.numpy()", "def T(self): return self.transpose() def array(*args, **kwargs): return ndarray(*args, **kwargs)", "other.shape(): self.array = self.array.divi(other) else: x, y = broadcast(self.array, other)", ": SUPPORTED_JAVA_DTYPES[i] for i in range(len(SUPPORTED_JAVA_DTYPES))} _J2PY = {SUPPORTED_JAVA_DTYPES[i] :", "other) self.array = x.div(y) return self def __ipow__(self, other): self.numpy().__ipow__(_nparray(other))", "typ in (int, float): return Nd4j.scalar(x) else: raise Exception('Data type", "numpy(self): try: return self.np_array except AttributeError: self.np_array = _to_numpy(self.array) return", "stop - start <= 0: return None if step is", "range(len(SUPPORTED_JAVA_DTYPES))} _J2PY = {SUPPORTED_JAVA_DTYPES[i] : SUPPORTED_PYTHON_DTYPES[i] for i in range(len(SUPPORTED_JAVA_DTYPES))}", "SUPPORTED_JAVA_DTYPES = [ DOUBLE, FLOAT, HALF, LONG, INT, SHORT, BOOL", "UTF8 = DataType.UTF8 COMPRESSED = DataType.COMPRESSED UNKNOWN = DataType.UNKNOWN SUPPORTED_JAVA_DTYPES", "def __div__(self, other): return ndarray(self.numpy() / _nparray(other)) other = _indarray(other)", "Apache License, Version 2.0 which is available at # https://www.apache.org/licenses/LICENSE-2.0.", "not set context dtype now. Set it at the beginning", "broadcast(self.array, other) self.array = Transforms.pow(x, y) return self def __getattr__(self,", "tuple(ys) nx = len(xs) ny = len(ys) if nx >", "return ndarray(Transforms.pow(x, y)) def __iadd__(self, other): self.numpy().__iadd__(_nparray(other)) return self other", "stop = shape[1] else: stop = shape[0] if stop -", "'numpy' in str(typ): return _from_numpy(x) elif typ in (list, tuple):", "Available dtypes are 'float' and 'double'.\".format(dtype)) dtype_ = DataTypeUtil.getDtypeFromContext(dtype) DataTypeUtil.setDTypeForContext(dtype_)", "y = broadcast(self.array, other) self.array = x.add(y) return self def", "'HALF': ctypes.c_short, 'LONG': ctypes.c_long, 'INT': ctypes.c_int, 'SHORT': ctypes.c_short, 'BOOL': ctypes.c_bool", "# we ignore dtype for now typ = type(data) if", "NotImplementedError( 'Sorry, this type of indexing is not supported yet.')", "and ' + str(_ys)) elif yd == 1: yt.append(xd) rep_y", "limitations # under the License. # # SPDX-License-Identifier: Apache-2.0 ################################################################################", "return self.array.length() @property def shape(self): return tuple(self.array.shape()) @shape.setter def shape(self,", "np.dtype(dtype).type elif isinstance(dtype, np.dtype): dtype = dtype.type jtype = _PY2J.get(dtype)", "= nx - ny ys = ([1] * diff) +", "None or step == 1: return ndarray(self.array.get(NDArrayIndex.interval(start, stop))) else: return", "shapes ' + str(_xs) + '' ' and ' +", "str(_xs) + '' ' and ' + str(_ys)) if rep_y:", "typ = type(x) if typ is INDArray: return ndarray(x).numpy() elif", "np.dtype): dtype = dtype.type jtype = _PY2J.get(dtype) if jtype is", "if dim == slice(None): args.append(NDArrayIndex.all()) else: start = dim.start stop", "np_array.__array_interface__['data'] _refs.append(np_array) pointer = native_ops.pointerForAddress(pointer_address) size = np_array.size pointer.limit(size) jdtype", "len(key) key += [slice(None)] * (ndim - nk) args =", "if xd == yd: yt.append(1) elif xd == 1: raise", "= ctypes.cast(address, Pointer) np_array = np.ctypeslib.as_array(pointer, tuple(nd4j_array.shape())) return np_array def", "in (list, tuple): return np.array(x) elif typ in (int, float):", "self.array.addi(other) else: x, y = broadcast(self.array, other) self.array = x.add(y)", "= broadcast(self.array, other) self.array = x.mul(y) return self def __idiv__(self,", "__getattr__(self, attr): import ops f = getattr(ops, attr) setattr(ndarray, attr,", "License for the specific language governing permissions and limitations #", "def _to_numpy(nd4j_array): ''' Convert nd4j array to numpy array '''", "is available at # https://www.apache.org/licenses/LICENSE-2.0. # # Unless required by", "Nd4j.create(buff, shape, strides, 0) assert buff.address() == nd4j_array.data().address() return nd4j_array", "@property def T(self): return self.transpose() def array(*args, **kwargs): return ndarray(*args,", "= [] def _from_numpy(np_array): ''' Convert numpy array to nd4j", "''' Convert nd4j array to numpy array ''' buff =", "_refs.append(np_array) pointer = native_ops.pointerForAddress(pointer_address) size = np_array.size pointer.limit(size) jdtype =", "elif yd == 1: yt.append(xd) rep_y = True else: raise", "step, stop))) if type(key) is list: raise NotImplementedError( 'Sorry, this", "# # This program and the accompanying materials are made", "self def __isub__(self, other): self.numpy().__isub__(_nparray(other)) return self other = _indarray(other)", "len(shape) nk = len(key) key += [slice(None)] * (ndim -", "if rep_x: x = Nd4j.tile(x, *xt) if rep_y: try: y", "self.array = self.array.muli(other) else: x, y = broadcast(self.array, other) self.array", "isinstance(dtype, str): dtype = np.dtype(dtype).type elif isinstance(dtype, np.dtype): dtype =", "'float' or 'double' ''' dtype_map = { 'float32': 'float', 'float64':", "= _indarray(other) view = self[key] if view is None: return", "''' buff = Nd4j.createBuffer(pointer, size, jdtype) assert buff.address() == pointer_address", "################################################################################ # Copyright (c) 2015-2018 Skymind, Inc. # # This", "__float__(self): if self.array.length() == 1: return self.array.getDouble(0) raise Exception('Applicable only", "DataType.BYTE BOOL = DataType.BOOL UTF8 = DataType.UTF8 COMPRESSED = DataType.COMPRESSED", "ndarray(self.numpy() * _nparray(other)) other = _indarray(other) x, y = broadcast(self.array,", "xs == ys: return x, y _xs = tuple(xs) _ys", "jdtype) assert buff.address() == pointer_address _refs.append(buff) elem_size = buff.getElementSize() assert", "made available under the # terms of the Apache License,", "SHORT, BOOL #UTF8 ] SUPPORTED_PYTHON_DTYPES = [ np.float64, np.float32, np.float16,", "elif type(dim) in (list, tuple): raise NotImplementedError( 'Sorry, this type", "= len(xs) ny = len(ys) if nx > ny: diff", "x): xs = x.shape() ys = y.shape() if xs ==", "DataTypeUtil.getDtypeFromContext() return DataTypeUtil.getDTypeForName(dtype) _refs = [] def _from_numpy(np_array): ''' Convert", "LONG: LongPointer, INT: IntPointer, SHORT: ShortPointer, BOOL: BoolPointer } pc", "the # License for the specific language governing permissions and", "FLOAT: FloatPointer, HALF: HalfPointer, LONG: LongPointer, INT: IntPointer, SHORT: ShortPointer,", "elif 'numpy' in str(typ): return _from_numpy(x) elif typ in (list,", "= { DOUBLE: DoublePointer, FLOAT: FloatPointer, HALF: HalfPointer, LONG: LongPointer,", "type not understood :' + str(typ)) def broadcast_like(y, x): xs", "np.float16, np.int64, np.int32, np.int16, np.bool_ #np.str_ ] _PY2J = {SUPPORTED_PYTHON_DTYPES[i]", "_dtype_py2j(dtype): if isinstance(dtype, str): dtype = np.dtype(dtype).type elif isinstance(dtype, np.dtype):", "[] for i, dim in enumerate(key): if type(dim) is int:", "ny ys = ([1] * diff) + ys y =", "dtype ''' dtype = DataTypeUtil.getDtypeFromContext() return DataTypeUtil.getDTypeForName(dtype) _refs = []", "return np.array(x) else: raise Exception('Data type not understood :' +", "self.array.muli(other) else: x, y = broadcast(self.array, other) self.array = x.mul(y)", "= DataType.LONG INT = DataType.INT SHORT = DataType.SHORT UBYTE =", "other = _indarray(other) x, y = broadcast(self.array, other) return ndarray(x.sub(y))", "if view is None: return view = view.array other =", "self.numpy().__isub__(_nparray(other)) return self other = _indarray(other) if self.array.shape() == other.shape():", "def _nparray(x): typ = type(x) if typ is INDArray: return", "raise NotImplementedError(\"Unsupported type: \" + (str(dtype))) return pytype def set_context_dtype(dtype):", "ys = ([1] * diff) + ys y = y.reshape(ys)", "_indarray(other) x, y = broadcast(self.array, other) return ndarray(x.div(y)) def __pow__(self,", "try: return self.np_array except AttributeError: self.np_array = _to_numpy(self.array) return self.np_array", "return np.array(x) elif typ in (int, float): return np.array(x) else:", "= ny - nx xs = ([1] * diff) +", "ny: diff = nx - ny ys = ([1] *", "= nx elif ny > nx: diff = ny -", "= np_array.size pointer.limit(size) jdtype = _dtype_py2j(np_array.dtype) ''' mapping = {", "if self.array.shape() == other.shape(): self.array = self.array.subi(other) else: x, y", "== yd: yt.append(1) elif xd == 1: raise Exception('Unable to", "DoublePointer, FLOAT: FloatPointer, HALF: HalfPointer, LONG: LongPointer, INT: IntPointer, SHORT:", "other.shape(): self.array = self.array.subi(other) else: x, y = broadcast(self.array, other)", "if type(key) is int: return ndarray(self.array.get(NDArrayIndex.point(key))) if type(key) is slice:", "key, other): self.numpy()[key] = _nparray(other) return other = _indarray(other) view", "= self.array.shape() ndim = len(shape) nk = len(key) key +=", "SUPPORTED_PYTHON_DTYPES[i] for i in range(len(SUPPORTED_JAVA_DTYPES))} def _dtype_py2j(dtype): if isinstance(dtype, str):", "ctypes.c_long, 'INT': ctypes.c_int, 'SHORT': ctypes.c_short, 'BOOL': ctypes.c_bool } Pointer =", "ndarray(self.array.get(*args)) def __setitem__(self, key, other): self.numpy()[key] = _nparray(other) return other", "y.repmat(*yt) return y def broadcast(x, y): xs = x.shape() ys", "def shape(self, value): arr = self.reshape(value) self.array = arr.array @property", "= _from_numpy(data) def numpy(self): try: return self.np_array except AttributeError: self.np_array", "if stop is None: stop = shape[i] if stop -", "slice: start = key.start stop = key.stop step = key.step", "elif type(dim) is slice: if dim == slice(None): args.append(NDArrayIndex.all()) else:", "== other.shape(): self.array = self.array.subi(other) else: x, y = broadcast(self.array,", "def __getattr__(self, attr): import ops f = getattr(ops, attr) setattr(ndarray,", "broadcast(x, y): xs = x.shape() ys = y.shape() if xs", "attr): import ops f = getattr(ops, attr) setattr(ndarray, attr, f)", "= ny xt = [] yt = [] rep_x =", "is not np.ndarray: data = np.array(data) self.array = _from_numpy(data) def", "tuple): return np.array(x) elif typ in (int, float): return np.array(x)", "don't make a copy here self.array = data elif typ", "SHORT: ShortPointer, BOOL: BoolPointer } pc = mapping[jdtype] #pointer =", "\" + (str(dtype))) return pytype def set_context_dtype(dtype): ''' Sets the", "dim.start stop = dim.stop step = dim.step if start is", "y = broadcast(self.array, other) return ndarray(x.add(y)) def __sub__(self, other): return", "self.array = _from_numpy(data) def numpy(self): try: return self.np_array except AttributeError:", "= [ DOUBLE, FLOAT, HALF, LONG, INT, SHORT, BOOL #UTF8", "other) self.array = Transforms.pow(x, y) return self def __getattr__(self, attr):", "self.array.length() == 1: return self.array.getInt(0) raise Exception('Applicable only for scalars')", "] _PY2J = {SUPPORTED_PYTHON_DTYPES[i] : SUPPORTED_JAVA_DTYPES[i] for i in range(len(SUPPORTED_JAVA_DTYPES))}", "only for scalars') @property def T(self): return self.transpose() def array(*args,", "yd: xt.append(1) yt.append(1) elif xd == 1: xt.append(yd) yt.append(1) rep_x", "ndarray: return x.array elif 'numpy' in str(typ): return _from_numpy(x) elif", "other) return ndarray(Transforms.pow(x, y)) def __iadd__(self, other): self.numpy().__iadd__(_nparray(other)) return self", "context dtype now. Set it at the beginning of your", "https://www.apache.org/licenses/LICENSE-2.0. # # Unless required by applicable law or agreed", "Exception('Data type not understood :' + str(typ)) def broadcast_like(y, x):", "= [dim / elem_size for dim in strides] shape =", "= DataType.BYTE BOOL = DataType.BOOL UTF8 = DataType.UTF8 COMPRESSED =", "str(typ): return x elif typ in (list, tuple): return np.array(x)", "jtype def _dtype_j2py(dtype): pytype = _J2PY.get(dtype) if pytype is None:", "= _indarray(other) x, y = broadcast(self.array, other) return ndarray(x.add(y)) def", "self.array.shape() == other.shape(): self.array = self.array.muli(other) else: x, y =", "= [] for i, dim in enumerate(key): if type(dim) is", "= {SUPPORTED_PYTHON_DTYPES[i] : SUPPORTED_JAVA_DTYPES[i] for i in range(len(SUPPORTED_JAVA_DTYPES))} _J2PY =", "** _nparray(other)) other = _indarray(other) x, y = broadcast(self.array, other)", "for xd, yd in zip(xs, ys): if xd == yd:", "yd: yt.append(1) elif xd == 1: raise Exception('Unable to broadcast", "return nd4j_array def _to_numpy(nd4j_array): ''' Convert nd4j array to numpy", "array ''' pointer_address, _ = np_array.__array_interface__['data'] _refs.append(np_array) pointer = native_ops.pointerForAddress(pointer_address)", "make a copy here self.array = data elif typ is", "= len(ys) if nx > ny: diff = nx -", "language governing permissions and limitations # under the License. #", "is int: args.append(NDArrayIndex.point(dim)) elif type(dim) is slice: if dim ==", "# WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "= y.repmat(*yt) return y def broadcast(x, y): xs = x.shape()", "_indarray(other) if self.array.shape() == other.shape(): self.array = self.array.divi(other) else: x,", "dtype = DataTypeUtil.getDtypeFromContext() return DataTypeUtil.getDTypeForName(dtype) _refs = [] def _from_numpy(np_array):", "__imul__(self, other): self.numpy().__imul__(_nparray(other)) return self other = _indarray(other) if self.array.shape()", "''' Returns the nd4j dtype ''' dtype = DataTypeUtil.getDtypeFromContext() return", "1: return self.array.getInt(0) raise Exception('Applicable only for scalars') def __float__(self):", "dim in strides] shape = np_array.shape nd4j_array = Nd4j.create(buff, shape,", "is slice: start = key.start stop = key.stop step =", "other) return ndarray(x.mul(y)) def __div__(self, other): return ndarray(self.numpy() / _nparray(other))", "for the specific language governing permissions and limitations # under", "1: return ndarray(self.array.get(NDArrayIndex.interval(start, stop))) else: return ndarray(self.array.get(NDArrayIndex.interval(start, step, stop))) if", "in str(typ): return _from_numpy(x) elif typ in (list, tuple): return", "raise NotImplementedError(\"Unsupported type: \" + dtype.name) return jtype def _dtype_j2py(dtype):", "> nx: diff = ny - nx xs = ([1]", "xt.append(yd) yt.append(1) rep_x = True elif yd == 1: xt.append(1)", "yet.') return ndarray(self.array.get(*args)) def __setitem__(self, key, other): self.numpy()[key] = _nparray(other)", "self.numpy().__idiv__(_nparray(other)) return self other = _indarray(other) if self.array.shape() == other.shape():", "= DataType.UTF8 COMPRESSED = DataType.COMPRESSED UNKNOWN = DataType.UNKNOWN SUPPORTED_JAVA_DTYPES =", "if self.array.length() == 1: return self.array.getInt(0) raise Exception('Applicable only for", "in (list, tuple): return _from_numpy(np.array(x)) elif typ in (int, float):", "'numpy' in str(typ): return x elif typ in (list, tuple):", "dtype) if dtype not in ['float', 'double']: raise ValueError(\"Invalid dtype", "is None: shape = self.array.shape() if shape[0] == 1: stop", "self.array.divi(other) else: x, y = broadcast(self.array, other) self.array = Transforms.pow(x,", "self.np_array = _to_numpy(self.array) return self.np_array @property def size(self): return self.array.length()", "stop = shape[0] if stop - start <= 0: return", "return x.array elif 'numpy' in str(typ): return _from_numpy(x) elif typ", "self.numpy()[key] = _nparray(other) return other = _indarray(other) view = self[key]", "np.int64, np.int32, np.int16, np.bool_ #np.str_ ] _PY2J = {SUPPORTED_PYTHON_DTYPES[i] :", "False for xd, yd in zip(xs, ys): if xd ==", "diff = ny - nx xs = ([1] * diff)", "pointer_address _refs.append(buff) elem_size = buff.getElementSize() assert elem_size == np_array.dtype.itemsize strides", "return ndarray(self.numpy() ** _nparray(other)) other = _indarray(other) x, y =", "= ctypes.POINTER(mapping[dtype]) pointer = ctypes.cast(address, Pointer) np_array = np.ctypeslib.as_array(pointer, tuple(nd4j_array.shape()))", "y _xs = tuple(xs) _ys = tuple(ys) nx = len(xs)", "not np.ndarray: data = np.array(data) self.array = _from_numpy(data) def numpy(self):", "other) return ndarray(x.sub(y)) def __mul__(self, other): return ndarray(self.numpy() * _nparray(other))", "+ dtype.name) return jtype def _dtype_j2py(dtype): pytype = _J2PY.get(dtype) if", "return x.numpy() elif 'numpy' in str(typ): return x elif typ", "is None or step == 1: return ndarray(self.array.get(NDArrayIndex.interval(start, stop))) else:", "other.shape(): self.array = self.array.addi(other) else: x, y = broadcast(self.array, other)", "''' dtype_map = { 'float32': 'float', 'float64': 'double' } dtype", "self.array = x.mul(y) return self def __idiv__(self, other): self.numpy().__idiv__(_nparray(other)) return", "type of indexing is not supported yet.') if type(key) is", "['float', 'double']: raise ValueError(\"Invalid dtype '{}'. Available dtypes are 'float'", "' + str(_ys)) if rep_x: x = Nd4j.tile(x, *xt) if", "+ '' ' and ' + str(_ys)) if rep_x: x", "License. # # SPDX-License-Identifier: Apache-2.0 ################################################################################ from .java_classes import *", "if start is None: start = 0 if stop is", "= dim.start stop = dim.stop step = dim.step if start", "type(dim) is slice: if dim == slice(None): args.append(NDArrayIndex.all()) else: start", "__init__(self, data, dtype=None): # we ignore dtype for now typ", "TYPE MANAGEMENT DOUBLE = DataType.DOUBLE FLOAT = DataType.FLOAT HALF =", "pytype = _J2PY.get(dtype) if pytype is None: raise NotImplementedError(\"Unsupported type:", "= type(x) if typ is INDArray: return ndarray(x).numpy() elif typ", "elif yd == 1: xt.append(1) yt.append(xd) rep_y = True else:", "return self.np_array except AttributeError: self.np_array = _to_numpy(self.array) return self.np_array @property", "and the accompanying materials are made available under the #", "== other.shape(): self.array = self.array.muli(other) else: x, y = broadcast(self.array,", "if typ is INDArray: return x elif typ is ndarray:", "not in ['float', 'double']: raise ValueError(\"Invalid dtype '{}'. Available dtypes", "== ys: return x, y _xs = tuple(xs) _ys =", "= pc(pointer) ''' buff = Nd4j.createBuffer(pointer, size, jdtype) assert buff.address()", "x, y = broadcast(self.array, other) return ndarray(x.div(y)) def __pow__(self, other):", "if typ is not np.ndarray: data = np.array(data) self.array =", "ndarray(self.array.get(NDArrayIndex.interval(start, stop))) else: return ndarray(self.array.get(NDArrayIndex.interval(start, step, stop))) if type(key) is", "elif typ in (int, float): return np.array(x) else: raise Exception('Data", "view.assign(other) def __add__(self, other): return ndarray(self.numpy() + _nparray(other)) other =", "= dtype.type jtype = _PY2J.get(dtype) if jtype is None: raise", "= self.array.muli(other) else: x, y = broadcast(self.array, other) self.array =", "else: return ndarray(self.array.get(NDArrayIndex.interval(start, step, stop))) if type(key) is list: raise", "if type(key) is list: raise NotImplementedError( 'Sorry, this type of", "= shape[i] if stop - start <= 0: return None", "= [] rep_x = False rep_y = False for xd,", "def size(self): return self.array.length() @property def shape(self): return tuple(self.array.shape()) @shape.setter", "__sub__(self, other): return ndarray(self.numpy() - _nparray(other)) other = _indarray(other) x,", "x, y = broadcast(self.array, other) return ndarray(x.add(y)) def __sub__(self, other):", "software # distributed under the License is distributed on an", "_indarray(other) if self.array.shape() == other.shape(): self.array = self.array.muli(other) else: x,", "np.array(x) elif typ in (int, float): return np.array(x) else: raise", "is None: stop = shape[i] if stop - start <=", "supported yet.') return ndarray(self.array.get(*args)) def __setitem__(self, key, other): self.numpy()[key] =", "= NativeOpsHolder.getInstance().getDeviceNativeOps() # DATA TYPE MANAGEMENT DOUBLE = DataType.DOUBLE FLOAT", "''' dtype = DataTypeUtil.getDtypeFromContext() return DataTypeUtil.getDTypeForName(dtype) _refs = [] def", "y = broadcast(self.array, other) self.array = x.sub(y) return self def", "ny = nx elif ny > nx: raise Exception('Unable to", "y = broadcast(self.array, other) return ndarray(Transforms.pow(x, y)) def __iadd__(self, other):", "type(data) if 'nd4j' in typ.__name__: # Note that we don't", "float): return Nd4j.scalar(x) else: raise Exception('Data type not understood :'", "# # SPDX-License-Identifier: Apache-2.0 ################################################################################ from .java_classes import * import", "* (ndim - nk) args = [] for i, dim", "{ 'DOUBLE': ctypes.c_double, 'FLOAT': ctypes.c_float, 'HALF': ctypes.c_short, 'LONG': ctypes.c_long, 'INT':", "other = _indarray(other) view = self[key] if view is None:", "str(_xs) + '' ' and ' + str(_ys)) if rep_x:", "step == 1: return ndarray(self.array.get(NDArrayIndex.interval(start, stop))) else: return ndarray(self.array.get(NDArrayIndex.interval(start, step,", "typ is ndarray: return x.array elif 'numpy' in str(typ): return", "y def broadcast(x, y): xs = x.shape() ys = y.shape()", "broadcast(self.array, other) self.array = x.div(y) return self def __ipow__(self, other):", "<= 0: return None if step is None or step", "dtype for nd4j # Arguments dtype: 'float' or 'double' '''", "= ([1] * diff) + ys y = y.reshape(*ys) ny", "\"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY", "if type(key) is slice: start = key.start stop = key.stop", "ctypes.c_short, 'BOOL': ctypes.c_bool } Pointer = ctypes.POINTER(mapping[dtype]) pointer = ctypes.cast(address,", "y.reshape(ys) ny = nx elif ny > nx: raise Exception('Unable", "'FLOAT': ctypes.c_float, 'HALF': ctypes.c_short, 'LONG': ctypes.c_long, 'INT': ctypes.c_int, 'SHORT': ctypes.c_short,", "mapping = { DOUBLE: DoublePointer, FLOAT: FloatPointer, HALF: HalfPointer, LONG:", "rep_y = True else: raise Exception('Unable to broadcast shapes '", "y = Nd4j.tile(y, *yt) except: y = Nd4j.tile(y, *yt) return", "pc = mapping[jdtype] #pointer = pc(pointer) ''' buff = Nd4j.createBuffer(pointer,", "DataType.UNKNOWN SUPPORTED_JAVA_DTYPES = [ DOUBLE, FLOAT, HALF, LONG, INT, SHORT,", "broadcast(self.array, other) return ndarray(x.sub(y)) def __mul__(self, other): return ndarray(self.numpy() *", "of the Apache License, Version 2.0 which is available at", "xd == yd: yt.append(1) elif xd == 1: raise Exception('Unable", "broadcast(self.array, other) self.array = x.mul(y) return self def __idiv__(self, other):", "_indarray(other) x, y = broadcast(self.array, other) return ndarray(x.sub(y)) def __mul__(self,", "y)) def __iadd__(self, other): self.numpy().__iadd__(_nparray(other)) return self other = _indarray(other)", "other) self.array = x.add(y) return self def __isub__(self, other): self.numpy().__isub__(_nparray(other))", "other = _indarray(other) x, y = broadcast(self.array, other) return ndarray(x.div(y))", "pc(pointer) ''' buff = Nd4j.createBuffer(pointer, size, jdtype) assert buff.address() ==", "_nparray(other)) other = _indarray(other) x, y = broadcast(self.array, other) return", "enumerate(key): if type(dim) is int: args.append(NDArrayIndex.point(dim)) elif type(dim) is slice:", "if stop - start <= 0: return None if step", "def __iadd__(self, other): self.numpy().__iadd__(_nparray(other)) return self other = _indarray(other) if", "(list, tuple): return _from_numpy(np.array(x)) elif typ in (int, float): return", "nd4j array ''' pointer_address, _ = np_array.__array_interface__['data'] _refs.append(np_array) pointer =", "+ '' ' and ' + str(_ys)) if rep_y: y", "DataType.UBYTE BYTE = DataType.BYTE BOOL = DataType.BOOL UTF8 = DataType.UTF8", "in typ.__name__: # Note that we don't make a copy", "other): return ndarray(self.numpy() / _nparray(other)) other = _indarray(other) x, y", "typ = type(data) if 'nd4j' in typ.__name__: # Note that", "(str(dtype))) return pytype def set_context_dtype(dtype): ''' Sets the dtype for", "= Nd4j.create(buff, shape, strides, 0) assert buff.address() == nd4j_array.data().address() return", "' and ' + str(_ys)) yt = [] rep_y =", "list: raise NotImplementedError( 'Sorry, this type of indexing is not", "+ ys y = y.reshape(*ys) ny = nx elif ny", "tuple: key = list(key) shape = self.array.shape() ndim = len(shape)", "x, y = broadcast(self.array, other) return ndarray(x.sub(y)) def __mul__(self, other):", "an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF", "self def __imul__(self, other): self.numpy().__imul__(_nparray(other)) return self other = _indarray(other)", "def broadcast(x, y): xs = x.shape() ys = y.shape() if", "this type of indexing is not supported yet.') return ndarray(self.array.get(*args))", "y = broadcast(self.array, other) self.array = x.mul(y) return self def", "'double'.\".format(dtype)) dtype_ = DataTypeUtil.getDtypeFromContext(dtype) DataTypeUtil.setDTypeForContext(dtype_) if get_context_dtype() != dtype: warnings.warn(\"Can", "to nd4j array ''' pointer_address, _ = np_array.__array_interface__['data'] _refs.append(np_array) pointer", "dtype not in ['float', 'double']: raise ValueError(\"Invalid dtype '{}'. Available", "len(self.array.shape()) def __getitem__(self, key): return ndarray(self.numpy()[key]) if type(key) is int:", "yd in zip(xs, ys): if xd == yd: yt.append(1) elif", "#pointer = pc(pointer) ''' buff = Nd4j.createBuffer(pointer, size, jdtype) assert", "BOOL #UTF8 ] SUPPORTED_PYTHON_DTYPES = [ np.float64, np.float32, np.float16, np.int64,", "= DataTypeUtil.getDtypeFromContext(dtype) DataTypeUtil.setDTypeForContext(dtype_) if get_context_dtype() != dtype: warnings.warn(\"Can not set", "self.array = arr.array @property def ndim(self): return len(self.array.shape()) def __getitem__(self,", "return x, y class ndarray(object): def __init__(self, data, dtype=None): #", "from .java_classes import * import numpy as np import ctypes", "of your program.\") def get_context_dtype(): ''' Returns the nd4j dtype", "diff) + ys y = y.reshape(ys) ny = nx elif", "np.array(data) self.array = _from_numpy(data) def numpy(self): try: return self.np_array except", "x, y = broadcast(self.array, other) self.array = Transforms.pow(x, y) return", "KIND, either express or implied. See the # License for", "IntPointer, SHORT: ShortPointer, BOOL: BoolPointer } pc = mapping[jdtype] #pointer", "def __add__(self, other): return ndarray(self.numpy() + _nparray(other)) other = _indarray(other)", "return ndarray(self.array.get(NDArrayIndex.point(key))) if type(key) is slice: start = key.start stop", "== other.shape(): self.array = self.array.addi(other) else: x, y = broadcast(self.array,", "== pointer_address _refs.append(buff) elem_size = buff.getElementSize() assert elem_size == np_array.dtype.itemsize", "step == 1: args.append(NDArrayIndex.interval(start, stop)) else: args.append(NDArrayIndex.interval( start, step, stop))", "return ndarray(x).numpy() elif typ is ndarray: return x.numpy() elif 'numpy'", "other) self.array = x.mul(y) return self def __idiv__(self, other): self.numpy().__idiv__(_nparray(other))", "This program and the accompanying materials are made available under", "DataType.LONG INT = DataType.INT SHORT = DataType.SHORT UBYTE = DataType.UBYTE", "ndarray(self.array.get(NDArrayIndex.interval(start, step, stop))) if type(key) is list: raise NotImplementedError( 'Sorry,", "if type(dim) is int: args.append(NDArrayIndex.point(dim)) elif type(dim) is slice: if", "ndarray(x.mul(y)) def __div__(self, other): return ndarray(self.numpy() / _nparray(other)) other =", "= DataType.UNKNOWN SUPPORTED_JAVA_DTYPES = [ DOUBLE, FLOAT, HALF, LONG, INT,", "def __isub__(self, other): self.numpy().__isub__(_nparray(other)) return self other = _indarray(other) if", "at the beginning of your program.\") def get_context_dtype(): ''' Returns", "key = list(key) shape = self.array.shape() ndim = len(shape) nk", "None: raise NotImplementedError(\"Unsupported type: \" + (str(dtype))) return pytype def", "start = 0 if stop is None: shape = self.array.shape()", "is slice: if dim == slice(None): args.append(NDArrayIndex.all()) else: start =", "np import ctypes import warnings native_ops = NativeOpsHolder.getInstance().getDeviceNativeOps() # DATA", "DataType.COMPRESSED UNKNOWN = DataType.UNKNOWN SUPPORTED_JAVA_DTYPES = [ DOUBLE, FLOAT, HALF,", "def numpy(self): try: return self.np_array except AttributeError: self.np_array = _to_numpy(self.array)", "= buff.getElementSize() assert elem_size == np_array.dtype.itemsize strides = np_array.strides strides", "return view = view.array other = broadcast_like(other, view) view.assign(other) def", "def broadcast_like(y, x): xs = x.shape() ys = y.shape() if", "implied. See the # License for the specific language governing", "== ys: return y _xs = tuple(xs) _ys = tuple(ys)", "= False for xd, yd in zip(xs, ys): if xd", "= nd4j_array.dataType().toString() mapping = { 'DOUBLE': ctypes.c_double, 'FLOAT': ctypes.c_float, 'HALF':", "{ 'float32': 'float', 'float64': 'double' } dtype = dtype_map.get(dtype, dtype)", "in zip(xs, ys): if xd == yd: yt.append(1) elif xd", "if jtype is None: raise NotImplementedError(\"Unsupported type: \" + dtype.name)", "other): return ndarray(self.numpy() * _nparray(other)) other = _indarray(other) x, y", "FLOAT = DataType.FLOAT HALF = DataType.HALF LONG = DataType.LONG INT", "ys): if xd == yd: yt.append(1) elif xd == 1:", "False rep_y = False for xd, yd in zip(xs, ys):", "terms of the Apache License, Version 2.0 which is available", "_from_numpy(np.array(x)) elif typ in (int, float): return Nd4j.scalar(x) else: raise", "address = buff.pointer().address() dtype = nd4j_array.dataType().toString() mapping = { 'DOUBLE':", "numpy array to nd4j array ''' pointer_address, _ = np_array.__array_interface__['data']", "'Sorry, this type of indexing is not supported yet.') if", "except: y = Nd4j.tile(y, *yt) return x, y class ndarray(object):", "ys y = y.reshape(*ys) ny = nx elif ny >", "_refs.append(buff) elem_size = buff.getElementSize() assert elem_size == np_array.dtype.itemsize strides =", "return Nd4j.scalar(x) else: raise Exception('Data type not understood :' +", "Transforms.pow(x, y) return self def __getattr__(self, attr): import ops f", "xd == 1: xt.append(yd) yt.append(1) rep_x = True elif yd", "only for scalars') def __float__(self): if self.array.length() == 1: return", "x, y = broadcast(self.array, other) return ndarray(Transforms.pow(x, y)) def __iadd__(self,", "y.shape() if xs == ys: return y _xs = tuple(xs)", "return getattr(self, attr) def __int__(self): if self.array.length() == 1: return", "int: return ndarray(self.array.get(NDArrayIndex.point(key))) if type(key) is slice: start = key.start", "elif 'numpy' in str(typ): return x elif typ in (list,", "tuple): raise NotImplementedError( 'Sorry, this type of indexing is not", "DataType.FLOAT HALF = DataType.HALF LONG = DataType.LONG INT = DataType.INT", "= x.reshape(*xs) nx = ny xt = [] yt =", "__getitem__(self, key): return ndarray(self.numpy()[key]) if type(key) is int: return ndarray(self.array.get(NDArrayIndex.point(key)))", "ny xt = [] yt = [] rep_x = False", "that we don't make a copy here self.array = data", "@property def size(self): return self.array.length() @property def shape(self): return tuple(self.array.shape())", "size(self): return self.array.length() @property def shape(self): return tuple(self.array.shape()) @shape.setter def", "in zip(xs, ys): if xd == yd: xt.append(1) yt.append(1) elif", "_to_numpy(self.array) return self.np_array @property def size(self): return self.array.length() @property def", "return ndarray(self.array.get(NDArrayIndex.interval(start, step, stop))) if type(key) is list: raise NotImplementedError(", "broadcast(self.array, other) self.array = x.sub(y) return self def __imul__(self, other):", "= False rep_y = False for xd, yd in zip(xs,", "np_array = np.ctypeslib.as_array(pointer, tuple(nd4j_array.shape())) return np_array def _indarray(x): typ =", "{ DOUBLE: DoublePointer, FLOAT: FloatPointer, HALF: HalfPointer, LONG: LongPointer, INT:", "shape, strides, 0) assert buff.address() == nd4j_array.data().address() return nd4j_array def", "ndarray(x.div(y)) def __pow__(self, other): return ndarray(self.numpy() ** _nparray(other)) other =", "Pointer = ctypes.POINTER(mapping[dtype]) pointer = ctypes.cast(address, Pointer) np_array = np.ctypeslib.as_array(pointer,", "dim == slice(None): args.append(NDArrayIndex.all()) else: start = dim.start stop =", "= getattr(ops, attr) setattr(ndarray, attr, f) return getattr(self, attr) def", "dtype now. Set it at the beginning of your program.\")", "assert buff.address() == nd4j_array.data().address() return nd4j_array def _to_numpy(nd4j_array): ''' Convert", "else: x, y = broadcast(self.array, other) self.array = x.sub(y) return", "size = np_array.size pointer.limit(size) jdtype = _dtype_py2j(np_array.dtype) ''' mapping =", "stop = shape[i] if stop - start <= 0: return", "of indexing is not supported yet.') return ndarray(self.array.get(*args)) def __setitem__(self,", "raise Exception('Data type not understood :' + str(typ)) def _nparray(x):", "accompanying materials are made available under the # terms of", "and limitations # under the License. # # SPDX-License-Identifier: Apache-2.0", "return ndarray(self.array.get(NDArrayIndex.interval(start, stop))) else: return ndarray(self.array.get(NDArrayIndex.interval(start, step, stop))) if type(key)", "return self def __getattr__(self, attr): import ops f = getattr(ops,", "other): self.numpy().__isub__(_nparray(other)) return self other = _indarray(other) if self.array.shape() ==", "self.numpy().__imul__(_nparray(other)) return self other = _indarray(other) if self.array.shape() == other.shape():", "slice: if dim == slice(None): args.append(NDArrayIndex.all()) else: start = dim.start", "range(len(SUPPORTED_JAVA_DTYPES))} def _dtype_py2j(dtype): if isinstance(dtype, str): dtype = np.dtype(dtype).type elif", "NotImplementedError(\"Unsupported type: \" + dtype.name) return jtype def _dtype_j2py(dtype): pytype", "_from_numpy(data) def numpy(self): try: return self.np_array except AttributeError: self.np_array =", "get_context_dtype() != dtype: warnings.warn(\"Can not set context dtype now. Set", "the License. # # SPDX-License-Identifier: Apache-2.0 ################################################################################ from .java_classes import", "= self.array.divi(other) else: x, y = broadcast(self.array, other) self.array =", "HALF = DataType.HALF LONG = DataType.LONG INT = DataType.INT SHORT", "0 if stop is None: stop = shape[i] if stop", "= _to_numpy(self.array) return self.np_array @property def size(self): return self.array.length() @property", "step = key.step if start is None: start = 0", "i, dim in enumerate(key): if type(dim) is int: args.append(NDArrayIndex.point(dim)) elif", "type(key) is int: return ndarray(self.array.get(NDArrayIndex.point(key))) if type(key) is slice: start", "buff.pointer().address() dtype = nd4j_array.dataType().toString() mapping = { 'DOUBLE': ctypes.c_double, 'FLOAT':", "f = getattr(ops, attr) setattr(ndarray, attr, f) return getattr(self, attr)", "= mapping[jdtype] #pointer = pc(pointer) ''' buff = Nd4j.createBuffer(pointer, size,", "of indexing is not supported yet.') if type(key) is tuple:", "not supported yet.') return ndarray(self.array.get(*args)) def __setitem__(self, key, other): self.numpy()[key]", "in (list, tuple): raise NotImplementedError( 'Sorry, this type of indexing", "in strides] shape = np_array.shape nd4j_array = Nd4j.create(buff, shape, strides,", "x = x.reshape(*xs) nx = ny xt = [] yt", "([1] * diff) + ys y = y.reshape(*ys) ny =", "_indarray(other) x, y = broadcast(self.array, other) return ndarray(x.add(y)) def __sub__(self,", "type not understood :' + str(typ)) def _nparray(x): typ =", "available at # https://www.apache.org/licenses/LICENSE-2.0. # # Unless required by applicable", "typ is not np.ndarray: data = np.array(data) self.array = _from_numpy(data)", "for scalars') def __float__(self): if self.array.length() == 1: return self.array.getDouble(0)", "by applicable law or agreed to in writing, software #", "f) return getattr(self, attr) def __int__(self): if self.array.length() == 1:", "= native_ops.pointerForAddress(pointer_address) size = np_array.size pointer.limit(size) jdtype = _dtype_py2j(np_array.dtype) '''", "+ ys y = y.reshape(ys) ny = nx elif ny", "attr) def __int__(self): if self.array.length() == 1: return self.array.getInt(0) raise", "other) return ndarray(x.add(y)) def __sub__(self, other): return ndarray(self.numpy() - _nparray(other))", "other = _indarray(other) if self.array.shape() == other.shape(): self.array = self.array.subi(other)", "materials are made available under the # terms of the", "SPDX-License-Identifier: Apache-2.0 ################################################################################ from .java_classes import * import numpy as", "*yt) except: y = Nd4j.tile(y, *yt) return x, y class", "return self other = _indarray(other) if self.array.shape() == other.shape(): self.array", "> ny: diff = nx - ny ys = ([1]", "governing permissions and limitations # under the License. # #", "= tuple(ys) nx = len(xs) ny = len(ys) if nx", "args.append(NDArrayIndex.point(dim)) elif type(dim) is slice: if dim == slice(None): args.append(NDArrayIndex.all())", "0) assert buff.address() == nd4j_array.data().address() return nd4j_array def _to_numpy(nd4j_array): '''", "xd == 1: raise Exception('Unable to broadcast shapes ' +", "DOUBLE, FLOAT, HALF, LONG, INT, SHORT, BOOL #UTF8 ] SUPPORTED_PYTHON_DTYPES", "np_array.strides strides = [dim / elem_size for dim in strides]", "beginning of your program.\") def get_context_dtype(): ''' Returns the nd4j", "_refs = [] def _from_numpy(np_array): ''' Convert numpy array to", "(int, float): return np.array(x) else: raise Exception('Data type not understood", "if self.array.shape() == other.shape(): self.array = self.array.muli(other) else: x, y", "True else: raise Exception('Unable to broadcast shapes ' + str(_xs)", "nx - ny ys = ([1] * diff) + ys", "for i, dim in enumerate(key): if type(dim) is int: args.append(NDArrayIndex.point(dim))", "y) return self def __getattr__(self, attr): import ops f =", "applicable law or agreed to in writing, software # distributed", "broadcast(self.array, other) return ndarray(x.add(y)) def __sub__(self, other): return ndarray(self.numpy() -", "= _indarray(other) if self.array.shape() == other.shape(): self.array = self.array.addi(other) else:", "np.bool_ #np.str_ ] _PY2J = {SUPPORTED_PYTHON_DTYPES[i] : SUPPORTED_JAVA_DTYPES[i] for i", "if typ is INDArray: return ndarray(x).numpy() elif typ is ndarray:", "other = _indarray(other) x, y = broadcast(self.array, other) return ndarray(Transforms.pow(x,", "Version 2.0 which is available at # https://www.apache.org/licenses/LICENSE-2.0. # #", "nx xs = ([1] * diff) + xs x =", "WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express", "getattr(self, attr) def __int__(self): if self.array.length() == 1: return self.array.getInt(0)", "self.array = x.sub(y) return self def __imul__(self, other): self.numpy().__imul__(_nparray(other)) return", "- nx xs = ([1] * diff) + xs x", "str(_xs) + '' ' and ' + str(_ys)) elif yd", "''' mapping = { DOUBLE: DoublePointer, FLOAT: FloatPointer, HALF: HalfPointer,", ":' + str(typ)) def _nparray(x): typ = type(x) if typ", "for now typ = type(data) if 'nd4j' in typ.__name__: #", "ctypes import warnings native_ops = NativeOpsHolder.getInstance().getDeviceNativeOps() # DATA TYPE MANAGEMENT", "typ is ndarray: return x.numpy() elif 'numpy' in str(typ): return", "other.shape(): self.array = self.array.muli(other) else: x, y = broadcast(self.array, other)", "ctypes.POINTER(mapping[dtype]) pointer = ctypes.cast(address, Pointer) np_array = np.ctypeslib.as_array(pointer, tuple(nd4j_array.shape())) return", "self.array.shape() == other.shape(): self.array = self.array.divi(other) else: x, y =", "Set it at the beginning of your program.\") def get_context_dtype():", "mapping[jdtype] #pointer = pc(pointer) ''' buff = Nd4j.createBuffer(pointer, size, jdtype)", "# License for the specific language governing permissions and limitations", "strides] shape = np_array.shape nd4j_array = Nd4j.create(buff, shape, strides, 0)", "strides = [dim / elem_size for dim in strides] shape", "diff) + ys y = y.reshape(*ys) ny = nx elif", "return self.np_array @property def size(self): return self.array.length() @property def shape(self):", "dtype: 'float' or 'double' ''' dtype_map = { 'float32': 'float',", "self.numpy().__ipow__(_nparray(other)) return self other = _indarray(other) if self.array.shape() == other.shape():", "= DataType.COMPRESSED UNKNOWN = DataType.UNKNOWN SUPPORTED_JAVA_DTYPES = [ DOUBLE, FLOAT,", "pointer = native_ops.pointerForAddress(pointer_address) size = np_array.size pointer.limit(size) jdtype = _dtype_py2j(np_array.dtype)", "i in range(len(SUPPORTED_JAVA_DTYPES))} def _dtype_py2j(dtype): if isinstance(dtype, str): dtype =", "DataTypeUtil.getDtypeFromContext(dtype) DataTypeUtil.setDTypeForContext(dtype_) if get_context_dtype() != dtype: warnings.warn(\"Can not set context", "nd4j_array.data() address = buff.pointer().address() dtype = nd4j_array.dataType().toString() mapping = {", "elif isinstance(dtype, np.dtype): dtype = dtype.type jtype = _PY2J.get(dtype) if", "import ctypes import warnings native_ops = NativeOpsHolder.getInstance().getDeviceNativeOps() # DATA TYPE", "y = y.reshape(*ys) ny = nx elif ny > nx:", "xs = ([1] * diff) + xs x = x.reshape(*xs)", "+ (str(dtype))) return pytype def set_context_dtype(dtype): ''' Sets the dtype", "program and the accompanying materials are made available under the", "else: x, y = broadcast(self.array, other) self.array = Transforms.pow(x, y)", "return self.array.getDouble(0) raise Exception('Applicable only for scalars') @property def T(self):", "(list, tuple): raise NotImplementedError( 'Sorry, this type of indexing is", "str(_ys)) if rep_y: y = y.repmat(*yt) return y def broadcast(x,", "under the License. # # SPDX-License-Identifier: Apache-2.0 ################################################################################ from .java_classes", "__setitem__(self, key, other): self.numpy()[key] = _nparray(other) return other = _indarray(other)", "/ elem_size for dim in strides] shape = np_array.shape nd4j_array", "buff = Nd4j.createBuffer(pointer, size, jdtype) assert buff.address() == pointer_address _refs.append(buff)", "dtype '{}'. Available dtypes are 'float' and 'double'.\".format(dtype)) dtype_ =", "_indarray(other) if self.array.shape() == other.shape(): self.array = self.array.subi(other) else: x,", "str(_ys)) elif yd == 1: yt.append(xd) rep_y = True else:", "other = _indarray(other) if self.array.shape() == other.shape(): self.array = self.array.muli(other)", "key.start stop = key.stop step = key.step if start is", "ys: return y _xs = tuple(xs) _ys = tuple(ys) nx", "= broadcast_like(other, view) view.assign(other) def __add__(self, other): return ndarray(self.numpy() +", "typ = type(x) if typ is INDArray: return x elif", "= broadcast(self.array, other) return ndarray(x.div(y)) def __pow__(self, other): return ndarray(self.numpy()", "yet.') if type(key) is tuple: key = list(key) shape =", "scalars') def __float__(self): if self.array.length() == 1: return self.array.getDouble(0) raise", "x.shape() ys = y.shape() if xs == ys: return y", "+ str(_ys)) if rep_y: y = y.repmat(*yt) return y def", "nx = ny xt = [] yt = [] rep_x", "ANY KIND, either express or implied. See the # License", "== slice(None): args.append(NDArrayIndex.all()) else: start = dim.start stop = dim.stop", "INT: IntPointer, SHORT: ShortPointer, BOOL: BoolPointer } pc = mapping[jdtype]", "ndarray(x).numpy() elif typ is ndarray: return x.numpy() elif 'numpy' in", "== 1: xt.append(yd) yt.append(1) rep_x = True elif yd ==", "x, y = broadcast(self.array, other) self.array = x.mul(y) return self", "typ in (list, tuple): return np.array(x) elif typ in (int,", "other = _indarray(other) x, y = broadcast(self.array, other) return ndarray(x.add(y))", "self.array.length() @property def shape(self): return tuple(self.array.shape()) @shape.setter def shape(self, value):", "shape(self): return tuple(self.array.shape()) @shape.setter def shape(self, value): arr = self.reshape(value)", "if nx > ny: diff = nx - ny ys", "shape[0] == 1: stop = shape[1] else: stop = shape[0]", "rep_y: try: y = Nd4j.tile(y, *yt) except: y = Nd4j.tile(y,", "ndarray(self.numpy() ** _nparray(other)) other = _indarray(other) x, y = broadcast(self.array,", "arr.array @property def ndim(self): return len(self.array.shape()) def __getitem__(self, key): return", "ShortPointer, BOOL: BoolPointer } pc = mapping[jdtype] #pointer = pc(pointer)", "x, y = broadcast(self.array, other) self.array = x.sub(y) return self", "self[key] if view is None: return view = view.array other", "Sets the dtype for nd4j # Arguments dtype: 'float' or", "else: if typ is not np.ndarray: data = np.array(data) self.array", "else: raise Exception('Data type not understood :' + str(typ)) def", "or implied. See the # License for the specific language", "ndarray(x.sub(y)) def __mul__(self, other): return ndarray(self.numpy() * _nparray(other)) other =" ]
[ "mode 177,163,181,181 ser.flush() ser.flushInput() obs = ser.read(8) if len(obs) !=", "% (keys, usec) ser.write(\"\\xb1\\xa3\\xa9\\xa9\") #turn off oscilloscope: set keyboard mode", "8: print('Error: no buttons presses detected') print 'Observed data (as", "(obsBin[3] << 24)+ (obsBin[4] << 16)+ (obsBin[5] << 8)+obsBin[6] keys", "serial ser = serial.Serial('/dev/tty.usbmodem7071', 115200, timeout=10) ser.write(\"\\xb1\\xa3\\xb5\\xb5\") #set usec mode", "if len(obs) != 8: print('Error: no buttons presses detected') print", "24)+ (obsBin[4] << 16)+ (obsBin[5] << 8)+obsBin[6] keys = (obsBin[1]", "detected') print 'Observed data (as hex): '+ obs.encode('hex') obsBin =", "ser = serial.Serial('/dev/tty.usbmodem7071', 115200, timeout=10) ser.write(\"\\xb1\\xa3\\xb5\\xb5\") #set usec mode 177,163,181,181", "(obsBin[5] << 8)+obsBin[6] keys = (obsBin[1] << 8)+obsBin[2] print 'keys", "= [ord(c) for c in obs] usec = (obsBin[3] <<", "print 'Observed data (as hex): '+ obs.encode('hex') obsBin = [ord(c)", "usec = (obsBin[3] << 24)+ (obsBin[4] << 16)+ (obsBin[5] <<", "%d usec' % (keys, usec) ser.write(\"\\xb1\\xa3\\xa9\\xa9\") #turn off oscilloscope: set", "usec) ser.write(\"\\xb1\\xa3\\xa9\\xa9\") #turn off oscilloscope: set keyboard mode 177,163,169,169 ser.close()", "ser.write(\"\\xb1\\xa3\\xb5\\xb5\") #set usec mode 177,163,181,181 ser.flush() ser.flushInput() obs = ser.read(8)", "177,163,181,181 ser.flush() ser.flushInput() obs = ser.read(8) if len(obs) != 8:", "'Observed data (as hex): '+ obs.encode('hex') obsBin = [ord(c) for", "= (obsBin[3] << 24)+ (obsBin[4] << 16)+ (obsBin[5] << 8)+obsBin[6]", "c in obs] usec = (obsBin[3] << 24)+ (obsBin[4] <<", "'+ obs.encode('hex') obsBin = [ord(c) for c in obs] usec", "= ser.read(8) if len(obs) != 8: print('Error: no buttons presses", "= (obsBin[1] << 8)+obsBin[2] print 'keys pressed %d at %d", "pressed %d at %d usec' % (keys, usec) ser.write(\"\\xb1\\xa3\\xa9\\xa9\") #turn", "!= 8: print('Error: no buttons presses detected') print 'Observed data", "16)+ (obsBin[5] << 8)+obsBin[6] keys = (obsBin[1] << 8)+obsBin[2] print", "obs] usec = (obsBin[3] << 24)+ (obsBin[4] << 16)+ (obsBin[5]", "obs.encode('hex') obsBin = [ord(c) for c in obs] usec =", "<< 16)+ (obsBin[5] << 8)+obsBin[6] keys = (obsBin[1] << 8)+obsBin[2]", "obsBin = [ord(c) for c in obs] usec = (obsBin[3]", "<< 8)+obsBin[2] print 'keys pressed %d at %d usec' %", "8)+obsBin[2] print 'keys pressed %d at %d usec' % (keys,", "import serial ser = serial.Serial('/dev/tty.usbmodem7071', 115200, timeout=10) ser.write(\"\\xb1\\xa3\\xb5\\xb5\") #set usec", "for c in obs] usec = (obsBin[3] << 24)+ (obsBin[4]", "usec' % (keys, usec) ser.write(\"\\xb1\\xa3\\xa9\\xa9\") #turn off oscilloscope: set keyboard", "115200, timeout=10) ser.write(\"\\xb1\\xa3\\xb5\\xb5\") #set usec mode 177,163,181,181 ser.flush() ser.flushInput() obs", "buttons presses detected') print 'Observed data (as hex): '+ obs.encode('hex')", "= serial.Serial('/dev/tty.usbmodem7071', 115200, timeout=10) ser.write(\"\\xb1\\xa3\\xb5\\xb5\") #set usec mode 177,163,181,181 ser.flush()", "timeout=10) ser.write(\"\\xb1\\xa3\\xb5\\xb5\") #set usec mode 177,163,181,181 ser.flush() ser.flushInput() obs =", "(as hex): '+ obs.encode('hex') obsBin = [ord(c) for c in", "at %d usec' % (keys, usec) ser.write(\"\\xb1\\xa3\\xa9\\xa9\") #turn off oscilloscope:", "usec mode 177,163,181,181 ser.flush() ser.flushInput() obs = ser.read(8) if len(obs)", "obs = ser.read(8) if len(obs) != 8: print('Error: no buttons", "print('Error: no buttons presses detected') print 'Observed data (as hex):", "%d at %d usec' % (keys, usec) ser.write(\"\\xb1\\xa3\\xa9\\xa9\") #turn off", "ser.flush() ser.flushInput() obs = ser.read(8) if len(obs) != 8: print('Error:", "[ord(c) for c in obs] usec = (obsBin[3] << 24)+", "no buttons presses detected') print 'Observed data (as hex): '+", "in obs] usec = (obsBin[3] << 24)+ (obsBin[4] << 16)+", "(obsBin[1] << 8)+obsBin[2] print 'keys pressed %d at %d usec'", "8)+obsBin[6] keys = (obsBin[1] << 8)+obsBin[2] print 'keys pressed %d", "keys = (obsBin[1] << 8)+obsBin[2] print 'keys pressed %d at", "(obsBin[4] << 16)+ (obsBin[5] << 8)+obsBin[6] keys = (obsBin[1] <<", "print 'keys pressed %d at %d usec' % (keys, usec)", "serial.Serial('/dev/tty.usbmodem7071', 115200, timeout=10) ser.write(\"\\xb1\\xa3\\xb5\\xb5\") #set usec mode 177,163,181,181 ser.flush() ser.flushInput()", "<< 24)+ (obsBin[4] << 16)+ (obsBin[5] << 8)+obsBin[6] keys =", "'keys pressed %d at %d usec' % (keys, usec) ser.write(\"\\xb1\\xa3\\xa9\\xa9\")", "#set usec mode 177,163,181,181 ser.flush() ser.flushInput() obs = ser.read(8) if", "ser.flushInput() obs = ser.read(8) if len(obs) != 8: print('Error: no", "ser.read(8) if len(obs) != 8: print('Error: no buttons presses detected')", "len(obs) != 8: print('Error: no buttons presses detected') print 'Observed", "data (as hex): '+ obs.encode('hex') obsBin = [ord(c) for c", "<< 8)+obsBin[6] keys = (obsBin[1] << 8)+obsBin[2] print 'keys pressed", "presses detected') print 'Observed data (as hex): '+ obs.encode('hex') obsBin", "(keys, usec) ser.write(\"\\xb1\\xa3\\xa9\\xa9\") #turn off oscilloscope: set keyboard mode 177,163,169,169", "hex): '+ obs.encode('hex') obsBin = [ord(c) for c in obs]" ]
[ "download_url(url, root, hash_value=checksum) extract_archive(archive) walker = walk_files( self._path, suffix=self._ext_audio, prefix=False,", "torch import Tensor from torch.utils.data import Dataset from torchaudio.datasets.utils import", "_ext_audio = \".wav\" def __init__( self, root: str, url: str", "file_audio = os.path.join(path, speaker_id, chapter_id, file_audio) # Load audio waveform,", "torchaudio from torch import Tensor from torch.utils.data import Dataset from", "download the dataset if it is not found at root", "walker = walk_files( self._path, suffix=self._ext_audio, prefix=False, remove_suffix=True ) self._walker =", "= fileid normalized_text = utterance_id + ext_normalized_txt normalized_text = os.path.join(path,", "base_url = \"http://www.openslr.org/resources/60/\" url = os.path.join(base_url, url + ext_archive) basename", "Args: n (int): The index of the sample to be", "as ft: normalized_text = ft.readline() return ( waveform, sample_rate, original_text,", "class LIBRITTS(Dataset): \"\"\"Create a Dataset for LibriTTS. Args: root (str):", "folder_in_archive: str = FOLDER_IN_ARCHIVE, download: bool = False, ) ->", "to download the dataset from, or the type of the", "the dataset. (default: ``\"LibriTTS\"``) download (bool, optional): Whether to download", "original_text) file_audio = utterance_id + ext_audio file_audio = os.path.join(path, speaker_id,", "= \"train-clean-100\" FOLDER_IN_ARCHIVE = \"LibriTTS\" _CHECKSUMS = { \"http://www.openslr.org/60/dev-clean.tar.gz\": \"0c3076c1e5245bb3f0af7d82087ee207\",", "= os.path.join(path, speaker_id, chapter_id, original_text) file_audio = utterance_id + ext_audio", "Allowed type values are ``\"dev-clean\"``, ``\"dev-other\"``, ``\"test-clean\"``, ``\"test-other\"``, ``\"train-clean-100\"``, ``\"train-clean-360\"``", "self._walker = list(walker) def __getitem__(self, n: int) -> Tuple[Tensor, int,", "\".tar.gz\" base_url = \"http://www.openslr.org/resources/60/\" url = os.path.join(base_url, url + ext_archive)", "sample_rate = torchaudio.load(file_audio) # Load original text with open(original_text) as", ") self._walker = list(walker) def __getitem__(self, n: int) -> Tuple[Tensor,", "\"http://www.openslr.org/60/test-clean.tar.gz\": \"7bed3bdb047c4c197f1ad3bc412db59f\", \"http://www.openslr.org/60/test-other.tar.gz\": \"ae3258249472a13b5abef2a816f733e4\", \"http://www.openslr.org/60/train-clean-100.tar.gz\": \"4a8c202b78fe1bc0c47916a98f3a2ea8\", \"http://www.openslr.org/60/train-clean-360.tar.gz\": \"a84ef10ddade5fd25df69596a2767b2d\", \"http://www.openslr.org/60/train-other-500.tar.gz\": \"7b181dd5ace343a5f38427999684aa6f\",", "\"\"\" _ext_original_txt = \".original.txt\" _ext_normalized_txt = \".normalized.txt\" _ext_audio = \".wav\"", "\"r\") as ft: normalized_text = ft.readline() return ( waveform, sample_rate,", "to the directory where the dataset is found or downloaded.", "(default: ``\"train-clean-100\"``) folder_in_archive (str, optional): The top-level directory of the", "= os.path.basename(url) archive = os.path.join(root, basename) basename = basename.split(\".\")[0] folder_in_archive", "int, str]: \"\"\"Load the n-th sample from the dataset. Args:", "found at root path. (default: ``False``). \"\"\" _ext_original_txt = \".original.txt\"", "index of the sample to be loaded Returns: tuple: ``(waveform,", "URL = \"train-clean-100\" FOLDER_IN_ARCHIVE = \"LibriTTS\" _CHECKSUMS = { \"http://www.openslr.org/60/dev-clean.tar.gz\":", "os.path.basename(url) archive = os.path.join(root, basename) basename = basename.split(\".\")[0] folder_in_archive =", "= os.path.join(root, basename) basename = basename.split(\".\")[0] folder_in_archive = os.path.join(folder_in_archive, basename)", "= \".tar.gz\" base_url = \"http://www.openslr.org/resources/60/\" url = os.path.join(base_url, url +", "ft: original_text = ft.readline() # Load normalized text with open(normalized_text,", "Dataset from torchaudio.datasets.utils import ( download_url, extract_archive, walk_files, ) URL", "\"\"\" fileid = self._walker[n] return load_libritts_item( fileid, self._path, self._ext_audio, self._ext_original_txt,", "= \".normalized.txt\" _ext_audio = \".wav\" def __init__( self, root: str,", "FOLDER_IN_ARCHIVE, download: bool = False, ) -> None: if url", "-> Tuple[Tensor, int, str, str, int, int, str]: speaker_id, chapter_id,", "( waveform, sample_rate, original_text, normalized_text, int(speaker_id), int(chapter_id), utterance_id, ) class", "basename = os.path.basename(url) archive = os.path.join(root, basename) basename = basename.split(\".\")[0]", "= utterance_id + ext_original_txt original_text = os.path.join(path, speaker_id, chapter_id, original_text)", "Load audio waveform, sample_rate = torchaudio.load(file_audio) # Load original text", "def __getitem__(self, n: int) -> Tuple[Tensor, int, str, str, int,", "_ext_original_txt = \".original.txt\" _ext_normalized_txt = \".normalized.txt\" _ext_audio = \".wav\" def", "None) download_url(url, root, hash_value=checksum) extract_archive(archive) walker = walk_files( self._path, suffix=self._ext_audio,", "root (str): Path to the directory where the dataset is", "directory of the dataset. (default: ``\"LibriTTS\"``) download (bool, optional): Whether", "(str, optional): The top-level directory of the dataset. (default: ``\"LibriTTS\"``)", "file_audio = utterance_id + ext_audio file_audio = os.path.join(path, speaker_id, chapter_id,", "\"http://www.openslr.org/60/dev-clean.tar.gz\": \"0c3076c1e5245bb3f0af7d82087ee207\", \"http://www.openslr.org/60/dev-other.tar.gz\": \"815555d8d75995782ac3ccd7f047213d\", \"http://www.openslr.org/60/test-clean.tar.gz\": \"7bed3bdb047c4c197f1ad3bc412db59f\", \"http://www.openslr.org/60/test-other.tar.gz\": \"ae3258249472a13b5abef2a816f733e4\", \"http://www.openslr.org/60/train-clean-100.tar.gz\": \"4a8c202b78fe1bc0c47916a98f3a2ea8\",", "directory where the dataset is found or downloaded. url (str,", "\"train-clean-100\" FOLDER_IN_ARCHIVE = \"LibriTTS\" _CHECKSUMS = { \"http://www.openslr.org/60/dev-clean.tar.gz\": \"0c3076c1e5245bb3f0af7d82087ee207\", \"http://www.openslr.org/60/dev-other.tar.gz\":", "os.path.isdir(self._path): if not os.path.isfile(archive): checksum = _CHECKSUMS.get(url, None) download_url(url, root,", "waveform, sample_rate, original_text, normalized_text, int(speaker_id), int(chapter_id), utterance_id, ) class LIBRITTS(Dataset):", "chapter_id, normalized_text) original_text = utterance_id + ext_original_txt original_text = os.path.join(path,", "torchaudio.datasets.utils import ( download_url, extract_archive, walk_files, ) URL = \"train-clean-100\"", "``\"dev-other\"``, ``\"test-clean\"``, ``\"test-other\"``, ``\"train-clean-100\"``, ``\"train-clean-360\"`` and ``\"train-other-500\"``. (default: ``\"train-clean-100\"``) folder_in_archive", "int, str, str, int, int, str]: speaker_id, chapter_id, segment_id, utterance_id", "str = FOLDER_IN_ARCHIVE, download: bool = False, ) -> None:", "of the dataset to dowload. Allowed type values are ``\"dev-clean\"``,", "download: if not os.path.isdir(self._path): if not os.path.isfile(archive): checksum = _CHECKSUMS.get(url,", "None: if url in [ \"dev-clean\", \"dev-other\", \"test-clean\", \"test-other\", \"train-clean-100\",", "= basename.split(\".\")[0] folder_in_archive = os.path.join(folder_in_archive, basename) self._path = os.path.join(root, folder_in_archive)", "+ ext_normalized_txt normalized_text = os.path.join(path, speaker_id, chapter_id, normalized_text) original_text =", "str = URL, folder_in_archive: str = FOLDER_IN_ARCHIVE, download: bool =", "Whether to download the dataset if it is not found", "self._walker[n] return load_libritts_item( fileid, self._path, self._ext_audio, self._ext_original_txt, self._ext_normalized_txt, ) def", "root: str, url: str = URL, folder_in_archive: str = FOLDER_IN_ARCHIVE,", "sample_rate, original_text, normalized_text, speaker_id, chapter_id, utterance_id)`` \"\"\" fileid = self._walker[n]", "fileid normalized_text = utterance_id + ext_normalized_txt normalized_text = os.path.join(path, speaker_id,", "= os.path.join(folder_in_archive, basename) self._path = os.path.join(root, folder_in_archive) if download: if", "def load_libritts_item( fileid: str, path: str, ext_audio: str, ext_original_txt: str,", "= walk_files( self._path, suffix=self._ext_audio, prefix=False, remove_suffix=True ) self._walker = list(walker)", "The index of the sample to be loaded Returns: tuple:", "\"http://www.openslr.org/60/train-other-500.tar.gz\": \"7b181dd5ace343a5f38427999684aa6f\", } def load_libritts_item( fileid: str, path: str, ext_audio:", "\"train-clean-100\", \"train-clean-360\", \"train-other-500\", ]: ext_archive = \".tar.gz\" base_url = \"http://www.openslr.org/resources/60/\"", "be loaded Returns: tuple: ``(waveform, sample_rate, original_text, normalized_text, speaker_id, chapter_id,", "``\"train-clean-100\"``) folder_in_archive (str, optional): The top-level directory of the dataset.", "to be loaded Returns: tuple: ``(waveform, sample_rate, original_text, normalized_text, speaker_id,", "# Load original text with open(original_text) as ft: original_text =", "} def load_libritts_item( fileid: str, path: str, ext_audio: str, ext_original_txt:", "type of the dataset to dowload. Allowed type values are", "\"\"\"Load the n-th sample from the dataset. Args: n (int):", "os.path.join(path, speaker_id, chapter_id, file_audio) # Load audio waveform, sample_rate =", "ext_original_txt original_text = os.path.join(path, speaker_id, chapter_id, original_text) file_audio = utterance_id", "if it is not found at root path. (default: ``False``).", "chapter_id, file_audio) # Load audio waveform, sample_rate = torchaudio.load(file_audio) #", "os.path.join(folder_in_archive, basename) self._path = os.path.join(root, folder_in_archive) if download: if not", "at root path. (default: ``False``). \"\"\" _ext_original_txt = \".original.txt\" _ext_normalized_txt", "utterance_id)`` \"\"\" fileid = self._walker[n] return load_libritts_item( fileid, self._path, self._ext_audio,", "self._ext_audio, self._ext_original_txt, self._ext_normalized_txt, ) def __len__(self) -> int: return len(self._walker)", "\"7b181dd5ace343a5f38427999684aa6f\", } def load_libritts_item( fileid: str, path: str, ext_audio: str,", "= \"LibriTTS\" _CHECKSUMS = { \"http://www.openslr.org/60/dev-clean.tar.gz\": \"0c3076c1e5245bb3f0af7d82087ee207\", \"http://www.openslr.org/60/dev-other.tar.gz\": \"815555d8d75995782ac3ccd7f047213d\", \"http://www.openslr.org/60/test-clean.tar.gz\":", "speaker_id, chapter_id, segment_id, utterance_id = fileid.split(\"_\") utterance_id = fileid normalized_text", "\"http://www.openslr.org/60/test-other.tar.gz\": \"ae3258249472a13b5abef2a816f733e4\", \"http://www.openslr.org/60/train-clean-100.tar.gz\": \"4a8c202b78fe1bc0c47916a98f3a2ea8\", \"http://www.openslr.org/60/train-clean-360.tar.gz\": \"a84ef10ddade5fd25df69596a2767b2d\", \"http://www.openslr.org/60/train-other-500.tar.gz\": \"7b181dd5ace343a5f38427999684aa6f\", } def", "the dataset. Args: n (int): The index of the sample", ") -> Tuple[Tensor, int, str, str, int, int, str]: speaker_id,", "the sample to be loaded Returns: tuple: ``(waveform, sample_rate, original_text,", "``\"test-clean\"``, ``\"test-other\"``, ``\"train-clean-100\"``, ``\"train-clean-360\"`` and ``\"train-other-500\"``. (default: ``\"train-clean-100\"``) folder_in_archive (str,", "\"http://www.openslr.org/60/train-clean-360.tar.gz\": \"a84ef10ddade5fd25df69596a2767b2d\", \"http://www.openslr.org/60/train-other-500.tar.gz\": \"7b181dd5ace343a5f38427999684aa6f\", } def load_libritts_item( fileid: str, path:", "basename) self._path = os.path.join(root, folder_in_archive) if download: if not os.path.isdir(self._path):", "speaker_id, chapter_id, original_text) file_audio = utterance_id + ext_audio file_audio =", "normalized_text) original_text = utterance_id + ext_original_txt original_text = os.path.join(path, speaker_id,", "and ``\"train-other-500\"``. (default: ``\"train-clean-100\"``) folder_in_archive (str, optional): The top-level directory", "self._path, suffix=self._ext_audio, prefix=False, remove_suffix=True ) self._walker = list(walker) def __getitem__(self,", "``(waveform, sample_rate, original_text, normalized_text, speaker_id, chapter_id, utterance_id)`` \"\"\" fileid =", "top-level directory of the dataset. (default: ``\"LibriTTS\"``) download (bool, optional):", "def __init__( self, root: str, url: str = URL, folder_in_archive:", "\"dev-clean\", \"dev-other\", \"test-clean\", \"test-other\", \"train-clean-100\", \"train-clean-360\", \"train-other-500\", ]: ext_archive =", "+ ext_archive) basename = os.path.basename(url) archive = os.path.join(root, basename) basename", "str]: speaker_id, chapter_id, segment_id, utterance_id = fileid.split(\"_\") utterance_id = fileid", "with open(original_text) as ft: original_text = ft.readline() # Load normalized", "ft.readline() # Load normalized text with open(normalized_text, \"r\") as ft:", "os.path.isfile(archive): checksum = _CHECKSUMS.get(url, None) download_url(url, root, hash_value=checksum) extract_archive(archive) walker", "basename = basename.split(\".\")[0] folder_in_archive = os.path.join(folder_in_archive, basename) self._path = os.path.join(root,", "checksum = _CHECKSUMS.get(url, None) download_url(url, root, hash_value=checksum) extract_archive(archive) walker =", "__getitem__(self, n: int) -> Tuple[Tensor, int, str, str, int, int,", "it is not found at root path. (default: ``False``). \"\"\"", "\"0c3076c1e5245bb3f0af7d82087ee207\", \"http://www.openslr.org/60/dev-other.tar.gz\": \"815555d8d75995782ac3ccd7f047213d\", \"http://www.openslr.org/60/test-clean.tar.gz\": \"7bed3bdb047c4c197f1ad3bc412db59f\", \"http://www.openslr.org/60/test-other.tar.gz\": \"ae3258249472a13b5abef2a816f733e4\", \"http://www.openslr.org/60/train-clean-100.tar.gz\": \"4a8c202b78fe1bc0c47916a98f3a2ea8\", \"http://www.openslr.org/60/train-clean-360.tar.gz\":", "Tuple[Tensor, int, str, str, int, int, str]: \"\"\"Load the n-th", "in [ \"dev-clean\", \"dev-other\", \"test-clean\", \"test-other\", \"train-clean-100\", \"train-clean-360\", \"train-other-500\", ]:", "\"a84ef10ddade5fd25df69596a2767b2d\", \"http://www.openslr.org/60/train-other-500.tar.gz\": \"7b181dd5ace343a5f38427999684aa6f\", } def load_libritts_item( fileid: str, path: str,", "utterance_id + ext_normalized_txt normalized_text = os.path.join(path, speaker_id, chapter_id, normalized_text) original_text", "+ ext_original_txt original_text = os.path.join(path, speaker_id, chapter_id, original_text) file_audio =", "\"ae3258249472a13b5abef2a816f733e4\", \"http://www.openslr.org/60/train-clean-100.tar.gz\": \"4a8c202b78fe1bc0c47916a98f3a2ea8\", \"http://www.openslr.org/60/train-clean-360.tar.gz\": \"a84ef10ddade5fd25df69596a2767b2d\", \"http://www.openslr.org/60/train-other-500.tar.gz\": \"7b181dd5ace343a5f38427999684aa6f\", } def load_libritts_item(", "os.path.join(root, basename) basename = basename.split(\".\")[0] folder_in_archive = os.path.join(folder_in_archive, basename) self._path", "import os from typing import Tuple import torchaudio from torch", "url = os.path.join(base_url, url + ext_archive) basename = os.path.basename(url) archive", "``\"dev-clean\"``, ``\"dev-other\"``, ``\"test-clean\"``, ``\"test-other\"``, ``\"train-clean-100\"``, ``\"train-clean-360\"`` and ``\"train-other-500\"``. (default: ``\"train-clean-100\"``)", "str, ) -> Tuple[Tensor, int, str, str, int, int, str]:", "-> None: if url in [ \"dev-clean\", \"dev-other\", \"test-clean\", \"test-other\",", "(bool, optional): Whether to download the dataset if it is", "dataset. Args: n (int): The index of the sample to", "original_text = os.path.join(path, speaker_id, chapter_id, original_text) file_audio = utterance_id +", "= FOLDER_IN_ARCHIVE, download: bool = False, ) -> None: if", "remove_suffix=True ) self._walker = list(walker) def __getitem__(self, n: int) ->", "URL, folder_in_archive: str = FOLDER_IN_ARCHIVE, download: bool = False, )", "(str): Path to the directory where the dataset is found", "= URL, folder_in_archive: str = FOLDER_IN_ARCHIVE, download: bool = False,", "(int): The index of the sample to be loaded Returns:", "not os.path.isdir(self._path): if not os.path.isfile(archive): checksum = _CHECKSUMS.get(url, None) download_url(url,", "fileid, self._path, self._ext_audio, self._ext_original_txt, self._ext_normalized_txt, ) def __len__(self) -> int:", "``False``). \"\"\" _ext_original_txt = \".original.txt\" _ext_normalized_txt = \".normalized.txt\" _ext_audio =", "values are ``\"dev-clean\"``, ``\"dev-other\"``, ``\"test-clean\"``, ``\"test-other\"``, ``\"train-clean-100\"``, ``\"train-clean-360\"`` and ``\"train-other-500\"``.", "if url in [ \"dev-clean\", \"dev-other\", \"test-clean\", \"test-other\", \"train-clean-100\", \"train-clean-360\",", "normalized text with open(normalized_text, \"r\") as ft: normalized_text = ft.readline()", "The top-level directory of the dataset. (default: ``\"LibriTTS\"``) download (bool,", "``\"train-clean-360\"`` and ``\"train-other-500\"``. (default: ``\"train-clean-100\"``) folder_in_archive (str, optional): The top-level", "path: str, ext_audio: str, ext_original_txt: str, ext_normalized_txt: str, ) ->", "the n-th sample from the dataset. Args: n (int): The", "int, str]: speaker_id, chapter_id, segment_id, utterance_id = fileid.split(\"_\") utterance_id =", "download the dataset from, or the type of the dataset", "torch.utils.data import Dataset from torchaudio.datasets.utils import ( download_url, extract_archive, walk_files,", "ext_normalized_txt: str, ) -> Tuple[Tensor, int, str, str, int, int,", "dowload. Allowed type values are ``\"dev-clean\"``, ``\"dev-other\"``, ``\"test-clean\"``, ``\"test-other\"``, ``\"train-clean-100\"``,", "-> Tuple[Tensor, int, str, str, int, int, str]: \"\"\"Load the", "(default: ``\"LibriTTS\"``) download (bool, optional): Whether to download the dataset", "LibriTTS. Args: root (str): Path to the directory where the", "extract_archive(archive) walker = walk_files( self._path, suffix=self._ext_audio, prefix=False, remove_suffix=True ) self._walker", "\"test-other\", \"train-clean-100\", \"train-clean-360\", \"train-other-500\", ]: ext_archive = \".tar.gz\" base_url =", "dataset if it is not found at root path. (default:", "\"7bed3bdb047c4c197f1ad3bc412db59f\", \"http://www.openslr.org/60/test-other.tar.gz\": \"ae3258249472a13b5abef2a816f733e4\", \"http://www.openslr.org/60/train-clean-100.tar.gz\": \"4a8c202b78fe1bc0c47916a98f3a2ea8\", \"http://www.openslr.org/60/train-clean-360.tar.gz\": \"a84ef10ddade5fd25df69596a2767b2d\", \"http://www.openslr.org/60/train-other-500.tar.gz\": \"7b181dd5ace343a5f38427999684aa6f\", }", "as ft: original_text = ft.readline() # Load normalized text with", "list(walker) def __getitem__(self, n: int) -> Tuple[Tensor, int, str, str,", "download_url, extract_archive, walk_files, ) URL = \"train-clean-100\" FOLDER_IN_ARCHIVE = \"LibriTTS\"", "int, int, str]: speaker_id, chapter_id, segment_id, utterance_id = fileid.split(\"_\") utterance_id", "URL to download the dataset from, or the type of", "= list(walker) def __getitem__(self, n: int) -> Tuple[Tensor, int, str,", "= { \"http://www.openslr.org/60/dev-clean.tar.gz\": \"0c3076c1e5245bb3f0af7d82087ee207\", \"http://www.openslr.org/60/dev-other.tar.gz\": \"815555d8d75995782ac3ccd7f047213d\", \"http://www.openslr.org/60/test-clean.tar.gz\": \"7bed3bdb047c4c197f1ad3bc412db59f\", \"http://www.openslr.org/60/test-other.tar.gz\": \"ae3258249472a13b5abef2a816f733e4\",", "\"\"\"Create a Dataset for LibriTTS. Args: root (str): Path to", ") class LIBRITTS(Dataset): \"\"\"Create a Dataset for LibriTTS. Args: root", "str, ext_audio: str, ext_original_txt: str, ext_normalized_txt: str, ) -> Tuple[Tensor,", "\"LibriTTS\" _CHECKSUMS = { \"http://www.openslr.org/60/dev-clean.tar.gz\": \"0c3076c1e5245bb3f0af7d82087ee207\", \"http://www.openslr.org/60/dev-other.tar.gz\": \"815555d8d75995782ac3ccd7f047213d\", \"http://www.openslr.org/60/test-clean.tar.gz\": \"7bed3bdb047c4c197f1ad3bc412db59f\",", "_CHECKSUMS.get(url, None) download_url(url, root, hash_value=checksum) extract_archive(archive) walker = walk_files( self._path,", "= utterance_id + ext_audio file_audio = os.path.join(path, speaker_id, chapter_id, file_audio)", "utterance_id = fileid normalized_text = utterance_id + ext_normalized_txt normalized_text =", "n: int) -> Tuple[Tensor, int, str, str, int, int, str]:", "os from typing import Tuple import torchaudio from torch import", "int(chapter_id), utterance_id, ) class LIBRITTS(Dataset): \"\"\"Create a Dataset for LibriTTS.", "folder_in_archive (str, optional): The top-level directory of the dataset. (default:", "where the dataset is found or downloaded. url (str, optional):", "Load normalized text with open(normalized_text, \"r\") as ft: normalized_text =", "self, root: str, url: str = URL, folder_in_archive: str =", "= os.path.join(root, folder_in_archive) if download: if not os.path.isdir(self._path): if not", "= torchaudio.load(file_audio) # Load original text with open(original_text) as ft:", "= \"http://www.openslr.org/resources/60/\" url = os.path.join(base_url, url + ext_archive) basename =", "speaker_id, chapter_id, utterance_id)`` \"\"\" fileid = self._walker[n] return load_libritts_item( fileid,", "a Dataset for LibriTTS. Args: root (str): Path to the", "normalized_text = os.path.join(path, speaker_id, chapter_id, normalized_text) original_text = utterance_id +", "is found or downloaded. url (str, optional): The URL to", "type values are ``\"dev-clean\"``, ``\"dev-other\"``, ``\"test-clean\"``, ``\"test-other\"``, ``\"train-clean-100\"``, ``\"train-clean-360\"`` and", "normalized_text = utterance_id + ext_normalized_txt normalized_text = os.path.join(path, speaker_id, chapter_id,", "torchaudio.load(file_audio) # Load original text with open(original_text) as ft: original_text", "from the dataset. Args: n (int): The index of the", "= os.path.join(base_url, url + ext_archive) basename = os.path.basename(url) archive =", "are ``\"dev-clean\"``, ``\"dev-other\"``, ``\"test-clean\"``, ``\"test-other\"``, ``\"train-clean-100\"``, ``\"train-clean-360\"`` and ``\"train-other-500\"``. (default:", "Tensor from torch.utils.data import Dataset from torchaudio.datasets.utils import ( download_url,", "_ext_normalized_txt = \".normalized.txt\" _ext_audio = \".wav\" def __init__( self, root:", "download (bool, optional): Whether to download the dataset if it", "str, int, int, str]: \"\"\"Load the n-th sample from the", "_CHECKSUMS = { \"http://www.openslr.org/60/dev-clean.tar.gz\": \"0c3076c1e5245bb3f0af7d82087ee207\", \"http://www.openslr.org/60/dev-other.tar.gz\": \"815555d8d75995782ac3ccd7f047213d\", \"http://www.openslr.org/60/test-clean.tar.gz\": \"7bed3bdb047c4c197f1ad3bc412db59f\", \"http://www.openslr.org/60/test-other.tar.gz\":", "Tuple[Tensor, int, str, str, int, int, str]: speaker_id, chapter_id, segment_id,", "self._path = os.path.join(root, folder_in_archive) if download: if not os.path.isdir(self._path): if", "{ \"http://www.openslr.org/60/dev-clean.tar.gz\": \"0c3076c1e5245bb3f0af7d82087ee207\", \"http://www.openslr.org/60/dev-other.tar.gz\": \"815555d8d75995782ac3ccd7f047213d\", \"http://www.openslr.org/60/test-clean.tar.gz\": \"7bed3bdb047c4c197f1ad3bc412db59f\", \"http://www.openslr.org/60/test-other.tar.gz\": \"ae3258249472a13b5abef2a816f733e4\", \"http://www.openslr.org/60/train-clean-100.tar.gz\":", "= os.path.join(path, speaker_id, chapter_id, file_audio) # Load audio waveform, sample_rate", "not found at root path. (default: ``False``). \"\"\" _ext_original_txt =", "audio waveform, sample_rate = torchaudio.load(file_audio) # Load original text with", "sample from the dataset. Args: n (int): The index of", "Path to the directory where the dataset is found or", "\"815555d8d75995782ac3ccd7f047213d\", \"http://www.openslr.org/60/test-clean.tar.gz\": \"7bed3bdb047c4c197f1ad3bc412db59f\", \"http://www.openslr.org/60/test-other.tar.gz\": \"ae3258249472a13b5abef2a816f733e4\", \"http://www.openslr.org/60/train-clean-100.tar.gz\": \"4a8c202b78fe1bc0c47916a98f3a2ea8\", \"http://www.openslr.org/60/train-clean-360.tar.gz\": \"a84ef10ddade5fd25df69596a2767b2d\", \"http://www.openslr.org/60/train-other-500.tar.gz\":", "path. (default: ``False``). \"\"\" _ext_original_txt = \".original.txt\" _ext_normalized_txt = \".normalized.txt\"", "= \".wav\" def __init__( self, root: str, url: str =", "\"http://www.openslr.org/60/dev-other.tar.gz\": \"815555d8d75995782ac3ccd7f047213d\", \"http://www.openslr.org/60/test-clean.tar.gz\": \"7bed3bdb047c4c197f1ad3bc412db59f\", \"http://www.openslr.org/60/test-other.tar.gz\": \"ae3258249472a13b5abef2a816f733e4\", \"http://www.openslr.org/60/train-clean-100.tar.gz\": \"4a8c202b78fe1bc0c47916a98f3a2ea8\", \"http://www.openslr.org/60/train-clean-360.tar.gz\": \"a84ef10ddade5fd25df69596a2767b2d\",", "if download: if not os.path.isdir(self._path): if not os.path.isfile(archive): checksum =", "load_libritts_item( fileid: str, path: str, ext_audio: str, ext_original_txt: str, ext_normalized_txt:", "= ft.readline() # Load normalized text with open(normalized_text, \"r\") as", "\"test-clean\", \"test-other\", \"train-clean-100\", \"train-clean-360\", \"train-other-500\", ]: ext_archive = \".tar.gz\" base_url", "return load_libritts_item( fileid, self._path, self._ext_audio, self._ext_original_txt, self._ext_normalized_txt, ) def __len__(self)", "basename.split(\".\")[0] folder_in_archive = os.path.join(folder_in_archive, basename) self._path = os.path.join(root, folder_in_archive) if", "chapter_id, utterance_id)`` \"\"\" fileid = self._walker[n] return load_libritts_item( fileid, self._path,", "int, int, str]: \"\"\"Load the n-th sample from the dataset.", "to dowload. Allowed type values are ``\"dev-clean\"``, ``\"dev-other\"``, ``\"test-clean\"``, ``\"test-other\"``,", "int, str, str, int, int, str]: \"\"\"Load the n-th sample", "walk_files, ) URL = \"train-clean-100\" FOLDER_IN_ARCHIVE = \"LibriTTS\" _CHECKSUMS =", "(str, optional): The URL to download the dataset from, or", "= self._walker[n] return load_libritts_item( fileid, self._path, self._ext_audio, self._ext_original_txt, self._ext_normalized_txt, )", "\".wav\" def __init__( self, root: str, url: str = URL,", "str, str, int, int, str]: speaker_id, chapter_id, segment_id, utterance_id =", "\".original.txt\" _ext_normalized_txt = \".normalized.txt\" _ext_audio = \".wav\" def __init__( self,", "FOLDER_IN_ARCHIVE = \"LibriTTS\" _CHECKSUMS = { \"http://www.openslr.org/60/dev-clean.tar.gz\": \"0c3076c1e5245bb3f0af7d82087ee207\", \"http://www.openslr.org/60/dev-other.tar.gz\": \"815555d8d75995782ac3ccd7f047213d\",", "= \".original.txt\" _ext_normalized_txt = \".normalized.txt\" _ext_audio = \".wav\" def __init__(", "# Load audio waveform, sample_rate = torchaudio.load(file_audio) # Load original", "Dataset for LibriTTS. Args: root (str): Path to the directory", "original_text, normalized_text, int(speaker_id), int(chapter_id), utterance_id, ) class LIBRITTS(Dataset): \"\"\"Create a", "sample to be loaded Returns: tuple: ``(waveform, sample_rate, original_text, normalized_text,", "the dataset from, or the type of the dataset to", "False, ) -> None: if url in [ \"dev-clean\", \"dev-other\",", "utterance_id, ) class LIBRITTS(Dataset): \"\"\"Create a Dataset for LibriTTS. Args:", "from torch import Tensor from torch.utils.data import Dataset from torchaudio.datasets.utils", "= _CHECKSUMS.get(url, None) download_url(url, root, hash_value=checksum) extract_archive(archive) walker = walk_files(", "archive = os.path.join(root, basename) basename = basename.split(\".\")[0] folder_in_archive = os.path.join(folder_in_archive,", "\"train-other-500\", ]: ext_archive = \".tar.gz\" base_url = \"http://www.openslr.org/resources/60/\" url =", "str, ext_original_txt: str, ext_normalized_txt: str, ) -> Tuple[Tensor, int, str,", "sample_rate, original_text, normalized_text, int(speaker_id), int(chapter_id), utterance_id, ) class LIBRITTS(Dataset): \"\"\"Create", "__init__( self, root: str, url: str = URL, folder_in_archive: str", "utterance_id = fileid.split(\"_\") utterance_id = fileid normalized_text = utterance_id +", "dataset. (default: ``\"LibriTTS\"``) download (bool, optional): Whether to download the", "dataset to dowload. Allowed type values are ``\"dev-clean\"``, ``\"dev-other\"``, ``\"test-clean\"``,", "[ \"dev-clean\", \"dev-other\", \"test-clean\", \"test-other\", \"train-clean-100\", \"train-clean-360\", \"train-other-500\", ]: ext_archive", "url + ext_archive) basename = os.path.basename(url) archive = os.path.join(root, basename)", "ext_archive = \".tar.gz\" base_url = \"http://www.openslr.org/resources/60/\" url = os.path.join(base_url, url", "import torchaudio from torch import Tensor from torch.utils.data import Dataset", "the type of the dataset to dowload. Allowed type values", "typing import Tuple import torchaudio from torch import Tensor from", "self._path, self._ext_audio, self._ext_original_txt, self._ext_normalized_txt, ) def __len__(self) -> int: return", "normalized_text, speaker_id, chapter_id, utterance_id)`` \"\"\" fileid = self._walker[n] return load_libritts_item(", "\"http://www.openslr.org/60/train-clean-100.tar.gz\": \"4a8c202b78fe1bc0c47916a98f3a2ea8\", \"http://www.openslr.org/60/train-clean-360.tar.gz\": \"a84ef10ddade5fd25df69596a2767b2d\", \"http://www.openslr.org/60/train-other-500.tar.gz\": \"7b181dd5ace343a5f38427999684aa6f\", } def load_libritts_item( fileid:", "+ ext_audio file_audio = os.path.join(path, speaker_id, chapter_id, file_audio) # Load", "dataset from, or the type of the dataset to dowload.", "Args: root (str): Path to the directory where the dataset", "is not found at root path. (default: ``False``). \"\"\" _ext_original_txt", "speaker_id, chapter_id, normalized_text) original_text = utterance_id + ext_original_txt original_text =", "original text with open(original_text) as ft: original_text = ft.readline() #", "for LibriTTS. Args: root (str): Path to the directory where", "# Load normalized text with open(normalized_text, \"r\") as ft: normalized_text", "Returns: tuple: ``(waveform, sample_rate, original_text, normalized_text, speaker_id, chapter_id, utterance_id)`` \"\"\"", "waveform, sample_rate = torchaudio.load(file_audio) # Load original text with open(original_text)", "the directory where the dataset is found or downloaded. url", "fileid = self._walker[n] return load_libritts_item( fileid, self._path, self._ext_audio, self._ext_original_txt, self._ext_normalized_txt,", "str, ext_normalized_txt: str, ) -> Tuple[Tensor, int, str, str, int,", "Tuple import torchaudio from torch import Tensor from torch.utils.data import", "root, hash_value=checksum) extract_archive(archive) walker = walk_files( self._path, suffix=self._ext_audio, prefix=False, remove_suffix=True", "(default: ``False``). \"\"\" _ext_original_txt = \".original.txt\" _ext_normalized_txt = \".normalized.txt\" _ext_audio", "import Tensor from torch.utils.data import Dataset from torchaudio.datasets.utils import (", "file_audio) # Load audio waveform, sample_rate = torchaudio.load(file_audio) # Load", "open(normalized_text, \"r\") as ft: normalized_text = ft.readline() return ( waveform,", "= os.path.join(path, speaker_id, chapter_id, normalized_text) original_text = utterance_id + ext_original_txt", "\"dev-other\", \"test-clean\", \"test-other\", \"train-clean-100\", \"train-clean-360\", \"train-other-500\", ]: ext_archive = \".tar.gz\"", "n-th sample from the dataset. Args: n (int): The index", "text with open(normalized_text, \"r\") as ft: normalized_text = ft.readline() return", "tuple: ``(waveform, sample_rate, original_text, normalized_text, speaker_id, chapter_id, utterance_id)`` \"\"\" fileid", "chapter_id, original_text) file_audio = utterance_id + ext_audio file_audio = os.path.join(path,", "walk_files( self._path, suffix=self._ext_audio, prefix=False, remove_suffix=True ) self._walker = list(walker) def", "text with open(original_text) as ft: original_text = ft.readline() # Load", "normalized_text = ft.readline() return ( waveform, sample_rate, original_text, normalized_text, int(speaker_id),", "found or downloaded. url (str, optional): The URL to download", "``\"LibriTTS\"``) download (bool, optional): Whether to download the dataset if", "ext_audio: str, ext_original_txt: str, ext_normalized_txt: str, ) -> Tuple[Tensor, int,", "from, or the type of the dataset to dowload. Allowed", "from torchaudio.datasets.utils import ( download_url, extract_archive, walk_files, ) URL =", "ext_audio file_audio = os.path.join(path, speaker_id, chapter_id, file_audio) # Load audio", "ft: normalized_text = ft.readline() return ( waveform, sample_rate, original_text, normalized_text,", "of the sample to be loaded Returns: tuple: ``(waveform, sample_rate,", "\"train-clean-360\", \"train-other-500\", ]: ext_archive = \".tar.gz\" base_url = \"http://www.openslr.org/resources/60/\" url", "str, url: str = URL, folder_in_archive: str = FOLDER_IN_ARCHIVE, download:", "prefix=False, remove_suffix=True ) self._walker = list(walker) def __getitem__(self, n: int)", "]: ext_archive = \".tar.gz\" base_url = \"http://www.openslr.org/resources/60/\" url = os.path.join(base_url,", "return ( waveform, sample_rate, original_text, normalized_text, int(speaker_id), int(chapter_id), utterance_id, )", "ext_normalized_txt normalized_text = os.path.join(path, speaker_id, chapter_id, normalized_text) original_text = utterance_id", "original_text = utterance_id + ext_original_txt original_text = os.path.join(path, speaker_id, chapter_id,", "= ft.readline() return ( waveform, sample_rate, original_text, normalized_text, int(speaker_id), int(chapter_id),", "loaded Returns: tuple: ``(waveform, sample_rate, original_text, normalized_text, speaker_id, chapter_id, utterance_id)``", "fileid: str, path: str, ext_audio: str, ext_original_txt: str, ext_normalized_txt: str,", "url (str, optional): The URL to download the dataset from,", "utterance_id + ext_audio file_audio = os.path.join(path, speaker_id, chapter_id, file_audio) #", "from torch.utils.data import Dataset from torchaudio.datasets.utils import ( download_url, extract_archive,", "= False, ) -> None: if url in [ \"dev-clean\",", "folder_in_archive) if download: if not os.path.isdir(self._path): if not os.path.isfile(archive): checksum", "utterance_id + ext_original_txt original_text = os.path.join(path, speaker_id, chapter_id, original_text) file_audio", "\"4a8c202b78fe1bc0c47916a98f3a2ea8\", \"http://www.openslr.org/60/train-clean-360.tar.gz\": \"a84ef10ddade5fd25df69596a2767b2d\", \"http://www.openslr.org/60/train-other-500.tar.gz\": \"7b181dd5ace343a5f38427999684aa6f\", } def load_libritts_item( fileid: str,", ") -> None: if url in [ \"dev-clean\", \"dev-other\", \"test-clean\",", "from typing import Tuple import torchaudio from torch import Tensor", "str, str, int, int, str]: \"\"\"Load the n-th sample from", "fileid.split(\"_\") utterance_id = fileid normalized_text = utterance_id + ext_normalized_txt normalized_text", "int(speaker_id), int(chapter_id), utterance_id, ) class LIBRITTS(Dataset): \"\"\"Create a Dataset for", "str, int, int, str]: speaker_id, chapter_id, segment_id, utterance_id = fileid.split(\"_\")", "os.path.join(path, speaker_id, chapter_id, original_text) file_audio = utterance_id + ext_audio file_audio", "or the type of the dataset to dowload. Allowed type", "the dataset if it is not found at root path.", "ext_archive) basename = os.path.basename(url) archive = os.path.join(root, basename) basename =", "str, path: str, ext_audio: str, ext_original_txt: str, ext_normalized_txt: str, )", "The URL to download the dataset from, or the type", "``\"test-other\"``, ``\"train-clean-100\"``, ``\"train-clean-360\"`` and ``\"train-other-500\"``. (default: ``\"train-clean-100\"``) folder_in_archive (str, optional):", "if not os.path.isdir(self._path): if not os.path.isfile(archive): checksum = _CHECKSUMS.get(url, None)", "= fileid.split(\"_\") utterance_id = fileid normalized_text = utterance_id + ext_normalized_txt", "open(original_text) as ft: original_text = ft.readline() # Load normalized text", "optional): The URL to download the dataset from, or the", "segment_id, utterance_id = fileid.split(\"_\") utterance_id = fileid normalized_text = utterance_id", "extract_archive, walk_files, ) URL = \"train-clean-100\" FOLDER_IN_ARCHIVE = \"LibriTTS\" _CHECKSUMS", "downloaded. url (str, optional): The URL to download the dataset", "import Dataset from torchaudio.datasets.utils import ( download_url, extract_archive, walk_files, )", "LIBRITTS(Dataset): \"\"\"Create a Dataset for LibriTTS. Args: root (str): Path", "str]: \"\"\"Load the n-th sample from the dataset. Args: n", "dataset is found or downloaded. url (str, optional): The URL", "suffix=self._ext_audio, prefix=False, remove_suffix=True ) self._walker = list(walker) def __getitem__(self, n:", "int) -> Tuple[Tensor, int, str, str, int, int, str]: \"\"\"Load", "with open(normalized_text, \"r\") as ft: normalized_text = ft.readline() return (", "hash_value=checksum) extract_archive(archive) walker = walk_files( self._path, suffix=self._ext_audio, prefix=False, remove_suffix=True )", "load_libritts_item( fileid, self._path, self._ext_audio, self._ext_original_txt, self._ext_normalized_txt, ) def __len__(self) ->", "url: str = URL, folder_in_archive: str = FOLDER_IN_ARCHIVE, download: bool", "speaker_id, chapter_id, file_audio) # Load audio waveform, sample_rate = torchaudio.load(file_audio)", "( download_url, extract_archive, walk_files, ) URL = \"train-clean-100\" FOLDER_IN_ARCHIVE =", "os.path.join(path, speaker_id, chapter_id, normalized_text) original_text = utterance_id + ext_original_txt original_text", "os.path.join(root, folder_in_archive) if download: if not os.path.isdir(self._path): if not os.path.isfile(archive):", "if not os.path.isfile(archive): checksum = _CHECKSUMS.get(url, None) download_url(url, root, hash_value=checksum)", "ext_original_txt: str, ext_normalized_txt: str, ) -> Tuple[Tensor, int, str, str,", "import ( download_url, extract_archive, walk_files, ) URL = \"train-clean-100\" FOLDER_IN_ARCHIVE", "os.path.join(base_url, url + ext_archive) basename = os.path.basename(url) archive = os.path.join(root,", "original_text = ft.readline() # Load normalized text with open(normalized_text, \"r\")", "to download the dataset if it is not found at", "of the dataset. (default: ``\"LibriTTS\"``) download (bool, optional): Whether to", "optional): Whether to download the dataset if it is not", "the dataset to dowload. Allowed type values are ``\"dev-clean\"``, ``\"dev-other\"``,", "bool = False, ) -> None: if url in [", "import Tuple import torchaudio from torch import Tensor from torch.utils.data", "= utterance_id + ext_normalized_txt normalized_text = os.path.join(path, speaker_id, chapter_id, normalized_text)", "original_text, normalized_text, speaker_id, chapter_id, utterance_id)`` \"\"\" fileid = self._walker[n] return", "n (int): The index of the sample to be loaded", "Load original text with open(original_text) as ft: original_text = ft.readline()", "ft.readline() return ( waveform, sample_rate, original_text, normalized_text, int(speaker_id), int(chapter_id), utterance_id,", "\"http://www.openslr.org/resources/60/\" url = os.path.join(base_url, url + ext_archive) basename = os.path.basename(url)", "folder_in_archive = os.path.join(folder_in_archive, basename) self._path = os.path.join(root, folder_in_archive) if download:", "root path. (default: ``False``). \"\"\" _ext_original_txt = \".original.txt\" _ext_normalized_txt =", ") URL = \"train-clean-100\" FOLDER_IN_ARCHIVE = \"LibriTTS\" _CHECKSUMS = {", "download: bool = False, ) -> None: if url in", "basename) basename = basename.split(\".\")[0] folder_in_archive = os.path.join(folder_in_archive, basename) self._path =", "chapter_id, segment_id, utterance_id = fileid.split(\"_\") utterance_id = fileid normalized_text =", "``\"train-clean-100\"``, ``\"train-clean-360\"`` and ``\"train-other-500\"``. (default: ``\"train-clean-100\"``) folder_in_archive (str, optional): The", "``\"train-other-500\"``. (default: ``\"train-clean-100\"``) folder_in_archive (str, optional): The top-level directory of", "the dataset is found or downloaded. url (str, optional): The", "optional): The top-level directory of the dataset. (default: ``\"LibriTTS\"``) download", "\".normalized.txt\" _ext_audio = \".wav\" def __init__( self, root: str, url:", "or downloaded. url (str, optional): The URL to download the", "normalized_text, int(speaker_id), int(chapter_id), utterance_id, ) class LIBRITTS(Dataset): \"\"\"Create a Dataset", "url in [ \"dev-clean\", \"dev-other\", \"test-clean\", \"test-other\", \"train-clean-100\", \"train-clean-360\", \"train-other-500\",", "not os.path.isfile(archive): checksum = _CHECKSUMS.get(url, None) download_url(url, root, hash_value=checksum) extract_archive(archive)" ]
[ "# # # This program is protected by copyright laws.", "设置标题 plt.title(\"Java与Android图书对比\") # 为两条坐标轴设置名称 plt.xlabel(\"销量\") plt.ylabel(\"年份\") # 显示图例 plt.legend() plt.show()", "90500, 107000] y_data2 = [52000, 54200, 51500,58300, 56800, 59500, 62700]", "x in enumerate(y_data2): plt.text(x+5000, y+bar_width/2, '%s' % x, ha='center', va='bottom')", "va='bottom') # 为Y轴设置刻度值 plt.yticks(np.arange(len(x_data))+bar_width/2, x_data) # 设置标题 plt.title(\"Java与Android图书对比\") # 为两条坐标轴设置名称", "Y轴数据使用range(len(x_data), 就是0、1、2... plt.barh(y=range(len(x_data)), width=y_data, label='疯狂Java讲义', color='steelblue', alpha=0.8, height=bar_width) # Y轴数据使用np.arange(len(x_data))+bar_width,", "y_data = [58000, 60200, 63000, 71000, 84000, 90500, 107000] y_data2", "x_data) # 设置标题 plt.title(\"Java与Android图书对比\") # 为两条坐标轴设置名称 plt.xlabel(\"销量\") plt.ylabel(\"年份\") # 显示图例", "# # Copyright (C), 2001-2018, yeeku.H.Lee # # # #", "# 网站: <a href=\"http://www.crazyit.org\">疯狂Java联盟</a> # # author yeeku.H.lee <EMAIL> #", "y_data2 = [52000, 54200, 51500,58300, 56800, 59500, 62700] bar_width=0.3 #", "# 在柱状图上显示具体数值, ha参数控制水平对齐方式, va控制垂直对齐方式 for y, x in enumerate(y_data): plt.text(x+5000,", "numpy as np # 构建数据 x_data = ['2011', '2012', '2013',", "yeeku.H.lee <EMAIL> # # # # version 1.0 # #", "# Y轴数据使用range(len(x_data), 就是0、1、2... plt.barh(y=range(len(x_data)), width=y_data, label='疯狂Java讲义', color='steelblue', alpha=0.8, height=bar_width) #", "program is protected by copyright laws. # # # #", "np # 构建数据 x_data = ['2011', '2012', '2013', '2014', '2015',", "label='疯狂Java讲义', color='steelblue', alpha=0.8, height=bar_width) # Y轴数据使用np.arange(len(x_data))+bar_width, # 就是bar_width、1+bar_width、2+bar_width...这样就和第一个柱状图并列了 plt.barh(y=np.arange(len(x_data))+bar_width, width=y_data2,", "# This program is protected by copyright laws. # #", "# ######################################################################### import matplotlib.pyplot as plt import numpy as np", "y-bar_width/2, '%s' % x, ha='center', va='bottom') for y, x in", "plt.text(x+5000, y+bar_width/2, '%s' % x, ha='center', va='bottom') # 为Y轴设置刻度值 plt.yticks(np.arange(len(x_data))+bar_width/2,", "# 设置标题 plt.title(\"Java与Android图书对比\") # 为两条坐标轴设置名称 plt.xlabel(\"销量\") plt.ylabel(\"年份\") # 显示图例 plt.legend()", "# 构建数据 x_data = ['2011', '2012', '2013', '2014', '2015', '2016',", "as plt import numpy as np # 构建数据 x_data =", "[52000, 54200, 51500,58300, 56800, 59500, 62700] bar_width=0.3 # Y轴数据使用range(len(x_data), 就是0、1、2...", "51500,58300, 56800, 59500, 62700] bar_width=0.3 # Y轴数据使用range(len(x_data), 就是0、1、2... plt.barh(y=range(len(x_data)), width=y_data,", "# Y轴数据使用np.arange(len(x_data))+bar_width, # 就是bar_width、1+bar_width、2+bar_width...这样就和第一个柱状图并列了 plt.barh(y=np.arange(len(x_data))+bar_width, width=y_data2, label='疯狂Android讲义', color='indianred', alpha=0.8, height=bar_width)", "<a href=\"http://www.crazyit.org\">疯狂Java联盟</a> # # author yeeku.H.lee <EMAIL> # # #", "import matplotlib.pyplot as plt import numpy as np # 构建数据", "x, ha='center', va='bottom') # 为Y轴设置刻度值 plt.yticks(np.arange(len(x_data))+bar_width/2, x_data) # 设置标题 plt.title(\"Java与Android图书对比\")", "color='steelblue', alpha=0.8, height=bar_width) # Y轴数据使用np.arange(len(x_data))+bar_width, # 就是bar_width、1+bar_width、2+bar_width...这样就和第一个柱状图并列了 plt.barh(y=np.arange(len(x_data))+bar_width, width=y_data2, label='疯狂Android讲义',", "matplotlib.pyplot as plt import numpy as np # 构建数据 x_data", "is protected by copyright laws. # # # # Program", "######################################################################### # 网站: <a href=\"http://www.crazyit.org\">疯狂Java联盟</a> # # author yeeku.H.lee <EMAIL>", "# # version 1.0 # # # # Copyright (C),", "width=y_data, label='疯狂Java讲义', color='steelblue', alpha=0.8, height=bar_width) # Y轴数据使用np.arange(len(x_data))+bar_width, # 就是bar_width、1+bar_width、2+bar_width...这样就和第一个柱状图并列了 plt.barh(y=np.arange(len(x_data))+bar_width,", "bar_width=0.3 # Y轴数据使用range(len(x_data), 就是0、1、2... plt.barh(y=range(len(x_data)), width=y_data, label='疯狂Java讲义', color='steelblue', alpha=0.8, height=bar_width)", "# version 1.0 # # # # Copyright (C), 2001-2018,", "'2017'] y_data = [58000, 60200, 63000, 71000, 84000, 90500, 107000]", "x in enumerate(y_data): plt.text(x+5000, y-bar_width/2, '%s' % x, ha='center', va='bottom')", "ha='center', va='bottom') for y, x in enumerate(y_data2): plt.text(x+5000, y+bar_width/2, '%s'", "yeeku.H.Lee # # # # This program is protected by", "构建数据 x_data = ['2011', '2012', '2013', '2014', '2015', '2016', '2017']", "x, ha='center', va='bottom') for y, x in enumerate(y_data2): plt.text(x+5000, y+bar_width/2,", "by copyright laws. # # # # Program Name: #", "71000, 84000, 90500, 107000] y_data2 = [52000, 54200, 51500,58300, 56800,", "= ['2011', '2012', '2013', '2014', '2015', '2016', '2017'] y_data =", "(C), 2001-2018, yeeku.H.Lee # # # # This program is", "2001-2018, yeeku.H.Lee # # # # This program is protected", "protected by copyright laws. # # # # Program Name:", "# # <br>Date: # ######################################################################### import matplotlib.pyplot as plt import", "import numpy as np # 构建数据 x_data = ['2011', '2012',", "copyright laws. # # # # Program Name: # #", "'2016', '2017'] y_data = [58000, 60200, 63000, 71000, 84000, 90500,", "# # author yeeku.H.lee <EMAIL> # # # # version", "plt.text(x+5000, y-bar_width/2, '%s' % x, ha='center', va='bottom') for y, x", "# # # Copyright (C), 2001-2018, yeeku.H.Lee # # #", "'2014', '2015', '2016', '2017'] y_data = [58000, 60200, 63000, 71000,", "in enumerate(y_data2): plt.text(x+5000, y+bar_width/2, '%s' % x, ha='center', va='bottom') #", "网站: <a href=\"http://www.crazyit.org\">疯狂Java联盟</a> # # author yeeku.H.lee <EMAIL> # #", "height=bar_width) # 在柱状图上显示具体数值, ha参数控制水平对齐方式, va控制垂直对齐方式 for y, x in enumerate(y_data):", "plt.yticks(np.arange(len(x_data))+bar_width/2, x_data) # 设置标题 plt.title(\"Java与Android图书对比\") # 为两条坐标轴设置名称 plt.xlabel(\"销量\") plt.ylabel(\"年份\") #", "Program Name: # # # # <br>Date: # ######################################################################### import", "为Y轴设置刻度值 plt.yticks(np.arange(len(x_data))+bar_width/2, x_data) # 设置标题 plt.title(\"Java与Android图书对比\") # 为两条坐标轴设置名称 plt.xlabel(\"销量\") plt.ylabel(\"年份\")", "color='indianred', alpha=0.8, height=bar_width) # 在柱状图上显示具体数值, ha参数控制水平对齐方式, va控制垂直对齐方式 for y, x", "107000] y_data2 = [52000, 54200, 51500,58300, 56800, 59500, 62700] bar_width=0.3", "for y, x in enumerate(y_data): plt.text(x+5000, y-bar_width/2, '%s' % x,", "'2012', '2013', '2014', '2015', '2016', '2017'] y_data = [58000, 60200,", "# # # # This program is protected by copyright", "enumerate(y_data2): plt.text(x+5000, y+bar_width/2, '%s' % x, ha='center', va='bottom') # 为Y轴设置刻度值", "plt import numpy as np # 构建数据 x_data = ['2011',", "# # # # Copyright (C), 2001-2018, yeeku.H.Lee # #", "Y轴数据使用np.arange(len(x_data))+bar_width, # 就是bar_width、1+bar_width、2+bar_width...这样就和第一个柱状图并列了 plt.barh(y=np.arange(len(x_data))+bar_width, width=y_data2, label='疯狂Android讲义', color='indianred', alpha=0.8, height=bar_width) #", "enumerate(y_data): plt.text(x+5000, y-bar_width/2, '%s' % x, ha='center', va='bottom') for y,", "# # # Program Name: # # # # <br>Date:", "62700] bar_width=0.3 # Y轴数据使用range(len(x_data), 就是0、1、2... plt.barh(y=range(len(x_data)), width=y_data, label='疯狂Java讲义', color='steelblue', alpha=0.8,", "'%s' % x, ha='center', va='bottom') for y, x in enumerate(y_data2):", "# # # # <br>Date: # ######################################################################### import matplotlib.pyplot as", "59500, 62700] bar_width=0.3 # Y轴数据使用range(len(x_data), 就是0、1、2... plt.barh(y=range(len(x_data)), width=y_data, label='疯狂Java讲义', color='steelblue',", "href=\"http://www.crazyit.org\">疯狂Java联盟</a> # # author yeeku.H.lee <EMAIL> # # # #", "# Copyright (C), 2001-2018, yeeku.H.Lee # # # # This", "'2015', '2016', '2017'] y_data = [58000, 60200, 63000, 71000, 84000,", "plt.barh(y=np.arange(len(x_data))+bar_width, width=y_data2, label='疯狂Android讲义', color='indianred', alpha=0.8, height=bar_width) # 在柱状图上显示具体数值, ha参数控制水平对齐方式, va控制垂直对齐方式", "x_data = ['2011', '2012', '2013', '2014', '2015', '2016', '2017'] y_data", "ha='center', va='bottom') # 为Y轴设置刻度值 plt.yticks(np.arange(len(x_data))+bar_width/2, x_data) # 设置标题 plt.title(\"Java与Android图书对比\") #", "# <br>Date: # ######################################################################### import matplotlib.pyplot as plt import numpy", "就是bar_width、1+bar_width、2+bar_width...这样就和第一个柱状图并列了 plt.barh(y=np.arange(len(x_data))+bar_width, width=y_data2, label='疯狂Android讲义', color='indianred', alpha=0.8, height=bar_width) # 在柱状图上显示具体数值, ha参数控制水平对齐方式,", "54200, 51500,58300, 56800, 59500, 62700] bar_width=0.3 # Y轴数据使用range(len(x_data), 就是0、1、2... plt.barh(y=range(len(x_data)),", "<br>Date: # ######################################################################### import matplotlib.pyplot as plt import numpy as", "y, x in enumerate(y_data): plt.text(x+5000, y-bar_width/2, '%s' % x, ha='center',", "######################################################################### import matplotlib.pyplot as plt import numpy as np #", "ha参数控制水平对齐方式, va控制垂直对齐方式 for y, x in enumerate(y_data): plt.text(x+5000, y-bar_width/2, '%s'", "author yeeku.H.lee <EMAIL> # # # # version 1.0 #", "['2011', '2012', '2013', '2014', '2015', '2016', '2017'] y_data = [58000,", "Name: # # # # <br>Date: # ######################################################################### import matplotlib.pyplot", "plt.barh(y=range(len(x_data)), width=y_data, label='疯狂Java讲义', color='steelblue', alpha=0.8, height=bar_width) # Y轴数据使用np.arange(len(x_data))+bar_width, # 就是bar_width、1+bar_width、2+bar_width...这样就和第一个柱状图并列了", "laws. # # # # Program Name: # # #", "# # Program Name: # # # # <br>Date: #", "= [58000, 60200, 63000, 71000, 84000, 90500, 107000] y_data2 =", "height=bar_width) # Y轴数据使用np.arange(len(x_data))+bar_width, # 就是bar_width、1+bar_width、2+bar_width...这样就和第一个柱状图并列了 plt.barh(y=np.arange(len(x_data))+bar_width, width=y_data2, label='疯狂Android讲义', color='indianred', alpha=0.8,", "56800, 59500, 62700] bar_width=0.3 # Y轴数据使用range(len(x_data), 就是0、1、2... plt.barh(y=range(len(x_data)), width=y_data, label='疯狂Java讲义',", "utf-8 ######################################################################### # 网站: <a href=\"http://www.crazyit.org\">疯狂Java联盟</a> # # author yeeku.H.lee", "Copyright (C), 2001-2018, yeeku.H.Lee # # # # This program", "在柱状图上显示具体数值, ha参数控制水平对齐方式, va控制垂直对齐方式 for y, x in enumerate(y_data): plt.text(x+5000, y-bar_width/2,", "in enumerate(y_data): plt.text(x+5000, y-bar_width/2, '%s' % x, ha='center', va='bottom') for", "This program is protected by copyright laws. # # #", "% x, ha='center', va='bottom') # 为Y轴设置刻度值 plt.yticks(np.arange(len(x_data))+bar_width/2, x_data) # 设置标题", "# # # # version 1.0 # # # #", "# # # # Program Name: # # # #", "60200, 63000, 71000, 84000, 90500, 107000] y_data2 = [52000, 54200,", "'%s' % x, ha='center', va='bottom') # 为Y轴设置刻度值 plt.yticks(np.arange(len(x_data))+bar_width/2, x_data) #", "# # # version 1.0 # # # # Copyright", "<EMAIL> # # # # version 1.0 # # #", "'2013', '2014', '2015', '2016', '2017'] y_data = [58000, 60200, 63000,", "label='疯狂Android讲义', color='indianred', alpha=0.8, height=bar_width) # 在柱状图上显示具体数值, ha参数控制水平对齐方式, va控制垂直对齐方式 for y,", "coding: utf-8 ######################################################################### # 网站: <a href=\"http://www.crazyit.org\">疯狂Java联盟</a> # # author", "y, x in enumerate(y_data2): plt.text(x+5000, y+bar_width/2, '%s' % x, ha='center',", "就是0、1、2... plt.barh(y=range(len(x_data)), width=y_data, label='疯狂Java讲义', color='steelblue', alpha=0.8, height=bar_width) # Y轴数据使用np.arange(len(x_data))+bar_width, #", "alpha=0.8, height=bar_width) # Y轴数据使用np.arange(len(x_data))+bar_width, # 就是bar_width、1+bar_width、2+bar_width...这样就和第一个柱状图并列了 plt.barh(y=np.arange(len(x_data))+bar_width, width=y_data2, label='疯狂Android讲义', color='indianred',", "# 就是bar_width、1+bar_width、2+bar_width...这样就和第一个柱状图并列了 plt.barh(y=np.arange(len(x_data))+bar_width, width=y_data2, label='疯狂Android讲义', color='indianred', alpha=0.8, height=bar_width) # 在柱状图上显示具体数值,", "# 为Y轴设置刻度值 plt.yticks(np.arange(len(x_data))+bar_width/2, x_data) # 设置标题 plt.title(\"Java与Android图书对比\") # 为两条坐标轴设置名称 plt.xlabel(\"销量\")", "# # # <br>Date: # ######################################################################### import matplotlib.pyplot as plt", "= [52000, 54200, 51500,58300, 56800, 59500, 62700] bar_width=0.3 # Y轴数据使用range(len(x_data),", "# coding: utf-8 ######################################################################### # 网站: <a href=\"http://www.crazyit.org\">疯狂Java联盟</a> # #", "[58000, 60200, 63000, 71000, 84000, 90500, 107000] y_data2 = [52000,", "% x, ha='center', va='bottom') for y, x in enumerate(y_data2): plt.text(x+5000,", "# Program Name: # # # # <br>Date: # #########################################################################", "84000, 90500, 107000] y_data2 = [52000, 54200, 51500,58300, 56800, 59500,", "1.0 # # # # Copyright (C), 2001-2018, yeeku.H.Lee #", "for y, x in enumerate(y_data2): plt.text(x+5000, y+bar_width/2, '%s' % x,", "as np # 构建数据 x_data = ['2011', '2012', '2013', '2014',", "width=y_data2, label='疯狂Android讲义', color='indianred', alpha=0.8, height=bar_width) # 在柱状图上显示具体数值, ha参数控制水平对齐方式, va控制垂直对齐方式 for", "va控制垂直对齐方式 for y, x in enumerate(y_data): plt.text(x+5000, y-bar_width/2, '%s' %", "version 1.0 # # # # Copyright (C), 2001-2018, yeeku.H.Lee", "# # This program is protected by copyright laws. #", "y+bar_width/2, '%s' % x, ha='center', va='bottom') # 为Y轴设置刻度值 plt.yticks(np.arange(len(x_data))+bar_width/2, x_data)", "# author yeeku.H.lee <EMAIL> # # # # version 1.0", "63000, 71000, 84000, 90500, 107000] y_data2 = [52000, 54200, 51500,58300,", "alpha=0.8, height=bar_width) # 在柱状图上显示具体数值, ha参数控制水平对齐方式, va控制垂直对齐方式 for y, x in", "va='bottom') for y, x in enumerate(y_data2): plt.text(x+5000, y+bar_width/2, '%s' %" ]
[ "Meta: write_concern = WriteConcern(j=True) connection_alias = 'my-app' @app.route(\"/\") def hello():", "import Flask, Response from pymongo import MongoClient from bson import", "\"<h3> Hello world...</h3>\" #User('<EMAIL>', name, 'Ross').save() return html @app.route(\"/add_user/<name>\") def", "upsert=True ) return Response(number, status=200, mimetype='application/json') @app.route(\"/random-list\") def last_number_list(): last_numbers", "return Response(json.dumps(extracted, default=json_util.default), status=200, mimetype='application/json') if __name__ == \"__main__\": port", "20:13:57 2018 @author: allen \"\"\" import random, os, json, datetime,", "to MongoDB and call the connection \"my-app\". connect(\"mongodb://mongodb:27017/myDatabase\", alias=\"my-app\") class", "@app.route(\"/random/<int:lower>/<int:upper>\") def random_generator(lower, upper): number = str(random.randint(lower, upper)) random_numbers.update( {\"_id\"", "\"mongodb:<container_name>:27017\" mongdb_client= MongoClient(MONGO_URI) random_numbers = mongdb_client.demo.random_numbers time.sleep(5) # hack for", ") return Response(number, status=200, mimetype='application/json') @app.route(\"/random-list\") def last_number_list(): last_numbers =", "from flask import Flask, Response from pymongo import MongoClient from", ": -1}, \"$slice\" : 5 } }}, upsert=True ) return", "pymodm.connection import connect from pymongo.write_concern import WriteConcern from pymodm import", "utf-8 -*- \"\"\" Created on Tue Dec 18 20:13:57 2018", "{\"_id\" : \"lasts\"}, {\"$push\" : { \"items\" : { \"$each\":", "to database\".format(name) @app.route(\"/random/<int:lower>/<int:upper>\") def random_generator(lower, upper): number = str(random.randint(lower, upper))", "json, datetime, time from flask import Flask, Response from pymongo", "# \"mongodb:<container_name>:27017\" mongdb_client= MongoClient(MONGO_URI) random_numbers = mongdb_client.demo.random_numbers time.sleep(5) # hack", "name, 'Ross').save() html = \"<h3> Hello </h3>\" User('<EMAIL>', name, 'Ross').save()", "pymodm import MongoModel, fields # Connect to MongoDB and call", "in last_numbers[0]['items']] return Response(json.dumps(extracted, default=json_util.default), status=200, mimetype='application/json') if __name__ ==", "from pymodm.connection import connect from pymongo.write_concern import WriteConcern from pymodm", "allen \"\"\" import random, os, json, datetime, time from flask", "-1}, \"$slice\" : 5 } }}, upsert=True ) return Response(number,", "time from flask import Flask, Response from pymongo import MongoClient", "= \"<h3> Hello world...</h3>\" #User('<EMAIL>', name, 'Ross').save() return html @app.route(\"/add_user/<name>\")", "list(random_numbers.find({\"_id\" : \"lasts\"})) extracted = [d['value'] for d in last_numbers[0]['items']]", "__name__ == \"__main__\": port = int(os.environ.get('PORT', 5000)) app.config['DEBUG'] = True", ": { \"items\" : { \"$each\": [{\"value\" : number, \"date\":", "\"date\": datetime.datetime.utcnow()}], \"$sort\" : {\"date\" : -1}, \"$slice\" : 5", "import json_util app = Flask(__name__) MONGO_URI = \"mongodb://mongodb:27017\" # \"mongodb:<container_name>:27017\"", "Hello </h3>\" User('<EMAIL>', name, 'Ross').save() return \"name {} save to", "class User(MongoModel): email = fields.EmailField(primary_key=True) first_name = fields.CharField() last_name =", "running ###################### ## ########################## from pymodm.connection import connect from pymongo.write_concern", "'Ross').save() return html @app.route(\"/add_user/<name>\") def add_user(name): #User('<EMAIL>', name, 'Ross').save() html", "fields.CharField() class Meta: write_concern = WriteConcern(j=True) connection_alias = 'my-app' @app.route(\"/\")", "email = fields.EmailField(primary_key=True) first_name = fields.CharField() last_name = fields.CharField() class", "first_name = fields.CharField() last_name = fields.CharField() class Meta: write_concern =", "= fields.CharField() class Meta: write_concern = WriteConcern(j=True) connection_alias = 'my-app'", "last_numbers = list(random_numbers.find({\"_id\" : \"lasts\"})) extracted = [d['value'] for d", "import MongoModel, fields # Connect to MongoDB and call the", "<gh_stars>1-10 #!/usr/bin/env python3 # -*- coding: utf-8 -*- \"\"\" Created", "json_util app = Flask(__name__) MONGO_URI = \"mongodb://mongodb:27017\" # \"mongodb:<container_name>:27017\" mongdb_client=", "[d['value'] for d in last_numbers[0]['items']] return Response(json.dumps(extracted, default=json_util.default), status=200, mimetype='application/json')", "\"<h3> Hello </h3>\" User('<EMAIL>', name, 'Ross').save() return \"name {} save", "########################## from pymodm.connection import connect from pymongo.write_concern import WriteConcern from", "}}, upsert=True ) return Response(number, status=200, mimetype='application/json') @app.route(\"/random-list\") def last_number_list():", "os, json, datetime, time from flask import Flask, Response from", "2018 @author: allen \"\"\" import random, os, json, datetime, time", "connection \"my-app\". connect(\"mongodb://mongodb:27017/myDatabase\", alias=\"my-app\") class User(MongoModel): email = fields.EmailField(primary_key=True) first_name", "connection_alias = 'my-app' @app.route(\"/\") def hello(): html = \"<h3> Hello", "html = \"<h3> Hello </h3>\" User('<EMAIL>', name, 'Ross').save() return \"name", "fields # Connect to MongoDB and call the connection \"my-app\".", "Connect to MongoDB and call the connection \"my-app\". connect(\"mongodb://mongodb:27017/myDatabase\", alias=\"my-app\")", "write_concern = WriteConcern(j=True) connection_alias = 'my-app' @app.route(\"/\") def hello(): html", "datetime.datetime.utcnow()}], \"$sort\" : {\"date\" : -1}, \"$slice\" : 5 }", "mongdb_client.demo.random_numbers time.sleep(5) # hack for the mongoDb database to get", "= fields.EmailField(primary_key=True) first_name = fields.CharField() last_name = fields.CharField() class Meta:", "User('<EMAIL>', name, 'Ross').save() return \"name {} save to database\".format(name) @app.route(\"/random/<int:lower>/<int:upper>\")", "Tue Dec 18 20:13:57 2018 @author: allen \"\"\" import random,", "save to database\".format(name) @app.route(\"/random/<int:lower>/<int:upper>\") def random_generator(lower, upper): number = str(random.randint(lower,", "last_number_list(): last_numbers = list(random_numbers.find({\"_id\" : \"lasts\"})) extracted = [d['value'] for", "mongoDb database to get running ###################### ## ########################## from pymodm.connection", "fields.EmailField(primary_key=True) first_name = fields.CharField() last_name = fields.CharField() class Meta: write_concern", ": \"lasts\"})) extracted = [d['value'] for d in last_numbers[0]['items']] return", "name, 'Ross').save() return \"name {} save to database\".format(name) @app.route(\"/random/<int:lower>/<int:upper>\") def", "class Meta: write_concern = WriteConcern(j=True) connection_alias = 'my-app' @app.route(\"/\") def", "18 20:13:57 2018 @author: allen \"\"\" import random, os, json,", "for d in last_numbers[0]['items']] return Response(json.dumps(extracted, default=json_util.default), status=200, mimetype='application/json') if", "connect(\"mongodb://mongodb:27017/myDatabase\", alias=\"my-app\") class User(MongoModel): email = fields.EmailField(primary_key=True) first_name = fields.CharField()", "[{\"value\" : number, \"date\": datetime.datetime.utcnow()}], \"$sort\" : {\"date\" : -1},", "world...</h3>\" #User('<EMAIL>', name, 'Ross').save() return html @app.route(\"/add_user/<name>\") def add_user(name): #User('<EMAIL>',", "return Response(number, status=200, mimetype='application/json') @app.route(\"/random-list\") def last_number_list(): last_numbers = list(random_numbers.find({\"_id\"", "import MongoClient from bson import json_util app = Flask(__name__) MONGO_URI", "mongdb_client= MongoClient(MONGO_URI) random_numbers = mongdb_client.demo.random_numbers time.sleep(5) # hack for the", "import WriteConcern from pymodm import MongoModel, fields # Connect to", "def last_number_list(): last_numbers = list(random_numbers.find({\"_id\" : \"lasts\"})) extracted = [d['value']", "{} save to database\".format(name) @app.route(\"/random/<int:lower>/<int:upper>\") def random_generator(lower, upper): number =", "{ \"$each\": [{\"value\" : number, \"date\": datetime.datetime.utcnow()}], \"$sort\" : {\"date\"", "#!/usr/bin/env python3 # -*- coding: utf-8 -*- \"\"\" Created on", "#User('<EMAIL>', name, 'Ross').save() html = \"<h3> Hello </h3>\" User('<EMAIL>', name,", "= \"<h3> Hello </h3>\" User('<EMAIL>', name, 'Ross').save() return \"name {}", "upper)) random_numbers.update( {\"_id\" : \"lasts\"}, {\"$push\" : { \"items\" :", "# hack for the mongoDb database to get running ######################", "MongoModel, fields # Connect to MongoDB and call the connection", "###################### ## ########################## from pymodm.connection import connect from pymongo.write_concern import", "== \"__main__\": port = int(os.environ.get('PORT', 5000)) app.config['DEBUG'] = True app.run(host='0.0.0.0',", "'Ross').save() return \"name {} save to database\".format(name) @app.route(\"/random/<int:lower>/<int:upper>\") def random_generator(lower,", "from bson import json_util app = Flask(__name__) MONGO_URI = \"mongodb://mongodb:27017\"", "# -*- coding: utf-8 -*- \"\"\" Created on Tue Dec", "= mongdb_client.demo.random_numbers time.sleep(5) # hack for the mongoDb database to", "and call the connection \"my-app\". connect(\"mongodb://mongodb:27017/myDatabase\", alias=\"my-app\") class User(MongoModel): email", "bson import json_util app = Flask(__name__) MONGO_URI = \"mongodb://mongodb:27017\" #", "add_user(name): #User('<EMAIL>', name, 'Ross').save() html = \"<h3> Hello </h3>\" User('<EMAIL>',", "hack for the mongoDb database to get running ###################### ##", "= fields.CharField() last_name = fields.CharField() class Meta: write_concern = WriteConcern(j=True)", "-*- \"\"\" Created on Tue Dec 18 20:13:57 2018 @author:", "call the connection \"my-app\". connect(\"mongodb://mongodb:27017/myDatabase\", alias=\"my-app\") class User(MongoModel): email =", "@app.route(\"/\") def hello(): html = \"<h3> Hello world...</h3>\" #User('<EMAIL>', name,", "upper): number = str(random.randint(lower, upper)) random_numbers.update( {\"_id\" : \"lasts\"}, {\"$push\"", "Response(json.dumps(extracted, default=json_util.default), status=200, mimetype='application/json') if __name__ == \"__main__\": port =", "\"\"\" import random, os, json, datetime, time from flask import", "mimetype='application/json') if __name__ == \"__main__\": port = int(os.environ.get('PORT', 5000)) app.config['DEBUG']", "name, 'Ross').save() return html @app.route(\"/add_user/<name>\") def add_user(name): #User('<EMAIL>', name, 'Ross').save()", "python3 # -*- coding: utf-8 -*- \"\"\" Created on Tue", "html = \"<h3> Hello world...</h3>\" #User('<EMAIL>', name, 'Ross').save() return html", "@app.route(\"/add_user/<name>\") def add_user(name): #User('<EMAIL>', name, 'Ross').save() html = \"<h3> Hello", "default=json_util.default), status=200, mimetype='application/json') if __name__ == \"__main__\": port = int(os.environ.get('PORT',", "'Ross').save() html = \"<h3> Hello </h3>\" User('<EMAIL>', name, 'Ross').save() return", "\"\"\" Created on Tue Dec 18 20:13:57 2018 @author: allen", ": { \"$each\": [{\"value\" : number, \"date\": datetime.datetime.utcnow()}], \"$sort\" :", "\"$slice\" : 5 } }}, upsert=True ) return Response(number, status=200,", "random_numbers = mongdb_client.demo.random_numbers time.sleep(5) # hack for the mongoDb database", "if __name__ == \"__main__\": port = int(os.environ.get('PORT', 5000)) app.config['DEBUG'] =", "alias=\"my-app\") class User(MongoModel): email = fields.EmailField(primary_key=True) first_name = fields.CharField() last_name", "last_name = fields.CharField() class Meta: write_concern = WriteConcern(j=True) connection_alias =", "MongoClient from bson import json_util app = Flask(__name__) MONGO_URI =", "{\"date\" : -1}, \"$slice\" : 5 } }}, upsert=True )", "@app.route(\"/random-list\") def last_number_list(): last_numbers = list(random_numbers.find({\"_id\" : \"lasts\"})) extracted =", "MongoClient(MONGO_URI) random_numbers = mongdb_client.demo.random_numbers time.sleep(5) # hack for the mongoDb", "import random, os, json, datetime, time from flask import Flask,", "Response from pymongo import MongoClient from bson import json_util app", "str(random.randint(lower, upper)) random_numbers.update( {\"_id\" : \"lasts\"}, {\"$push\" : { \"items\"", "Flask, Response from pymongo import MongoClient from bson import json_util", "\"name {} save to database\".format(name) @app.route(\"/random/<int:lower>/<int:upper>\") def random_generator(lower, upper): number", "hello(): html = \"<h3> Hello world...</h3>\" #User('<EMAIL>', name, 'Ross').save() return", "\"lasts\"}, {\"$push\" : { \"items\" : { \"$each\": [{\"value\" :", "app = Flask(__name__) MONGO_URI = \"mongodb://mongodb:27017\" # \"mongodb:<container_name>:27017\" mongdb_client= MongoClient(MONGO_URI)", "'my-app' @app.route(\"/\") def hello(): html = \"<h3> Hello world...</h3>\" #User('<EMAIL>',", "= \"mongodb://mongodb:27017\" # \"mongodb:<container_name>:27017\" mongdb_client= MongoClient(MONGO_URI) random_numbers = mongdb_client.demo.random_numbers time.sleep(5)", "the mongoDb database to get running ###################### ## ########################## from", "User(MongoModel): email = fields.EmailField(primary_key=True) first_name = fields.CharField() last_name = fields.CharField()", "} }}, upsert=True ) return Response(number, status=200, mimetype='application/json') @app.route(\"/random-list\") def", "mimetype='application/json') @app.route(\"/random-list\") def last_number_list(): last_numbers = list(random_numbers.find({\"_id\" : \"lasts\"})) extracted", "= WriteConcern(j=True) connection_alias = 'my-app' @app.route(\"/\") def hello(): html =", "## ########################## from pymodm.connection import connect from pymongo.write_concern import WriteConcern", "def add_user(name): #User('<EMAIL>', name, 'Ross').save() html = \"<h3> Hello </h3>\"", "flask import Flask, Response from pymongo import MongoClient from bson", "return \"name {} save to database\".format(name) @app.route(\"/random/<int:lower>/<int:upper>\") def random_generator(lower, upper):", ": 5 } }}, upsert=True ) return Response(number, status=200, mimetype='application/json')", ": \"lasts\"}, {\"$push\" : { \"items\" : { \"$each\": [{\"value\"", "= list(random_numbers.find({\"_id\" : \"lasts\"})) extracted = [d['value'] for d in", "\"$each\": [{\"value\" : number, \"date\": datetime.datetime.utcnow()}], \"$sort\" : {\"date\" :", "random_numbers.update( {\"_id\" : \"lasts\"}, {\"$push\" : { \"items\" : {", "= Flask(__name__) MONGO_URI = \"mongodb://mongodb:27017\" # \"mongodb:<container_name>:27017\" mongdb_client= MongoClient(MONGO_URI) random_numbers", "return html @app.route(\"/add_user/<name>\") def add_user(name): #User('<EMAIL>', name, 'Ross').save() html =", "</h3>\" User('<EMAIL>', name, 'Ross').save() return \"name {} save to database\".format(name)", "\"my-app\". connect(\"mongodb://mongodb:27017/myDatabase\", alias=\"my-app\") class User(MongoModel): email = fields.EmailField(primary_key=True) first_name =", "to get running ###################### ## ########################## from pymodm.connection import connect", "database\".format(name) @app.route(\"/random/<int:lower>/<int:upper>\") def random_generator(lower, upper): number = str(random.randint(lower, upper)) random_numbers.update(", "datetime, time from flask import Flask, Response from pymongo import", "Flask(__name__) MONGO_URI = \"mongodb://mongodb:27017\" # \"mongodb:<container_name>:27017\" mongdb_client= MongoClient(MONGO_URI) random_numbers =", "for the mongoDb database to get running ###################### ## ##########################", "\"__main__\": port = int(os.environ.get('PORT', 5000)) app.config['DEBUG'] = True app.run(host='0.0.0.0', port=port)", "status=200, mimetype='application/json') if __name__ == \"__main__\": port = int(os.environ.get('PORT', 5000))", "time.sleep(5) # hack for the mongoDb database to get running", "\"mongodb://mongodb:27017\" # \"mongodb:<container_name>:27017\" mongdb_client= MongoClient(MONGO_URI) random_numbers = mongdb_client.demo.random_numbers time.sleep(5) #", "\"items\" : { \"$each\": [{\"value\" : number, \"date\": datetime.datetime.utcnow()}], \"$sort\"", "pymongo.write_concern import WriteConcern from pymodm import MongoModel, fields # Connect", "{ \"items\" : { \"$each\": [{\"value\" : number, \"date\": datetime.datetime.utcnow()}],", "# Connect to MongoDB and call the connection \"my-app\". connect(\"mongodb://mongodb:27017/myDatabase\",", "WriteConcern(j=True) connection_alias = 'my-app' @app.route(\"/\") def hello(): html = \"<h3>", "5 } }}, upsert=True ) return Response(number, status=200, mimetype='application/json') @app.route(\"/random-list\")", "= [d['value'] for d in last_numbers[0]['items']] return Response(json.dumps(extracted, default=json_util.default), status=200,", "the connection \"my-app\". connect(\"mongodb://mongodb:27017/myDatabase\", alias=\"my-app\") class User(MongoModel): email = fields.EmailField(primary_key=True)", "Hello world...</h3>\" #User('<EMAIL>', name, 'Ross').save() return html @app.route(\"/add_user/<name>\") def add_user(name):", "number, \"date\": datetime.datetime.utcnow()}], \"$sort\" : {\"date\" : -1}, \"$slice\" :", ": {\"date\" : -1}, \"$slice\" : 5 } }}, upsert=True", "random, os, json, datetime, time from flask import Flask, Response", "d in last_numbers[0]['items']] return Response(json.dumps(extracted, default=json_util.default), status=200, mimetype='application/json') if __name__", "Response(number, status=200, mimetype='application/json') @app.route(\"/random-list\") def last_number_list(): last_numbers = list(random_numbers.find({\"_id\" :", "from pymongo import MongoClient from bson import json_util app =", "connect from pymongo.write_concern import WriteConcern from pymodm import MongoModel, fields", "from pymodm import MongoModel, fields # Connect to MongoDB and", "MONGO_URI = \"mongodb://mongodb:27017\" # \"mongodb:<container_name>:27017\" mongdb_client= MongoClient(MONGO_URI) random_numbers = mongdb_client.demo.random_numbers", "def random_generator(lower, upper): number = str(random.randint(lower, upper)) random_numbers.update( {\"_id\" :", "fields.CharField() last_name = fields.CharField() class Meta: write_concern = WriteConcern(j=True) connection_alias", ": number, \"date\": datetime.datetime.utcnow()}], \"$sort\" : {\"date\" : -1}, \"$slice\"", "on Tue Dec 18 20:13:57 2018 @author: allen \"\"\" import", "@author: allen \"\"\" import random, os, json, datetime, time from", "pymongo import MongoClient from bson import json_util app = Flask(__name__)", "database to get running ###################### ## ########################## from pymodm.connection import", "WriteConcern from pymodm import MongoModel, fields # Connect to MongoDB", "html @app.route(\"/add_user/<name>\") def add_user(name): #User('<EMAIL>', name, 'Ross').save() html = \"<h3>", "last_numbers[0]['items']] return Response(json.dumps(extracted, default=json_util.default), status=200, mimetype='application/json') if __name__ == \"__main__\":", "number = str(random.randint(lower, upper)) random_numbers.update( {\"_id\" : \"lasts\"}, {\"$push\" :", "def hello(): html = \"<h3> Hello world...</h3>\" #User('<EMAIL>', name, 'Ross').save()", "get running ###################### ## ########################## from pymodm.connection import connect from", "from pymongo.write_concern import WriteConcern from pymodm import MongoModel, fields #", "import connect from pymongo.write_concern import WriteConcern from pymodm import MongoModel,", "\"$sort\" : {\"date\" : -1}, \"$slice\" : 5 } }},", "= 'my-app' @app.route(\"/\") def hello(): html = \"<h3> Hello world...</h3>\"", "\"lasts\"})) extracted = [d['value'] for d in last_numbers[0]['items']] return Response(json.dumps(extracted,", "Dec 18 20:13:57 2018 @author: allen \"\"\" import random, os,", "MongoDB and call the connection \"my-app\". connect(\"mongodb://mongodb:27017/myDatabase\", alias=\"my-app\") class User(MongoModel):", "-*- coding: utf-8 -*- \"\"\" Created on Tue Dec 18", "Created on Tue Dec 18 20:13:57 2018 @author: allen \"\"\"", "status=200, mimetype='application/json') @app.route(\"/random-list\") def last_number_list(): last_numbers = list(random_numbers.find({\"_id\" : \"lasts\"}))", "coding: utf-8 -*- \"\"\" Created on Tue Dec 18 20:13:57", "#User('<EMAIL>', name, 'Ross').save() return html @app.route(\"/add_user/<name>\") def add_user(name): #User('<EMAIL>', name,", "random_generator(lower, upper): number = str(random.randint(lower, upper)) random_numbers.update( {\"_id\" : \"lasts\"},", "= str(random.randint(lower, upper)) random_numbers.update( {\"_id\" : \"lasts\"}, {\"$push\" : {", "{\"$push\" : { \"items\" : { \"$each\": [{\"value\" : number,", "extracted = [d['value'] for d in last_numbers[0]['items']] return Response(json.dumps(extracted, default=json_util.default)," ]
[ "6: print('arguments wrong!') print(len(sys.argv)) exit() else: words = [sys.argv[2], sys.argv[3],", "Space---------') print('to word-4: ', 1-spatial.distance.cosine(m2+m3-m1, m4)) print('to word-3: ', 1-spatial.distance.cosine(m1+m4-m2,", "import KeyedVectors from scipy import spatial from numpy import linalg", "/ linalg.norm(w2) m3 = w3 / linalg.norm(w3) m4 = w4", "KeyedVectors.load_word2vec_format(vector_file, binary=True) print('WVs loaded.') for w in words: if w", "m4 = w4 / linalg.norm(w4) diff1 = w1 - w2", "m3 = w3 / linalg.norm(w3) m4 = w4 / linalg.norm(w4)", "miff2 = m3 - m4 print('-------Word Space---------') print('to word-4: ',", "= KeyedVectors.load_word2vec_format(vector_file, binary=True) print('WVs loaded.') for w in words: if", "m1)) print('------Analogy Space-------') print(' cosine: ', 1-spatial.distance.cosine(diff1, diff2)) print(' Euclidean:", "exit() #print(wvs.most_similar(positive=[words[1], words[2]], negative=[words[0]], topn=3)) w1 = wvs[words[0]] w2 =", "of vocab!') exit() #print(wvs.most_similar(positive=[words[1], words[2]], negative=[words[0]], topn=3)) w1 = wvs[words[0]]", "miff1 = m1 - m2 miff2 = m3 - m4", "sys.argv[1] if len(sys.argv) != 6: print('arguments wrong!') print(len(sys.argv)) exit() else:", "', 1-spatial.distance.cosine(m1+m4-m2, m3)) print('to word-2: ', 1-spatial.distance.cosine(m4+m1-m3, m2)) print('to word-1:", "in wvs.vocab: print('out of vocab!') exit() #print(wvs.most_similar(positive=[words[1], words[2]], negative=[words[0]], topn=3))", "Space-------') print(' cosine: ', 1-spatial.distance.cosine(diff1, diff2)) print(' Euclidean: ', 1-linalg.norm(diff1-diff2)/(linalg.norm(diff1)+linalg.norm(diff2)))", "import spatial from numpy import linalg import argparse import sys", "negative=[words[0]], topn=3)) w1 = wvs[words[0]] w2 = wvs[words[1]] w3 =", "import linalg import argparse import sys vector_file = sys.argv[1] if", "m4)) print('to word-3: ', 1-spatial.distance.cosine(m1+m4-m2, m3)) print('to word-2: ', 1-spatial.distance.cosine(m4+m1-m3,", "from numpy import linalg import argparse import sys vector_file =", "wvs.vocab: print('out of vocab!') exit() #print(wvs.most_similar(positive=[words[1], words[2]], negative=[words[0]], topn=3)) w1", "numpy import linalg import argparse import sys vector_file = sys.argv[1]", "/ linalg.norm(w1) m2 = w2 / linalg.norm(w2) m3 = w3", "w2 = wvs[words[1]] w3 = wvs[words[2]] w4 = wvs[words[3]] m1", "= wvs[words[1]] w3 = wvs[words[2]] w4 = wvs[words[3]] m1 =", "= wvs[words[2]] w4 = wvs[words[3]] m1 = w1 / linalg.norm(w1)", "', 1-spatial.distance.cosine(m4+m1-m3, m2)) print('to word-1: ', 1-spatial.distance.cosine(m2+m3-m4, m1)) print('------Analogy Space-------')", "scipy import spatial from numpy import linalg import argparse import", "if len(sys.argv) != 6: print('arguments wrong!') print(len(sys.argv)) exit() else: words", "1-spatial.distance.cosine(m2+m3-m4, m1)) print('------Analogy Space-------') print(' cosine: ', 1-spatial.distance.cosine(diff1, diff2)) print('", "diff2)) print(' Euclidean: ', 1-linalg.norm(diff1-diff2)/(linalg.norm(diff1)+linalg.norm(diff2))) print(' M-cosine: ', 1-spatial.distance.cosine(miff1, miff2))", "for w in words: if w not in wvs.vocab: print('out", "w1 = wvs[words[0]] w2 = wvs[words[1]] w3 = wvs[words[2]] w4", "w3 = wvs[words[2]] w4 = wvs[words[3]] m1 = w1 /", "w1 / linalg.norm(w1) m2 = w2 / linalg.norm(w2) m3 =", "print('-------Word Space---------') print('to word-4: ', 1-spatial.distance.cosine(m2+m3-m1, m4)) print('to word-3: ',", "m4 print('-------Word Space---------') print('to word-4: ', 1-spatial.distance.cosine(m2+m3-m1, m4)) print('to word-3:", "print(words) wvs = KeyedVectors.load_word2vec_format(vector_file, binary=True) print('WVs loaded.') for w in", "in words: if w not in wvs.vocab: print('out of vocab!')", "binary=True) print('WVs loaded.') for w in words: if w not", "1-spatial.distance.cosine(m2+m3-m1, m4)) print('to word-3: ', 1-spatial.distance.cosine(m1+m4-m2, m3)) print('to word-2: ',", "= m1 - m2 miff2 = m3 - m4 print('-------Word", "print(' Euclidean: ', 1-linalg.norm(diff1-diff2)/(linalg.norm(diff1)+linalg.norm(diff2))) print(' M-cosine: ', 1-spatial.distance.cosine(miff1, miff2)) print('M-Euclidean:", "= wvs[words[0]] w2 = wvs[words[1]] w3 = wvs[words[2]] w4 =", "m2 miff2 = m3 - m4 print('-------Word Space---------') print('to word-4:", "', 1-spatial.distance.cosine(m2+m3-m1, m4)) print('to word-3: ', 1-spatial.distance.cosine(m1+m4-m2, m3)) print('to word-2:", "linalg import argparse import sys vector_file = sys.argv[1] if len(sys.argv)", "exit() else: words = [sys.argv[2], sys.argv[3], sys.argv[4], sys.argv[5]] print(words) wvs", "w4 / linalg.norm(w4) diff1 = w1 - w2 diff2 =", "/ linalg.norm(w3) m4 = w4 / linalg.norm(w4) diff1 = w1", "- w4 miff1 = m1 - m2 miff2 = m3", "sys.argv[4], sys.argv[5]] print(words) wvs = KeyedVectors.load_word2vec_format(vector_file, binary=True) print('WVs loaded.') for", "KeyedVectors from scipy import spatial from numpy import linalg import", "print('------Analogy Space-------') print(' cosine: ', 1-spatial.distance.cosine(diff1, diff2)) print(' Euclidean: ',", "import sys vector_file = sys.argv[1] if len(sys.argv) != 6: print('arguments", "w2 diff2 = w3 - w4 miff1 = m1 -", "import argparse import sys vector_file = sys.argv[1] if len(sys.argv) !=", "m2)) print('to word-1: ', 1-spatial.distance.cosine(m2+m3-m4, m1)) print('------Analogy Space-------') print(' cosine:", "', 1-spatial.distance.cosine(diff1, diff2)) print(' Euclidean: ', 1-linalg.norm(diff1-diff2)/(linalg.norm(diff1)+linalg.norm(diff2))) print(' M-cosine: ',", "if w not in wvs.vocab: print('out of vocab!') exit() #print(wvs.most_similar(positive=[words[1],", "w not in wvs.vocab: print('out of vocab!') exit() #print(wvs.most_similar(positive=[words[1], words[2]],", "m3)) print('to word-2: ', 1-spatial.distance.cosine(m4+m1-m3, m2)) print('to word-1: ', 1-spatial.distance.cosine(m2+m3-m4,", "/usr/bin/Python from gensim.models.keyedvectors import KeyedVectors from scipy import spatial from", "sys.argv[5]] print(words) wvs = KeyedVectors.load_word2vec_format(vector_file, binary=True) print('WVs loaded.') for w", "= w1 - w2 diff2 = w3 - w4 miff1", "linalg.norm(w3) m4 = w4 / linalg.norm(w4) diff1 = w1 -", "vector_file = sys.argv[1] if len(sys.argv) != 6: print('arguments wrong!') print(len(sys.argv))", "= w2 / linalg.norm(w2) m3 = w3 / linalg.norm(w3) m4", "- w2 diff2 = w3 - w4 miff1 = m1", "wvs[words[2]] w4 = wvs[words[3]] m1 = w1 / linalg.norm(w1) m2", "word-3: ', 1-spatial.distance.cosine(m1+m4-m2, m3)) print('to word-2: ', 1-spatial.distance.cosine(m4+m1-m3, m2)) print('to", "m1 = w1 / linalg.norm(w1) m2 = w2 / linalg.norm(w2)", "from scipy import spatial from numpy import linalg import argparse", "!= 6: print('arguments wrong!') print(len(sys.argv)) exit() else: words = [sys.argv[2],", "#print(wvs.most_similar(positive=[words[1], words[2]], negative=[words[0]], topn=3)) w1 = wvs[words[0]] w2 = wvs[words[1]]", "print('to word-2: ', 1-spatial.distance.cosine(m4+m1-m3, m2)) print('to word-1: ', 1-spatial.distance.cosine(m2+m3-m4, m1))", "Euclidean: ', 1-linalg.norm(diff1-diff2)/(linalg.norm(diff1)+linalg.norm(diff2))) print(' M-cosine: ', 1-spatial.distance.cosine(miff1, miff2)) print('M-Euclidean: ',", "linalg.norm(w4) diff1 = w1 - w2 diff2 = w3 -", "diff2 = w3 - w4 miff1 = m1 - m2", "wvs[words[1]] w3 = wvs[words[2]] w4 = wvs[words[3]] m1 = w1", "word-4: ', 1-spatial.distance.cosine(m2+m3-m1, m4)) print('to word-3: ', 1-spatial.distance.cosine(m1+m4-m2, m3)) print('to", "= sys.argv[1] if len(sys.argv) != 6: print('arguments wrong!') print(len(sys.argv)) exit()", "print('to word-4: ', 1-spatial.distance.cosine(m2+m3-m1, m4)) print('to word-3: ', 1-spatial.distance.cosine(m1+m4-m2, m3))", "w1 - w2 diff2 = w3 - w4 miff1 =", "from gensim.models.keyedvectors import KeyedVectors from scipy import spatial from numpy", "linalg.norm(w1) m2 = w2 / linalg.norm(w2) m3 = w3 /", "not in wvs.vocab: print('out of vocab!') exit() #print(wvs.most_similar(positive=[words[1], words[2]], negative=[words[0]],", "wvs[words[3]] m1 = w1 / linalg.norm(w1) m2 = w2 /", "word-1: ', 1-spatial.distance.cosine(m2+m3-m4, m1)) print('------Analogy Space-------') print(' cosine: ', 1-spatial.distance.cosine(diff1,", "print('arguments wrong!') print(len(sys.argv)) exit() else: words = [sys.argv[2], sys.argv[3], sys.argv[4],", "= [sys.argv[2], sys.argv[3], sys.argv[4], sys.argv[5]] print(words) wvs = KeyedVectors.load_word2vec_format(vector_file, binary=True)", "gensim.models.keyedvectors import KeyedVectors from scipy import spatial from numpy import", "wrong!') print(len(sys.argv)) exit() else: words = [sys.argv[2], sys.argv[3], sys.argv[4], sys.argv[5]]", "print(len(sys.argv)) exit() else: words = [sys.argv[2], sys.argv[3], sys.argv[4], sys.argv[5]] print(words)", "print('to word-3: ', 1-spatial.distance.cosine(m1+m4-m2, m3)) print('to word-2: ', 1-spatial.distance.cosine(m4+m1-m3, m2))", "topn=3)) w1 = wvs[words[0]] w2 = wvs[words[1]] w3 = wvs[words[2]]", "- m2 miff2 = m3 - m4 print('-------Word Space---------') print('to", "', 1-linalg.norm(diff1-diff2)/(linalg.norm(diff1)+linalg.norm(diff2))) print(' M-cosine: ', 1-spatial.distance.cosine(miff1, miff2)) print('M-Euclidean: ', 1-linalg.norm(miff1-miff2)/(linalg.norm(miff1)+linalg.norm(miff2)))", "w4 = wvs[words[3]] m1 = w1 / linalg.norm(w1) m2 =", "w3 - w4 miff1 = m1 - m2 miff2 =", "print('to word-1: ', 1-spatial.distance.cosine(m2+m3-m4, m1)) print('------Analogy Space-------') print(' cosine: ',", "vocab!') exit() #print(wvs.most_similar(positive=[words[1], words[2]], negative=[words[0]], topn=3)) w1 = wvs[words[0]] w2", "= w3 - w4 miff1 = m1 - m2 miff2", "w4 miff1 = m1 - m2 miff2 = m3 -", "[sys.argv[2], sys.argv[3], sys.argv[4], sys.argv[5]] print(words) wvs = KeyedVectors.load_word2vec_format(vector_file, binary=True) print('WVs", "words[2]], negative=[words[0]], topn=3)) w1 = wvs[words[0]] w2 = wvs[words[1]] w3", "= w3 / linalg.norm(w3) m4 = w4 / linalg.norm(w4) diff1", "words = [sys.argv[2], sys.argv[3], sys.argv[4], sys.argv[5]] print(words) wvs = KeyedVectors.load_word2vec_format(vector_file,", "= m3 - m4 print('-------Word Space---------') print('to word-4: ', 1-spatial.distance.cosine(m2+m3-m1,", "words: if w not in wvs.vocab: print('out of vocab!') exit()", "m3 - m4 print('-------Word Space---------') print('to word-4: ', 1-spatial.distance.cosine(m2+m3-m1, m4))", "m1 - m2 miff2 = m3 - m4 print('-------Word Space---------')", "linalg.norm(w2) m3 = w3 / linalg.norm(w3) m4 = w4 /", "m2 = w2 / linalg.norm(w2) m3 = w3 / linalg.norm(w3)", "diff1 = w1 - w2 diff2 = w3 - w4", "#! /usr/bin/Python from gensim.models.keyedvectors import KeyedVectors from scipy import spatial", "= w4 / linalg.norm(w4) diff1 = w1 - w2 diff2", "= wvs[words[3]] m1 = w1 / linalg.norm(w1) m2 = w2", "print('WVs loaded.') for w in words: if w not in", "wvs[words[0]] w2 = wvs[words[1]] w3 = wvs[words[2]] w4 = wvs[words[3]]", "w2 / linalg.norm(w2) m3 = w3 / linalg.norm(w3) m4 =", "w in words: if w not in wvs.vocab: print('out of", "spatial from numpy import linalg import argparse import sys vector_file", "print('out of vocab!') exit() #print(wvs.most_similar(positive=[words[1], words[2]], negative=[words[0]], topn=3)) w1 =", "1-spatial.distance.cosine(m1+m4-m2, m3)) print('to word-2: ', 1-spatial.distance.cosine(m4+m1-m3, m2)) print('to word-1: ',", "/ linalg.norm(w4) diff1 = w1 - w2 diff2 = w3", "1-spatial.distance.cosine(m4+m1-m3, m2)) print('to word-1: ', 1-spatial.distance.cosine(m2+m3-m4, m1)) print('------Analogy Space-------') print('", "= w1 / linalg.norm(w1) m2 = w2 / linalg.norm(w2) m3", "argparse import sys vector_file = sys.argv[1] if len(sys.argv) != 6:", "loaded.') for w in words: if w not in wvs.vocab:", "cosine: ', 1-spatial.distance.cosine(diff1, diff2)) print(' Euclidean: ', 1-linalg.norm(diff1-diff2)/(linalg.norm(diff1)+linalg.norm(diff2))) print(' M-cosine:", "1-spatial.distance.cosine(diff1, diff2)) print(' Euclidean: ', 1-linalg.norm(diff1-diff2)/(linalg.norm(diff1)+linalg.norm(diff2))) print(' M-cosine: ', 1-spatial.distance.cosine(miff1,", "- m4 print('-------Word Space---------') print('to word-4: ', 1-spatial.distance.cosine(m2+m3-m1, m4)) print('to", "else: words = [sys.argv[2], sys.argv[3], sys.argv[4], sys.argv[5]] print(words) wvs =", "print(' cosine: ', 1-spatial.distance.cosine(diff1, diff2)) print(' Euclidean: ', 1-linalg.norm(diff1-diff2)/(linalg.norm(diff1)+linalg.norm(diff2))) print('", "', 1-spatial.distance.cosine(m2+m3-m4, m1)) print('------Analogy Space-------') print(' cosine: ', 1-spatial.distance.cosine(diff1, diff2))", "wvs = KeyedVectors.load_word2vec_format(vector_file, binary=True) print('WVs loaded.') for w in words:", "w3 / linalg.norm(w3) m4 = w4 / linalg.norm(w4) diff1 =", "word-2: ', 1-spatial.distance.cosine(m4+m1-m3, m2)) print('to word-1: ', 1-spatial.distance.cosine(m2+m3-m4, m1)) print('------Analogy", "sys.argv[3], sys.argv[4], sys.argv[5]] print(words) wvs = KeyedVectors.load_word2vec_format(vector_file, binary=True) print('WVs loaded.')", "sys vector_file = sys.argv[1] if len(sys.argv) != 6: print('arguments wrong!')", "len(sys.argv) != 6: print('arguments wrong!') print(len(sys.argv)) exit() else: words =" ]
[ "normalized Laplacian matrix then it uses sweep cut to round", "F = np.real(p[:,1:]) if normalize: F *= g.dn_sqrt[:,np.newaxis] return F,", "g.dn_sqrt[:,np.newaxis] return F, emb_eig_val \"\"\" Random walks and local cuts", "eigenvectors or dimensions to compute. tol_eigs: positive float, double default", "the normalized Laplacian matrix then it uses sweep cut to", "\"\"\" def eig2nL_subgraph(g, ref_nodes, tol_eigs = 1.0e-6, normalize: bool =", "sweep cut to round the solution. PARAMETERS (mandatory) ---------------------- g:", "cuts in graphs, Chung, LAA 2007 We just form the", "ref_nodes, tol_eigs = 1.0e-6, normalize: bool = True): A_sub =", "sp.sparse.spdiags(g.dn_sqrt[ref_nodes].transpose(), 0, nref, nref) L_sub = sp.sparse.identity(nref) - D_sqrt_neg.dot((A_sub.dot(D_sqrt_neg))) emb_eig_val,", "tol_eigs = 1.0e-6, normalize:bool = True, dim:int=1): \"\"\" DESCRIPTION -----------", "= emb_eig[:,0] if normalize: f *= g.dn_sqrt[ref_nodes] return ((ref_nodes,f), emb_eig_val)", "use the eigenvector there. \"\"\" def eig2nL_subgraph(g, ref_nodes, tol_eigs =", "emb_eig_val, emb_eig = splinalg.eigsh(L_sub, which='SM', k=1, tol=tol_eigs) emb_eig *= -1", "default == 1.0e-6 Tolerance for computation of the eigenvector that", "smallest eigenvalue of the normalized Laplacian matrix and larger eigenvectors", "eigenvalue of the normalized Laplacian matrix and larger eigenvectors if", "tol = tol_eigs) F = np.real(p[:,1:]) if normalize: F *=", "form the sub-matrix of the Laplacian and use the eigenvector", "matrix. normalize: bool, default == True True if we should", "as splinalg def eig2_nL(g, tol_eigs = 1.0e-6, normalize:bool = True,", "D_sqrt_neg = sp.sparse.spdiags(g.dn_sqrt.transpose(), 0, n, n) L = sp.sparse.identity(n) -", "sp.sparse.identity(n) - D_sqrt_neg.dot((g.adjacency_matrix.dot(D_sqrt_neg))) emb_eig_val, p = splinalg.eigsh(L, which='SM', k=1+dim, tol", "on unless you know what you are doing. RETURNS ------", "to compute. tol_eigs: positive float, double default == 1.0e-6 Tolerance", "should return the eigenvectors of the generalized eigenvalue problem associated", "emb_eig *= -1 if max(emb_eig) < 0 else 1 f", "scipy as sp import scipy.sparse.linalg as splinalg def eig2_nL(g, tol_eigs", "unless you know what you are doing. RETURNS ------ p:", "0, n, n) L = sp.sparse.identity(n) - D_sqrt_neg.dot((g.adjacency_matrix.dot(D_sqrt_neg))) emb_eig_val, p", "which='SM', k=1+dim, tol = tol_eigs) F = np.real(p[:,1:]) if normalize:", "matrix then it uses sweep cut to round the solution.", "smallest eigenvalue of the normalized Laplacian matrix. normalize: bool, default", "should be on unless you know what you are doing.", "len(ref_nodes) D_sqrt_neg = sp.sparse.spdiags(g.dn_sqrt[ref_nodes].transpose(), 0, nref, nref) L_sub = sp.sparse.identity(nref)", "object PARAMETERS (optional) --------------------- dim: positive, int default == 1", "n) L = sp.sparse.identity(n) - D_sqrt_neg.dot((g.adjacency_matrix.dot(D_sqrt_neg))) emb_eig_val, p = splinalg.eigsh(L,", "of the eigenvector that corresponds to the second smallest eigenvalue", "(optional) --------------------- dim: positive, int default == 1 The number", "the Laplacian and use the eigenvector there. \"\"\" def eig2nL_subgraph(g,", "\"\"\" DESCRIPTION ----------- Computes the eigenvector that corresponds to the", "max(emb_eig) < 0 else 1 f = emb_eig[:,0] if normalize:", "----------- Computes the eigenvector that corresponds to the second smallest", "Chung, LAA 2007 We just form the sub-matrix of the", "Eigenvector or Eigenvector matrixthat corresponds to the second smallest eigenvalue", "Tolerance for computation of the eigenvector that corresponds to the", "(mandatory) ---------------------- g: graph object PARAMETERS (optional) --------------------- dim: positive,", "g: graph object PARAMETERS (optional) --------------------- dim: positive, int default", "with the normalized Laplacian. This should be on unless you", "Laplacian matrix. normalize: bool, default == True True if we", "of the normalized Laplacian matrix and larger eigenvectors if dim", "tol=tol_eigs) emb_eig *= -1 if max(emb_eig) < 0 else 1", "p = splinalg.eigsh(L, which='SM', k=1+dim, tol = tol_eigs) F =", "and local cuts in graphs, Chung, LAA 2007 We just", "uses sweep cut to round the solution. PARAMETERS (mandatory) ----------------------", "-1 if max(emb_eig) < 0 else 1 f = emb_eig[:,0]", "F, emb_eig_val \"\"\" Random walks and local cuts in graphs,", "= tol_eigs) F = np.real(p[:,1:]) if normalize: F *= g.dn_sqrt[:,np.newaxis]", "= sp.sparse.identity(nref) - D_sqrt_neg.dot((A_sub.dot(D_sqrt_neg))) emb_eig_val, emb_eig = splinalg.eigsh(L_sub, which='SM', k=1,", "D_sqrt_neg.dot((A_sub.dot(D_sqrt_neg))) emb_eig_val, emb_eig = splinalg.eigsh(L_sub, which='SM', k=1, tol=tol_eigs) emb_eig *=", "which='SM', k=1, tol=tol_eigs) emb_eig *= -1 if max(emb_eig) < 0", "you are doing. RETURNS ------ p: Eigenvector or Eigenvector matrixthat", "normalize:bool = True, dim:int=1): \"\"\" DESCRIPTION ----------- Computes the eigenvector", "the eigenvector that corresponds to the second smallest eigenvalue of", "float, double default == 1.0e-6 Tolerance for computation of the", "Laplacian matrix and larger eigenvectors if dim >= 0. \"\"\"", "sp.sparse.identity(nref) - D_sqrt_neg.dot((A_sub.dot(D_sqrt_neg))) emb_eig_val, emb_eig = splinalg.eigsh(L_sub, which='SM', k=1, tol=tol_eigs)", "to round the solution. PARAMETERS (mandatory) ---------------------- g: graph object", "D_sqrt_neg.dot((g.adjacency_matrix.dot(D_sqrt_neg))) emb_eig_val, p = splinalg.eigsh(L, which='SM', k=1+dim, tol = tol_eigs)", "what you are doing. RETURNS ------ p: Eigenvector or Eigenvector", "normalize: bool, default == True True if we should return", "This should be on unless you know what you are", "second smallest eigenvalue of the normalized Laplacian matrix. normalize: bool,", "def eig2_nL(g, tol_eigs = 1.0e-6, normalize:bool = True, dim:int=1): \"\"\"", "L = sp.sparse.identity(n) - D_sqrt_neg.dot((g.adjacency_matrix.dot(D_sqrt_neg))) emb_eig_val, p = splinalg.eigsh(L, which='SM',", "Laplacian matrix then it uses sweep cut to round the", "if dim >= 0. \"\"\" n = g.adjacency_matrix.shape[0] D_sqrt_neg =", "*= g.dn_sqrt[:,np.newaxis] return F, emb_eig_val \"\"\" Random walks and local", "of eigenvectors or dimensions to compute. tol_eigs: positive float, double", "nref, nref) L_sub = sp.sparse.identity(nref) - D_sqrt_neg.dot((A_sub.dot(D_sqrt_neg))) emb_eig_val, emb_eig =", "doing. RETURNS ------ p: Eigenvector or Eigenvector matrixthat corresponds to", "Eigenvector matrixthat corresponds to the second smallest eigenvalue of the", "def eig2nL_subgraph(g, ref_nodes, tol_eigs = 1.0e-6, normalize: bool = True):", "2007 We just form the sub-matrix of the Laplacian and", "second smallest eigenvalue of the normalized Laplacian matrix then it", "know what you are doing. RETURNS ------ p: Eigenvector or", "*= -1 if max(emb_eig) < 0 else 1 f =", "as sp import scipy.sparse.linalg as splinalg def eig2_nL(g, tol_eigs =", "return the eigenvectors of the generalized eigenvalue problem associated with", "dim:int=1): \"\"\" DESCRIPTION ----------- Computes the eigenvector that corresponds to", "dim: positive, int default == 1 The number of eigenvectors", "== 1.0e-6 Tolerance for computation of the eigenvector that corresponds", "import scipy as sp import scipy.sparse.linalg as splinalg def eig2_nL(g,", "you know what you are doing. RETURNS ------ p: Eigenvector", "to the second smallest eigenvalue of the normalized Laplacian matrix.", "second smallest eigenvalue of the normalized Laplacian matrix and larger", "import numpy as np import scipy as sp import scipy.sparse.linalg", "ref_nodes] nref = len(ref_nodes) D_sqrt_neg = sp.sparse.spdiags(g.dn_sqrt[ref_nodes].transpose(), 0, nref, nref)", "0. \"\"\" n = g.adjacency_matrix.shape[0] D_sqrt_neg = sp.sparse.spdiags(g.dn_sqrt.transpose(), 0, n,", "eigenvector there. \"\"\" def eig2nL_subgraph(g, ref_nodes, tol_eigs = 1.0e-6, normalize:", "eigenvectors of the generalized eigenvalue problem associated with the normalized", "np.real(p[:,1:]) if normalize: F *= g.dn_sqrt[:,np.newaxis] return F, emb_eig_val \"\"\"", "True if we should return the eigenvectors of the generalized", "import scipy.sparse.linalg as splinalg def eig2_nL(g, tol_eigs = 1.0e-6, normalize:bool", "walks and local cuts in graphs, Chung, LAA 2007 We", "tol_eigs: positive float, double default == 1.0e-6 Tolerance for computation", "splinalg def eig2_nL(g, tol_eigs = 1.0e-6, normalize:bool = True, dim:int=1):", "sp.sparse.spdiags(g.dn_sqrt.transpose(), 0, n, n) L = sp.sparse.identity(n) - D_sqrt_neg.dot((g.adjacency_matrix.dot(D_sqrt_neg))) emb_eig_val,", "else 1 f = emb_eig[:,0] if normalize: f *= g.dn_sqrt[ref_nodes]", "we should return the eigenvectors of the generalized eigenvalue problem", "== 1 The number of eigenvectors or dimensions to compute.", "emb_eig_val \"\"\" Random walks and local cuts in graphs, Chung,", "local cuts in graphs, Chung, LAA 2007 We just form", "or dimensions to compute. tol_eigs: positive float, double default ==", "cut to round the solution. PARAMETERS (mandatory) ---------------------- g: graph", "= splinalg.eigsh(L, which='SM', k=1+dim, tol = tol_eigs) F = np.real(p[:,1:])", "and larger eigenvectors if dim >= 0. \"\"\" n =", "F *= g.dn_sqrt[:,np.newaxis] return F, emb_eig_val \"\"\" Random walks and", "to the second smallest eigenvalue of the normalized Laplacian matrix", "just form the sub-matrix of the Laplacian and use the", "We just form the sub-matrix of the Laplacian and use", "computation of the eigenvector that corresponds to the second smallest", "= sp.sparse.spdiags(g.dn_sqrt.transpose(), 0, n, n) L = sp.sparse.identity(n) - D_sqrt_neg.dot((g.adjacency_matrix.dot(D_sqrt_neg)))", "------ p: Eigenvector or Eigenvector matrixthat corresponds to the second", "normalize: bool = True): A_sub = g.adjacency_matrix.tocsr()[ref_nodes, :].tocsc()[:, ref_nodes] nref", "- D_sqrt_neg.dot((g.adjacency_matrix.dot(D_sqrt_neg))) emb_eig_val, p = splinalg.eigsh(L, which='SM', k=1+dim, tol =", ">= 0. \"\"\" n = g.adjacency_matrix.shape[0] D_sqrt_neg = sp.sparse.spdiags(g.dn_sqrt.transpose(), 0,", "the solution. PARAMETERS (mandatory) ---------------------- g: graph object PARAMETERS (optional)", "normalized Laplacian. This should be on unless you know what", "that corresponds to the second smallest eigenvalue of the normalized", "are doing. RETURNS ------ p: Eigenvector or Eigenvector matrixthat corresponds", "associated with the normalized Laplacian. This should be on unless", "p: Eigenvector or Eigenvector matrixthat corresponds to the second smallest", "normalize: F *= g.dn_sqrt[:,np.newaxis] return F, emb_eig_val \"\"\" Random walks", "return F, emb_eig_val \"\"\" Random walks and local cuts in", "numpy as np import scipy as sp import scipy.sparse.linalg as", "RETURNS ------ p: Eigenvector or Eigenvector matrixthat corresponds to the", "double default == 1.0e-6 Tolerance for computation of the eigenvector", "number of eigenvectors or dimensions to compute. tol_eigs: positive float,", "The number of eigenvectors or dimensions to compute. tol_eigs: positive", "LAA 2007 We just form the sub-matrix of the Laplacian", "eigenvalue problem associated with the normalized Laplacian. This should be", "the eigenvector there. \"\"\" def eig2nL_subgraph(g, ref_nodes, tol_eigs = 1.0e-6,", "Random walks and local cuts in graphs, Chung, LAA 2007", "sub-matrix of the Laplacian and use the eigenvector there. \"\"\"", "of the normalized Laplacian matrix. normalize: bool, default == True", "D_sqrt_neg = sp.sparse.spdiags(g.dn_sqrt[ref_nodes].transpose(), 0, nref, nref) L_sub = sp.sparse.identity(nref) -", "= True): A_sub = g.adjacency_matrix.tocsr()[ref_nodes, :].tocsc()[:, ref_nodes] nref = len(ref_nodes)", "if normalize: F *= g.dn_sqrt[:,np.newaxis] return F, emb_eig_val \"\"\" Random", "k=1+dim, tol = tol_eigs) F = np.real(p[:,1:]) if normalize: F", "True): A_sub = g.adjacency_matrix.tocsr()[ref_nodes, :].tocsc()[:, ref_nodes] nref = len(ref_nodes) D_sqrt_neg", "n = g.adjacency_matrix.shape[0] D_sqrt_neg = sp.sparse.spdiags(g.dn_sqrt.transpose(), 0, n, n) L", "positive float, double default == 1.0e-6 Tolerance for computation of", "= np.real(p[:,1:]) if normalize: F *= g.dn_sqrt[:,np.newaxis] return F, emb_eig_val", "in graphs, Chung, LAA 2007 We just form the sub-matrix", "the generalized eigenvalue problem associated with the normalized Laplacian. This", "DESCRIPTION ----------- Computes the eigenvector that corresponds to the second", "the second smallest eigenvalue of the normalized Laplacian matrix then", "1 f = emb_eig[:,0] if normalize: f *= g.dn_sqrt[ref_nodes] return", "eigenvectors if dim >= 0. \"\"\" n = g.adjacency_matrix.shape[0] D_sqrt_neg", "generalized eigenvalue problem associated with the normalized Laplacian. This should", "k=1, tol=tol_eigs) emb_eig *= -1 if max(emb_eig) < 0 else", "--------------------- dim: positive, int default == 1 The number of", "= 1.0e-6, normalize: bool = True): A_sub = g.adjacency_matrix.tocsr()[ref_nodes, :].tocsc()[:,", "problem associated with the normalized Laplacian. This should be on", "PARAMETERS (optional) --------------------- dim: positive, int default == 1 The", "== True True if we should return the eigenvectors of", "be on unless you know what you are doing. RETURNS", "1.0e-6, normalize: bool = True): A_sub = g.adjacency_matrix.tocsr()[ref_nodes, :].tocsc()[:, ref_nodes]", "or Eigenvector matrixthat corresponds to the second smallest eigenvalue of", "of the generalized eigenvalue problem associated with the normalized Laplacian.", "and use the eigenvector there. \"\"\" def eig2nL_subgraph(g, ref_nodes, tol_eigs", "corresponds to the second smallest eigenvalue of the normalized Laplacian", "Laplacian and use the eigenvector there. \"\"\" def eig2nL_subgraph(g, ref_nodes,", "normalized Laplacian matrix. normalize: bool, default == True True if", ":].tocsc()[:, ref_nodes] nref = len(ref_nodes) D_sqrt_neg = sp.sparse.spdiags(g.dn_sqrt[ref_nodes].transpose(), 0, nref,", "= sp.sparse.identity(n) - D_sqrt_neg.dot((g.adjacency_matrix.dot(D_sqrt_neg))) emb_eig_val, p = splinalg.eigsh(L, which='SM', k=1+dim,", "of the Laplacian and use the eigenvector there. \"\"\" def", "1.0e-6 Tolerance for computation of the eigenvector that corresponds to", "smallest eigenvalue of the normalized Laplacian matrix then it uses", "L_sub = sp.sparse.identity(nref) - D_sqrt_neg.dot((A_sub.dot(D_sqrt_neg))) emb_eig_val, emb_eig = splinalg.eigsh(L_sub, which='SM',", "PARAMETERS (mandatory) ---------------------- g: graph object PARAMETERS (optional) --------------------- dim:", "bool, default == True True if we should return the", "< 0 else 1 f = emb_eig[:,0] if normalize: f", "eigenvalue of the normalized Laplacian matrix. normalize: bool, default ==", "nref) L_sub = sp.sparse.identity(nref) - D_sqrt_neg.dot((A_sub.dot(D_sqrt_neg))) emb_eig_val, emb_eig = splinalg.eigsh(L_sub,", "emb_eig_val, p = splinalg.eigsh(L, which='SM', k=1+dim, tol = tol_eigs) F", "compute. tol_eigs: positive float, double default == 1.0e-6 Tolerance for", "of the normalized Laplacian matrix then it uses sweep cut", "matrix and larger eigenvectors if dim >= 0. \"\"\" n", "g.adjacency_matrix.shape[0] D_sqrt_neg = sp.sparse.spdiags(g.dn_sqrt.transpose(), 0, n, n) L = sp.sparse.identity(n)", "= 1.0e-6, normalize:bool = True, dim:int=1): \"\"\" DESCRIPTION ----------- Computes", "the second smallest eigenvalue of the normalized Laplacian matrix. normalize:", "larger eigenvectors if dim >= 0. \"\"\" n = g.adjacency_matrix.shape[0]", "splinalg.eigsh(L, which='SM', k=1+dim, tol = tol_eigs) F = np.real(p[:,1:]) if", "graphs, Chung, LAA 2007 We just form the sub-matrix of", "splinalg.eigsh(L_sub, which='SM', k=1, tol=tol_eigs) emb_eig *= -1 if max(emb_eig) <", "positive, int default == 1 The number of eigenvectors or", "normalized Laplacian matrix and larger eigenvectors if dim >= 0.", "bool = True): A_sub = g.adjacency_matrix.tocsr()[ref_nodes, :].tocsc()[:, ref_nodes] nref =", "1 The number of eigenvectors or dimensions to compute. tol_eigs:", "---------------------- g: graph object PARAMETERS (optional) --------------------- dim: positive, int", "graph object PARAMETERS (optional) --------------------- dim: positive, int default ==", "for computation of the eigenvector that corresponds to the second", "- D_sqrt_neg.dot((A_sub.dot(D_sqrt_neg))) emb_eig_val, emb_eig = splinalg.eigsh(L_sub, which='SM', k=1, tol=tol_eigs) emb_eig", "it uses sweep cut to round the solution. PARAMETERS (mandatory)", "\"\"\" Random walks and local cuts in graphs, Chung, LAA", "sp import scipy.sparse.linalg as splinalg def eig2_nL(g, tol_eigs = 1.0e-6,", "f = emb_eig[:,0] if normalize: f *= g.dn_sqrt[ref_nodes] return ((ref_nodes,f),", "Computes the eigenvector that corresponds to the second smallest eigenvalue", "True, dim:int=1): \"\"\" DESCRIPTION ----------- Computes the eigenvector that corresponds", "= g.adjacency_matrix.tocsr()[ref_nodes, :].tocsc()[:, ref_nodes] nref = len(ref_nodes) D_sqrt_neg = sp.sparse.spdiags(g.dn_sqrt[ref_nodes].transpose(),", "scipy.sparse.linalg as splinalg def eig2_nL(g, tol_eigs = 1.0e-6, normalize:bool =", "1.0e-6, normalize:bool = True, dim:int=1): \"\"\" DESCRIPTION ----------- Computes the", "tol_eigs = 1.0e-6, normalize: bool = True): A_sub = g.adjacency_matrix.tocsr()[ref_nodes,", "Laplacian. This should be on unless you know what you", "the normalized Laplacian matrix and larger eigenvectors if dim >=", "tol_eigs) F = np.real(p[:,1:]) if normalize: F *= g.dn_sqrt[:,np.newaxis] return", "= sp.sparse.spdiags(g.dn_sqrt[ref_nodes].transpose(), 0, nref, nref) L_sub = sp.sparse.identity(nref) - D_sqrt_neg.dot((A_sub.dot(D_sqrt_neg)))", "emb_eig = splinalg.eigsh(L_sub, which='SM', k=1, tol=tol_eigs) emb_eig *= -1 if", "= g.adjacency_matrix.shape[0] D_sqrt_neg = sp.sparse.spdiags(g.dn_sqrt.transpose(), 0, n, n) L =", "eig2nL_subgraph(g, ref_nodes, tol_eigs = 1.0e-6, normalize: bool = True): A_sub", "if we should return the eigenvectors of the generalized eigenvalue", "if max(emb_eig) < 0 else 1 f = emb_eig[:,0] if", "the normalized Laplacian matrix. normalize: bool, default == True True", "= len(ref_nodes) D_sqrt_neg = sp.sparse.spdiags(g.dn_sqrt[ref_nodes].transpose(), 0, nref, nref) L_sub =", "= True, dim:int=1): \"\"\" DESCRIPTION ----------- Computes the eigenvector that", "True True if we should return the eigenvectors of the", "default == True True if we should return the eigenvectors", "the eigenvectors of the generalized eigenvalue problem associated with the", "\"\"\" n = g.adjacency_matrix.shape[0] D_sqrt_neg = sp.sparse.spdiags(g.dn_sqrt.transpose(), 0, n, n)", "then it uses sweep cut to round the solution. PARAMETERS", "round the solution. PARAMETERS (mandatory) ---------------------- g: graph object PARAMETERS", "the second smallest eigenvalue of the normalized Laplacian matrix and", "dim >= 0. \"\"\" n = g.adjacency_matrix.shape[0] D_sqrt_neg = sp.sparse.spdiags(g.dn_sqrt.transpose(),", "n, n) L = sp.sparse.identity(n) - D_sqrt_neg.dot((g.adjacency_matrix.dot(D_sqrt_neg))) emb_eig_val, p =", "the sub-matrix of the Laplacian and use the eigenvector there.", "nref = len(ref_nodes) D_sqrt_neg = sp.sparse.spdiags(g.dn_sqrt[ref_nodes].transpose(), 0, nref, nref) L_sub", "= splinalg.eigsh(L_sub, which='SM', k=1, tol=tol_eigs) emb_eig *= -1 if max(emb_eig)", "0 else 1 f = emb_eig[:,0] if normalize: f *=", "0, nref, nref) L_sub = sp.sparse.identity(nref) - D_sqrt_neg.dot((A_sub.dot(D_sqrt_neg))) emb_eig_val, emb_eig", "A_sub = g.adjacency_matrix.tocsr()[ref_nodes, :].tocsc()[:, ref_nodes] nref = len(ref_nodes) D_sqrt_neg =", "eigenvector that corresponds to the second smallest eigenvalue of the", "dimensions to compute. tol_eigs: positive float, double default == 1.0e-6", "default == 1 The number of eigenvectors or dimensions to", "eig2_nL(g, tol_eigs = 1.0e-6, normalize:bool = True, dim:int=1): \"\"\" DESCRIPTION", "int default == 1 The number of eigenvectors or dimensions", "eigenvalue of the normalized Laplacian matrix then it uses sweep", "matrixthat corresponds to the second smallest eigenvalue of the normalized", "np import scipy as sp import scipy.sparse.linalg as splinalg def", "there. \"\"\" def eig2nL_subgraph(g, ref_nodes, tol_eigs = 1.0e-6, normalize: bool", "g.adjacency_matrix.tocsr()[ref_nodes, :].tocsc()[:, ref_nodes] nref = len(ref_nodes) D_sqrt_neg = sp.sparse.spdiags(g.dn_sqrt[ref_nodes].transpose(), 0,", "the normalized Laplacian. This should be on unless you know", "solution. PARAMETERS (mandatory) ---------------------- g: graph object PARAMETERS (optional) ---------------------", "as np import scipy as sp import scipy.sparse.linalg as splinalg" ]
[ "hexU8(len(a.data) >> 8) + \", 0x\" + hexU8(len(a.data)) + \",", "args = parser.parse_args() if args.hex == None: raise Exception(\"Missing hex", "\", 0x\" + hexU8(len(a.data) >> 16) + \", 0x\" +", "\"\"\" from ledgerblue.hexParser import IntelHexParser import argparse parser = argparse.ArgumentParser()", "ledgerblue.hexParser import IntelHexParser import argparse parser = argparse.ArgumentParser() parser.add_argument(\"--hex\", help=\"Hex", "16) + \", 0x\" + hexU8(len(a.data) >> 8) + \",", "0x\" + hexU8(len(a.data) >> 8) + \", 0x\" + hexU8(len(a.data))", "Unless required by applicable law or agreed to in writing,", "******************************************************************************** \"\"\" from ledgerblue.hexParser import IntelHexParser import argparse parser =", "import argparse parser = argparse.ArgumentParser() parser.add_argument(\"--hex\", help=\"Hex file to be", "converted as a C array\") args = parser.parse_args() if args.hex", "* distributed under the License is distributed on an \"AS", "distributed under the License is distributed on an \"AS IS\"", "+ \", 0x\" + hexU8(len(a.data)) + \", \" # low", "under the Apache License, Version 2.0 (the \"License\"); * you", "\", 0x\" + hexU8(a.start >> 8) + \", 0x\" +", "License for the specific language governing permissions and * limitations", "\"\" for i in range(8): if offset+i < len(a.data): string", "except in compliance with the License. * You may obtain", "as a C array\") args = parser.parse_args() if args.hex ==", "\"License\"); * you may not use this file except in", "= argparse.ArgumentParser() parser.add_argument(\"--hex\", help=\"Hex file to be converted as a", "\"0x\" + hexU8(a.start >> 24) + \", 0x\" + hexU8(a.start", "a C array\") args = parser.parse_args() if args.hex == None:", "len(a.data): string += \" 0x\" + hexU8(a.data[offset+i]) + \",\" print", "high @ offset = 0 while offset < len(a.data): string", "the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required", "24) + \", 0x\" + hexU8(a.start >> 16) + \",", "16) + \", 0x\" + hexU8(a.start >> 8) + \",", "range(8): if offset+i < len(a.data): string += \" 0x\" +", "not use this file except in compliance with the License.", "use this file except in compliance with the License. *", "raise BaseException(\"data must be splitted in chunks of 64k\") print", "hexU8(a.start >> 8) + \", 0x\" + hexU8(a.start) + \",", "* * Licensed under the Apache License, Version 2.0 (the", "array\") args = parser.parse_args() if args.hex == None: raise Exception(\"Missing", "print \"0x\" + hexU8(a.start >> 24) + \", 0x\" +", "+ \", 0x\" + hexU8(len(a.data) >> 8) + \", 0x\"", "# low @ to high @ offset = 0 while", "0 while offset < len(a.data): string = \"\" for i", "while offset < len(a.data): string = \"\" for i in", "License, Version 2.0 (the \"License\"); * you may not use", "< len(a.data): string = \"\" for i in range(8): if", "(the \"License\"); * you may not use this file except", "if (len(a.data) > 0x10000): raise BaseException(\"data must be splitted in", "applicable law or agreed to in writing, software * distributed", "you may not use this file except in compliance with", "= 0 while offset < len(a.data): string = \"\" for", "2.0 (the \"License\"); * you may not use this file", "and * limitations under the License. ******************************************************************************** \"\"\" from ledgerblue.hexParser", "of 64k\") print \"0x\" + hexU8(a.start >> 24) + \",", "* * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law", "this file except in compliance with the License. * You", "License. * You may obtain a copy of the License", "BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "import IntelHexParser import argparse parser = argparse.ArgumentParser() parser.add_argument(\"--hex\", help=\"Hex file", "argparse parser = argparse.ArgumentParser() parser.add_argument(\"--hex\", help=\"Hex file to be converted", "+ hexU8(a.start >> 16) + \", 0x\" + hexU8(a.start >>", "\", 0x\" + hexU8(len(a.data) >> 8) + \", 0x\" +", "\"\"\" ******************************************************************************* * Ledger Blue * (c) 2016 Ledger *", "parser.add_argument(\"--hex\", help=\"Hex file to be converted as a C array\")", "to high @ offset = 0 while offset < len(a.data):", "help=\"Hex file to be converted as a C array\") args", "* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "Ledger Blue * (c) 2016 Ledger * * Licensed under", "License is distributed on an \"AS IS\" BASIS, * WITHOUT", ">> 16) + \", 0x\" + hexU8(len(a.data) >> 8) +", "* You may obtain a copy of the License at", "of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless", "hexU8(len(a.data) >> 24) + \", 0x\" + hexU8(len(a.data) >> 16)", ">> 16) + \", 0x\" + hexU8(a.start >> 8) +", ">> 24) + \", 0x\" + hexU8(len(a.data) >> 16) +", "hex filename to sign\") parser = IntelHexParser(args.hex) def hexU8(value): return", "express or implied. * See the License for the specific", "string = \"\" for i in range(8): if offset+i <", "be splitted in chunks of 64k\") print \"0x\" + hexU8(a.start", "parser = IntelHexParser(args.hex) def hexU8(value): return hex(0x100|(value & 0xFF))[3:] for", "24) + \", 0x\" + hexU8(len(a.data) >> 16) + \",", "* (c) 2016 Ledger * * Licensed under the Apache", "string += \" 0x\" + hexU8(a.data[offset+i]) + \",\" print string", "+= \" 0x\" + hexU8(a.data[offset+i]) + \",\" print string offset+=8", "the License. ******************************************************************************** \"\"\" from ledgerblue.hexParser import IntelHexParser import argparse", "Licensed under the Apache License, Version 2.0 (the \"License\"); *", "file except in compliance with the License. * You may", "obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0", "on an \"AS IS\" BASIS, * WITHOUT WARRANTIES OR CONDITIONS", "8) + \", 0x\" + hexU8(len(a.data)) + \", \" #", "Exception(\"Missing hex filename to sign\") parser = IntelHexParser(args.hex) def hexU8(value):", "offset < len(a.data): string = \"\" for i in range(8):", "Apache License, Version 2.0 (the \"License\"); * you may not", "under the License is distributed on an \"AS IS\" BASIS,", ">> 24) + \", 0x\" + hexU8(a.start >> 16) +", "+ \", \" print \"0x\" + hexU8(len(a.data) >> 24) +", "for a in parser.getAreas(): if (len(a.data) > 0x10000): raise BaseException(\"data", "hexU8(a.start >> 16) + \", 0x\" + hexU8(a.start >> 8)", "len(a.data): string = \"\" for i in range(8): if offset+i", "None: raise Exception(\"Missing hex filename to sign\") parser = IntelHexParser(args.hex)", "0x\" + hexU8(a.start >> 8) + \", 0x\" + hexU8(a.start)", "\" # low @ to high @ offset = 0", "under the License. ******************************************************************************** \"\"\" from ledgerblue.hexParser import IntelHexParser import", "language governing permissions and * limitations under the License. ********************************************************************************", "\"0x\" + hexU8(len(a.data) >> 24) + \", 0x\" + hexU8(len(a.data)", "* Unless required by applicable law or agreed to in", "if args.hex == None: raise Exception(\"Missing hex filename to sign\")", "args.hex == None: raise Exception(\"Missing hex filename to sign\") parser", "& 0xFF))[3:] for a in parser.getAreas(): if (len(a.data) > 0x10000):", "+ hexU8(a.start >> 24) + \", 0x\" + hexU8(a.start >>", "* you may not use this file except in compliance", "<gh_stars>10-100 \"\"\" ******************************************************************************* * Ledger Blue * (c) 2016 Ledger", "* http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or", "parser.getAreas(): if (len(a.data) > 0x10000): raise BaseException(\"data must be splitted", "offset = 0 while offset < len(a.data): string = \"\"", "limitations under the License. ******************************************************************************** \"\"\" from ledgerblue.hexParser import IntelHexParser", "+ \", \" # low @ to high @ offset", "must be splitted in chunks of 64k\") print \"0x\" +", "software * distributed under the License is distributed on an", "\", \" # low @ to high @ offset =", "* limitations under the License. ******************************************************************************** \"\"\" from ledgerblue.hexParser import", "******************************************************************************* * Ledger Blue * (c) 2016 Ledger * *", "in parser.getAreas(): if (len(a.data) > 0x10000): raise BaseException(\"data must be", "is distributed on an \"AS IS\" BASIS, * WITHOUT WARRANTIES", "to sign\") parser = IntelHexParser(args.hex) def hexU8(value): return hex(0x100|(value &", "> 0x10000): raise BaseException(\"data must be splitted in chunks of", "hexU8(len(a.data)) + \", \" # low @ to high @", "the specific language governing permissions and * limitations under the", "the License is distributed on an \"AS IS\" BASIS, *", "may obtain a copy of the License at * *", "* Ledger Blue * (c) 2016 Ledger * * Licensed", "filename to sign\") parser = IntelHexParser(args.hex) def hexU8(value): return hex(0x100|(value", "+ hexU8(len(a.data) >> 8) + \", 0x\" + hexU8(len(a.data)) +", "+ \", 0x\" + hexU8(a.start >> 8) + \", 0x\"", "+ \", 0x\" + hexU8(len(a.data) >> 16) + \", 0x\"", "* * Unless required by applicable law or agreed to", "BaseException(\"data must be splitted in chunks of 64k\") print \"0x\"", "You may obtain a copy of the License at *", "for the specific language governing permissions and * limitations under", ">> 8) + \", 0x\" + hexU8(a.start) + \", \"", "@ to high @ offset = 0 while offset <", "+ hexU8(a.start) + \", \" print \"0x\" + hexU8(len(a.data) >>", "= IntelHexParser(args.hex) def hexU8(value): return hex(0x100|(value & 0xFF))[3:] for a", "compliance with the License. * You may obtain a copy", "< len(a.data): string += \" 0x\" + hexU8(a.data[offset+i]) + \",\"", "in range(8): if offset+i < len(a.data): string += \" 0x\"", "* See the License for the specific language governing permissions", "file to be converted as a C array\") args =", "Blue * (c) 2016 Ledger * * Licensed under the", "or implied. * See the License for the specific language", "splitted in chunks of 64k\") print \"0x\" + hexU8(a.start >>", "+ \", 0x\" + hexU8(a.start >> 16) + \", 0x\"", "http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed", "the License for the specific language governing permissions and *", "for i in range(8): if offset+i < len(a.data): string +=", "2016 Ledger * * Licensed under the Apache License, Version", "hexU8(a.start >> 24) + \", 0x\" + hexU8(a.start >> 16)", "hex(0x100|(value & 0xFF))[3:] for a in parser.getAreas(): if (len(a.data) >", "writing, software * distributed under the License is distributed on", "Ledger * * Licensed under the Apache License, Version 2.0", "return hex(0x100|(value & 0xFF))[3:] for a in parser.getAreas(): if (len(a.data)", "agreed to in writing, software * distributed under the License", "@ offset = 0 while offset < len(a.data): string =", "hexU8(a.start) + \", \" print \"0x\" + hexU8(len(a.data) >> 24)", "\"AS IS\" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY", "CONDITIONS OF ANY KIND, either express or implied. * See", "with the License. * You may obtain a copy of", "or agreed to in writing, software * distributed under the", "+ hexU8(len(a.data) >> 16) + \", 0x\" + hexU8(len(a.data) >>", "ANY KIND, either express or implied. * See the License", "+ hexU8(len(a.data) >> 24) + \", 0x\" + hexU8(len(a.data) >>", "64k\") print \"0x\" + hexU8(a.start >> 24) + \", 0x\"", "\" print \"0x\" + hexU8(len(a.data) >> 24) + \", 0x\"", "Version 2.0 (the \"License\"); * you may not use this", "to in writing, software * distributed under the License is", "from ledgerblue.hexParser import IntelHexParser import argparse parser = argparse.ArgumentParser() parser.add_argument(\"--hex\",", "0x10000): raise BaseException(\"data must be splitted in chunks of 64k\")", "\", 0x\" + hexU8(a.start) + \", \" print \"0x\" +", "i in range(8): if offset+i < len(a.data): string += \"", "hexU8(value): return hex(0x100|(value & 0xFF))[3:] for a in parser.getAreas(): if", "a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 *", "implied. * See the License for the specific language governing", "License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by", "be converted as a C array\") args = parser.parse_args() if", "0xFF))[3:] for a in parser.getAreas(): if (len(a.data) > 0x10000): raise", "the Apache License, Version 2.0 (the \"License\"); * you may", "in compliance with the License. * You may obtain a", "License. ******************************************************************************** \"\"\" from ledgerblue.hexParser import IntelHexParser import argparse parser", "parser.parse_args() if args.hex == None: raise Exception(\"Missing hex filename to", "(len(a.data) > 0x10000): raise BaseException(\"data must be splitted in chunks", "+ \", 0x\" + hexU8(a.start) + \", \" print \"0x\"", "raise Exception(\"Missing hex filename to sign\") parser = IntelHexParser(args.hex) def", "OR CONDITIONS OF ANY KIND, either express or implied. *", "an \"AS IS\" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF", "+ hexU8(a.start >> 8) + \", 0x\" + hexU8(a.start) +", "IntelHexParser import argparse parser = argparse.ArgumentParser() parser.add_argument(\"--hex\", help=\"Hex file to", "0x\" + hexU8(a.start) + \", \" print \"0x\" + hexU8(len(a.data)", "the License. * You may obtain a copy of the", "* Licensed under the Apache License, Version 2.0 (the \"License\");", "specific language governing permissions and * limitations under the License.", "copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * *", "def hexU8(value): return hex(0x100|(value & 0xFF))[3:] for a in parser.getAreas():", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "parser = argparse.ArgumentParser() parser.add_argument(\"--hex\", help=\"Hex file to be converted as", "0x\" + hexU8(len(a.data) >> 16) + \", 0x\" + hexU8(len(a.data)", "= \"\" for i in range(8): if offset+i < len(a.data):", "See the License for the specific language governing permissions and", ">> 8) + \", 0x\" + hexU8(len(a.data)) + \", \"", "low @ to high @ offset = 0 while offset", "by applicable law or agreed to in writing, software *", "law or agreed to in writing, software * distributed under", "= parser.parse_args() if args.hex == None: raise Exception(\"Missing hex filename", "a in parser.getAreas(): if (len(a.data) > 0x10000): raise BaseException(\"data must", "if offset+i < len(a.data): string += \" 0x\" + hexU8(a.data[offset+i])", "OF ANY KIND, either express or implied. * See the", "at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable", "argparse.ArgumentParser() parser.add_argument(\"--hex\", help=\"Hex file to be converted as a C", "to be converted as a C array\") args = parser.parse_args()", "IS\" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "== None: raise Exception(\"Missing hex filename to sign\") parser =", "may not use this file except in compliance with the", "+ hexU8(len(a.data)) + \", \" # low @ to high", "required by applicable law or agreed to in writing, software", "either express or implied. * See the License for the", "in chunks of 64k\") print \"0x\" + hexU8(a.start >> 24)", "(c) 2016 Ledger * * Licensed under the Apache License,", "\", \" print \"0x\" + hexU8(len(a.data) >> 24) + \",", "distributed on an \"AS IS\" BASIS, * WITHOUT WARRANTIES OR", "governing permissions and * limitations under the License. ******************************************************************************** \"\"\"", "\", 0x\" + hexU8(len(a.data)) + \", \" # low @", "0x\" + hexU8(len(a.data)) + \", \" # low @ to", "in writing, software * distributed under the License is distributed", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "\", 0x\" + hexU8(a.start >> 16) + \", 0x\" +", "offset+i < len(a.data): string += \" 0x\" + hexU8(a.data[offset+i]) +", "sign\") parser = IntelHexParser(args.hex) def hexU8(value): return hex(0x100|(value & 0xFF))[3:]", "print \"0x\" + hexU8(len(a.data) >> 24) + \", 0x\" +", "C array\") args = parser.parse_args() if args.hex == None: raise", "8) + \", 0x\" + hexU8(a.start) + \", \" print", "chunks of 64k\") print \"0x\" + hexU8(a.start >> 24) +", "hexU8(len(a.data) >> 16) + \", 0x\" + hexU8(len(a.data) >> 8)", "permissions and * limitations under the License. ******************************************************************************** \"\"\" from", "IntelHexParser(args.hex) def hexU8(value): return hex(0x100|(value & 0xFF))[3:] for a in", "0x\" + hexU8(a.start >> 16) + \", 0x\" + hexU8(a.start", "KIND, either express or implied. * See the License for" ]
[ "> project. Originally inspired by my colleague's work, I thought", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "with strong support for continuous updates, reliable functions and overall", "strong support for continuous updates, reliable functions and overall ease", "comes with strong support for continuous updates, reliable functions and", "be named XXXXX > project. Originally inspired by my colleague's", "# # Licensed under the Apache License, Version 2.0 (the", "compliance with the License. # You may obtain a copy", "an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "All Rights Reserved. # # Licensed under the Apache License,", "2.0 (the \"License\"); # you may not use this file", "file except in compliance with the License. # You may", "agreed to in writing, software # distributed under the License", "Unless required by applicable law or agreed to in writing,", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "limitations under the License. # # ====================================================================== \"\"\" vdoXA is", "videos. It is built as a subsystem for < XXXXX", "from setuptools import find_packages, setup from vdoxa.vars import dev doclines", "OSI Approved :: Apache Software License', 'Natural Language :: English',", "distributed under the License is distributed on an \"AS IS\"", "ease of use. Read complete documentation at: <https://github.com/xames3/vdoxa>. \"\"\" from", "End Users/Desktop', 'Intended Audience :: Information Technology', 'Intended Audience ::", "project. Originally inspired by my colleague's work, I thought of", "a tool to simplify the process. I hope it comes", "to simplify the process. I hope it comes with strong", "in requirements] setup( name=dev.PROJECT_NAME, version=dev.PROJECT_VERSION, url=dev.PROJECT_LINK, download_url=dev.PROJECT_LINK, author=dev.AUTHOR, author_email=dev.AUTHOR_EMAIL, maintainer=dev.AUTHOR,", "or # implied. # See the License for the specific", "# ====================================================================== \"\"\" vdoXA is an open-source python package for", "as file: return file.read() with open('requirements.txt', 'r') as requirements: required_packages", ":: Apache Software License', 'Natural Language :: English', ], license=dev.PROJECT_LICENSE,", "return file.read() with open('requirements.txt', 'r') as requirements: required_packages = [package.rstrip()", "Language :: English', ], license=dev.PROJECT_LICENSE, description=f'{doclines[1]}', long_description=use_readme(), long_description_content_type='text/markdown', keywords='opencv2 cv2", "author_email=dev.AUTHOR_EMAIL, maintainer=dev.AUTHOR, maintainer_email=dev.AUTHOR_EMAIL, classifiers=[ 'Intended Audience :: Developers', 'Intended Audience", "the specific language governing permissions and # limitations under the", "'License :: OSI Approved :: Apache Software License', 'Natural Language", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "a subsystem for < XXXXX Not to be named XXXXX", "setup( name=dev.PROJECT_NAME, version=dev.PROJECT_VERSION, url=dev.PROJECT_LINK, download_url=dev.PROJECT_LINK, author=dev.AUTHOR, author_email=dev.AUTHOR_EMAIL, maintainer=dev.AUTHOR, maintainer_email=dev.AUTHOR_EMAIL, classifiers=[", "Audience :: Developers', 'Intended Audience :: End Users/Desktop', 'Intended Audience", "Apache Software License', 'Natural Language :: English', ], license=dev.PROJECT_LICENSE, description=f'{doclines[1]}',", "applicable law or agreed to in writing, software # distributed", "except in compliance with the License. # You may obtain", "named XXXXX > project. Originally inspired by my colleague's work,", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "thought of improving the concept and build a tool to", "moviepy', zip_safe=False, install_requires=required_packages, python_requires='~=3.6', include_package_data=True, packages=find_packages(), entry_points={ 'console_scripts': [ 'vdoxa", "for continuous updates, reliable functions and overall ease of use.", "I hope it comes with strong support for continuous updates,", "# limitations under the License. # # ====================================================================== \"\"\" vdoXA", "Licensed under the Apache License, Version 2.0 (the \"License\"); #", "Originally inspired by my colleague's work, I thought of improving", "requirements: required_packages = [package.rstrip() for package in requirements] setup( name=dev.PROJECT_NAME,", "not use this file except in compliance with the License.", "for < XXXXX Not to be named XXXXX > project.", "express or # implied. # See the License for the", "to be named XXXXX > project. Originally inspired by my", "url=dev.PROJECT_LINK, download_url=dev.PROJECT_LINK, author=dev.AUTHOR, author_email=dev.AUTHOR_EMAIL, maintainer=dev.AUTHOR, maintainer_email=dev.AUTHOR_EMAIL, classifiers=[ 'Intended Audience ::", "for trimming the videos. It is built as a subsystem", ":: Information Technology', 'Intended Audience :: Science/Research', 'License :: OSI", "Copyright 2020 XAMES3. All Rights Reserved. # # Licensed under", "writing, software # distributed under the License is distributed on", "Software License', 'Natural Language :: English', ], license=dev.PROJECT_LICENSE, description=f'{doclines[1]}', long_description=use_readme(),", "in writing, software # distributed under the License is distributed", "governing permissions and # limitations under the License. # #", "I thought of improving the concept and build a tool", "you may not use this file except in compliance with", "use. Read complete documentation at: <https://github.com/xames3/vdoxa>. \"\"\" from setuptools import", "requirements] setup( name=dev.PROJECT_NAME, version=dev.PROJECT_VERSION, url=dev.PROJECT_LINK, download_url=dev.PROJECT_LINK, author=dev.AUTHOR, author_email=dev.AUTHOR_EMAIL, maintainer=dev.AUTHOR, maintainer_email=dev.AUTHOR_EMAIL,", "ANY KIND, either express or # implied. # See the", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "open-source python package for trimming the videos. It is built", "subsystem for < XXXXX Not to be named XXXXX >", "hope it comes with strong support for continuous updates, reliable", "download_url=dev.PROJECT_LINK, author=dev.AUTHOR, author_email=dev.AUTHOR_EMAIL, maintainer=dev.AUTHOR, maintainer_email=dev.AUTHOR_EMAIL, classifiers=[ 'Intended Audience :: Developers',", "concept and build a tool to simplify the process. I", "inspired by my colleague's work, I thought of improving the", "XXXXX > project. Originally inspired by my colleague's work, I", "long description.\"\"\" with open('README.md') as file: return file.read() with open('requirements.txt',", "Audience :: End Users/Desktop', 'Intended Audience :: Information Technology', 'Intended", "use this file except in compliance with the License. #", "for parsing long description.\"\"\" with open('README.md') as file: return file.read()", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "], license=dev.PROJECT_LICENSE, description=f'{doclines[1]}', long_description=use_readme(), long_description_content_type='text/markdown', keywords='opencv2 cv2 moviepy', zip_safe=False, install_requires=required_packages,", "use_readme() -> str: \"\"\"Use `README.md` for parsing long description.\"\"\" with", "package for trimming the videos. It is built as a", "the License. # # ====================================================================== \"\"\" vdoXA is an open-source", "'Intended Audience :: Science/Research', 'License :: OSI Approved :: Apache", "process. I hope it comes with strong support for continuous", "keywords='opencv2 cv2 moviepy', zip_safe=False, install_requires=required_packages, python_requires='~=3.6', include_package_data=True, packages=find_packages(), entry_points={ 'console_scripts':", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "improving the concept and build a tool to simplify the", "Science/Research', 'License :: OSI Approved :: Apache Software License', 'Natural", "overall ease of use. Read complete documentation at: <https://github.com/xames3/vdoxa>. \"\"\"", "License is distributed on an \"AS IS\" BASIS, # WITHOUT", "Rights Reserved. # # Licensed under the Apache License, Version", "OF ANY KIND, either express or # implied. # See", "License. # You may obtain a copy of the License", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "License, Version 2.0 (the \"License\"); # you may not use", "def use_readme() -> str: \"\"\"Use `README.md` for parsing long description.\"\"\"", "-> str: \"\"\"Use `README.md` for parsing long description.\"\"\" with open('README.md')", "# You may obtain a copy of the License at", "specific language governing permissions and # limitations under the License.", "\"\"\"Use `README.md` for parsing long description.\"\"\" with open('README.md') as file:", "cv2 moviepy', zip_safe=False, install_requires=required_packages, python_requires='~=3.6', include_package_data=True, packages=find_packages(), entry_points={ 'console_scripts': [", "under the License is distributed on an \"AS IS\" BASIS,", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "and build a tool to simplify the process. I hope", "License for the specific language governing permissions and # limitations", ":: Developers', 'Intended Audience :: End Users/Desktop', 'Intended Audience ::", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "zip_safe=False, install_requires=required_packages, python_requires='~=3.6', include_package_data=True, packages=find_packages(), entry_points={ 'console_scripts': [ 'vdoxa =", "either express or # implied. # See the License for", "Reserved. # # Licensed under the Apache License, Version 2.0", "Read complete documentation at: <https://github.com/xames3/vdoxa>. \"\"\" from setuptools import find_packages,", "the concept and build a tool to simplify the process.", "license=dev.PROJECT_LICENSE, description=f'{doclines[1]}', long_description=use_readme(), long_description_content_type='text/markdown', keywords='opencv2 cv2 moviepy', zip_safe=False, install_requires=required_packages, python_requires='~=3.6',", "====================================================================== \"\"\" vdoXA is an open-source python package for trimming", "open('requirements.txt', 'r') as requirements: required_packages = [package.rstrip() for package in", "the License for the specific language governing permissions and #", "and overall ease of use. Read complete documentation at: <https://github.com/xames3/vdoxa>.", "= [package.rstrip() for package in requirements] setup( name=dev.PROJECT_NAME, version=dev.PROJECT_VERSION, url=dev.PROJECT_LINK,", "Technology', 'Intended Audience :: Science/Research', 'License :: OSI Approved ::", "(the \"License\"); # you may not use this file except", "trimming the videos. It is built as a subsystem for", "Apache License, Version 2.0 (the \"License\"); # you may not", "setuptools import find_packages, setup from vdoxa.vars import dev doclines =", "dev doclines = __doc__.split('\\n') def use_readme() -> str: \"\"\"Use `README.md`", "# you may not use this file except in compliance", "__doc__.split('\\n') def use_readme() -> str: \"\"\"Use `README.md` for parsing long", "author=dev.AUTHOR, author_email=dev.AUTHOR_EMAIL, maintainer=dev.AUTHOR, maintainer_email=dev.AUTHOR_EMAIL, classifiers=[ 'Intended Audience :: Developers', 'Intended", "English', ], license=dev.PROJECT_LICENSE, description=f'{doclines[1]}', long_description=use_readme(), long_description_content_type='text/markdown', keywords='opencv2 cv2 moviepy', zip_safe=False,", "str: \"\"\"Use `README.md` for parsing long description.\"\"\" with open('README.md') as", "and # limitations under the License. # # ====================================================================== \"\"\"", "2020 XAMES3. All Rights Reserved. # # Licensed under the", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "for package in requirements] setup( name=dev.PROJECT_NAME, version=dev.PROJECT_VERSION, url=dev.PROJECT_LINK, download_url=dev.PROJECT_LINK, author=dev.AUTHOR,", "the License is distributed on an \"AS IS\" BASIS, #", "description.\"\"\" with open('README.md') as file: return file.read() with open('requirements.txt', 'r')", "in compliance with the License. # You may obtain a", "maintainer_email=dev.AUTHOR_EMAIL, classifiers=[ 'Intended Audience :: Developers', 'Intended Audience :: End", "software # distributed under the License is distributed on an", "packages=find_packages(), entry_points={ 'console_scripts': [ 'vdoxa = vdoxa.parser:main', ], } )", "find_packages, setup from vdoxa.vars import dev doclines = __doc__.split('\\n') def", "'Natural Language :: English', ], license=dev.PROJECT_LICENSE, description=f'{doclines[1]}', long_description=use_readme(), long_description_content_type='text/markdown', keywords='opencv2", "as requirements: required_packages = [package.rstrip() for package in requirements] setup(", "maintainer=dev.AUTHOR, maintainer_email=dev.AUTHOR_EMAIL, classifiers=[ 'Intended Audience :: Developers', 'Intended Audience ::", "It is built as a subsystem for < XXXXX Not", "`README.md` for parsing long description.\"\"\" with open('README.md') as file: return", "Audience :: Science/Research', 'License :: OSI Approved :: Apache Software", "work, I thought of improving the concept and build a", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or #", "<https://github.com/xames3/vdoxa>. \"\"\" from setuptools import find_packages, setup from vdoxa.vars import", "permissions and # limitations under the License. # # ======================================================================", "# # Unless required by applicable law or agreed to", "# implied. # See the License for the specific language", "the videos. It is built as a subsystem for <", "'Intended Audience :: Information Technology', 'Intended Audience :: Science/Research', 'License", ":: Science/Research', 'License :: OSI Approved :: Apache Software License',", "long_description_content_type='text/markdown', keywords='opencv2 cv2 moviepy', zip_safe=False, install_requires=required_packages, python_requires='~=3.6', include_package_data=True, packages=find_packages(), entry_points={", "vdoXA is an open-source python package for trimming the videos.", "\"\"\" vdoXA is an open-source python package for trimming the", "long_description=use_readme(), long_description_content_type='text/markdown', keywords='opencv2 cv2 moviepy', zip_safe=False, install_requires=required_packages, python_requires='~=3.6', include_package_data=True, packages=find_packages(),", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "import find_packages, setup from vdoxa.vars import dev doclines = __doc__.split('\\n')", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "reliable functions and overall ease of use. Read complete documentation", "License. # # ====================================================================== \"\"\" vdoXA is an open-source python", "Version 2.0 (the \"License\"); # you may not use this", "classifiers=[ 'Intended Audience :: Developers', 'Intended Audience :: End Users/Desktop',", "updates, reliable functions and overall ease of use. Read complete", "an open-source python package for trimming the videos. It is", "'Intended Audience :: Developers', 'Intended Audience :: End Users/Desktop', 'Intended", "install_requires=required_packages, python_requires='~=3.6', include_package_data=True, packages=find_packages(), entry_points={ 'console_scripts': [ 'vdoxa = vdoxa.parser:main',", "law or agreed to in writing, software # distributed under", "python package for trimming the videos. It is built as", "XXXXX Not to be named XXXXX > project. Originally inspired", ":: OSI Approved :: Apache Software License', 'Natural Language ::", "Developers', 'Intended Audience :: End Users/Desktop', 'Intended Audience :: Information", "name=dev.PROJECT_NAME, version=dev.PROJECT_VERSION, url=dev.PROJECT_LINK, download_url=dev.PROJECT_LINK, author=dev.AUTHOR, author_email=dev.AUTHOR_EMAIL, maintainer=dev.AUTHOR, maintainer_email=dev.AUTHOR_EMAIL, classifiers=[ 'Intended", "of use. Read complete documentation at: <https://github.com/xames3/vdoxa>. \"\"\" from setuptools", "functions and overall ease of use. Read complete documentation at:", "complete documentation at: <https://github.com/xames3/vdoxa>. \"\"\" from setuptools import find_packages, setup", "continuous updates, reliable functions and overall ease of use. Read", "KIND, either express or # implied. # See the License", "implied. # See the License for the specific language governing", "documentation at: <https://github.com/xames3/vdoxa>. \"\"\" from setuptools import find_packages, setup from", "is built as a subsystem for < XXXXX Not to", "built as a subsystem for < XXXXX Not to be", "under the Apache License, Version 2.0 (the \"License\"); # you", "# Copyright 2020 XAMES3. All Rights Reserved. # # Licensed", "tool to simplify the process. I hope it comes with", "\"License\"); # you may not use this file except in", "Not to be named XXXXX > project. Originally inspired by", "XAMES3. All Rights Reserved. # # Licensed under the Apache", "simplify the process. I hope it comes with strong support", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "vdoxa.vars import dev doclines = __doc__.split('\\n') def use_readme() -> str:", "< XXXXX Not to be named XXXXX > project. Originally", "with open('README.md') as file: return file.read() with open('requirements.txt', 'r') as", "Approved :: Apache Software License', 'Natural Language :: English', ],", "open('README.md') as file: return file.read() with open('requirements.txt', 'r') as requirements:", "CONDITIONS OF ANY KIND, either express or # implied. #", "[package.rstrip() for package in requirements] setup( name=dev.PROJECT_NAME, version=dev.PROJECT_VERSION, url=dev.PROJECT_LINK, download_url=dev.PROJECT_LINK,", "# # ====================================================================== \"\"\" vdoXA is an open-source python package", "colleague's work, I thought of improving the concept and build", "Information Technology', 'Intended Audience :: Science/Research', 'License :: OSI Approved", "from vdoxa.vars import dev doclines = __doc__.split('\\n') def use_readme() ->", "by applicable law or agreed to in writing, software #", "# distributed under the License is distributed on an \"AS", ":: English', ], license=dev.PROJECT_LICENSE, description=f'{doclines[1]}', long_description=use_readme(), long_description_content_type='text/markdown', keywords='opencv2 cv2 moviepy',", "package in requirements] setup( name=dev.PROJECT_NAME, version=dev.PROJECT_VERSION, url=dev.PROJECT_LINK, download_url=dev.PROJECT_LINK, author=dev.AUTHOR, author_email=dev.AUTHOR_EMAIL,", "may obtain a copy of the License at # #", "# Unless required by applicable law or agreed to in", "See the License for the specific language governing permissions and", "parsing long description.\"\"\" with open('README.md') as file: return file.read() with", ":: End Users/Desktop', 'Intended Audience :: Information Technology', 'Intended Audience", "the License. # You may obtain a copy of the", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "for the specific language governing permissions and # limitations under", "is an open-source python package for trimming the videos. It", "it comes with strong support for continuous updates, reliable functions", "License', 'Natural Language :: English', ], license=dev.PROJECT_LICENSE, description=f'{doclines[1]}', long_description=use_readme(), long_description_content_type='text/markdown',", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "python_requires='~=3.6', include_package_data=True, packages=find_packages(), entry_points={ 'console_scripts': [ 'vdoxa = vdoxa.parser:main', ],", "to in writing, software # distributed under the License is", "file.read() with open('requirements.txt', 'r') as requirements: required_packages = [package.rstrip() for", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "# See the License for the specific language governing permissions", "under the License. # # ====================================================================== \"\"\" vdoXA is an", "import dev doclines = __doc__.split('\\n') def use_readme() -> str: \"\"\"Use", "with open('requirements.txt', 'r') as requirements: required_packages = [package.rstrip() for package", "OR CONDITIONS OF ANY KIND, either express or # implied.", "support for continuous updates, reliable functions and overall ease of", "'r') as requirements: required_packages = [package.rstrip() for package in requirements]", "version=dev.PROJECT_VERSION, url=dev.PROJECT_LINK, download_url=dev.PROJECT_LINK, author=dev.AUTHOR, author_email=dev.AUTHOR_EMAIL, maintainer=dev.AUTHOR, maintainer_email=dev.AUTHOR_EMAIL, classifiers=[ 'Intended Audience", "description=f'{doclines[1]}', long_description=use_readme(), long_description_content_type='text/markdown', keywords='opencv2 cv2 moviepy', zip_safe=False, install_requires=required_packages, python_requires='~=3.6', include_package_data=True,", "You may obtain a copy of the License at #", "of improving the concept and build a tool to simplify", "build a tool to simplify the process. I hope it", "file: return file.read() with open('requirements.txt', 'r') as requirements: required_packages =", "language governing permissions and # limitations under the License. #", "Users/Desktop', 'Intended Audience :: Information Technology', 'Intended Audience :: Science/Research',", "may not use this file except in compliance with the", "or agreed to in writing, software # distributed under the", "include_package_data=True, packages=find_packages(), entry_points={ 'console_scripts': [ 'vdoxa = vdoxa.parser:main', ], }", "at: <https://github.com/xames3/vdoxa>. \"\"\" from setuptools import find_packages, setup from vdoxa.vars", "required by applicable law or agreed to in writing, software", "'Intended Audience :: End Users/Desktop', 'Intended Audience :: Information Technology',", "Audience :: Information Technology', 'Intended Audience :: Science/Research', 'License ::", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "with the License. # You may obtain a copy of", "setup from vdoxa.vars import dev doclines = __doc__.split('\\n') def use_readme()", "this file except in compliance with the License. # You", "\"\"\" from setuptools import find_packages, setup from vdoxa.vars import dev", "the Apache License, Version 2.0 (the \"License\"); # you may", "doclines = __doc__.split('\\n') def use_readme() -> str: \"\"\"Use `README.md` for", "my colleague's work, I thought of improving the concept and", "the process. I hope it comes with strong support for", "as a subsystem for < XXXXX Not to be named", "by my colleague's work, I thought of improving the concept", "required_packages = [package.rstrip() for package in requirements] setup( name=dev.PROJECT_NAME, version=dev.PROJECT_VERSION,", "= __doc__.split('\\n') def use_readme() -> str: \"\"\"Use `README.md` for parsing" ]
[ "username and password pair.', extra_tags='danger') self.context['form'] = AuthenticateForm(data) return render(request,", "reverse from django.views import View from application.forms import AuthenticateForm from", "= request.POST form = AuthenticateForm(data) if form.is_valid(): user = authenticate(", "if user: login(request, user) messages.success(request, 'You have successfully logged in!')", "View from application.forms import AuthenticateForm from application.views import get_navbar, Page", "username and password pair.', extra_tags='danger') else: messages.error(request, 'Invalid username and", "data = request.POST form = AuthenticateForm(data) if form.is_valid(): user =", "**kwargs): super().__init__(**kwargs) self.context = {} def get(self, request): self.context['navbar'] =", "from django.contrib import messages from django.contrib.auth import login, authenticate from", "messages.success(request, 'You have successfully logged in!') return redirect(reverse('main')) messages.error(request, 'Invalid", "import View from application.forms import AuthenticateForm from application.views import get_navbar,", "AuthenticateForm from application.views import get_navbar, Page class LoginView(View): def __init__(self,", "'You have successfully logged in!') return redirect(reverse('main')) messages.error(request, 'Invalid username", "= get_navbar(request) data = request.POST form = AuthenticateForm(data) if form.is_valid():", "extra_tags='danger') else: messages.error(request, 'Invalid username and password pair.', extra_tags='danger') self.context['form']", "from django.views import View from application.forms import AuthenticateForm from application.views", "form = AuthenticateForm(data) if form.is_valid(): user = authenticate( username=data['username'], password=data['password'],", "{} def get(self, request): self.context['navbar'] = get_navbar(request) self.context['form'] = AuthenticateForm()", "super().__init__(**kwargs) self.context = {} def get(self, request): self.context['navbar'] = get_navbar(request)", "self.context = {} def get(self, request): self.context['navbar'] = get_navbar(request) self.context['form']", "self.context) def post(self, request): self.context['navbar'] = get_navbar(request) data = request.POST", "application.forms import AuthenticateForm from application.views import get_navbar, Page class LoginView(View):", "user: login(request, user) messages.success(request, 'You have successfully logged in!') return", "get_navbar(request) data = request.POST form = AuthenticateForm(data) if form.is_valid(): user", "= authenticate( username=data['username'], password=data['password'], ) if user: login(request, user) messages.success(request,", "get_navbar(request) self.context['form'] = AuthenticateForm() return render(request, Page.login, self.context) def post(self,", "import get_navbar, Page class LoginView(View): def __init__(self, **kwargs): super().__init__(**kwargs) self.context", "import reverse from django.views import View from application.forms import AuthenticateForm", "username=data['username'], password=data['password'], ) if user: login(request, user) messages.success(request, 'You have", "= AuthenticateForm() return render(request, Page.login, self.context) def post(self, request): self.context['navbar']", "user) messages.success(request, 'You have successfully logged in!') return redirect(reverse('main')) messages.error(request,", "in!') return redirect(reverse('main')) messages.error(request, 'Invalid username and password pair.', extra_tags='danger')", "import render, redirect from django.urls import reverse from django.views import", "Page class LoginView(View): def __init__(self, **kwargs): super().__init__(**kwargs) self.context = {}", "get_navbar, Page class LoginView(View): def __init__(self, **kwargs): super().__init__(**kwargs) self.context =", "messages.error(request, 'Invalid username and password pair.', extra_tags='danger') else: messages.error(request, 'Invalid", "from application.forms import AuthenticateForm from application.views import get_navbar, Page class", "get(self, request): self.context['navbar'] = get_navbar(request) self.context['form'] = AuthenticateForm() return render(request,", "LoginView(View): def __init__(self, **kwargs): super().__init__(**kwargs) self.context = {} def get(self,", "from django.urls import reverse from django.views import View from application.forms", "= get_navbar(request) self.context['form'] = AuthenticateForm() return render(request, Page.login, self.context) def", "login(request, user) messages.success(request, 'You have successfully logged in!') return redirect(reverse('main'))", "render, redirect from django.urls import reverse from django.views import View", "redirect from django.urls import reverse from django.views import View from", "if form.is_valid(): user = authenticate( username=data['username'], password=data['password'], ) if user:", "django.urls import reverse from django.views import View from application.forms import", "user = authenticate( username=data['username'], password=data['password'], ) if user: login(request, user)", "messages.error(request, 'Invalid username and password pair.', extra_tags='danger') self.context['form'] = AuthenticateForm(data)", "render(request, Page.login, self.context) def post(self, request): self.context['navbar'] = get_navbar(request) data", "'Invalid username and password pair.', extra_tags='danger') self.context['form'] = AuthenticateForm(data) return", "have successfully logged in!') return redirect(reverse('main')) messages.error(request, 'Invalid username and", "self.context['navbar'] = get_navbar(request) data = request.POST form = AuthenticateForm(data) if", "return render(request, Page.login, self.context) def post(self, request): self.context['navbar'] = get_navbar(request)", "AuthenticateForm() return render(request, Page.login, self.context) def post(self, request): self.context['navbar'] =", "'Invalid username and password pair.', extra_tags='danger') else: messages.error(request, 'Invalid username", "django.views import View from application.forms import AuthenticateForm from application.views import", "successfully logged in!') return redirect(reverse('main')) messages.error(request, 'Invalid username and password", "import messages from django.contrib.auth import login, authenticate from django.shortcuts import", "else: messages.error(request, 'Invalid username and password pair.', extra_tags='danger') self.context['form'] =", "def get(self, request): self.context['navbar'] = get_navbar(request) self.context['form'] = AuthenticateForm() return", "request.POST form = AuthenticateForm(data) if form.is_valid(): user = authenticate( username=data['username'],", "password pair.', extra_tags='danger') else: messages.error(request, 'Invalid username and password pair.',", "login, authenticate from django.shortcuts import render, redirect from django.urls import", "request): self.context['navbar'] = get_navbar(request) self.context['form'] = AuthenticateForm() return render(request, Page.login,", "redirect(reverse('main')) messages.error(request, 'Invalid username and password pair.', extra_tags='danger') else: messages.error(request,", "django.contrib.auth import login, authenticate from django.shortcuts import render, redirect from", "import login, authenticate from django.shortcuts import render, redirect from django.urls", "django.shortcuts import render, redirect from django.urls import reverse from django.views", "def post(self, request): self.context['navbar'] = get_navbar(request) data = request.POST form", "class LoginView(View): def __init__(self, **kwargs): super().__init__(**kwargs) self.context = {} def", "messages from django.contrib.auth import login, authenticate from django.shortcuts import render,", "<gh_stars>0 from django.contrib import messages from django.contrib.auth import login, authenticate", "authenticate( username=data['username'], password=data['password'], ) if user: login(request, user) messages.success(request, 'You", "from django.shortcuts import render, redirect from django.urls import reverse from", "django.contrib import messages from django.contrib.auth import login, authenticate from django.shortcuts", "return redirect(reverse('main')) messages.error(request, 'Invalid username and password pair.', extra_tags='danger') else:", "post(self, request): self.context['navbar'] = get_navbar(request) data = request.POST form =", "__init__(self, **kwargs): super().__init__(**kwargs) self.context = {} def get(self, request): self.context['navbar']", "= {} def get(self, request): self.context['navbar'] = get_navbar(request) self.context['form'] =", "logged in!') return redirect(reverse('main')) messages.error(request, 'Invalid username and password pair.',", "password=data['password'], ) if user: login(request, user) messages.success(request, 'You have successfully", "= AuthenticateForm(data) if form.is_valid(): user = authenticate( username=data['username'], password=data['password'], )", "AuthenticateForm(data) if form.is_valid(): user = authenticate( username=data['username'], password=data['password'], ) if", "and password pair.', extra_tags='danger') self.context['form'] = AuthenticateForm(data) return render(request, Page.login,", "form.is_valid(): user = authenticate( username=data['username'], password=data['password'], ) if user: login(request,", "Page.login, self.context) def post(self, request): self.context['navbar'] = get_navbar(request) data =", "pair.', extra_tags='danger') else: messages.error(request, 'Invalid username and password pair.', extra_tags='danger')", "and password pair.', extra_tags='danger') else: messages.error(request, 'Invalid username and password", "application.views import get_navbar, Page class LoginView(View): def __init__(self, **kwargs): super().__init__(**kwargs)", "authenticate from django.shortcuts import render, redirect from django.urls import reverse", "self.context['form'] = AuthenticateForm() return render(request, Page.login, self.context) def post(self, request):", ") if user: login(request, user) messages.success(request, 'You have successfully logged", "from application.views import get_navbar, Page class LoginView(View): def __init__(self, **kwargs):", "def __init__(self, **kwargs): super().__init__(**kwargs) self.context = {} def get(self, request):", "request): self.context['navbar'] = get_navbar(request) data = request.POST form = AuthenticateForm(data)", "from django.contrib.auth import login, authenticate from django.shortcuts import render, redirect", "password pair.', extra_tags='danger') self.context['form'] = AuthenticateForm(data) return render(request, Page.login, self.context)", "import AuthenticateForm from application.views import get_navbar, Page class LoginView(View): def", "self.context['navbar'] = get_navbar(request) self.context['form'] = AuthenticateForm() return render(request, Page.login, self.context)" ]
[ "%s', debug_str) 13:12:43.673 - :<module>:1 - DEBUG - My message:", "[0] - _log() # [1] - debug(), info(), warning(), or", "def _log(cls): name = \"\" if cls.name is not None:", "Copyright 2017 Mycroft AI Inc. # # Licensed under the", "name = cls.name + \" - \" # Stack: #", "logging.Formatter(fmt, datefmt) name = 'little_questions' level = \"DEBUG\" _loggers =", "2.0 (the \"License\"); # you may not use this file", "class that acts like logging.Logger The logger name is automatically", "name += record[3] + ':' + str(record[2]) logger = cls.create_logger(name)", "# [0] - frame object # [1] - filename #", "= level for n in cls._loggers: cls._loggers[n].setLevel(cls.level) @classmethod def create_logger(cls,", "logger class that acts like logging.Logger The logger name is", "\"\"\" Custom logger class that acts like logging.Logger The logger", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "Usage: >>> LOG.debug('My message: %s', debug_str) 13:12:43.673 - :<module>:1 -", "*args, **kwargs): cls._log().error(*args, **kwargs) @classmethod def exception(cls, *args, **kwargs): cls._log().exception(*args,", "return logger @classmethod def _log(cls): name = \"\" if cls.name", "LOG: \"\"\" Custom logger class that acts like logging.Logger The", "logger name is automatically generated by the module of the", "is automatically generated by the module of the caller Usage:", "create_logger(cls, name): if name in cls._loggers: return cls._loggers[name] logger =", "debug_str) 13:12:43.673 - :<module>:1 - DEBUG - My message: hi", "warning(cls, *args, **kwargs): cls._log().warning(*args, **kwargs) @classmethod def error(cls, *args, **kwargs):", "My message: hi >>> LOG('custom_name').debug('Another message') 13:13:10.462 - custom_name -", "- debug(), info(), warning(), or error() # [2] - caller", "# Record: # [0] - frame object # [1] -", "use this file except in compliance with the License. #", "logger.setLevel(cls.level) cls._loggers[name] = logger return logger @classmethod def _log(cls): name", "def warning(cls, *args, **kwargs): cls._log().warning(*args, **kwargs) @classmethod def error(cls, *args,", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "License. # You may obtain a copy of the License", "automatically generated by the module of the caller Usage: >>>", "under the License is distributed on an \"AS IS\" BASIS,", "License for the specific language governing permissions and # limitations", "+ \" - \" # Stack: # [0] - _log()", "return logger @classmethod def info(cls, *args, **kwargs): cls._log().info(*args, **kwargs) @classmethod", "*args, **kwargs): cls._log().warning(*args, **kwargs) @classmethod def error(cls, *args, **kwargs): cls._log().error(*args,", "level = \"DEBUG\" _loggers = {} @classmethod def set_level(cls, level=\"INFO\"):", "return cls._loggers[name] logger = logging.getLogger(name) logger.propagate = False stdout_handler =", "- %(message)s' datefmt = '%Y-%m-%d %H:%M:%S' formatter = logging.Formatter(fmt, datefmt)", "in compliance with the License. # You may obtain a", "= logging.StreamHandler(sys.stdout) stdout_handler.setFormatter(cls.formatter) logger.addHandler(stdout_handler) logger.setLevel(cls.level) cls._loggers[name] = logger return logger", "[2] - caller stack = inspect.stack() # Record: # [0]", "software # distributed under the License is distributed on an", "**kwargs): cls._log().error(*args, **kwargs) @classmethod def exception(cls, *args, **kwargs): cls._log().exception(*args, **kwargs)", "# [2] - caller stack = inspect.stack() # Record: #", "\"stdout\" fmt = '%(asctime)s.%(msecs)03d - ' \\ '%(name)s - %(levelname)s", "def error(cls, *args, **kwargs): cls._log().error(*args, **kwargs) @classmethod def exception(cls, *args,", "logging.StreamHandler(sys.stdout) stdout_handler.setFormatter(cls.formatter) logger.addHandler(stdout_handler) logger.setLevel(cls.level) cls._loggers[name] = logger return logger @classmethod", "the caller Usage: >>> LOG.debug('My message: %s', debug_str) 13:12:43.673 -", "cls._log().warning(*args, **kwargs) @classmethod def error(cls, *args, **kwargs): cls._log().error(*args, **kwargs) @classmethod", "= logging.getLogger(name) logger.propagate = False stdout_handler = logging.StreamHandler(sys.stdout) stdout_handler.setFormatter(cls.formatter) logger.addHandler(stdout_handler)", "_loggers = {} @classmethod def set_level(cls, level=\"INFO\"): cls.level = level", "logging.Logger The logger name is automatically generated by the module", "n in cls._loggers: cls._loggers[n].setLevel(cls.level) @classmethod def create_logger(cls, name): if name", "filename # [2] - line number # [3] - function", "# [1] - debug(), info(), warning(), or error() # [2]", "message') 13:13:10.462 - custom_name - DEBUG - Another message \"\"\"", "custom_name - DEBUG - Another message \"\"\" base_path = \"stdout\"", "- \" # Stack: # [0] - _log() # [1]", "OF ANY KIND, either express or implied. # See the", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "ANY KIND, either express or implied. # See the License", "See the License for the specific language governing permissions and", "the License. # You may obtain a copy of the", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "for the specific language governing permissions and # limitations under", "to in writing, software # distributed under the License is", "# [1] - filename # [2] - line number #", "# See the License for the specific language governing permissions", "the module of the caller Usage: >>> LOG.debug('My message: %s',", "**kwargs): cls._log().info(*args, **kwargs) @classmethod def debug(cls, *args, **kwargs): cls._log().debug(*args, **kwargs)", "level=\"INFO\"): cls.level = level for n in cls._loggers: cls._loggers[n].setLevel(cls.level) @classmethod", "language governing permissions and # limitations under the License. #", "or agreed to in writing, software # distributed under the", "required by applicable law or agreed to in writing, software", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "= \"DEBUG\" _loggers = {} @classmethod def set_level(cls, level=\"INFO\"): cls.level", "with the License. # You may obtain a copy of", "= 'little_questions' level = \"DEBUG\" _loggers = {} @classmethod def", "def create_logger(cls, name): if name in cls._loggers: return cls._loggers[name] logger", "\" # Stack: # [0] - _log() # [1] -", "number # [3] - function # ... record = stack[2]", "- custom_name - DEBUG - Another message \"\"\" base_path =", "AI Inc. # # Licensed under the Apache License, Version", "\\ '%(name)s - %(levelname)s - %(message)s' datefmt = '%Y-%m-%d %H:%M:%S'", "compliance with the License. # You may obtain a copy", "agreed to in writing, software # distributed under the License", "debug(cls, *args, **kwargs): cls._log().debug(*args, **kwargs) @classmethod def warning(cls, *args, **kwargs):", "@classmethod def warning(cls, *args, **kwargs): cls._log().warning(*args, **kwargs) @classmethod def error(cls,", "distributed under the License is distributed on an \"AS IS\"", "cls.create_logger(name) return logger @classmethod def info(cls, *args, **kwargs): cls._log().info(*args, **kwargs)", "LOG.debug('My message: %s', debug_str) 13:12:43.673 - :<module>:1 - DEBUG -", "express or implied. # See the License for the specific", "except in compliance with the License. # You may obtain", "- filename # [2] - line number # [3] -", "Licensed under the Apache License, Version 2.0 (the \"License\"); #", "not use this file except in compliance with the License.", "if name in cls._loggers: return cls._loggers[name] logger = logging.getLogger(name) logger.propagate", "function # ... record = stack[2] name += record[3] +", "writing, software # distributed under the License is distributed on", "info(), warning(), or error() # [2] - caller stack =", "def set_level(cls, level=\"INFO\"): cls.level = level for n in cls._loggers:", "you may not use this file except in compliance with", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "logging.getLogger(name) logger.propagate = False stdout_handler = logging.StreamHandler(sys.stdout) stdout_handler.setFormatter(cls.formatter) logger.addHandler(stdout_handler) logger.setLevel(cls.level)", "is not None: name = cls.name + \" - \"", "CONDITIONS OF ANY KIND, either express or implied. # See", "[1] - filename # [2] - line number # [3]", "- line number # [3] - function # ... record", "name): if name in cls._loggers: return cls._loggers[name] logger = logging.getLogger(name)", "frame object # [1] - filename # [2] - line", "def info(cls, *args, **kwargs): cls._log().info(*args, **kwargs) @classmethod def debug(cls, *args,", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "= cls.name + \" - \" # Stack: # [0]", "+ str(record[2]) logger = cls.create_logger(name) return logger @classmethod def info(cls,", "logger = logging.getLogger(name) logger.propagate = False stdout_handler = logging.StreamHandler(sys.stdout) stdout_handler.setFormatter(cls.formatter)", "acts like logging.Logger The logger name is automatically generated by", "- My message: hi >>> LOG('custom_name').debug('Another message') 13:13:10.462 - custom_name", "%(message)s' datefmt = '%Y-%m-%d %H:%M:%S' formatter = logging.Formatter(fmt, datefmt) name", "None: name = cls.name + \" - \" # Stack:", "\"\"\" base_path = \"stdout\" fmt = '%(asctime)s.%(msecs)03d - ' \\", "':' + str(record[2]) logger = cls.create_logger(name) return logger @classmethod def", "caller stack = inspect.stack() # Record: # [0] - frame", "in cls._loggers: cls._loggers[n].setLevel(cls.level) @classmethod def create_logger(cls, name): if name in", "datefmt) name = 'little_questions' level = \"DEBUG\" _loggers = {}", "**kwargs) @classmethod def error(cls, *args, **kwargs): cls._log().error(*args, **kwargs) @classmethod def", "= cls.create_logger(name) return logger @classmethod def info(cls, *args, **kwargs): cls._log().info(*args,", "error(cls, *args, **kwargs): cls._log().error(*args, **kwargs) @classmethod def exception(cls, *args, **kwargs):", "OR CONDITIONS OF ANY KIND, either express or implied. #", "logging import sys class LOG: \"\"\" Custom logger class that", "'little_questions' level = \"DEBUG\" _loggers = {} @classmethod def set_level(cls,", "logger @classmethod def info(cls, *args, **kwargs): cls._log().info(*args, **kwargs) @classmethod def", "# [3] - function # ... record = stack[2] name", "the License is distributed on an \"AS IS\" BASIS, #", "*args, **kwargs): cls._log().debug(*args, **kwargs) @classmethod def warning(cls, *args, **kwargs): cls._log().warning(*args,", "%(levelname)s - %(message)s' datefmt = '%Y-%m-%d %H:%M:%S' formatter = logging.Formatter(fmt,", ":<module>:1 - DEBUG - My message: hi >>> LOG('custom_name').debug('Another message')", "import sys class LOG: \"\"\" Custom logger class that acts", "stdout_handler = logging.StreamHandler(sys.stdout) stdout_handler.setFormatter(cls.formatter) logger.addHandler(stdout_handler) logger.setLevel(cls.level) cls._loggers[name] = logger return", "**kwargs) @classmethod def debug(cls, *args, **kwargs): cls._log().debug(*args, **kwargs) @classmethod def", "Stack: # [0] - _log() # [1] - debug(), info(),", "# Copyright 2017 Mycroft AI Inc. # # Licensed under", "= {} @classmethod def set_level(cls, level=\"INFO\"): cls.level = level for", "record = stack[2] name += record[3] + ':' + str(record[2])", "law or agreed to in writing, software # distributed under", "governing permissions and # limitations under the License. # import", "not None: name = cls.name + \" - \" #", "cls.level = level for n in cls._loggers: cls._loggers[n].setLevel(cls.level) @classmethod def", "- :<module>:1 - DEBUG - My message: hi >>> LOG('custom_name').debug('Another", "caller Usage: >>> LOG.debug('My message: %s', debug_str) 13:12:43.673 - :<module>:1", "name in cls._loggers: return cls._loggers[name] logger = logging.getLogger(name) logger.propagate =", "name = 'little_questions' level = \"DEBUG\" _loggers = {} @classmethod", "logger.propagate = False stdout_handler = logging.StreamHandler(sys.stdout) stdout_handler.setFormatter(cls.formatter) logger.addHandler(stdout_handler) logger.setLevel(cls.level) cls._loggers[name]", "formatter = logging.Formatter(fmt, datefmt) name = 'little_questions' level = \"DEBUG\"", "@classmethod def error(cls, *args, **kwargs): cls._log().error(*args, **kwargs) @classmethod def exception(cls,", "may obtain a copy of the License at # #", "name is automatically generated by the module of the caller", "def debug(cls, *args, **kwargs): cls._log().debug(*args, **kwargs) @classmethod def warning(cls, *args,", "object # [1] - filename # [2] - line number", "Custom logger class that acts like logging.Logger The logger name", "@classmethod def info(cls, *args, **kwargs): cls._log().info(*args, **kwargs) @classmethod def debug(cls,", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "Inc. # # Licensed under the Apache License, Version 2.0", "str(record[2]) logger = cls.create_logger(name) return logger @classmethod def info(cls, *args,", "hi >>> LOG('custom_name').debug('Another message') 13:13:10.462 - custom_name - DEBUG -", "- %(levelname)s - %(message)s' datefmt = '%Y-%m-%d %H:%M:%S' formatter =", "class LOG: \"\"\" Custom logger class that acts like logging.Logger", "= logging.Formatter(fmt, datefmt) name = 'little_questions' level = \"DEBUG\" _loggers", "may not use this file except in compliance with the", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "message \"\"\" base_path = \"stdout\" fmt = '%(asctime)s.%(msecs)03d - '", "this file except in compliance with the License. # You", "@classmethod def _log(cls): name = \"\" if cls.name is not", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "# # Licensed under the Apache License, Version 2.0 (the", "cls._loggers[name] logger = logging.getLogger(name) logger.propagate = False stdout_handler = logging.StreamHandler(sys.stdout)", "file except in compliance with the License. # You may", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "inspect.stack() # Record: # [0] - frame object # [1]", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "message: hi >>> LOG('custom_name').debug('Another message') 13:13:10.462 - custom_name - DEBUG", "for n in cls._loggers: cls._loggers[n].setLevel(cls.level) @classmethod def create_logger(cls, name): if", "like logging.Logger The logger name is automatically generated by the", "LOG('custom_name').debug('Another message') 13:13:10.462 - custom_name - DEBUG - Another message", "cls._loggers[n].setLevel(cls.level) @classmethod def create_logger(cls, name): if name in cls._loggers: return", "by the module of the caller Usage: >>> LOG.debug('My message:", "name = \"\" if cls.name is not None: name =", "- frame object # [1] - filename # [2] -", "_log() # [1] - debug(), info(), warning(), or error() #", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "message: %s', debug_str) 13:12:43.673 - :<module>:1 - DEBUG - My", "set_level(cls, level=\"INFO\"): cls.level = level for n in cls._loggers: cls._loggers[n].setLevel(cls.level)", "or implied. # See the License for the specific language", "KIND, either express or implied. # See the License for", "specific language governing permissions and # limitations under the License.", "# [0] - _log() # [1] - debug(), info(), warning(),", "= stack[2] name += record[3] + ':' + str(record[2]) logger", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "Another message \"\"\" base_path = \"stdout\" fmt = '%(asctime)s.%(msecs)03d -", "%H:%M:%S' formatter = logging.Formatter(fmt, datefmt) name = 'little_questions' level =", "cls.name is not None: name = cls.name + \" -", "False stdout_handler = logging.StreamHandler(sys.stdout) stdout_handler.setFormatter(cls.formatter) logger.addHandler(stdout_handler) logger.setLevel(cls.level) cls._loggers[name] = logger", "# Stack: # [0] - _log() # [1] - debug(),", "(the \"License\"); # you may not use this file except", "cls._log().info(*args, **kwargs) @classmethod def debug(cls, *args, **kwargs): cls._log().debug(*args, **kwargs) @classmethod", "# you may not use this file except in compliance", "that acts like logging.Logger The logger name is automatically generated", "\"DEBUG\" _loggers = {} @classmethod def set_level(cls, level=\"INFO\"): cls.level =", "and # limitations under the License. # import inspect import", "@classmethod def debug(cls, *args, **kwargs): cls._log().debug(*args, **kwargs) @classmethod def warning(cls,", "import inspect import logging import sys class LOG: \"\"\" Custom", "@classmethod def set_level(cls, level=\"INFO\"): cls.level = level for n in", "base_path = \"stdout\" fmt = '%(asctime)s.%(msecs)03d - ' \\ '%(name)s", "# # Unless required by applicable law or agreed to", "logger = cls.create_logger(name) return logger @classmethod def info(cls, *args, **kwargs):", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "in cls._loggers: return cls._loggers[name] logger = logging.getLogger(name) logger.propagate = False", "debug(), info(), warning(), or error() # [2] - caller stack", "Version 2.0 (the \"License\"); # you may not use this", "import logging import sys class LOG: \"\"\" Custom logger class", "@classmethod def create_logger(cls, name): if name in cls._loggers: return cls._loggers[name]", "- Another message \"\"\" base_path = \"stdout\" fmt = '%(asctime)s.%(msecs)03d", "fmt = '%(asctime)s.%(msecs)03d - ' \\ '%(name)s - %(levelname)s -", "error() # [2] - caller stack = inspect.stack() # Record:", "[0] - frame object # [1] - filename # [2]", "inspect import logging import sys class LOG: \"\"\" Custom logger", ">>> LOG.debug('My message: %s', debug_str) 13:12:43.673 - :<module>:1 - DEBUG", "implied. # See the License for the specific language governing", "- DEBUG - My message: hi >>> LOG('custom_name').debug('Another message') 13:13:10.462", "stack = inspect.stack() # Record: # [0] - frame object", "module of the caller Usage: >>> LOG.debug('My message: %s', debug_str)", "under the Apache License, Version 2.0 (the \"License\"); # you", "cls._loggers: return cls._loggers[name] logger = logging.getLogger(name) logger.propagate = False stdout_handler", "# limitations under the License. # import inspect import logging", "if cls.name is not None: name = cls.name + \"", "2017 Mycroft AI Inc. # # Licensed under the Apache", "13:12:43.673 - :<module>:1 - DEBUG - My message: hi >>>", "by applicable law or agreed to in writing, software #", "'%(name)s - %(levelname)s - %(message)s' datefmt = '%Y-%m-%d %H:%M:%S' formatter", "*args, **kwargs): cls._log().info(*args, **kwargs) @classmethod def debug(cls, *args, **kwargs): cls._log().debug(*args,", "_log(cls): name = \"\" if cls.name is not None: name", "[2] - line number # [3] - function # ...", "logger.addHandler(stdout_handler) logger.setLevel(cls.level) cls._loggers[name] = logger return logger @classmethod def _log(cls):", "[1] - debug(), info(), warning(), or error() # [2] -", "cls.name + \" - \" # Stack: # [0] -", "permissions and # limitations under the License. # import inspect", "DEBUG - My message: hi >>> LOG('custom_name').debug('Another message') 13:13:10.462 -", "= '%Y-%m-%d %H:%M:%S' formatter = logging.Formatter(fmt, datefmt) name = 'little_questions'", "- DEBUG - Another message \"\"\" base_path = \"stdout\" fmt", "an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "Unless required by applicable law or agreed to in writing,", "stdout_handler.setFormatter(cls.formatter) logger.addHandler(stdout_handler) logger.setLevel(cls.level) cls._loggers[name] = logger return logger @classmethod def", "or error() # [2] - caller stack = inspect.stack() #", "the specific language governing permissions and # limitations under the", "# [2] - line number # [3] - function #", "stack[2] name += record[3] + ':' + str(record[2]) logger =", "applicable law or agreed to in writing, software # distributed", "generated by the module of the caller Usage: >>> LOG.debug('My", "- caller stack = inspect.stack() # Record: # [0] -", "# ... record = stack[2] name += record[3] + ':'", "= '%(asctime)s.%(msecs)03d - ' \\ '%(name)s - %(levelname)s - %(message)s'", "in writing, software # distributed under the License is distributed", "= \"stdout\" fmt = '%(asctime)s.%(msecs)03d - ' \\ '%(name)s -", "cls._loggers[name] = logger return logger @classmethod def _log(cls): name =", "logger @classmethod def _log(cls): name = \"\" if cls.name is", "record[3] + ':' + str(record[2]) logger = cls.create_logger(name) return logger", "- function # ... record = stack[2] name += record[3]", "+ ':' + str(record[2]) logger = cls.create_logger(name) return logger @classmethod", "... record = stack[2] name += record[3] + ':' +", "License is distributed on an \"AS IS\" BASIS, # WITHOUT", "License, Version 2.0 (the \"License\"); # you may not use", "# You may obtain a copy of the License at", "limitations under the License. # import inspect import logging import", "**kwargs): cls._log().debug(*args, **kwargs) @classmethod def warning(cls, *args, **kwargs): cls._log().warning(*args, **kwargs)", "The logger name is automatically generated by the module of", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "line number # [3] - function # ... record =", "datefmt = '%Y-%m-%d %H:%M:%S' formatter = logging.Formatter(fmt, datefmt) name =", "= \"\" if cls.name is not None: name = cls.name", "the License. # import inspect import logging import sys class", "- _log() # [1] - debug(), info(), warning(), or error()", "the License for the specific language governing permissions and #", "Apache License, Version 2.0 (the \"License\"); # you may not", "Record: # [0] - frame object # [1] - filename", "either express or implied. # See the License for the", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "' \\ '%(name)s - %(levelname)s - %(message)s' datefmt = '%Y-%m-%d", "# import inspect import logging import sys class LOG: \"\"\"", "13:13:10.462 - custom_name - DEBUG - Another message \"\"\" base_path", "[3] - function # ... record = stack[2] name +=", "\" - \" # Stack: # [0] - _log() #", "under the License. # import inspect import logging import sys", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "= False stdout_handler = logging.StreamHandler(sys.stdout) stdout_handler.setFormatter(cls.formatter) logger.addHandler(stdout_handler) logger.setLevel(cls.level) cls._loggers[name] =", "sys class LOG: \"\"\" Custom logger class that acts like", ">>> LOG('custom_name').debug('Another message') 13:13:10.462 - custom_name - DEBUG - Another", "warning(), or error() # [2] - caller stack = inspect.stack()", "cls._log().debug(*args, **kwargs) @classmethod def warning(cls, *args, **kwargs): cls._log().warning(*args, **kwargs) @classmethod", "info(cls, *args, **kwargs): cls._log().info(*args, **kwargs) @classmethod def debug(cls, *args, **kwargs):", "cls._loggers: cls._loggers[n].setLevel(cls.level) @classmethod def create_logger(cls, name): if name in cls._loggers:", "- ' \\ '%(name)s - %(levelname)s - %(message)s' datefmt =", "License. # import inspect import logging import sys class LOG:", "\"License\"); # you may not use this file except in", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "logger return logger @classmethod def _log(cls): name = \"\" if", "level for n in cls._loggers: cls._loggers[n].setLevel(cls.level) @classmethod def create_logger(cls, name):", "Mycroft AI Inc. # # Licensed under the Apache License,", "# distributed under the License is distributed on an \"AS", "of the caller Usage: >>> LOG.debug('My message: %s', debug_str) 13:12:43.673", "'%(asctime)s.%(msecs)03d - ' \\ '%(name)s - %(levelname)s - %(message)s' datefmt", "+= record[3] + ':' + str(record[2]) logger = cls.create_logger(name) return", "# Unless required by applicable law or agreed to in", "= logger return logger @classmethod def _log(cls): name = \"\"", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "**kwargs) @classmethod def warning(cls, *args, **kwargs): cls._log().warning(*args, **kwargs) @classmethod def", "= inspect.stack() # Record: # [0] - frame object #", "You may obtain a copy of the License at #", "\"\" if cls.name is not None: name = cls.name +", "**kwargs): cls._log().warning(*args, **kwargs) @classmethod def error(cls, *args, **kwargs): cls._log().error(*args, **kwargs)", "{} @classmethod def set_level(cls, level=\"INFO\"): cls.level = level for n", "the Apache License, Version 2.0 (the \"License\"); # you may", "'%Y-%m-%d %H:%M:%S' formatter = logging.Formatter(fmt, datefmt) name = 'little_questions' level", "DEBUG - Another message \"\"\" base_path = \"stdout\" fmt =" ]
[ "None self._speed_up_memo = None @property def speed_up(self): return self._speed_up @speed_up.setter", "def parse_response_content(self, response_content): response = super(AlipayOpenMiniVersionAuditApplyResponse, self).parse_response_content(response_content) if 'speed_up' in", "# -*- coding: utf-8 -*- import json from alipay.aop.api.response.AlipayResponse import", "from alipay.aop.api.response.AlipayResponse import AlipayResponse class AlipayOpenMiniVersionAuditApplyResponse(AlipayResponse): def __init__(self): super(AlipayOpenMiniVersionAuditApplyResponse, self).__init__()", "response = super(AlipayOpenMiniVersionAuditApplyResponse, self).parse_response_content(response_content) if 'speed_up' in response: self.speed_up =", "speed_up_memo(self, value): self._speed_up_memo = value def parse_response_content(self, response_content): response =", "super(AlipayOpenMiniVersionAuditApplyResponse, self).parse_response_content(response_content) if 'speed_up' in response: self.speed_up = response['speed_up'] if", "coding: utf-8 -*- import json from alipay.aop.api.response.AlipayResponse import AlipayResponse class", "def speed_up(self, value): self._speed_up = value @property def speed_up_memo(self): return", "def speed_up_memo(self): return self._speed_up_memo @speed_up_memo.setter def speed_up_memo(self, value): self._speed_up_memo =", "speed_up(self): return self._speed_up @speed_up.setter def speed_up(self, value): self._speed_up = value", "None @property def speed_up(self): return self._speed_up @speed_up.setter def speed_up(self, value):", "@speed_up.setter def speed_up(self, value): self._speed_up = value @property def speed_up_memo(self):", "return self._speed_up_memo @speed_up_memo.setter def speed_up_memo(self, value): self._speed_up_memo = value def", "= value @property def speed_up_memo(self): return self._speed_up_memo @speed_up_memo.setter def speed_up_memo(self,", "parse_response_content(self, response_content): response = super(AlipayOpenMiniVersionAuditApplyResponse, self).parse_response_content(response_content) if 'speed_up' in response:", "= None @property def speed_up(self): return self._speed_up @speed_up.setter def speed_up(self,", "self).__init__() self._speed_up = None self._speed_up_memo = None @property def speed_up(self):", "in response: self.speed_up = response['speed_up'] if 'speed_up_memo' in response: self.speed_up_memo", "def speed_up_memo(self, value): self._speed_up_memo = value def parse_response_content(self, response_content): response", "@property def speed_up_memo(self): return self._speed_up_memo @speed_up_memo.setter def speed_up_memo(self, value): self._speed_up_memo", "self._speed_up = None self._speed_up_memo = None @property def speed_up(self): return", "= value def parse_response_content(self, response_content): response = super(AlipayOpenMiniVersionAuditApplyResponse, self).parse_response_content(response_content) if", "@speed_up_memo.setter def speed_up_memo(self, value): self._speed_up_memo = value def parse_response_content(self, response_content):", "value @property def speed_up_memo(self): return self._speed_up_memo @speed_up_memo.setter def speed_up_memo(self, value):", "= super(AlipayOpenMiniVersionAuditApplyResponse, self).parse_response_content(response_content) if 'speed_up' in response: self.speed_up = response['speed_up']", "alipay.aop.api.response.AlipayResponse import AlipayResponse class AlipayOpenMiniVersionAuditApplyResponse(AlipayResponse): def __init__(self): super(AlipayOpenMiniVersionAuditApplyResponse, self).__init__() self._speed_up", "AlipayResponse class AlipayOpenMiniVersionAuditApplyResponse(AlipayResponse): def __init__(self): super(AlipayOpenMiniVersionAuditApplyResponse, self).__init__() self._speed_up = None", "speed_up_memo(self): return self._speed_up_memo @speed_up_memo.setter def speed_up_memo(self, value): self._speed_up_memo = value", "-*- import json from alipay.aop.api.response.AlipayResponse import AlipayResponse class AlipayOpenMiniVersionAuditApplyResponse(AlipayResponse): def", "response: self.speed_up = response['speed_up'] if 'speed_up_memo' in response: self.speed_up_memo =", "import json from alipay.aop.api.response.AlipayResponse import AlipayResponse class AlipayOpenMiniVersionAuditApplyResponse(AlipayResponse): def __init__(self):", "self.speed_up = response['speed_up'] if 'speed_up_memo' in response: self.speed_up_memo = response['speed_up_memo']", "self._speed_up @speed_up.setter def speed_up(self, value): self._speed_up = value @property def", "self).parse_response_content(response_content) if 'speed_up' in response: self.speed_up = response['speed_up'] if 'speed_up_memo'", "response_content): response = super(AlipayOpenMiniVersionAuditApplyResponse, self).parse_response_content(response_content) if 'speed_up' in response: self.speed_up", "import AlipayResponse class AlipayOpenMiniVersionAuditApplyResponse(AlipayResponse): def __init__(self): super(AlipayOpenMiniVersionAuditApplyResponse, self).__init__() self._speed_up =", "self._speed_up_memo = None @property def speed_up(self): return self._speed_up @speed_up.setter def", "value): self._speed_up_memo = value def parse_response_content(self, response_content): response = super(AlipayOpenMiniVersionAuditApplyResponse,", "self._speed_up = value @property def speed_up_memo(self): return self._speed_up_memo @speed_up_memo.setter def", "'speed_up' in response: self.speed_up = response['speed_up'] if 'speed_up_memo' in response:", "@property def speed_up(self): return self._speed_up @speed_up.setter def speed_up(self, value): self._speed_up", "value): self._speed_up = value @property def speed_up_memo(self): return self._speed_up_memo @speed_up_memo.setter", "__init__(self): super(AlipayOpenMiniVersionAuditApplyResponse, self).__init__() self._speed_up = None self._speed_up_memo = None @property", "-*- coding: utf-8 -*- import json from alipay.aop.api.response.AlipayResponse import AlipayResponse", "#!/usr/bin/env python # -*- coding: utf-8 -*- import json from", "if 'speed_up' in response: self.speed_up = response['speed_up'] if 'speed_up_memo' in", "python # -*- coding: utf-8 -*- import json from alipay.aop.api.response.AlipayResponse", "self._speed_up_memo @speed_up_memo.setter def speed_up_memo(self, value): self._speed_up_memo = value def parse_response_content(self,", "def speed_up(self): return self._speed_up @speed_up.setter def speed_up(self, value): self._speed_up =", "json from alipay.aop.api.response.AlipayResponse import AlipayResponse class AlipayOpenMiniVersionAuditApplyResponse(AlipayResponse): def __init__(self): super(AlipayOpenMiniVersionAuditApplyResponse,", "= None self._speed_up_memo = None @property def speed_up(self): return self._speed_up", "self._speed_up_memo = value def parse_response_content(self, response_content): response = super(AlipayOpenMiniVersionAuditApplyResponse, self).parse_response_content(response_content)", "class AlipayOpenMiniVersionAuditApplyResponse(AlipayResponse): def __init__(self): super(AlipayOpenMiniVersionAuditApplyResponse, self).__init__() self._speed_up = None self._speed_up_memo", "utf-8 -*- import json from alipay.aop.api.response.AlipayResponse import AlipayResponse class AlipayOpenMiniVersionAuditApplyResponse(AlipayResponse):", "def __init__(self): super(AlipayOpenMiniVersionAuditApplyResponse, self).__init__() self._speed_up = None self._speed_up_memo = None", "speed_up(self, value): self._speed_up = value @property def speed_up_memo(self): return self._speed_up_memo", "value def parse_response_content(self, response_content): response = super(AlipayOpenMiniVersionAuditApplyResponse, self).parse_response_content(response_content) if 'speed_up'", "AlipayOpenMiniVersionAuditApplyResponse(AlipayResponse): def __init__(self): super(AlipayOpenMiniVersionAuditApplyResponse, self).__init__() self._speed_up = None self._speed_up_memo =", "return self._speed_up @speed_up.setter def speed_up(self, value): self._speed_up = value @property", "super(AlipayOpenMiniVersionAuditApplyResponse, self).__init__() self._speed_up = None self._speed_up_memo = None @property def" ]
[ "QCloseEvent, QShowEvent from PyQt5.QtWidgets import QDialog, QLabel, QVBoxLayout, QApplication, QWidget", "QMovie(gif_file) self.label = QLabel() self.label.setMovie(self.movie) self.layout = QVBoxLayout(self) self.layout.addWidget(self.label) def", "curr_theme = \"light\" if app: curr_theme = app.property(\"theme\") gif_file =", "QVBoxLayout(self) self.layout.addWidget(self.label) def center(self, host: QWidget = None): if host:", "PyQt5 import QtCore from PyQt5.QtCore import QRect, QPoint from PyQt5.QtGui", "import QRect, QPoint from PyQt5.QtGui import QMovie, QCloseEvent, QShowEvent from", "QLabel() self.label.setMovie(self.movie) self.layout = QVBoxLayout(self) self.layout.addWidget(self.label) def center(self, host: QWidget", "showEvent(self, e: QShowEvent): if self.movie.state() == QMovie.NotRunning: self.movie.start() def closeEvent(self,", "= QPoint(centerPoint.x() - offset, centerPoint.y() - offset) self.move(targetPoint) else: screen", "self.move(centerPoint) return self def showEvent(self, e: QShowEvent): if self.movie.state() ==", "offset, centerPoint.y() - offset) self.move(targetPoint) else: screen = QApplication.desktop().screenNumber(QApplication.desktop().cursor().pos()) centerPoint", "import QMovie, QCloseEvent, QShowEvent from PyQt5.QtWidgets import QDialog, QLabel, QVBoxLayout,", "self.setFixedSize(100, 100) # self.setWindowOpacity(0.8) self.setWindowFlags(QtCore.Qt.FramelessWindowHint) self.setAttribute(QtCore.Qt.WA_TranslucentBackground) app = QApplication.instance() curr_theme", "self.geometry() centerPoint: QPoint = hostGeometry.center() centerPoint = host.mapToGlobal(centerPoint) offset =", "QtCore from PyQt5.QtCore import QRect, QPoint from PyQt5.QtGui import QMovie,", ": QRect = self.geometry() centerPoint: QPoint = hostGeometry.center() centerPoint =", "screen = QApplication.desktop().screenNumber(QApplication.desktop().cursor().pos()) centerPoint = QApplication.desktop().screenGeometry(screen).center() self.move(centerPoint) return self def", "- offset) self.move(targetPoint) else: screen = QApplication.desktop().screenNumber(QApplication.desktop().cursor().pos()) centerPoint = QApplication.desktop().screenGeometry(screen).center()", "centerPoint: QPoint = hostGeometry.center() centerPoint = host.mapToGlobal(centerPoint) offset = 30", "QRect = self.geometry() centerPoint: QPoint = hostGeometry.center() centerPoint = host.mapToGlobal(centerPoint)", "self.movie.state() == QMovie.NotRunning: self.movie.start() def closeEvent(self, e: QCloseEvent): if self.movie.state()", "os.path.abspath(\"./assets/icons/{}/loading.gif\".format(curr_theme)) self.movie = QMovie(gif_file) self.label = QLabel() self.label.setMovie(self.movie) self.layout =", "QWidget = None): if host: hostGeometry: QRect = host.geometry() #", "= QApplication.desktop().screenGeometry(screen).center() self.move(centerPoint) return self def showEvent(self, e: QShowEvent): if", "QMovie.NotRunning: self.movie.start() def closeEvent(self, e: QCloseEvent): if self.movie.state() == QMovie.Running:", "\"light\" if app: curr_theme = app.property(\"theme\") gif_file = os.path.abspath(\"./assets/icons/{}/loading.gif\".format(curr_theme)) self.movie", "100) # self.setWindowOpacity(0.8) self.setWindowFlags(QtCore.Qt.FramelessWindowHint) self.setAttribute(QtCore.Qt.WA_TranslucentBackground) app = QApplication.instance() curr_theme =", "# self.setWindowOpacity(0.8) self.setWindowFlags(QtCore.Qt.FramelessWindowHint) self.setAttribute(QtCore.Qt.WA_TranslucentBackground) app = QApplication.instance() curr_theme = \"light\"", "= QMovie(gif_file) self.label = QLabel() self.label.setMovie(self.movie) self.layout = QVBoxLayout(self) self.layout.addWidget(self.label)", "if app: curr_theme = app.property(\"theme\") gif_file = os.path.abspath(\"./assets/icons/{}/loading.gif\".format(curr_theme)) self.movie =", "e: QShowEvent): if self.movie.state() == QMovie.NotRunning: self.movie.start() def closeEvent(self, e:", "QRect = host.geometry() # dialogGeometry : QRect = self.geometry() centerPoint:", "QShowEvent from PyQt5.QtWidgets import QDialog, QLabel, QVBoxLayout, QApplication, QWidget class", "None): if host: hostGeometry: QRect = host.geometry() # dialogGeometry :", "super(QLoadingDialog, self).__init__() self.setFixedSize(100, 100) # self.setWindowOpacity(0.8) self.setWindowFlags(QtCore.Qt.FramelessWindowHint) self.setAttribute(QtCore.Qt.WA_TranslucentBackground) app =", "= QLabel() self.label.setMovie(self.movie) self.layout = QVBoxLayout(self) self.layout.addWidget(self.label) def center(self, host:", "__init__(self, parent=None): super(QLoadingDialog, self).__init__() self.setFixedSize(100, 100) # self.setWindowOpacity(0.8) self.setWindowFlags(QtCore.Qt.FramelessWindowHint) self.setAttribute(QtCore.Qt.WA_TranslucentBackground)", "host.geometry() # dialogGeometry : QRect = self.geometry() centerPoint: QPoint =", "parent=None): super(QLoadingDialog, self).__init__() self.setFixedSize(100, 100) # self.setWindowOpacity(0.8) self.setWindowFlags(QtCore.Qt.FramelessWindowHint) self.setAttribute(QtCore.Qt.WA_TranslucentBackground) app", "QWidget class QLoadingDialog(QDialog): def __init__(self, parent=None): super(QLoadingDialog, self).__init__() self.setFixedSize(100, 100)", "= None): if host: hostGeometry: QRect = host.geometry() # dialogGeometry", "= self.geometry() centerPoint: QPoint = hostGeometry.center() centerPoint = host.mapToGlobal(centerPoint) offset", "QVBoxLayout, QApplication, QWidget class QLoadingDialog(QDialog): def __init__(self, parent=None): super(QLoadingDialog, self).__init__()", "def center(self, host: QWidget = None): if host: hostGeometry: QRect", "closeEvent(self, e: QCloseEvent): if self.movie.state() == QMovie.Running: self.movie.stop() def exec_(self):", "self.layout.addWidget(self.label) def center(self, host: QWidget = None): if host: hostGeometry:", "= host.geometry() # dialogGeometry : QRect = self.geometry() centerPoint: QPoint", "from PyQt5 import QtCore from PyQt5.QtCore import QRect, QPoint from", "from PyQt5.QtCore import QRect, QPoint from PyQt5.QtGui import QMovie, QCloseEvent,", "= os.path.abspath(\"./assets/icons/{}/loading.gif\".format(curr_theme)) self.movie = QMovie(gif_file) self.label = QLabel() self.label.setMovie(self.movie) self.layout", "= \"light\" if app: curr_theme = app.property(\"theme\") gif_file = os.path.abspath(\"./assets/icons/{}/loading.gif\".format(curr_theme))", "<filename>cvstudio/view/widgets/loading_dialog/loading_dialog.py import os from PyQt5 import QtCore from PyQt5.QtCore import", "= QApplication.desktop().screenNumber(QApplication.desktop().cursor().pos()) centerPoint = QApplication.desktop().screenGeometry(screen).center() self.move(centerPoint) return self def showEvent(self,", "if self.movie.state() == QMovie.Running: self.movie.stop() def exec_(self): self.center() return QDialog.exec_(self)", "def __init__(self, parent=None): super(QLoadingDialog, self).__init__() self.setFixedSize(100, 100) # self.setWindowOpacity(0.8) self.setWindowFlags(QtCore.Qt.FramelessWindowHint)", "= host.mapToGlobal(centerPoint) offset = 30 targetPoint = QPoint(centerPoint.x() - offset,", "QShowEvent): if self.movie.state() == QMovie.NotRunning: self.movie.start() def closeEvent(self, e: QCloseEvent):", "offset) self.move(targetPoint) else: screen = QApplication.desktop().screenNumber(QApplication.desktop().cursor().pos()) centerPoint = QApplication.desktop().screenGeometry(screen).center() self.move(centerPoint)", "else: screen = QApplication.desktop().screenNumber(QApplication.desktop().cursor().pos()) centerPoint = QApplication.desktop().screenGeometry(screen).center() self.move(centerPoint) return self", "- offset, centerPoint.y() - offset) self.move(targetPoint) else: screen = QApplication.desktop().screenNumber(QApplication.desktop().cursor().pos())", "app.property(\"theme\") gif_file = os.path.abspath(\"./assets/icons/{}/loading.gif\".format(curr_theme)) self.movie = QMovie(gif_file) self.label = QLabel()", "QPoint(centerPoint.x() - offset, centerPoint.y() - offset) self.move(targetPoint) else: screen =", "host: hostGeometry: QRect = host.geometry() # dialogGeometry : QRect =", "centerPoint.y() - offset) self.move(targetPoint) else: screen = QApplication.desktop().screenNumber(QApplication.desktop().cursor().pos()) centerPoint =", "QLoadingDialog(QDialog): def __init__(self, parent=None): super(QLoadingDialog, self).__init__() self.setFixedSize(100, 100) # self.setWindowOpacity(0.8)", "import QtCore from PyQt5.QtCore import QRect, QPoint from PyQt5.QtGui import", "host: QWidget = None): if host: hostGeometry: QRect = host.geometry()", "e: QCloseEvent): if self.movie.state() == QMovie.Running: self.movie.stop() def exec_(self): self.center()", "= QApplication.instance() curr_theme = \"light\" if app: curr_theme = app.property(\"theme\")", "QApplication.desktop().screenGeometry(screen).center() self.move(centerPoint) return self def showEvent(self, e: QShowEvent): if self.movie.state()", "from PyQt5.QtWidgets import QDialog, QLabel, QVBoxLayout, QApplication, QWidget class QLoadingDialog(QDialog):", "self.layout = QVBoxLayout(self) self.layout.addWidget(self.label) def center(self, host: QWidget = None):", "import QDialog, QLabel, QVBoxLayout, QApplication, QWidget class QLoadingDialog(QDialog): def __init__(self,", "= QVBoxLayout(self) self.layout.addWidget(self.label) def center(self, host: QWidget = None): if", "if host: hostGeometry: QRect = host.geometry() # dialogGeometry : QRect", "== QMovie.NotRunning: self.movie.start() def closeEvent(self, e: QCloseEvent): if self.movie.state() ==", "self.move(targetPoint) else: screen = QApplication.desktop().screenNumber(QApplication.desktop().cursor().pos()) centerPoint = QApplication.desktop().screenGeometry(screen).center() self.move(centerPoint) return", "centerPoint = host.mapToGlobal(centerPoint) offset = 30 targetPoint = QPoint(centerPoint.x() -", "centerPoint = QApplication.desktop().screenGeometry(screen).center() self.move(centerPoint) return self def showEvent(self, e: QShowEvent):", "QPoint = hostGeometry.center() centerPoint = host.mapToGlobal(centerPoint) offset = 30 targetPoint", "hostGeometry.center() centerPoint = host.mapToGlobal(centerPoint) offset = 30 targetPoint = QPoint(centerPoint.x()", "curr_theme = app.property(\"theme\") gif_file = os.path.abspath(\"./assets/icons/{}/loading.gif\".format(curr_theme)) self.movie = QMovie(gif_file) self.label", "= 30 targetPoint = QPoint(centerPoint.x() - offset, centerPoint.y() - offset)", "30 targetPoint = QPoint(centerPoint.x() - offset, centerPoint.y() - offset) self.move(targetPoint)", "QMovie, QCloseEvent, QShowEvent from PyQt5.QtWidgets import QDialog, QLabel, QVBoxLayout, QApplication,", "host.mapToGlobal(centerPoint) offset = 30 targetPoint = QPoint(centerPoint.x() - offset, centerPoint.y()", "PyQt5.QtCore import QRect, QPoint from PyQt5.QtGui import QMovie, QCloseEvent, QShowEvent", "PyQt5.QtWidgets import QDialog, QLabel, QVBoxLayout, QApplication, QWidget class QLoadingDialog(QDialog): def", "# dialogGeometry : QRect = self.geometry() centerPoint: QPoint = hostGeometry.center()", "def closeEvent(self, e: QCloseEvent): if self.movie.state() == QMovie.Running: self.movie.stop() def", "app: curr_theme = app.property(\"theme\") gif_file = os.path.abspath(\"./assets/icons/{}/loading.gif\".format(curr_theme)) self.movie = QMovie(gif_file)", "self.movie = QMovie(gif_file) self.label = QLabel() self.label.setMovie(self.movie) self.layout = QVBoxLayout(self)", "QRect, QPoint from PyQt5.QtGui import QMovie, QCloseEvent, QShowEvent from PyQt5.QtWidgets", "class QLoadingDialog(QDialog): def __init__(self, parent=None): super(QLoadingDialog, self).__init__() self.setFixedSize(100, 100) #", "self).__init__() self.setFixedSize(100, 100) # self.setWindowOpacity(0.8) self.setWindowFlags(QtCore.Qt.FramelessWindowHint) self.setAttribute(QtCore.Qt.WA_TranslucentBackground) app = QApplication.instance()", "= hostGeometry.center() centerPoint = host.mapToGlobal(centerPoint) offset = 30 targetPoint =", "app = QApplication.instance() curr_theme = \"light\" if app: curr_theme =", "gif_file = os.path.abspath(\"./assets/icons/{}/loading.gif\".format(curr_theme)) self.movie = QMovie(gif_file) self.label = QLabel() self.label.setMovie(self.movie)", "if self.movie.state() == QMovie.NotRunning: self.movie.start() def closeEvent(self, e: QCloseEvent): if", "return self def showEvent(self, e: QShowEvent): if self.movie.state() == QMovie.NotRunning:", "QCloseEvent): if self.movie.state() == QMovie.Running: self.movie.stop() def exec_(self): self.center() return", "QPoint from PyQt5.QtGui import QMovie, QCloseEvent, QShowEvent from PyQt5.QtWidgets import", "QApplication.instance() curr_theme = \"light\" if app: curr_theme = app.property(\"theme\") gif_file", "self.label.setMovie(self.movie) self.layout = QVBoxLayout(self) self.layout.addWidget(self.label) def center(self, host: QWidget =", "self.label = QLabel() self.label.setMovie(self.movie) self.layout = QVBoxLayout(self) self.layout.addWidget(self.label) def center(self,", "offset = 30 targetPoint = QPoint(centerPoint.x() - offset, centerPoint.y() -", "QApplication.desktop().screenNumber(QApplication.desktop().cursor().pos()) centerPoint = QApplication.desktop().screenGeometry(screen).center() self.move(centerPoint) return self def showEvent(self, e:", "= app.property(\"theme\") gif_file = os.path.abspath(\"./assets/icons/{}/loading.gif\".format(curr_theme)) self.movie = QMovie(gif_file) self.label =", "QLabel, QVBoxLayout, QApplication, QWidget class QLoadingDialog(QDialog): def __init__(self, parent=None): super(QLoadingDialog,", "self.setWindowOpacity(0.8) self.setWindowFlags(QtCore.Qt.FramelessWindowHint) self.setAttribute(QtCore.Qt.WA_TranslucentBackground) app = QApplication.instance() curr_theme = \"light\" if", "import os from PyQt5 import QtCore from PyQt5.QtCore import QRect,", "from PyQt5.QtGui import QMovie, QCloseEvent, QShowEvent from PyQt5.QtWidgets import QDialog,", "def showEvent(self, e: QShowEvent): if self.movie.state() == QMovie.NotRunning: self.movie.start() def", "QDialog, QLabel, QVBoxLayout, QApplication, QWidget class QLoadingDialog(QDialog): def __init__(self, parent=None):", "dialogGeometry : QRect = self.geometry() centerPoint: QPoint = hostGeometry.center() centerPoint", "targetPoint = QPoint(centerPoint.x() - offset, centerPoint.y() - offset) self.move(targetPoint) else:", "self.setAttribute(QtCore.Qt.WA_TranslucentBackground) app = QApplication.instance() curr_theme = \"light\" if app: curr_theme", "self def showEvent(self, e: QShowEvent): if self.movie.state() == QMovie.NotRunning: self.movie.start()", "self.setWindowFlags(QtCore.Qt.FramelessWindowHint) self.setAttribute(QtCore.Qt.WA_TranslucentBackground) app = QApplication.instance() curr_theme = \"light\" if app:", "PyQt5.QtGui import QMovie, QCloseEvent, QShowEvent from PyQt5.QtWidgets import QDialog, QLabel,", "self.movie.start() def closeEvent(self, e: QCloseEvent): if self.movie.state() == QMovie.Running: self.movie.stop()", "center(self, host: QWidget = None): if host: hostGeometry: QRect =", "QApplication, QWidget class QLoadingDialog(QDialog): def __init__(self, parent=None): super(QLoadingDialog, self).__init__() self.setFixedSize(100,", "hostGeometry: QRect = host.geometry() # dialogGeometry : QRect = self.geometry()", "os from PyQt5 import QtCore from PyQt5.QtCore import QRect, QPoint" ]
[ "3, 6, 1, 4, 1, 217, 16, 1, 2, 2),", "1)) mwHeap = MibIdentifier((1, 3, 6, 1, 4, 1, 217,", "\"NotificationGroup\") Gauge32, Unsigned32, ObjectIdentity, IpAddress, Bits, MibIdentifier, Integer32, enterprises, ModuleIdentity,", "\"OctetString\", \"Integer\") NamedValues, = mibBuilder.importSymbols(\"ASN1-ENUMERATION\", \"NamedValues\") ValueRangeConstraint, SingleValueConstraint, ConstraintsUnion, ValueSizeConstraint,", "\"TextualConvention\", \"DisplayString\") tecElite = MibIdentifier((1, 3, 6, 1, 4, 1,", "DisplayString = mibBuilder.importSymbols(\"SNMPv2-TC\", \"TextualConvention\", \"DisplayString\") tecElite = MibIdentifier((1, 3, 6,", "TextualConvention, DisplayString = mibBuilder.importSymbols(\"SNMPv2-TC\", \"TextualConvention\", \"DisplayString\") tecElite = MibIdentifier((1, 3,", "= mibBuilder.importSymbols(\"ASN1\", \"ObjectIdentifier\", \"OctetString\", \"Integer\") NamedValues, = mibBuilder.importSymbols(\"ASN1-ENUMERATION\", \"NamedValues\") ValueRangeConstraint,", "PySNMP MIB module MWORKS-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/MWORKS-MIB #", "\"Integer\") NamedValues, = mibBuilder.importSymbols(\"ASN1-ENUMERATION\", \"NamedValues\") ValueRangeConstraint, SingleValueConstraint, ConstraintsUnion, ValueSizeConstraint, ConstraintsIntersection", "the agent to use.') mwMemUsed = MibScalar((1, 3, 6, 1,", "mwHeap = MibIdentifier((1, 3, 6, 1, 4, 1, 217, 16,", "6, 1, 4, 1, 217, 16, 1, 2)) mwMemCeiling =", "if mibBuilder.loadTexts: mwHeapUsed.setStatus('mandatory') if mibBuilder.loadTexts: mwHeapUsed.setDescription('bytes of available memory in", "memory in the heap.') mibBuilder.exportSymbols(\"MWORKS-MIB\", mwHeap=mwHeap, mwHeapUsed=mwHeapUsed, mwMemCeiling=mwMemCeiling, meterWorks=meterWorks, tecElite=tecElite,", "= MibIdentifier((1, 3, 6, 1, 4, 1, 217)) meterWorks =", "if mibBuilder.loadTexts: mwMemCeiling.setStatus('mandatory') if mibBuilder.loadTexts: mwMemCeiling.setDescription('bytes of memory the agent", "DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using", "if mibBuilder.loadTexts: mwHeapTotal.setStatus('mandatory') if mibBuilder.loadTexts: mwHeapTotal.setDescription('bytes of memory given to", "SingleValueConstraint, ConstraintsUnion, ValueSizeConstraint, ConstraintsIntersection = mibBuilder.importSymbols(\"ASN1-REFINEMENT\", \"ValueRangeConstraint\", \"SingleValueConstraint\", \"ConstraintsUnion\", \"ValueSizeConstraint\",", "mibBuilder.importSymbols(\"SNMPv2-TC\", \"TextualConvention\", \"DisplayString\") tecElite = MibIdentifier((1, 3, 6, 1, 4,", "2), Counter32()).setMaxAccess(\"readonly\") if mibBuilder.loadTexts: mwHeapUsed.setStatus('mandatory') if mibBuilder.loadTexts: mwHeapUsed.setDescription('bytes of available", "217, 16, 1, 2, 1), Counter32()).setMaxAccess(\"readonly\") if mibBuilder.loadTexts: mwHeapTotal.setStatus('mandatory') if", "= mibBuilder.importSymbols(\"SNMPv2-TC\", \"TextualConvention\", \"DisplayString\") tecElite = MibIdentifier((1, 3, 6, 1,", "\"Unsigned32\", \"ObjectIdentity\", \"IpAddress\", \"Bits\", \"MibIdentifier\", \"Integer32\", \"enterprises\", \"ModuleIdentity\", \"TimeTicks\", \"Counter32\",", "4, 1, 217, 16, 1, 2)) mwMemCeiling = MibScalar((1, 3,", "4, 1, 217, 16, 1, 2, 1), Counter32()).setMaxAccess(\"readonly\") if mibBuilder.loadTexts:", "Counter32()).setMaxAccess(\"readonly\") if mibBuilder.loadTexts: mwHeapUsed.setStatus('mandatory') if mibBuilder.loadTexts: mwHeapUsed.setDescription('bytes of available memory", "1, 217, 16)) mw501 = MibIdentifier((1, 3, 6, 1, 4,", "mibBuilder.loadTexts: mwHeapTotal.setStatus('mandatory') if mibBuilder.loadTexts: mwHeapTotal.setDescription('bytes of memory given to the", "mibBuilder.importSymbols(\"ASN1-REFINEMENT\", \"ValueRangeConstraint\", \"SingleValueConstraint\", \"ConstraintsUnion\", \"ValueSizeConstraint\", \"ConstraintsIntersection\") ModuleCompliance, NotificationGroup = mibBuilder.importSymbols(\"SNMPv2-CONF\",", "NotificationGroup = mibBuilder.importSymbols(\"SNMPv2-CONF\", \"ModuleCompliance\", \"NotificationGroup\") Gauge32, Unsigned32, ObjectIdentity, IpAddress, Bits,", "ConstraintsIntersection = mibBuilder.importSymbols(\"ASN1-REFINEMENT\", \"ValueRangeConstraint\", \"SingleValueConstraint\", \"ConstraintsUnion\", \"ValueSizeConstraint\", \"ConstraintsIntersection\") ModuleCompliance, NotificationGroup", "has malloc'ed. some of this may be in free pools.\")", "14:16:04 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0", "4, 1, 217, 16)) mw501 = MibIdentifier((1, 3, 6, 1,", "16, 1, 1)) mwHeap = MibIdentifier((1, 3, 6, 1, 4,", "217, 16, 1, 1, 1), Counter32()).setMaxAccess(\"readonly\") if mibBuilder.loadTexts: mwMemCeiling.setStatus('mandatory') if", "3.7.3 (default, Mar 27 2019, 09:23:15) # ObjectIdentifier, OctetString, Integer", "Integer32, enterprises, ModuleIdentity, TimeTicks, Counter32, NotificationType, iso, Counter64, MibScalar, MibTable,", "\"ObjectIdentity\", \"IpAddress\", \"Bits\", \"MibIdentifier\", \"Integer32\", \"enterprises\", \"ModuleIdentity\", \"TimeTicks\", \"Counter32\", \"NotificationType\",", "(default, Mar 27 2019, 09:23:15) # ObjectIdentifier, OctetString, Integer =", "\"DisplayString\") tecElite = MibIdentifier((1, 3, 6, 1, 4, 1, 217))", "16, 1, 2)) mwMemCeiling = MibScalar((1, 3, 6, 1, 4,", "4, 1, 217, 16, 1)) mwMem = MibIdentifier((1, 3, 6,", "may be in free pools.\") mwHeapTotal = MibScalar((1, 3, 6,", "6, 1, 4, 1, 217, 16, 1, 1)) mwHeap =", "davwang4 # Using Python version 3.7.3 (default, Mar 27 2019,", "1, 1, 2), Counter32()).setMaxAccess(\"readonly\") if mibBuilder.loadTexts: mwMemUsed.setStatus('mandatory') if mibBuilder.loadTexts: mwMemUsed.setDescription(\"bytes", "\"MibTable\", \"MibTableRow\", \"MibTableColumn\") TextualConvention, DisplayString = mibBuilder.importSymbols(\"SNMPv2-TC\", \"TextualConvention\", \"DisplayString\") tecElite", "1, 4, 1, 217, 16, 1, 2, 1), Counter32()).setMaxAccess(\"readonly\") if", "source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/MWORKS-MIB # Produced by pysmi-0.3.4 at Wed May 1", "217, 16, 1)) mwMem = MibIdentifier((1, 3, 6, 1, 4,", "\"SingleValueConstraint\", \"ConstraintsUnion\", \"ValueSizeConstraint\", \"ConstraintsIntersection\") ModuleCompliance, NotificationGroup = mibBuilder.importSymbols(\"SNMPv2-CONF\", \"ModuleCompliance\", \"NotificationGroup\")", "1, 2)) mwMemCeiling = MibScalar((1, 3, 6, 1, 4, 1,", "MibScalar, MibTable, MibTableRow, MibTableColumn = mibBuilder.importSymbols(\"SNMPv2-SMI\", \"Gauge32\", \"Unsigned32\", \"ObjectIdentity\", \"IpAddress\",", "MibIdentifier((1, 3, 6, 1, 4, 1, 217)) meterWorks = MibIdentifier((1,", "mwMemUsed = MibScalar((1, 3, 6, 1, 4, 1, 217, 16,", "mibBuilder.exportSymbols(\"MWORKS-MIB\", mwHeap=mwHeap, mwHeapUsed=mwHeapUsed, mwMemCeiling=mwMemCeiling, meterWorks=meterWorks, tecElite=tecElite, mwMem=mwMem, mw501=mw501, mwHeapTotal=mwHeapTotal, mwMemUsed=mwMemUsed)", "= mibBuilder.importSymbols(\"SNMPv2-CONF\", \"ModuleCompliance\", \"NotificationGroup\") Gauge32, Unsigned32, ObjectIdentity, IpAddress, Bits, MibIdentifier,", "2), Counter32()).setMaxAccess(\"readonly\") if mibBuilder.loadTexts: mwMemUsed.setStatus('mandatory') if mibBuilder.loadTexts: mwMemUsed.setDescription(\"bytes of memory", "4, 1, 217, 16, 1, 2, 2), Counter32()).setMaxAccess(\"readonly\") if mibBuilder.loadTexts:", "\"ModuleIdentity\", \"TimeTicks\", \"Counter32\", \"NotificationType\", \"iso\", \"Counter64\", \"MibScalar\", \"MibTable\", \"MibTableRow\", \"MibTableColumn\")", "= MibIdentifier((1, 3, 6, 1, 4, 1, 217, 16, 1,", "1, 217, 16, 1, 1, 2), Counter32()).setMaxAccess(\"readonly\") if mibBuilder.loadTexts: mwMemUsed.setStatus('mandatory')", "TimeTicks, Counter32, NotificationType, iso, Counter64, MibScalar, MibTable, MibTableRow, MibTableColumn =", "mibBuilder.loadTexts: mwMemCeiling.setStatus('mandatory') if mibBuilder.loadTexts: mwMemCeiling.setDescription('bytes of memory the agent memory", "to the heap manager.') mwHeapUsed = MibScalar((1, 3, 6, 1,", "2019, 09:23:15) # ObjectIdentifier, OctetString, Integer = mibBuilder.importSymbols(\"ASN1\", \"ObjectIdentifier\", \"OctetString\",", "2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by", "3, 6, 1, 4, 1, 217, 16, 1, 1, 2),", "2)) mwMemCeiling = MibScalar((1, 3, 6, 1, 4, 1, 217,", "1, 217, 16, 1, 2)) mwMemCeiling = MibScalar((1, 3, 6,", "some of this may be in free pools.\") mwHeapTotal =", "1, 2, 2), Counter32()).setMaxAccess(\"readonly\") if mibBuilder.loadTexts: mwHeapUsed.setStatus('mandatory') if mibBuilder.loadTexts: mwHeapUsed.setDescription('bytes", "mwMem = MibIdentifier((1, 3, 6, 1, 4, 1, 217, 16,", "will allow the agent to use.') mwMemUsed = MibScalar((1, 3,", "ValueSizeConstraint, ConstraintsIntersection = mibBuilder.importSymbols(\"ASN1-REFINEMENT\", \"ValueRangeConstraint\", \"SingleValueConstraint\", \"ConstraintsUnion\", \"ValueSizeConstraint\", \"ConstraintsIntersection\") ModuleCompliance,", "MibIdentifier((1, 3, 6, 1, 4, 1, 217, 16)) mw501 =", "Counter32()).setMaxAccess(\"readonly\") if mibBuilder.loadTexts: mwMemCeiling.setStatus('mandatory') if mibBuilder.loadTexts: mwMemCeiling.setDescription('bytes of memory the", "1, 4, 1, 217, 16, 1, 2, 2), Counter32()).setMaxAccess(\"readonly\") if", "= MibIdentifier((1, 3, 6, 1, 4, 1, 217, 16)) mw501", "\"NotificationType\", \"iso\", \"Counter64\", \"MibScalar\", \"MibTable\", \"MibTableRow\", \"MibTableColumn\") TextualConvention, DisplayString =", "free pools.\") mwHeapTotal = MibScalar((1, 3, 6, 1, 4, 1,", "at Wed May 1 14:16:04 2019 # On host DAVWANG4-M-1475", "\"Bits\", \"MibIdentifier\", \"Integer32\", \"enterprises\", \"ModuleIdentity\", \"TimeTicks\", \"Counter32\", \"NotificationType\", \"iso\", \"Counter64\",", "OctetString, Integer = mibBuilder.importSymbols(\"ASN1\", \"ObjectIdentifier\", \"OctetString\", \"Integer\") NamedValues, = mibBuilder.importSymbols(\"ASN1-ENUMERATION\",", "the agent memory manager will allow the agent to use.')", "MWORKS-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/MWORKS-MIB # Produced by pysmi-0.3.4", "6, 1, 4, 1, 217, 16, 1, 2, 1), Counter32()).setMaxAccess(\"readonly\")", "Unsigned32, ObjectIdentity, IpAddress, Bits, MibIdentifier, Integer32, enterprises, ModuleIdentity, TimeTicks, Counter32,", "agent to use.') mwMemUsed = MibScalar((1, 3, 6, 1, 4,", "MibIdentifier, Integer32, enterprises, ModuleIdentity, TimeTicks, Counter32, NotificationType, iso, Counter64, MibScalar,", "MibIdentifier((1, 3, 6, 1, 4, 1, 217, 16, 1)) mwMem", "217, 16, 1, 1)) mwHeap = MibIdentifier((1, 3, 6, 1,", "NamedValues, = mibBuilder.importSymbols(\"ASN1-ENUMERATION\", \"NamedValues\") ValueRangeConstraint, SingleValueConstraint, ConstraintsUnion, ValueSizeConstraint, ConstraintsIntersection =", "the heap.') mibBuilder.exportSymbols(\"MWORKS-MIB\", mwHeap=mwHeap, mwHeapUsed=mwHeapUsed, mwMemCeiling=mwMemCeiling, meterWorks=meterWorks, tecElite=tecElite, mwMem=mwMem, mw501=mw501,", "16, 1, 1, 2), Counter32()).setMaxAccess(\"readonly\") if mibBuilder.loadTexts: mwMemUsed.setStatus('mandatory') if mibBuilder.loadTexts:", "\"IpAddress\", \"Bits\", \"MibIdentifier\", \"Integer32\", \"enterprises\", \"ModuleIdentity\", \"TimeTicks\", \"Counter32\", \"NotificationType\", \"iso\",", "1, 4, 1, 217, 16, 1, 1, 1), Counter32()).setMaxAccess(\"readonly\") if", "Counter32()).setMaxAccess(\"readonly\") if mibBuilder.loadTexts: mwMemUsed.setStatus('mandatory') if mibBuilder.loadTexts: mwMemUsed.setDescription(\"bytes of memory that", "1, 217, 16, 1, 2, 1), Counter32()).setMaxAccess(\"readonly\") if mibBuilder.loadTexts: mwHeapTotal.setStatus('mandatory')", "Mar 27 2019, 09:23:15) # ObjectIdentifier, OctetString, Integer = mibBuilder.importSymbols(\"ASN1\",", "IpAddress, Bits, MibIdentifier, Integer32, enterprises, ModuleIdentity, TimeTicks, Counter32, NotificationType, iso,", "enterprises, ModuleIdentity, TimeTicks, Counter32, NotificationType, iso, Counter64, MibScalar, MibTable, MibTableRow,", "mwHeapUsed.setDescription('bytes of available memory in the heap.') mibBuilder.exportSymbols(\"MWORKS-MIB\", mwHeap=mwHeap, mwHeapUsed=mwHeapUsed,", "1)) mwMem = MibIdentifier((1, 3, 6, 1, 4, 1, 217,", "\"ValueRangeConstraint\", \"SingleValueConstraint\", \"ConstraintsUnion\", \"ValueSizeConstraint\", \"ConstraintsIntersection\") ModuleCompliance, NotificationGroup = mibBuilder.importSymbols(\"SNMPv2-CONF\", \"ModuleCompliance\",", "\"ConstraintsUnion\", \"ValueSizeConstraint\", \"ConstraintsIntersection\") ModuleCompliance, NotificationGroup = mibBuilder.importSymbols(\"SNMPv2-CONF\", \"ModuleCompliance\", \"NotificationGroup\") Gauge32,", "1, 217, 16, 1)) mwMem = MibIdentifier((1, 3, 6, 1,", "mibBuilder.loadTexts: mwMemUsed.setStatus('mandatory') if mibBuilder.loadTexts: mwMemUsed.setDescription(\"bytes of memory that meterworks has", "Gauge32, Unsigned32, ObjectIdentity, IpAddress, Bits, MibIdentifier, Integer32, enterprises, ModuleIdentity, TimeTicks,", "1, 1)) mwHeap = MibIdentifier((1, 3, 6, 1, 4, 1,", "3, 6, 1, 4, 1, 217, 16)) mw501 = MibIdentifier((1,", "6, 1, 4, 1, 217, 16, 1, 2, 2), Counter32()).setMaxAccess(\"readonly\")", "mibBuilder.loadTexts: mwHeapUsed.setDescription('bytes of available memory in the heap.') mibBuilder.exportSymbols(\"MWORKS-MIB\", mwHeap=mwHeap,", "\"TimeTicks\", \"Counter32\", \"NotificationType\", \"iso\", \"Counter64\", \"MibScalar\", \"MibTable\", \"MibTableRow\", \"MibTableColumn\") TextualConvention,", "of this may be in free pools.\") mwHeapTotal = MibScalar((1,", "# ObjectIdentifier, OctetString, Integer = mibBuilder.importSymbols(\"ASN1\", \"ObjectIdentifier\", \"OctetString\", \"Integer\") NamedValues,", "# Produced by pysmi-0.3.4 at Wed May 1 14:16:04 2019", "\"ObjectIdentifier\", \"OctetString\", \"Integer\") NamedValues, = mibBuilder.importSymbols(\"ASN1-ENUMERATION\", \"NamedValues\") ValueRangeConstraint, SingleValueConstraint, ConstraintsUnion,", "# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user", "heap manager.') mwHeapUsed = MibScalar((1, 3, 6, 1, 4, 1,", "mwMemCeiling.setStatus('mandatory') if mibBuilder.loadTexts: mwMemCeiling.setDescription('bytes of memory the agent memory manager", "6, 1, 4, 1, 217, 16, 1, 1, 2), Counter32()).setMaxAccess(\"readonly\")", "heap.') mibBuilder.exportSymbols(\"MWORKS-MIB\", mwHeap=mwHeap, mwHeapUsed=mwHeapUsed, mwMemCeiling=mwMemCeiling, meterWorks=meterWorks, tecElite=tecElite, mwMem=mwMem, mw501=mw501, mwHeapTotal=mwHeapTotal,", "1, 4, 1, 217)) meterWorks = MibIdentifier((1, 3, 6, 1,", "ValueRangeConstraint, SingleValueConstraint, ConstraintsUnion, ValueSizeConstraint, ConstraintsIntersection = mibBuilder.importSymbols(\"ASN1-REFINEMENT\", \"ValueRangeConstraint\", \"SingleValueConstraint\", \"ConstraintsUnion\",", "version 18.5.0 by user davwang4 # Using Python version 3.7.3", "4, 1, 217, 16, 1, 1, 2), Counter32()).setMaxAccess(\"readonly\") if mibBuilder.loadTexts:", "217)) meterWorks = MibIdentifier((1, 3, 6, 1, 4, 1, 217,", "mibBuilder.importSymbols(\"ASN1-ENUMERATION\", \"NamedValues\") ValueRangeConstraint, SingleValueConstraint, ConstraintsUnion, ValueSizeConstraint, ConstraintsIntersection = mibBuilder.importSymbols(\"ASN1-REFINEMENT\", \"ValueRangeConstraint\",", "# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)", "\"enterprises\", \"ModuleIdentity\", \"TimeTicks\", \"Counter32\", \"NotificationType\", \"iso\", \"Counter64\", \"MibScalar\", \"MibTable\", \"MibTableRow\",", "# PySNMP MIB module MWORKS-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/MWORKS-MIB", "\"ModuleCompliance\", \"NotificationGroup\") Gauge32, Unsigned32, ObjectIdentity, IpAddress, Bits, MibIdentifier, Integer32, enterprises,", "if mibBuilder.loadTexts: mwMemUsed.setStatus('mandatory') if mibBuilder.loadTexts: mwMemUsed.setDescription(\"bytes of memory that meterworks", "16, 1, 2, 1), Counter32()).setMaxAccess(\"readonly\") if mibBuilder.loadTexts: mwHeapTotal.setStatus('mandatory') if mibBuilder.loadTexts:", "manager.') mwHeapUsed = MibScalar((1, 3, 6, 1, 4, 1, 217,", "1 14:16:04 2019 # On host DAVWANG4-M-1475 platform Darwin version", "3, 6, 1, 4, 1, 217, 16, 1, 2)) mwMemCeiling", "09:23:15) # ObjectIdentifier, OctetString, Integer = mibBuilder.importSymbols(\"ASN1\", \"ObjectIdentifier\", \"OctetString\", \"Integer\")", "\"MibScalar\", \"MibTable\", \"MibTableRow\", \"MibTableColumn\") TextualConvention, DisplayString = mibBuilder.importSymbols(\"SNMPv2-TC\", \"TextualConvention\", \"DisplayString\")", "ConstraintsUnion, ValueSizeConstraint, ConstraintsIntersection = mibBuilder.importSymbols(\"ASN1-REFINEMENT\", \"ValueRangeConstraint\", \"SingleValueConstraint\", \"ConstraintsUnion\", \"ValueSizeConstraint\", \"ConstraintsIntersection\")", "mibBuilder.loadTexts: mwHeapTotal.setDescription('bytes of memory given to the heap manager.') mwHeapUsed", "mwMemUsed.setStatus('mandatory') if mibBuilder.loadTexts: mwMemUsed.setDescription(\"bytes of memory that meterworks has malloc'ed.", "\"Gauge32\", \"Unsigned32\", \"ObjectIdentity\", \"IpAddress\", \"Bits\", \"MibIdentifier\", \"Integer32\", \"enterprises\", \"ModuleIdentity\", \"TimeTicks\",", "MibIdentifier((1, 3, 6, 1, 4, 1, 217, 16, 1, 1))", "1, 2, 1), Counter32()).setMaxAccess(\"readonly\") if mibBuilder.loadTexts: mwHeapTotal.setStatus('mandatory') if mibBuilder.loadTexts: mwHeapTotal.setDescription('bytes", "version 3.7.3 (default, Mar 27 2019, 09:23:15) # ObjectIdentifier, OctetString,", "mibBuilder.importSymbols(\"ASN1\", \"ObjectIdentifier\", \"OctetString\", \"Integer\") NamedValues, = mibBuilder.importSymbols(\"ASN1-ENUMERATION\", \"NamedValues\") ValueRangeConstraint, SingleValueConstraint,", "mibBuilder.importSymbols(\"SNMPv2-CONF\", \"ModuleCompliance\", \"NotificationGroup\") Gauge32, Unsigned32, ObjectIdentity, IpAddress, Bits, MibIdentifier, Integer32,", "mwMemCeiling = MibScalar((1, 3, 6, 1, 4, 1, 217, 16,", "mibBuilder.loadTexts: mwMemCeiling.setDescription('bytes of memory the agent memory manager will allow", "MibIdentifier((1, 3, 6, 1, 4, 1, 217, 16, 1, 2))", "1, 4, 1, 217, 16, 1, 1, 2), Counter32()).setMaxAccess(\"readonly\") if", "1), Counter32()).setMaxAccess(\"readonly\") if mibBuilder.loadTexts: mwHeapTotal.setStatus('mandatory') if mibBuilder.loadTexts: mwHeapTotal.setDescription('bytes of memory", "mwHeapTotal = MibScalar((1, 3, 6, 1, 4, 1, 217, 16,", "Produced by pysmi-0.3.4 at Wed May 1 14:16:04 2019 #", "\"MibTableRow\", \"MibTableColumn\") TextualConvention, DisplayString = mibBuilder.importSymbols(\"SNMPv2-TC\", \"TextualConvention\", \"DisplayString\") tecElite =", "18.5.0 by user davwang4 # Using Python version 3.7.3 (default,", "= MibScalar((1, 3, 6, 1, 4, 1, 217, 16, 1,", "memory the agent memory manager will allow the agent to", "of memory that meterworks has malloc'ed. some of this may", "if mibBuilder.loadTexts: mwHeapTotal.setDescription('bytes of memory given to the heap manager.')", "memory manager will allow the agent to use.') mwMemUsed =", "MibScalar((1, 3, 6, 1, 4, 1, 217, 16, 1, 1,", "6, 1, 4, 1, 217)) meterWorks = MibIdentifier((1, 3, 6,", "1, 1), Counter32()).setMaxAccess(\"readonly\") if mibBuilder.loadTexts: mwMemCeiling.setStatus('mandatory') if mibBuilder.loadTexts: mwMemCeiling.setDescription('bytes of", "memory that meterworks has malloc'ed. some of this may be", "ObjectIdentity, IpAddress, Bits, MibIdentifier, Integer32, enterprises, ModuleIdentity, TimeTicks, Counter32, NotificationType,", "MibTableRow, MibTableColumn = mibBuilder.importSymbols(\"SNMPv2-SMI\", \"Gauge32\", \"Unsigned32\", \"ObjectIdentity\", \"IpAddress\", \"Bits\", \"MibIdentifier\",", "in the heap.') mibBuilder.exportSymbols(\"MWORKS-MIB\", mwHeap=mwHeap, mwHeapUsed=mwHeapUsed, mwMemCeiling=mwMemCeiling, meterWorks=meterWorks, tecElite=tecElite, mwMem=mwMem,", "\"NamedValues\") ValueRangeConstraint, SingleValueConstraint, ConstraintsUnion, ValueSizeConstraint, ConstraintsIntersection = mibBuilder.importSymbols(\"ASN1-REFINEMENT\", \"ValueRangeConstraint\", \"SingleValueConstraint\",", "1, 4, 1, 217, 16)) mw501 = MibIdentifier((1, 3, 6,", "1, 4, 1, 217, 16, 1, 1)) mwHeap = MibIdentifier((1,", "May 1 14:16:04 2019 # On host DAVWANG4-M-1475 platform Darwin", "16, 1, 1, 1), Counter32()).setMaxAccess(\"readonly\") if mibBuilder.loadTexts: mwMemCeiling.setStatus('mandatory') if mibBuilder.loadTexts:", "if mibBuilder.loadTexts: mwMemCeiling.setDescription('bytes of memory the agent memory manager will", "= MibIdentifier((1, 3, 6, 1, 4, 1, 217, 16, 1))", "of memory the agent memory manager will allow the agent", "Bits, MibIdentifier, Integer32, enterprises, ModuleIdentity, TimeTicks, Counter32, NotificationType, iso, Counter64,", "4, 1, 217, 16, 1, 1)) mwHeap = MibIdentifier((1, 3,", "given to the heap manager.') mwHeapUsed = MibScalar((1, 3, 6,", "MibTableColumn = mibBuilder.importSymbols(\"SNMPv2-SMI\", \"Gauge32\", \"Unsigned32\", \"ObjectIdentity\", \"IpAddress\", \"Bits\", \"MibIdentifier\", \"Integer32\",", "1, 4, 1, 217, 16, 1, 2)) mwMemCeiling = MibScalar((1,", "Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # ObjectIdentifier,", "Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) #", "\"iso\", \"Counter64\", \"MibScalar\", \"MibTable\", \"MibTableRow\", \"MibTableColumn\") TextualConvention, DisplayString = mibBuilder.importSymbols(\"SNMPv2-TC\",", "1, 2), Counter32()).setMaxAccess(\"readonly\") if mibBuilder.loadTexts: mwMemUsed.setStatus('mandatory') if mibBuilder.loadTexts: mwMemUsed.setDescription(\"bytes of", "16)) mw501 = MibIdentifier((1, 3, 6, 1, 4, 1, 217,", "ObjectIdentifier, OctetString, Integer = mibBuilder.importSymbols(\"ASN1\", \"ObjectIdentifier\", \"OctetString\", \"Integer\") NamedValues, =", "mwHeapUsed = MibScalar((1, 3, 6, 1, 4, 1, 217, 16,", "1, 217, 16, 1, 2, 2), Counter32()).setMaxAccess(\"readonly\") if mibBuilder.loadTexts: mwHeapUsed.setStatus('mandatory')", "ModuleIdentity, TimeTicks, Counter32, NotificationType, iso, Counter64, MibScalar, MibTable, MibTableRow, MibTableColumn", "16, 1)) mwMem = MibIdentifier((1, 3, 6, 1, 4, 1,", "4, 1, 217)) meterWorks = MibIdentifier((1, 3, 6, 1, 4,", "be in free pools.\") mwHeapTotal = MibScalar((1, 3, 6, 1,", "3, 6, 1, 4, 1, 217, 16, 1, 1)) mwHeap", "by pysmi-0.3.4 at Wed May 1 14:16:04 2019 # On", "6, 1, 4, 1, 217, 16)) mw501 = MibIdentifier((1, 3,", "# # PySNMP MIB module MWORKS-MIB (http://snmplabs.com/pysmi) # ASN.1 source", "mibBuilder.loadTexts: mwHeapUsed.setStatus('mandatory') if mibBuilder.loadTexts: mwHeapUsed.setDescription('bytes of available memory in the", "host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 #", "in free pools.\") mwHeapTotal = MibScalar((1, 3, 6, 1, 4,", "NotificationType, iso, Counter64, MibScalar, MibTable, MibTableRow, MibTableColumn = mibBuilder.importSymbols(\"SNMPv2-SMI\", \"Gauge32\",", "tecElite = MibIdentifier((1, 3, 6, 1, 4, 1, 217)) meterWorks", "217, 16, 1, 1, 2), Counter32()).setMaxAccess(\"readonly\") if mibBuilder.loadTexts: mwMemUsed.setStatus('mandatory') if", "Counter32()).setMaxAccess(\"readonly\") if mibBuilder.loadTexts: mwHeapTotal.setStatus('mandatory') if mibBuilder.loadTexts: mwHeapTotal.setDescription('bytes of memory given", "(http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/MWORKS-MIB # Produced by pysmi-0.3.4 at", "= mibBuilder.importSymbols(\"ASN1-REFINEMENT\", \"ValueRangeConstraint\", \"SingleValueConstraint\", \"ConstraintsUnion\", \"ValueSizeConstraint\", \"ConstraintsIntersection\") ModuleCompliance, NotificationGroup =", "3, 6, 1, 4, 1, 217, 16, 1, 1, 1),", "iso, Counter64, MibScalar, MibTable, MibTableRow, MibTableColumn = mibBuilder.importSymbols(\"SNMPv2-SMI\", \"Gauge32\", \"Unsigned32\",", "217, 16)) mw501 = MibIdentifier((1, 3, 6, 1, 4, 1,", "217, 16, 1, 2, 2), Counter32()).setMaxAccess(\"readonly\") if mibBuilder.loadTexts: mwHeapUsed.setStatus('mandatory') if", "16, 1, 2, 2), Counter32()).setMaxAccess(\"readonly\") if mibBuilder.loadTexts: mwHeapUsed.setStatus('mandatory') if mibBuilder.loadTexts:", "3, 6, 1, 4, 1, 217, 16, 1)) mwMem =", "1), Counter32()).setMaxAccess(\"readonly\") if mibBuilder.loadTexts: mwMemCeiling.setStatus('mandatory') if mibBuilder.loadTexts: mwMemCeiling.setDescription('bytes of memory", "of available memory in the heap.') mibBuilder.exportSymbols(\"MWORKS-MIB\", mwHeap=mwHeap, mwHeapUsed=mwHeapUsed, mwMemCeiling=mwMemCeiling,", "by user davwang4 # Using Python version 3.7.3 (default, Mar", "\"ConstraintsIntersection\") ModuleCompliance, NotificationGroup = mibBuilder.importSymbols(\"SNMPv2-CONF\", \"ModuleCompliance\", \"NotificationGroup\") Gauge32, Unsigned32, ObjectIdentity,", "module MWORKS-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/MWORKS-MIB # Produced by", "ModuleCompliance, NotificationGroup = mibBuilder.importSymbols(\"SNMPv2-CONF\", \"ModuleCompliance\", \"NotificationGroup\") Gauge32, Unsigned32, ObjectIdentity, IpAddress,", "Darwin version 18.5.0 by user davwang4 # Using Python version", "Counter32, NotificationType, iso, Counter64, MibScalar, MibTable, MibTableRow, MibTableColumn = mibBuilder.importSymbols(\"SNMPv2-SMI\",", "memory given to the heap manager.') mwHeapUsed = MibScalar((1, 3,", "of memory given to the heap manager.') mwHeapUsed = MibScalar((1,", "Counter64, MibScalar, MibTable, MibTableRow, MibTableColumn = mibBuilder.importSymbols(\"SNMPv2-SMI\", \"Gauge32\", \"Unsigned32\", \"ObjectIdentity\",", "pools.\") mwHeapTotal = MibScalar((1, 3, 6, 1, 4, 1, 217,", "allow the agent to use.') mwMemUsed = MibScalar((1, 3, 6,", "1, 217, 16, 1, 1)) mwHeap = MibIdentifier((1, 3, 6,", "= mibBuilder.importSymbols(\"ASN1-ENUMERATION\", \"NamedValues\") ValueRangeConstraint, SingleValueConstraint, ConstraintsUnion, ValueSizeConstraint, ConstraintsIntersection = mibBuilder.importSymbols(\"ASN1-REFINEMENT\",", "1, 4, 1, 217, 16, 1)) mwMem = MibIdentifier((1, 3,", "available memory in the heap.') mibBuilder.exportSymbols(\"MWORKS-MIB\", mwHeap=mwHeap, mwHeapUsed=mwHeapUsed, mwMemCeiling=mwMemCeiling, meterWorks=meterWorks,", "1, 217)) meterWorks = MibIdentifier((1, 3, 6, 1, 4, 1,", "user davwang4 # Using Python version 3.7.3 (default, Mar 27", "if mibBuilder.loadTexts: mwMemUsed.setDescription(\"bytes of memory that meterworks has malloc'ed. some", "\"Integer32\", \"enterprises\", \"ModuleIdentity\", \"TimeTicks\", \"Counter32\", \"NotificationType\", \"iso\", \"Counter64\", \"MibScalar\", \"MibTable\",", "pysmi-0.3.4 at Wed May 1 14:16:04 2019 # On host", "4, 1, 217, 16, 1, 1, 1), Counter32()).setMaxAccess(\"readonly\") if mibBuilder.loadTexts:", "\"MibTableColumn\") TextualConvention, DisplayString = mibBuilder.importSymbols(\"SNMPv2-TC\", \"TextualConvention\", \"DisplayString\") tecElite = MibIdentifier((1,", "217, 16, 1, 2)) mwMemCeiling = MibScalar((1, 3, 6, 1,", "mw501 = MibIdentifier((1, 3, 6, 1, 4, 1, 217, 16,", "27 2019, 09:23:15) # ObjectIdentifier, OctetString, Integer = mibBuilder.importSymbols(\"ASN1\", \"ObjectIdentifier\",", "1, 217, 16, 1, 1, 1), Counter32()).setMaxAccess(\"readonly\") if mibBuilder.loadTexts: mwMemCeiling.setStatus('mandatory')", "= mibBuilder.importSymbols(\"SNMPv2-SMI\", \"Gauge32\", \"Unsigned32\", \"ObjectIdentity\", \"IpAddress\", \"Bits\", \"MibIdentifier\", \"Integer32\", \"enterprises\",", "# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/MWORKS-MIB # Produced by pysmi-0.3.4 at Wed", "mwMemCeiling.setDescription('bytes of memory the agent memory manager will allow the", "mwHeapUsed.setStatus('mandatory') if mibBuilder.loadTexts: mwHeapUsed.setDescription('bytes of available memory in the heap.')", "\"Counter32\", \"NotificationType\", \"iso\", \"Counter64\", \"MibScalar\", \"MibTable\", \"MibTableRow\", \"MibTableColumn\") TextualConvention, DisplayString", "6, 1, 4, 1, 217, 16, 1, 1, 1), Counter32()).setMaxAccess(\"readonly\")", "Wed May 1 14:16:04 2019 # On host DAVWANG4-M-1475 platform", "manager will allow the agent to use.') mwMemUsed = MibScalar((1,", "use.') mwMemUsed = MibScalar((1, 3, 6, 1, 4, 1, 217,", "\"ValueSizeConstraint\", \"ConstraintsIntersection\") ModuleCompliance, NotificationGroup = mibBuilder.importSymbols(\"SNMPv2-CONF\", \"ModuleCompliance\", \"NotificationGroup\") Gauge32, Unsigned32,", "1, 1, 1), Counter32()).setMaxAccess(\"readonly\") if mibBuilder.loadTexts: mwMemCeiling.setStatus('mandatory') if mibBuilder.loadTexts: mwMemCeiling.setDescription('bytes", "\"MibIdentifier\", \"Integer32\", \"enterprises\", \"ModuleIdentity\", \"TimeTicks\", \"Counter32\", \"NotificationType\", \"iso\", \"Counter64\", \"MibScalar\",", "this may be in free pools.\") mwHeapTotal = MibScalar((1, 3,", "that meterworks has malloc'ed. some of this may be in", "MibScalar((1, 3, 6, 1, 4, 1, 217, 16, 1, 2,", "MIB module MWORKS-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/MWORKS-MIB # Produced", "mibBuilder.importSymbols(\"SNMPv2-SMI\", \"Gauge32\", \"Unsigned32\", \"ObjectIdentity\", \"IpAddress\", \"Bits\", \"MibIdentifier\", \"Integer32\", \"enterprises\", \"ModuleIdentity\",", "mibBuilder.loadTexts: mwMemUsed.setDescription(\"bytes of memory that meterworks has malloc'ed. some of", "agent memory manager will allow the agent to use.') mwMemUsed", "the heap manager.') mwHeapUsed = MibScalar((1, 3, 6, 1, 4,", "platform Darwin version 18.5.0 by user davwang4 # Using Python", "MibTable, MibTableRow, MibTableColumn = mibBuilder.importSymbols(\"SNMPv2-SMI\", \"Gauge32\", \"Unsigned32\", \"ObjectIdentity\", \"IpAddress\", \"Bits\",", "if mibBuilder.loadTexts: mwHeapUsed.setDescription('bytes of available memory in the heap.') mibBuilder.exportSymbols(\"MWORKS-MIB\",", "ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/MWORKS-MIB # Produced by pysmi-0.3.4 at Wed May", "6, 1, 4, 1, 217, 16, 1)) mwMem = MibIdentifier((1,", "to use.') mwMemUsed = MibScalar((1, 3, 6, 1, 4, 1,", "mwMemUsed.setDescription(\"bytes of memory that meterworks has malloc'ed. some of this", "3, 6, 1, 4, 1, 217)) meterWorks = MibIdentifier((1, 3,", "file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/MWORKS-MIB # Produced by pysmi-0.3.4 at Wed May 1 14:16:04", "On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4", "meterworks has malloc'ed. some of this may be in free", "2, 1), Counter32()).setMaxAccess(\"readonly\") if mibBuilder.loadTexts: mwHeapTotal.setStatus('mandatory') if mibBuilder.loadTexts: mwHeapTotal.setDescription('bytes of", "\"Counter64\", \"MibScalar\", \"MibTable\", \"MibTableRow\", \"MibTableColumn\") TextualConvention, DisplayString = mibBuilder.importSymbols(\"SNMPv2-TC\", \"TextualConvention\",", "meterWorks = MibIdentifier((1, 3, 6, 1, 4, 1, 217, 16))", "malloc'ed. some of this may be in free pools.\") mwHeapTotal", "mwHeapTotal.setStatus('mandatory') if mibBuilder.loadTexts: mwHeapTotal.setDescription('bytes of memory given to the heap", "mwHeapTotal.setDescription('bytes of memory given to the heap manager.') mwHeapUsed =", "2, 2), Counter32()).setMaxAccess(\"readonly\") if mibBuilder.loadTexts: mwHeapUsed.setStatus('mandatory') if mibBuilder.loadTexts: mwHeapUsed.setDescription('bytes of", "3, 6, 1, 4, 1, 217, 16, 1, 2, 1),", "Integer = mibBuilder.importSymbols(\"ASN1\", \"ObjectIdentifier\", \"OctetString\", \"Integer\") NamedValues, = mibBuilder.importSymbols(\"ASN1-ENUMERATION\", \"NamedValues\")" ]
[ "if re_objc_excep.match(line): #Log(\"matched line: {0}\", re_objc_excep.match(line).group()) line = line.replace(\"NO\",\"YES\") Log(\"Objective-c", "sdk path. code: {0}, err: {1}\", proc.returncode, err) return None", "not in [0, 66]: Log(\"Could not retrieve Xcode sdk path.", "rewrite_unity_xcode_project(Log, unity_xcode_project_path): unity_xcode_lines = [] # Allow objective-c exceptions re_objc_excep", "project generated by unity3d\") with open('MpireNxusMeasurementPostBuildiOSLog.txt', 'w') as fileLog: #", "# Path of the Xcode SDK on the system. xcode_sdk_path", "as upf: for line in upf: if re_objc_excep.match(line): #Log(\"matched line:", "project using mod_pbxproj: # - Add the adSupport framework library.", "Log(\"Xcode sdk path: {0}\", xcode_sdk_path) return xcode_sdk_path if __name__ ==", "return None match = re.search(\"iPhoneOS.*?Path: (?P<sdk_path>.*?)\\n\", out, re.DOTALL) xcode_sdk_path =", "{0}\", unity_xcode_project_path) framework_path = xcode_sdk_path + \"/System/Library/Frameworks/\" Log(\"framework path: {0}\",", "match = re.search(\"iPhoneOS.*?Path: (?P<sdk_path>.*?)\\n\", out, re.DOTALL) xcode_sdk_path = match.group('sdk_path') if", "return unity_xcode_project_path, framework_path def edit_unity_xcode_project(Log, unity_xcode_project_path, framework_path): # load unity", "FileOptions(embed_framework=False, weak=True) unity_XcodeProject.add_file(framework_path + \"Security.framework\", parent=frameworks, tree='SDKROOT', force=False, file_options=file_options_security_framework) Log(\"added", "open(unity_xcode_project_path) as upf: for line in upf: if re_objc_excep.match(line): #Log(\"matched", "iOS Xcode project and framework on the system. unity_xcode_project_path, framework_path", "\"-version\", \"-sdk\"], stdout=PIPE, stderr=PIPE) out, err = proc.communicate() if proc.returncode", "line.replace(\"NO\",\"YES\") Log(\"Objective-c exceptions enabled\") unity_xcode_lines.append(line) with open(unity_xcode_project_path, \"w+\") as upf:", "# Path for unity iOS Xcode project and framework on", "Log(\"Unity3d Xcode project path: {0}\", unity_xcode_project_path) framework_path = xcode_sdk_path +", "stderr=PIPE) out, err = proc.communicate() if proc.returncode not in [0,", "re_objc_excep.match(line).group()) line = line.replace(\"NO\",\"YES\") Log(\"Objective-c exceptions enabled\") unity_xcode_lines.append(line) with open(unity_xcode_project_path,", "LogInput(fileLog) # Path of the Xcode SDK on the system.", "{0}\", re_objc_excep.match(line).group()) line = line.replace(\"NO\",\"YES\") Log(\"Objective-c exceptions enabled\") unity_xcode_lines.append(line) with", "message else \"None\") + \"\\n\" writeObject.write(messageNLine.format(*args)) return Log def get_paths(Log,", "subprocess import Popen, PIPE import argparse from pbxproj import XcodeProject,", "project file unity_XcodeProject = XcodeProject.load(unity_xcode_project_path) frameworks = unity_XcodeProject.get_or_create_group('Frameworks') file_options_security_framework =", "on the system. xcode_sdk_path = get_xcode_sdk_path(LogFunc) # Path for unity", "None match = re.search(\"iPhoneOS.*?Path: (?P<sdk_path>.*?)\\n\", out, re.DOTALL) xcode_sdk_path = match.group('sdk_path')", "sys.exit(0) def LogInput(writeObject): def Log(message, *args): messageNLine = (message if", "load unity iOS pbxproj project file unity_XcodeProject = XcodeProject.load(unity_xcode_project_path) frameworks", "upf: for line in upf: if re_objc_excep.match(line): #Log(\"matched line: {0}\",", "directly: # - Allow objective-c exceptions # rewrite_unity_xcode_project(LogFunc, unity_xcode_project_path) sys.exit(0)", "LogFunc = LogInput(fileLog) # Path of the Xcode SDK on", "Log function with file injected. LogFunc = LogInput(fileLog) # Path", "Allow objective-c exceptions re_objc_excep = re.compile(r\"\\s*GCC_ENABLE_OBJC_EXCEPTIONS *= *NO.*\") with open(unity_xcode_project_path)", "# load unity iOS pbxproj project file unity_XcodeProject = XcodeProject.load(unity_xcode_project_path)", "messageNLine = (message if message else \"None\") + \"\\n\" writeObject.write(messageNLine.format(*args))", "to \"Other Linker Flags\" project settings. unity_XcodeProject.add_other_ldflags('-ObjC') # Save changes.", "def get_xcode_sdk_path(Log): # Output all info from Xcode. proc =", "re.DOTALL) xcode_sdk_path = match.group('sdk_path') if match else None Log(\"Xcode sdk", "parser, xcode_sdk_path) # Edit the Xcode project using mod_pbxproj: #", "= (message if message else \"None\") + \"\\n\" writeObject.write(messageNLine.format(*args)) return", "ignored_args = parser.parse_known_args() ios_project_path = args.ios_project_path unity_xcode_project_path = ios_project_path +", "*= *NO.*\") with open(unity_xcode_project_path) as upf: for line in upf:", "# - Change the compilation flags of the adjust project", "\"None\") + \"\\n\" writeObject.write(messageNLine.format(*args)) return Log def get_paths(Log, parser, xcode_sdk_path):", "import FileOptions def main(): parser = argparse.ArgumentParser(description=\"MpireNxusMeasurement post build iOS", "#Log(\"matched line: {0}\", re_objc_excep.match(line).group()) line = line.replace(\"NO\",\"YES\") Log(\"Objective-c exceptions enabled\")", "-ObjC to \"Other Linker Flags\" project settings. unity_XcodeProject.add_other_ldflags('-ObjC') # Save", "= line.replace(\"NO\",\"YES\") Log(\"Objective-c exceptions enabled\") unity_xcode_lines.append(line) with open(unity_xcode_project_path, \"w+\") as", "injected. LogFunc = LogInput(fileLog) # Path of the Xcode SDK", "frameworks = unity_XcodeProject.get_or_create_group('Frameworks') file_options_security_framework = FileOptions(embed_framework=False, weak=True) unity_XcodeProject.add_file(framework_path + \"Security.framework\",", "framework library. # - Add the iAd framework library. #", "script\") parser.add_argument('ios_project_path', help=\"path to the folder of the iOS project", "using mod_pbxproj: # - Add the adSupport framework library. #", "the Xcode SDK on the system. xcode_sdk_path = get_xcode_sdk_path(LogFunc) #", "exceptions enabled\") unity_xcode_lines.append(line) with open(unity_xcode_project_path, \"w+\") as upf: upf.writelines(unity_xcode_lines) def", "unity_xcode_project_path): unity_xcode_lines = [] # Allow objective-c exceptions re_objc_excep =", "system. xcode_sdk_path = get_xcode_sdk_path(LogFunc) # Path for unity iOS Xcode", "Save changes. unity_XcodeProject.save() def rewrite_unity_xcode_project(Log, unity_xcode_project_path): unity_xcode_lines = [] #", "Path for unity iOS Xcode project and framework on the", "Xcode project path: {0}\", unity_xcode_project_path) framework_path = xcode_sdk_path + \"/System/Library/Frameworks/\"", "ios_project_path + \"/Unity-iPhone.xcodeproj/project.pbxproj\" Log(\"Unity3d Xcode project path: {0}\", unity_xcode_project_path) framework_path", "import argparse from pbxproj import XcodeProject, TreeType from pbxproj import", "Flags\" project settings. unity_XcodeProject.add_other_ldflags('-ObjC') # Save changes. unity_XcodeProject.save() def rewrite_unity_xcode_project(Log,", "+ \"/System/Library/Frameworks/\" Log(\"framework path: {0}\", framework_path) return unity_xcode_project_path, framework_path def", "unity_xcode_project_path) framework_path = xcode_sdk_path + \"/System/Library/Frameworks/\" Log(\"framework path: {0}\", framework_path)", "framework on the system. unity_xcode_project_path, framework_path = get_paths(LogFunc, parser, xcode_sdk_path)", "with open(unity_xcode_project_path) as upf: for line in upf: if re_objc_excep.match(line):", "import re from subprocess import Popen, PIPE import argparse from", "def LogInput(writeObject): def Log(message, *args): messageNLine = (message if message", "= LogInput(fileLog) # Path of the Xcode SDK on the", "Xcode. proc = Popen([\"xcodebuild\", \"-version\", \"-sdk\"], stdout=PIPE, stderr=PIPE) out, err", "project path: {0}\", unity_xcode_project_path) framework_path = xcode_sdk_path + \"/System/Library/Frameworks/\" Log(\"framework", "framework_path = get_paths(LogFunc, parser, xcode_sdk_path) # Edit the Xcode project", "rewrite_unity_xcode_project(LogFunc, unity_xcode_project_path) sys.exit(0) def LogInput(writeObject): def Log(message, *args): messageNLine =", "the compilation flags of the adjust project files to support", "= ios_project_path + \"/Unity-iPhone.xcodeproj/project.pbxproj\" Log(\"Unity3d Xcode project path: {0}\", unity_xcode_project_path)", "+ \"Security.framework\", parent=frameworks, tree='SDKROOT', force=False, file_options=file_options_security_framework) Log(\"added Security framework\") #", "# Output all info from Xcode. proc = Popen([\"xcodebuild\", \"-version\",", "as upf: upf.writelines(unity_xcode_lines) def get_xcode_sdk_path(Log): # Output all info from", "{1}\", proc.returncode, err) return None match = re.search(\"iPhoneOS.*?Path: (?P<sdk_path>.*?)\\n\", out,", "PIPE import argparse from pbxproj import XcodeProject, TreeType from pbxproj", "Log(\"Objective-c exceptions enabled\") unity_xcode_lines.append(line) with open(unity_xcode_project_path, \"w+\") as upf: upf.writelines(unity_xcode_lines)", "info from Xcode. proc = Popen([\"xcodebuild\", \"-version\", \"-sdk\"], stdout=PIPE, stderr=PIPE)", "xcode_sdk_path = get_xcode_sdk_path(LogFunc) # Path for unity iOS Xcode project", "Add -ObjC to \"Other Linker Flags\" project settings. unity_XcodeProject.add_other_ldflags('-ObjC') #", "project and framework on the system. unity_xcode_project_path, framework_path = get_paths(LogFunc,", "framework\") # Add -ObjC to \"Other Linker Flags\" project settings.", "from pbxproj import XcodeProject, TreeType from pbxproj import FileOptions def", "# Add -ObjC to \"Other Linker Flags\" project settings. unity_XcodeProject.add_other_ldflags('-ObjC')", "[] # Allow objective-c exceptions re_objc_excep = re.compile(r\"\\s*GCC_ENABLE_OBJC_EXCEPTIONS *= *NO.*\")", "all info from Xcode. proc = Popen([\"xcodebuild\", \"-version\", \"-sdk\"], stdout=PIPE,", "mod_pbxproj: # - Add the adSupport framework library. # -", "xcode_sdk_path + \"/System/Library/Frameworks/\" Log(\"framework path: {0}\", framework_path) return unity_xcode_project_path, framework_path", "argparse from pbxproj import XcodeProject, TreeType from pbxproj import FileOptions", "unity_XcodeProject = XcodeProject.load(unity_xcode_project_path) frameworks = unity_XcodeProject.get_or_create_group('Frameworks') file_options_security_framework = FileOptions(embed_framework=False, weak=True)", "xcode_sdk_path = match.group('sdk_path') if match else None Log(\"Xcode sdk path:", "path. code: {0}, err: {1}\", proc.returncode, err) return None match", "XcodeProject, TreeType from pbxproj import FileOptions def main(): parser =", "- Allow objective-c exceptions # rewrite_unity_xcode_project(LogFunc, unity_xcode_project_path) sys.exit(0) def LogInput(writeObject):", "SDK on the system. xcode_sdk_path = get_xcode_sdk_path(LogFunc) # Path for", "\"w+\") as upf: upf.writelines(unity_xcode_lines) def get_xcode_sdk_path(Log): # Output all info", "None Log(\"Xcode sdk path: {0}\", xcode_sdk_path) return xcode_sdk_path if __name__", "force=False, file_options=file_options_security_framework) Log(\"added Security framework\") # Add -ObjC to \"Other", "Xcode project directly: # - Allow objective-c exceptions # rewrite_unity_xcode_project(LogFunc,", "library. # - Add the iAd framework library. # -", "path: {0}\", framework_path) return unity_xcode_project_path, framework_path def edit_unity_xcode_project(Log, unity_xcode_project_path, framework_path):", "the folder of the iOS project generated by unity3d\") with", "with open(unity_xcode_project_path, \"w+\") as upf: upf.writelines(unity_xcode_lines) def get_xcode_sdk_path(Log): # Output", "unity_xcode_project_path, framework_path) # Removed. # Change the Xcode project directly:", "# Log function with file injected. LogFunc = LogInput(fileLog) #", "proc.returncode, err) return None match = re.search(\"iPhoneOS.*?Path: (?P<sdk_path>.*?)\\n\", out, re.DOTALL)", "match else None Log(\"Xcode sdk path: {0}\", xcode_sdk_path) return xcode_sdk_path", "def get_paths(Log, parser, xcode_sdk_path): args, ignored_args = parser.parse_known_args() ios_project_path =", "sdk path: {0}\", xcode_sdk_path) return xcode_sdk_path if __name__ == \"__main__\":", "path: {0}\", xcode_sdk_path) return xcode_sdk_path if __name__ == \"__main__\": main()", "of the iOS project generated by unity3d\") with open('MpireNxusMeasurementPostBuildiOSLog.txt', 'w')", "= match.group('sdk_path') if match else None Log(\"Xcode sdk path: {0}\",", "enabled\") unity_xcode_lines.append(line) with open(unity_xcode_project_path, \"w+\") as upf: upf.writelines(unity_xcode_lines) def get_xcode_sdk_path(Log):", "pbxproj import XcodeProject, TreeType from pbxproj import FileOptions def main():", "\"-sdk\"], stdout=PIPE, stderr=PIPE) out, err = proc.communicate() if proc.returncode not", "out, err = proc.communicate() if proc.returncode not in [0, 66]:", "err = proc.communicate() if proc.returncode not in [0, 66]: Log(\"Could", "'w') as fileLog: # Log function with file injected. LogFunc", "Path of the Xcode SDK on the system. xcode_sdk_path =", "upf: upf.writelines(unity_xcode_lines) def get_xcode_sdk_path(Log): # Output all info from Xcode.", "open('MpireNxusMeasurementPostBuildiOSLog.txt', 'w') as fileLog: # Log function with file injected.", "file_options=file_options_security_framework) Log(\"added Security framework\") # Add -ObjC to \"Other Linker", "objective-c exceptions # rewrite_unity_xcode_project(LogFunc, unity_xcode_project_path) sys.exit(0) def LogInput(writeObject): def Log(message,", "*args): messageNLine = (message if message else \"None\") + \"\\n\"", "args, ignored_args = parser.parse_known_args() ios_project_path = args.ios_project_path unity_xcode_project_path = ios_project_path", "generated by unity3d\") with open('MpireNxusMeasurementPostBuildiOSLog.txt', 'w') as fileLog: # Log", "library. # - Change the compilation flags of the adjust", "Log(\"added Security framework\") # Add -ObjC to \"Other Linker Flags\"", "project directly: # - Allow objective-c exceptions # rewrite_unity_xcode_project(LogFunc, unity_xcode_project_path)", "system. unity_xcode_project_path, framework_path = get_paths(LogFunc, parser, xcode_sdk_path) # Edit the", "unity iOS Xcode project and framework on the system. unity_xcode_project_path,", "return Log def get_paths(Log, parser, xcode_sdk_path): args, ignored_args = parser.parse_known_args()", "get_paths(Log, parser, xcode_sdk_path): args, ignored_args = parser.parse_known_args() ios_project_path = args.ios_project_path", "unity3d\") with open('MpireNxusMeasurementPostBuildiOSLog.txt', 'w') as fileLog: # Log function with", "out, re.DOTALL) xcode_sdk_path = match.group('sdk_path') if match else None Log(\"Xcode", "def rewrite_unity_xcode_project(Log, unity_xcode_project_path): unity_xcode_lines = [] # Allow objective-c exceptions", "the iAd framework library. # - Change the compilation flags", "line: {0}\", re_objc_excep.match(line).group()) line = line.replace(\"NO\",\"YES\") Log(\"Objective-c exceptions enabled\") unity_xcode_lines.append(line)", "= re.compile(r\"\\s*GCC_ENABLE_OBJC_EXCEPTIONS *= *NO.*\") with open(unity_xcode_project_path) as upf: for line", "fileLog: # Log function with file injected. LogFunc = LogInput(fileLog)", "# Change the Xcode project directly: # - Allow objective-c", "file_options_security_framework = FileOptions(embed_framework=False, weak=True) unity_XcodeProject.add_file(framework_path + \"Security.framework\", parent=frameworks, tree='SDKROOT', force=False,", "args.ios_project_path unity_xcode_project_path = ios_project_path + \"/Unity-iPhone.xcodeproj/project.pbxproj\" Log(\"Unity3d Xcode project path:", "parser.parse_known_args() ios_project_path = args.ios_project_path unity_xcode_project_path = ios_project_path + \"/Unity-iPhone.xcodeproj/project.pbxproj\" Log(\"Unity3d", "objective-c exceptions re_objc_excep = re.compile(r\"\\s*GCC_ENABLE_OBJC_EXCEPTIONS *= *NO.*\") with open(unity_xcode_project_path) as", "*NO.*\") with open(unity_xcode_project_path) as upf: for line in upf: if", "main(): parser = argparse.ArgumentParser(description=\"MpireNxusMeasurement post build iOS script\") parser.add_argument('ios_project_path', help=\"path", "# - Add the adSupport framework library. # - Add", "Xcode project and framework on the system. unity_xcode_project_path, framework_path =", "{0}\", framework_path) return unity_xcode_project_path, framework_path def edit_unity_xcode_project(Log, unity_xcode_project_path, framework_path): #", "path: {0}\", unity_xcode_project_path) framework_path = xcode_sdk_path + \"/System/Library/Frameworks/\" Log(\"framework path:", "line = line.replace(\"NO\",\"YES\") Log(\"Objective-c exceptions enabled\") unity_xcode_lines.append(line) with open(unity_xcode_project_path, \"w+\")", "re.compile(r\"\\s*GCC_ENABLE_OBJC_EXCEPTIONS *= *NO.*\") with open(unity_xcode_project_path) as upf: for line in", "= re.search(\"iPhoneOS.*?Path: (?P<sdk_path>.*?)\\n\", out, re.DOTALL) xcode_sdk_path = match.group('sdk_path') if match", "in upf: if re_objc_excep.match(line): #Log(\"matched line: {0}\", re_objc_excep.match(line).group()) line =", "err) return None match = re.search(\"iPhoneOS.*?Path: (?P<sdk_path>.*?)\\n\", out, re.DOTALL) xcode_sdk_path", "Popen, PIPE import argparse from pbxproj import XcodeProject, TreeType from", "= get_paths(LogFunc, parser, xcode_sdk_path) # Edit the Xcode project using", "proc = Popen([\"xcodebuild\", \"-version\", \"-sdk\"], stdout=PIPE, stderr=PIPE) out, err =", "unity iOS pbxproj project file unity_XcodeProject = XcodeProject.load(unity_xcode_project_path) frameworks =", "unity_XcodeProject.add_other_ldflags('-ObjC') # Save changes. unity_XcodeProject.save() def rewrite_unity_xcode_project(Log, unity_xcode_project_path): unity_xcode_lines =", "Security framework\") # Add -ObjC to \"Other Linker Flags\" project", "Output all info from Xcode. proc = Popen([\"xcodebuild\", \"-version\", \"-sdk\"],", "if proc.returncode not in [0, 66]: Log(\"Could not retrieve Xcode", "file unity_XcodeProject = XcodeProject.load(unity_xcode_project_path) frameworks = unity_XcodeProject.get_or_create_group('Frameworks') file_options_security_framework = FileOptions(embed_framework=False,", "from subprocess import Popen, PIPE import argparse from pbxproj import", "\"/Unity-iPhone.xcodeproj/project.pbxproj\" Log(\"Unity3d Xcode project path: {0}\", unity_xcode_project_path) framework_path = xcode_sdk_path", "retrieve Xcode sdk path. code: {0}, err: {1}\", proc.returncode, err)", "upf.writelines(unity_xcode_lines) def get_xcode_sdk_path(Log): # Output all info from Xcode. proc", "FileOptions def main(): parser = argparse.ArgumentParser(description=\"MpireNxusMeasurement post build iOS script\")", "Popen([\"xcodebuild\", \"-version\", \"-sdk\"], stdout=PIPE, stderr=PIPE) out, err = proc.communicate() if", "iOS pbxproj project file unity_XcodeProject = XcodeProject.load(unity_xcode_project_path) frameworks = unity_XcodeProject.get_or_create_group('Frameworks')", "line in upf: if re_objc_excep.match(line): #Log(\"matched line: {0}\", re_objc_excep.match(line).group()) line", "support non-ARC. edit_unity_xcode_project(LogFunc, unity_xcode_project_path, framework_path) # Removed. # Change the", "66]: Log(\"Could not retrieve Xcode sdk path. code: {0}, err:", "def main(): parser = argparse.ArgumentParser(description=\"MpireNxusMeasurement post build iOS script\") parser.add_argument('ios_project_path',", "xcode_sdk_path) # Edit the Xcode project using mod_pbxproj: # -", "by unity3d\") with open('MpireNxusMeasurementPostBuildiOSLog.txt', 'w') as fileLog: # Log function", "= args.ios_project_path unity_xcode_project_path = ios_project_path + \"/Unity-iPhone.xcodeproj/project.pbxproj\" Log(\"Unity3d Xcode project", "with open('MpireNxusMeasurementPostBuildiOSLog.txt', 'w') as fileLog: # Log function with file", "framework_path) return unity_xcode_project_path, framework_path def edit_unity_xcode_project(Log, unity_xcode_project_path, framework_path): # load", "# Edit the Xcode project using mod_pbxproj: # - Add", "{0}, err: {1}\", proc.returncode, err) return None match = re.search(\"iPhoneOS.*?Path:", "function with file injected. LogFunc = LogInput(fileLog) # Path of", "= proc.communicate() if proc.returncode not in [0, 66]: Log(\"Could not", "files to support non-ARC. edit_unity_xcode_project(LogFunc, unity_xcode_project_path, framework_path) # Removed. #", "compilation flags of the adjust project files to support non-ARC.", "proc.communicate() if proc.returncode not in [0, 66]: Log(\"Could not retrieve", "def edit_unity_xcode_project(Log, unity_xcode_project_path, framework_path): # load unity iOS pbxproj project", "Log(message, *args): messageNLine = (message if message else \"None\") +", "parser.add_argument('ios_project_path', help=\"path to the folder of the iOS project generated", "exceptions re_objc_excep = re.compile(r\"\\s*GCC_ENABLE_OBJC_EXCEPTIONS *= *NO.*\") with open(unity_xcode_project_path) as upf:", "build iOS script\") parser.add_argument('ios_project_path', help=\"path to the folder of the", "Change the Xcode project directly: # - Allow objective-c exceptions", "non-ARC. edit_unity_xcode_project(LogFunc, unity_xcode_project_path, framework_path) # Removed. # Change the Xcode", "framework_path): # load unity iOS pbxproj project file unity_XcodeProject =", "unity_XcodeProject.add_file(framework_path + \"Security.framework\", parent=frameworks, tree='SDKROOT', force=False, file_options=file_options_security_framework) Log(\"added Security framework\")", "of the adjust project files to support non-ARC. edit_unity_xcode_project(LogFunc, unity_xcode_project_path,", "pbxproj import FileOptions def main(): parser = argparse.ArgumentParser(description=\"MpireNxusMeasurement post build", "# Allow objective-c exceptions re_objc_excep = re.compile(r\"\\s*GCC_ENABLE_OBJC_EXCEPTIONS *= *NO.*\") with", "the Xcode project using mod_pbxproj: # - Add the adSupport", "Log def get_paths(Log, parser, xcode_sdk_path): args, ignored_args = parser.parse_known_args() ios_project_path", "ios_project_path = args.ios_project_path unity_xcode_project_path = ios_project_path + \"/Unity-iPhone.xcodeproj/project.pbxproj\" Log(\"Unity3d Xcode", "adSupport framework library. # - Add the iAd framework library.", "code: {0}, err: {1}\", proc.returncode, err) return None match =", "get_xcode_sdk_path(Log): # Output all info from Xcode. proc = Popen([\"xcodebuild\",", "if message else \"None\") + \"\\n\" writeObject.write(messageNLine.format(*args)) return Log def", "iOS project generated by unity3d\") with open('MpireNxusMeasurementPostBuildiOSLog.txt', 'w') as fileLog:", "pbxproj project file unity_XcodeProject = XcodeProject.load(unity_xcode_project_path) frameworks = unity_XcodeProject.get_or_create_group('Frameworks') file_options_security_framework", "for line in upf: if re_objc_excep.match(line): #Log(\"matched line: {0}\", re_objc_excep.match(line).group())", "Change the compilation flags of the adjust project files to", "as fileLog: # Log function with file injected. LogFunc =", "xcode_sdk_path): args, ignored_args = parser.parse_known_args() ios_project_path = args.ios_project_path unity_xcode_project_path =", "proc.returncode not in [0, 66]: Log(\"Could not retrieve Xcode sdk", "Log(\"Could not retrieve Xcode sdk path. code: {0}, err: {1}\",", "argparse.ArgumentParser(description=\"MpireNxusMeasurement post build iOS script\") parser.add_argument('ios_project_path', help=\"path to the folder", "get_paths(LogFunc, parser, xcode_sdk_path) # Edit the Xcode project using mod_pbxproj:", "and framework on the system. unity_xcode_project_path, framework_path = get_paths(LogFunc, parser,", "the adjust project files to support non-ARC. edit_unity_xcode_project(LogFunc, unity_xcode_project_path, framework_path)", "help=\"path to the folder of the iOS project generated by", "# Removed. # Change the Xcode project directly: # -", "- Add the iAd framework library. # - Change the", "\"Other Linker Flags\" project settings. unity_XcodeProject.add_other_ldflags('-ObjC') # Save changes. unity_XcodeProject.save()", "from Xcode. proc = Popen([\"xcodebuild\", \"-version\", \"-sdk\"], stdout=PIPE, stderr=PIPE) out,", "(?P<sdk_path>.*?)\\n\", out, re.DOTALL) xcode_sdk_path = match.group('sdk_path') if match else None", "for unity iOS Xcode project and framework on the system.", "= XcodeProject.load(unity_xcode_project_path) frameworks = unity_XcodeProject.get_or_create_group('Frameworks') file_options_security_framework = FileOptions(embed_framework=False, weak=True) unity_XcodeProject.add_file(framework_path", "the system. unity_xcode_project_path, framework_path = get_paths(LogFunc, parser, xcode_sdk_path) # Edit", "of the Xcode SDK on the system. xcode_sdk_path = get_xcode_sdk_path(LogFunc)", "[0, 66]: Log(\"Could not retrieve Xcode sdk path. code: {0},", "\"/System/Library/Frameworks/\" Log(\"framework path: {0}\", framework_path) return unity_xcode_project_path, framework_path def edit_unity_xcode_project(Log,", "post build iOS script\") parser.add_argument('ios_project_path', help=\"path to the folder of", "LogInput(writeObject): def Log(message, *args): messageNLine = (message if message else", "parser, xcode_sdk_path): args, ignored_args = parser.parse_known_args() ios_project_path = args.ios_project_path unity_xcode_project_path", "the iOS project generated by unity3d\") with open('MpireNxusMeasurementPostBuildiOSLog.txt', 'w') as", "framework_path def edit_unity_xcode_project(Log, unity_xcode_project_path, framework_path): # load unity iOS pbxproj", "parent=frameworks, tree='SDKROOT', force=False, file_options=file_options_security_framework) Log(\"added Security framework\") # Add -ObjC", "stdout=PIPE, stderr=PIPE) out, err = proc.communicate() if proc.returncode not in", "\"\\n\" writeObject.write(messageNLine.format(*args)) return Log def get_paths(Log, parser, xcode_sdk_path): args, ignored_args", "tree='SDKROOT', force=False, file_options=file_options_security_framework) Log(\"added Security framework\") # Add -ObjC to", "to the folder of the iOS project generated by unity3d\")", "framework_path) # Removed. # Change the Xcode project directly: #", "\"Security.framework\", parent=frameworks, tree='SDKROOT', force=False, file_options=file_options_security_framework) Log(\"added Security framework\") # Add", "Xcode project using mod_pbxproj: # - Add the adSupport framework", "exceptions # rewrite_unity_xcode_project(LogFunc, unity_xcode_project_path) sys.exit(0) def LogInput(writeObject): def Log(message, *args):", "= argparse.ArgumentParser(description=\"MpireNxusMeasurement post build iOS script\") parser.add_argument('ios_project_path', help=\"path to the", "unity_XcodeProject.get_or_create_group('Frameworks') file_options_security_framework = FileOptions(embed_framework=False, weak=True) unity_XcodeProject.add_file(framework_path + \"Security.framework\", parent=frameworks, tree='SDKROOT',", "framework_path = xcode_sdk_path + \"/System/Library/Frameworks/\" Log(\"framework path: {0}\", framework_path) return", "else None Log(\"Xcode sdk path: {0}\", xcode_sdk_path) return xcode_sdk_path if", "framework library. # - Change the compilation flags of the", "re.search(\"iPhoneOS.*?Path: (?P<sdk_path>.*?)\\n\", out, re.DOTALL) xcode_sdk_path = match.group('sdk_path') if match else", "= get_xcode_sdk_path(LogFunc) # Path for unity iOS Xcode project and", "the system. xcode_sdk_path = get_xcode_sdk_path(LogFunc) # Path for unity iOS", "# - Add the iAd framework library. # - Change", "writeObject.write(messageNLine.format(*args)) return Log def get_paths(Log, parser, xcode_sdk_path): args, ignored_args =", "def Log(message, *args): messageNLine = (message if message else \"None\")", "the Xcode project directly: # - Allow objective-c exceptions #", "not retrieve Xcode sdk path. code: {0}, err: {1}\", proc.returncode,", "if match else None Log(\"Xcode sdk path: {0}\", xcode_sdk_path) return", "iAd framework library. # - Change the compilation flags of", "flags of the adjust project files to support non-ARC. edit_unity_xcode_project(LogFunc,", "= [] # Allow objective-c exceptions re_objc_excep = re.compile(r\"\\s*GCC_ENABLE_OBJC_EXCEPTIONS *=", "unity_XcodeProject.save() def rewrite_unity_xcode_project(Log, unity_xcode_project_path): unity_xcode_lines = [] # Allow objective-c", "unity_xcode_project_path, framework_path): # load unity iOS pbxproj project file unity_XcodeProject", "XcodeProject.load(unity_xcode_project_path) frameworks = unity_XcodeProject.get_or_create_group('Frameworks') file_options_security_framework = FileOptions(embed_framework=False, weak=True) unity_XcodeProject.add_file(framework_path +", "upf: if re_objc_excep.match(line): #Log(\"matched line: {0}\", re_objc_excep.match(line).group()) line = line.replace(\"NO\",\"YES\")", "re_objc_excep = re.compile(r\"\\s*GCC_ENABLE_OBJC_EXCEPTIONS *= *NO.*\") with open(unity_xcode_project_path) as upf: for", "sys import re from subprocess import Popen, PIPE import argparse", "Add the adSupport framework library. # - Add the iAd", "get_xcode_sdk_path(LogFunc) # Path for unity iOS Xcode project and framework", "# Save changes. unity_XcodeProject.save() def rewrite_unity_xcode_project(Log, unity_xcode_project_path): unity_xcode_lines = []", "Allow objective-c exceptions # rewrite_unity_xcode_project(LogFunc, unity_xcode_project_path) sys.exit(0) def LogInput(writeObject): def", "unity_xcode_project_path = ios_project_path + \"/Unity-iPhone.xcodeproj/project.pbxproj\" Log(\"Unity3d Xcode project path: {0}\",", "iOS script\") parser.add_argument('ios_project_path', help=\"path to the folder of the iOS", "unity_xcode_lines.append(line) with open(unity_xcode_project_path, \"w+\") as upf: upf.writelines(unity_xcode_lines) def get_xcode_sdk_path(Log): #", "TreeType from pbxproj import FileOptions def main(): parser = argparse.ArgumentParser(description=\"MpireNxusMeasurement", "Xcode SDK on the system. xcode_sdk_path = get_xcode_sdk_path(LogFunc) # Path", "#!/usr/bin/env python import sys import re from subprocess import Popen,", "folder of the iOS project generated by unity3d\") with open('MpireNxusMeasurementPostBuildiOSLog.txt',", "import Popen, PIPE import argparse from pbxproj import XcodeProject, TreeType", "= unity_XcodeProject.get_or_create_group('Frameworks') file_options_security_framework = FileOptions(embed_framework=False, weak=True) unity_XcodeProject.add_file(framework_path + \"Security.framework\", parent=frameworks,", "(message if message else \"None\") + \"\\n\" writeObject.write(messageNLine.format(*args)) return Log", "Log(\"framework path: {0}\", framework_path) return unity_xcode_project_path, framework_path def edit_unity_xcode_project(Log, unity_xcode_project_path,", "settings. unity_XcodeProject.add_other_ldflags('-ObjC') # Save changes. unity_XcodeProject.save() def rewrite_unity_xcode_project(Log, unity_xcode_project_path): unity_xcode_lines", "- Add the adSupport framework library. # - Add the", "edit_unity_xcode_project(Log, unity_xcode_project_path, framework_path): # load unity iOS pbxproj project file", "re_objc_excep.match(line): #Log(\"matched line: {0}\", re_objc_excep.match(line).group()) line = line.replace(\"NO\",\"YES\") Log(\"Objective-c exceptions", "= FileOptions(embed_framework=False, weak=True) unity_XcodeProject.add_file(framework_path + \"Security.framework\", parent=frameworks, tree='SDKROOT', force=False, file_options=file_options_security_framework)", "= parser.parse_known_args() ios_project_path = args.ios_project_path unity_xcode_project_path = ios_project_path + \"/Unity-iPhone.xcodeproj/project.pbxproj\"", "python import sys import re from subprocess import Popen, PIPE", "import XcodeProject, TreeType from pbxproj import FileOptions def main(): parser", "unity_xcode_project_path, framework_path def edit_unity_xcode_project(Log, unity_xcode_project_path, framework_path): # load unity iOS", "edit_unity_xcode_project(LogFunc, unity_xcode_project_path, framework_path) # Removed. # Change the Xcode project", "unity_xcode_project_path) sys.exit(0) def LogInput(writeObject): def Log(message, *args): messageNLine = (message", "project files to support non-ARC. edit_unity_xcode_project(LogFunc, unity_xcode_project_path, framework_path) # Removed.", "unity_xcode_lines = [] # Allow objective-c exceptions re_objc_excep = re.compile(r\"\\s*GCC_ENABLE_OBJC_EXCEPTIONS", "to support non-ARC. edit_unity_xcode_project(LogFunc, unity_xcode_project_path, framework_path) # Removed. # Change", "err: {1}\", proc.returncode, err) return None match = re.search(\"iPhoneOS.*?Path: (?P<sdk_path>.*?)\\n\",", "from pbxproj import FileOptions def main(): parser = argparse.ArgumentParser(description=\"MpireNxusMeasurement post", "Edit the Xcode project using mod_pbxproj: # - Add the", "on the system. unity_xcode_project_path, framework_path = get_paths(LogFunc, parser, xcode_sdk_path) #", "unity_xcode_project_path, framework_path = get_paths(LogFunc, parser, xcode_sdk_path) # Edit the Xcode", "file injected. LogFunc = LogInput(fileLog) # Path of the Xcode", "Removed. # Change the Xcode project directly: # - Allow", "project settings. unity_XcodeProject.add_other_ldflags('-ObjC') # Save changes. unity_XcodeProject.save() def rewrite_unity_xcode_project(Log, unity_xcode_project_path):", "weak=True) unity_XcodeProject.add_file(framework_path + \"Security.framework\", parent=frameworks, tree='SDKROOT', force=False, file_options=file_options_security_framework) Log(\"added Security", "+ \"\\n\" writeObject.write(messageNLine.format(*args)) return Log def get_paths(Log, parser, xcode_sdk_path): args,", "match.group('sdk_path') if match else None Log(\"Xcode sdk path: {0}\", xcode_sdk_path)", "with file injected. LogFunc = LogInput(fileLog) # Path of the", "# - Allow objective-c exceptions # rewrite_unity_xcode_project(LogFunc, unity_xcode_project_path) sys.exit(0) def", "changes. unity_XcodeProject.save() def rewrite_unity_xcode_project(Log, unity_xcode_project_path): unity_xcode_lines = [] # Allow", "+ \"/Unity-iPhone.xcodeproj/project.pbxproj\" Log(\"Unity3d Xcode project path: {0}\", unity_xcode_project_path) framework_path =", "Linker Flags\" project settings. unity_XcodeProject.add_other_ldflags('-ObjC') # Save changes. unity_XcodeProject.save() def", "Xcode sdk path. code: {0}, err: {1}\", proc.returncode, err) return", "= Popen([\"xcodebuild\", \"-version\", \"-sdk\"], stdout=PIPE, stderr=PIPE) out, err = proc.communicate()", "# rewrite_unity_xcode_project(LogFunc, unity_xcode_project_path) sys.exit(0) def LogInput(writeObject): def Log(message, *args): messageNLine", "import sys import re from subprocess import Popen, PIPE import", "in [0, 66]: Log(\"Could not retrieve Xcode sdk path. code:", "Add the iAd framework library. # - Change the compilation", "re from subprocess import Popen, PIPE import argparse from pbxproj", "adjust project files to support non-ARC. edit_unity_xcode_project(LogFunc, unity_xcode_project_path, framework_path) #", "else \"None\") + \"\\n\" writeObject.write(messageNLine.format(*args)) return Log def get_paths(Log, parser,", "parser = argparse.ArgumentParser(description=\"MpireNxusMeasurement post build iOS script\") parser.add_argument('ios_project_path', help=\"path to", "- Change the compilation flags of the adjust project files", "open(unity_xcode_project_path, \"w+\") as upf: upf.writelines(unity_xcode_lines) def get_xcode_sdk_path(Log): # Output all", "the adSupport framework library. # - Add the iAd framework", "= xcode_sdk_path + \"/System/Library/Frameworks/\" Log(\"framework path: {0}\", framework_path) return unity_xcode_project_path," ]
[ "bar = [1, 2] foo = [] for i in", "f in foo)) bar[:] = [1, 2, 3, ] print(list(f()", "= [ lambda: i for i in bar ] print(list(f()", "f = foo(bar) print(f()) bar = [1, 2, 3, ]", "= sum(bar) return bar print(foo(bar)) # == 2 == bar", "2] foo = [] for i in bar: foo.append(lambda: i)", "== bar = [1, 2] def foo(): bar = sum(bar)", "= [ lambda i=i: i for i in bar ]", "foo(): bar = sum(bar) return bar print(foo()) # == 4", "for f in foo]) # == 11 == bar =", "= lambda: sum(bar) print(f()) bar = [1, 2, 3, ]", "bar ] print(list(f() for f in foo)) # == 12", "except ZeroDivisionError as bar: print(bar) print(bar) # == 7 ==", "sum(bar) f = foo(bar) print(f()) bar = [1, 2, 3,", "[] for i in bar: foo.append(lambda: i) print([f() for f", "print([f() for f in foo]) # == 11 == bar", "] print(list(f() for f in foo)) # == 13 ==", "= [] for i in bar: foo.append(lambda: i) print([f() for", "sum(bar) return bar print(foo()) # == 4 == bar =", "4 == bar = [1, 2] def foo(bar): bar =", "] return sum(bar) print(foo(bar), bar) # == 5 == bar", "9 == bar = [1, 2] def foo(bar): return lambda:", "= [1, 2] foo = [ lambda: i for i", "== try: bar = 1 / 0 print(bar) except ZeroDivisionError", "[1, 2] def foo(): bar = sum(bar) return bar print(foo())", "1 == bar = [1, 2] def foo(bar): bar =", "8 == bar = [1, 2] f = lambda: sum(bar)", "f in foo)) # == 13 == bar = [1,", "= [1, 2] def foo(bar): bar = sum(bar) return bar", "== 12 == bar = [1, 2] foo = [", "bar = [1, 2] f = lambda: sum(bar) print(f()) bar", "def foo(bar): bar = [1, 2, 3, ] return sum(bar)", "[1, 2] def foo(bar): return lambda: sum(bar) f = foo(bar)", "= [1, 2] def foo(bar): return lambda: sum(bar) f =", "return sum(bar) print(foo(bar), bar) # == 5 == bar =", "print(f()) bar = [1, 2, 3, ] print(f()) # ==", "/ 0 print(bar) except ZeroDivisionError as bar: print(bar) print(bar) #", "sum(bar) print(foo(bar), bar) # == 6 == try: bar =", "[1, 2] f = lambda: sum(bar) print(f()) bar = [1,", "print(foo()) # == 4 == bar = [1, 2] def", "def foo(bar): return lambda: sum(bar) f = foo(bar) print(f()) bar", "[1, 2] foo = [ lambda: i for i in", "print(list(f() for f in foo)) bar = [1, 2, 3,", "2] def foo(bar): bar[:] = [1, 2, 3, ] return", "print(foo(bar), bar) # == 6 == try: bar = 1", "= sum(bar) return bar print(foo()) # == 4 == bar", "= [1, 2] def foo(bar): bar = [1, 2, 3,", "3, ] return sum(bar) print(foo(bar), bar) # == 5 ==", "in bar)) print(bar) # == 8 == bar = [1,", "f in foo)) # == 12 == bar = [1,", "[1, 2] foo = [ lambda i=i: i for i", "[1, 2, 3, ] print(list(f() for f in foo)) #", "in foo)) # == 13 == bar = [1, 2]", "= [1, 2] def foo(bar): bar[0] = 1 return sum(bar)", "] print(list(f() for f in foo)) bar[:] = [1, 2,", "for f in foo)) bar[:] = [1, 2, 3, ]", "print(list(f() for f in foo)) # == 13 == bar", "[1, 2] foo = [] for i in bar: foo.append(lambda:", "ZeroDivisionError as bar: print(bar) print(bar) # == 7 == bar", "== bar = [1, 2] def foo(bar): bar[:] = [1,", "print(list(f() for f in foo)) bar[:] = [1, 2, 3,", "# == 5 == bar = [1, 2] def foo(bar):", "foo)) bar = [1, 2, 3, ] print(list(f() for f", "in foo)) bar[:] = [1, 2, 3, ] print(list(f() for", "bar = sum(bar) return bar print(foo()) # == 4 ==", "print(list(f() for f in foo)) # == 12 == bar", "try: bar = 1 / 0 print(bar) except ZeroDivisionError as", "return sum(bar) print(foo(bar), bar) # == 6 == try: bar", "= [1, 2, 3, ] return sum(bar) print(foo(bar), bar) #", "1 / 0 print(bar) except ZeroDivisionError as bar: print(bar) print(bar)", "foo)) bar[:] = [1, 2, 3, ] print(list(f() for f", "3, ] print(list(f() for f in foo)) bar[:] = [1,", "[1, 2] def foo(bar): bar = [1, 2, 3, ]", "= [1, 2, 3, ] print(list(f() for f in foo))", "bar print(foo()) # == 4 == bar = [1, 2]", "print(bar) # == 8 == bar = [1, 2] f", "3, ] print(f()) # == 10 == bar = [1,", "2] f = lambda: sum(bar) print(f()) bar = [1, 2,", "print(foo(bar), bar) # == 5 == bar = [1, 2]", "for f in foo)) # == 13 == bar =", "def foo(bar): bar[:] = [1, 2, 3, ] return sum(bar)", "# == 10 == bar = [1, 2] foo =", "= [1, 2] f = lambda: sum(bar) print(f()) bar =", "= [1, 2] print(list(bar for bar in bar)) print(bar) #", "foo)) # == 13 == bar = [1, 2] foo", "== bar = [1, 2] def foo(bar): bar = sum(bar)", "print(foo(bar)) # == 2 == bar = [1, 2] def", "i) print([f() for f in foo]) # == 11 ==", "# == 4 == bar = [1, 2] def foo(bar):", "for bar in bar)) print(bar) # == 8 == bar", "bar: foo.append(lambda: i) print([f() for f in foo]) # ==", "lambda: sum(bar) print(f()) bar = [1, 2, 3, ] print(f())", "foo]) # == 11 == bar = [1, 2] foo", "lambda: sum(bar) f = foo(bar) print(f()) bar = [1, 2,", "for f in foo)) # == 12 == bar =", "bar = [1, 2] foo = [ lambda i=i: i", "bar)) print(bar) # == 8 == bar = [1, 2]", "# == 1 == bar = [1, 2] def foo(bar):", "bar = [1, 2] def foo(): bar = sum(bar) return", "0 print(bar) except ZeroDivisionError as bar: print(bar) print(bar) # ==", "foo(bar): bar = [1, 2, 3, ] return sum(bar) print(foo(bar),", "[1, 2, 3, ] print(f()) # == 9 == bar", "for f in foo)) bar = [1, 2, 3, ]", "# == 7 == bar = [1, 2] print(list(bar for", "== 4 == bar = [1, 2] def foo(bar): bar", "6 == try: bar = 1 / 0 print(bar) except", "return lambda: sum(bar) f = foo(bar) print(f()) bar = [1,", "13 == bar = [1, 2] foo = [ lambda", "= [1, 2] foo = [ lambda i=i: i for", "# == 6 == try: bar = 1 / 0", "2, 3, ] print(f()) # == 10 == bar =", "] print(f()) # == 9 == bar = [1, 2]", "f in foo)) bar = [1, 2, 3, ] print(list(f()", "print(foo(bar)) # == 3 == bar = [1, 2] def", "foo(bar): return lambda: sum(bar) f = foo(bar) print(f()) bar =", "in foo]) # == 11 == bar = [1, 2]", "# == 2 == bar = [1, 2] def foo(bar):", "== 13 == bar = [1, 2] foo = [", "bar = [1, 2] def foo(bar): bar = sum(bar) return", "2, 3, ] print(list(f() for f in foo)) # ==", "== 6 == try: bar = 1 / 0 print(bar)", "in foo)) # == 12 == bar = [1, 2]", "== 5 == bar = [1, 2] def foo(bar): bar[:]", "print(f()) # == 10 == bar = [1, 2] foo", "bar = [1, 2] foo = [ lambda: i for", "bar[0] = 1 return sum(bar) print(foo(bar)) # == 3 ==", "print(bar) print(bar) # == 7 == bar = [1, 2]", "def foo(bar): bar[0] = 1 return sum(bar) print(foo(bar)) # ==", "5 == bar = [1, 2] def foo(bar): bar[:] =", "== bar = [1, 2] print(list(bar for bar in bar))", "foo = [ lambda: i for i in bar ]", "bar = [1, 2, 3, ] return sum(bar) print(foo(bar), bar)", "bar ] print(list(f() for f in foo)) bar = [1,", "return sum(bar) print(foo(bar)) # == 3 == bar = [1,", "def foo(bar): bar = sum(bar) return bar print(foo(bar)) # ==", "bar = 1 / 0 print(bar) except ZeroDivisionError as bar:", "3, ] print(f()) # == 9 == bar = [1,", "as bar: print(bar) print(bar) # == 7 == bar =", "== bar = [1, 2] foo = [ lambda: i", "foo(bar): bar[0] = 1 return sum(bar) print(foo(bar)) # == 3", "2 == bar = [1, 2] def foo(bar): bar[0] =", "foo(bar): bar[:] = [1, 2, 3, ] return sum(bar) print(foo(bar),", "== bar = [1, 2] foo = [] for i", "bar) # == 5 == bar = [1, 2] def", "for i in bar: foo.append(lambda: i) print([f() for f in", "# == 9 == bar = [1, 2] def foo(bar):", "bar in bar)) print(bar) # == 8 == bar =", "[1, 2, 3, ] return sum(bar) print(foo(bar), bar) # ==", "foo(bar): bar = sum(bar) return bar print(foo(bar)) # == 2", "7 == bar = [1, 2] print(list(bar for bar in", "] print(list(f() for f in foo)) bar = [1, 2,", "== bar = [1, 2] foo = [ lambda i=i:", "foo = [ lambda i=i: i for i in bar", "# == 8 == bar = [1, 2] f =", "foo)) # == 12 == bar = [1, 2] foo", "i=i: i for i in bar ] print(list(f() for f", "# == 3 == bar = [1, 2] def foo():", "[1, 2, 3, ] print(f()) # == 10 == bar", "f = lambda: sum(bar) print(f()) bar = [1, 2, 3,", "== 3 == bar = [1, 2] def foo(): bar", "== bar = [1, 2] def foo(bar): bar = [1,", "foo(bar) print(f()) bar = [1, 2, 3, ] print(f()) #", "bar[:] = [1, 2, 3, ] print(list(f() for f in", "== 9 == bar = [1, 2] def foo(bar): return", "in bar ] print(list(f() for f in foo)) # ==", "for i in bar ] print(list(f() for f in foo))", "return bar print(foo(bar)) # == 2 == bar = [1,", "foo.append(lambda: i) print([f() for f in foo]) # == 11", "2] def foo(bar): bar[0] = 1 return sum(bar) print(foo(bar)) #", "= [1, 2] foo = [] for i in bar:", "i in bar ] print(list(f() for f in foo)) bar", "2, 3, ] print(list(f() for f in foo)) bar[:] =", "== 1 == bar = [1, 2] def foo(bar): bar", "print(bar) except ZeroDivisionError as bar: print(bar) print(bar) # == 7", "2] foo = [ lambda: i for i in bar", "bar = [1, 2] def foo(bar): bar = [1, 2,", "2] def foo(bar): return lambda: sum(bar) f = foo(bar) print(f())", "] print(list(f() for f in foo)) # == 12 ==", "[1, 2] print(list(bar for bar in bar)) print(bar) # ==", "[1, 2] def foo(bar): bar = sum(bar) return bar print(foo(bar))", "[1, 2] def foo(bar): bar[0] = 1 return sum(bar) print(foo(bar))", "2, 3, ] print(f()) # == 9 == bar =", "[1, 2] def foo(bar): bar[:] = [1, 2, 3, ]", "[1, 2, 3, ] print(list(f() for f in foo)) bar[:]", "return bar print(foo()) # == 4 == bar = [1,", "bar = [1, 2] def foo(bar): bar[:] = [1, 2,", "def foo(): bar = sum(bar) return bar print(foo()) # ==", "foo = [] for i in bar: foo.append(lambda: i) print([f()", "# == 12 == bar = [1, 2] foo =", "3, ] return sum(bar) print(foo(bar), bar) # == 6 ==", "= [1, 2, 3, ] print(f()) # == 10 ==", "[ lambda i=i: i for i in bar ] print(list(f()", "sum(bar) print(foo(bar), bar) # == 5 == bar = [1,", "sum(bar) return bar print(foo(bar)) # == 2 == bar =", "= [1, 2, 3, ] print(f()) # == 9 ==", "f in foo]) # == 11 == bar = [1,", "in foo)) bar = [1, 2, 3, ] print(list(f() for", "2] def foo(): bar = sum(bar) return bar print(foo()) #", "2] def foo(bar): bar = [1, 2, 3, ] return", "i in bar ] print(list(f() for f in foo)) #", "3, ] print(list(f() for f in foo)) # == 13", "bar: print(bar) print(bar) # == 7 == bar = [1,", "lambda: i for i in bar ] print(list(f() for f", "11 == bar = [1, 2] foo = [ lambda:", "2] foo = [ lambda i=i: i for i in", "== 2 == bar = [1, 2] def foo(bar): bar[0]", "== bar = [1, 2] def foo(bar): return lambda: sum(bar)", "bar = [1, 2] def foo(bar): bar[0] = 1 return", "10 == bar = [1, 2] foo = [] for", "1 return sum(bar) print(foo(bar)) # == 3 == bar =", "print(f()) # == 9 == bar = [1, 2] def", "bar print(foo(bar)) # == 2 == bar = [1, 2]", "bar = [1, 2, 3, ] print(f()) # == 9", "<filename>vars_in_python.py<gh_stars>0 # == 1 == bar = [1, 2] def", "== 8 == bar = [1, 2] f = lambda:", "bar) # == 6 == try: bar = 1 /", "== bar = [1, 2] f = lambda: sum(bar) print(f())", "bar = [1, 2] print(list(bar for bar in bar)) print(bar)", "sum(bar) print(f()) bar = [1, 2, 3, ] print(f()) #", "# == 11 == bar = [1, 2] foo =", "[ lambda: i for i in bar ] print(list(f() for", "bar = [1, 2] def foo(bar): return lambda: sum(bar) f", "in bar ] print(list(f() for f in foo)) bar =", "= [1, 2] def foo(): bar = sum(bar) return bar", "2, 3, ] return sum(bar) print(foo(bar), bar) # == 5", "print(list(bar for bar in bar)) print(bar) # == 8 ==", "i for i in bar ] print(list(f() for f in", "bar = [1, 2, 3, ] print(f()) # == 10", "3 == bar = [1, 2] def foo(): bar =", "== bar = [1, 2] def foo(bar): bar[0] = 1", "== 7 == bar = [1, 2] print(list(bar for bar", "] return sum(bar) print(foo(bar), bar) # == 6 == try:", "2] print(list(bar for bar in bar)) print(bar) # == 8", "i in bar: foo.append(lambda: i) print([f() for f in foo])", "= [1, 2] def foo(bar): bar[:] = [1, 2, 3,", "== 10 == bar = [1, 2] foo = []", "# == 13 == bar = [1, 2] foo =", "bar = sum(bar) return bar print(foo(bar)) # == 2 ==", "print(bar) # == 7 == bar = [1, 2] print(list(bar", "in bar: foo.append(lambda: i) print([f() for f in foo]) #", "= foo(bar) print(f()) bar = [1, 2, 3, ] print(f())", "12 == bar = [1, 2] foo = [ lambda:", "bar = [1, 2, 3, ] print(list(f() for f in", "2] def foo(bar): bar = sum(bar) return bar print(foo(bar)) #", "= 1 return sum(bar) print(foo(bar)) # == 3 == bar", "sum(bar) print(foo(bar)) # == 3 == bar = [1, 2]", "lambda i=i: i for i in bar ] print(list(f() for", "== 11 == bar = [1, 2] foo = [", "2, 3, ] return sum(bar) print(foo(bar), bar) # == 6", "bar[:] = [1, 2, 3, ] return sum(bar) print(foo(bar), bar)", "= 1 / 0 print(bar) except ZeroDivisionError as bar: print(bar)", "] print(f()) # == 10 == bar = [1, 2]" ]
[ "to {args.save}\") sys.exit(0) else: token, webhook_secret, app_id = get_token_secret(github_api_url=args.api_url) delivery", "= get_controller_route() except subprocess.CalledProcessError: try: el = get_controller_ingress() except subprocess.CalledProcessError:", "def webhook_get_delivery( token: str, owner_repo: str, last: bool = False,", "app_get_delivery(token, args.last_event, args.api_url) jeez = delivery[\"request\"][\"payload\"] headers = delivery[\"request\"][\"headers\"] payload", "args.webhook_token, args.webhook_secret replays = webhook_get_delivery( token, last=args.last_event, api_url=args.api_url, owner_repo=args.webhook_repo, )", "headers.update( { \"X-Hub-Signature\": \"sha1=\" + esha1, \"X-Hub-Signature-256\": \"sha256=\" + esha256,", "int(webhooks[int(chosen) - 1][\"id\"]) else: print(\"could not find any webhook configuration", "hashlib import hmac import json import os import subprocess import", "jeez[\"repository\"][\"full_name\"]) headers.update( { \"X-Hub-Signature\": \"sha1=\" + esha1, \"X-Hub-Signature-256\": \"sha256=\" +", "{ \"Accept\": \"application/vnd.github.v3+json\", \"Authorization\": f\"Bearer {token}\", } return requests.request(\"GET\", url,", "_request_app_delivery(token, deliveries[0][\"id\"], api_url=api_url).json() chosen = ask_which(token, api_url, last, deliveries) return", "on openshift/ingress)\", default=os.environ.get(\"EL_ROUTE\"), ) parser.add_argument(\"--last-event\", \"-L\", action=\"store_true\") parser.add_argument( \"--webhook-repo\", \"-w\",", "pipelines-as-code/route=controller -o json\", shell=True, check=True, capture_output=True, ) return ( \"https://\"", "+= f\"/{iid}/deliveries\" headers = { \"Accept\": \"application/vnd.github.v3+json\", \"Authorization\": f\"Bearer {token}\",", "requests import sys payload = \\\"\\\"\\\"{json.dumps(payload)}\\\"\\\"\\\" headers={headers} el_route = \"http://localhost:8080\"", "directly it with: \") s = f\"http POST {api_url}/repos/{owner_repo}/hooks/{webhook_id}/deliveries/{delivery_id}/attempts\" s", "typing.Union[int, None] = None, api_url: str = ghapp_token.GITHUB_API_URL, ): url", "or app_id={app_id} or webhook_secret={webhook_secret} are empty\" ) sys.exit(1) gh =", ") -> dict: r = _request_app_delivery(token, api_url=api_url) r.raise_for_status() deliveries =", "not app_id or not webhook_secret: print( f\"private_key={private_key[1:10]} or app_id={app_id} or", "i += 1 chosen = input(\"Choose a delivery: \") #", "payload: str): s = f\"\"\"#!/usr/bin/env python3 import requests import sys", "= 1 if \"message\" in deliveries: print(deliveries) sys.exit(0) for delivery", "if not private_key or not app_id or not webhook_secret: print(", "10: break i += 1 chosen = input(\"Choose a delivery:", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "except subprocess.CalledProcessError: print(\"Could not find an ingress or route\") sys.exit(1)", "esha1 = hmac.new( webhook_secret.encode(\"utf-8\"), msg=payload.encode(\"utf-8\"), digestmod=hashlib.sha1, ).hexdigest() print(\"Replay event for", "ingress or route\") sys.exit(1) if args.webhook_repo: token, webhook_secret = args.webhook_token,", "str = ghapp_token.GITHUB_API_URL ) -> dict: r = _request_app_delivery(token, api_url=api_url)", "r = _request_app_delivery(token, api_url=api_url) r.raise_for_status() deliveries = r.json() if not", "specific language governing permissions and limitations # under the License.", "and sys.argv[1] == \"-l\") else \"{el_route}\" r = requests.request(\"POST\",el_route,data=payload.encode(\"utf-8\"),headers=headers) r.raise_for_status()", "headers=headers ) except requests.exceptions.ConnectionError: print(f\"sleeping until {el} is up\") time.sleep(5)", "# not use this file except in compliance with the", "saved to {target}\") def main(args): el = args.eroute if not", ") except requests.exceptions.ConnectionError: print(f\"sleeping until {el} is up\") time.sleep(5) continue", "<NAME> <<EMAIL>> # # Licensed under the Apache License, Version", "\") s = f\"http POST {api_url}/repos/{owner_repo}/hooks/{webhook_id}/deliveries/{delivery_id}/attempts\" s += f' Authorization:\"Bearer", "_ in range(args.retry): try: r = requests.request( \"POST\", el, data=payload.encode(\"utf-8\"),", "delivery[\"request\"][\"headers\"] payload = json.dumps(jeez) esha256 = hmac.new( webhook_secret.encode(\"utf-8\"), msg=payload.encode(\"utf-8\"), digestmod=hashlib.sha256,", "api_url=api_url, delivery_id=delivery_id, ) r.raise_for_status() print(f\"Delivery has been replayed, you can", "deliveries[chosen][\"id\"] r = _request_webhooks_reattempt( token=token, owner_repo=owner_repo, iid=webhook_id, api_url=api_url, delivery_id=delivery_id, )", "has been replayed, you can replay directly it with: \")", "f\"kubectl get ingress -n {NAMESPACE} -l pipelines-as-code/route=controller -o json\", shell=True,", "= json.loads(secret.stdout) private_key = base64.b64decode(jeez[\"data\"][\"github-private-key\"]) app_id = base64.b64decode(jeez[\"data\"][\"github-application-id\"]) webhook_secret =", "instead of app\" ) parser.add_argument(\"--webhook-token\", \"-t\", help=\"Use this token\") parser.add_argument(\"--webhook-secret\",", "in compliance with the License. You may obtain # a", "url = f\"{api_url}/repos/{owner_repo}/hooks/{iid}/deliveries/{delivery_id}/attempts\" print(url) headers = { \"Accept\": \"application/vnd.github.v3+json\", \"Authorization\":", "chosen = ask_which(token, api_url, last, deliveries) return _request_app_delivery( token, deliveries[chosen][\"id\"],", "str = ghapp_token.GITHUB_API_URL, ): url = f\"{api_url}/repos/{owner_repo}/hooks/{iid}/deliveries/{delivery_id}/attempts\" print(url) headers =", "{args.save}\") sys.exit(0) else: token, webhook_secret, app_id = get_token_secret(github_api_url=args.api_url) delivery =", "import hashlib import hmac import json import os import subprocess", "print( f\"{i}) Action={delivery['action']} Event={delivery['event']} Delivered at {delivery['delivered_at']}\" ) dico.append(delivery[\"id\"]) if", "webhook configuration on your repo {}\") sys.exit(1) r = _request_webhooks_installed(", "last: return _request_app_delivery(token, deliveries[0][\"id\"], api_url=api_url).json() chosen = ask_which(token, api_url, last,", "\"http://localhost:8080\" if (len(sys.argv) > 1 and sys.argv[1] == \"-l\") else", "maximum number of retries\") def parse_args(): parser = argparse.ArgumentParser(description=\"Replay a", "if iid: url += f\"/{iid}/deliveries\" headers = { \"Accept\": \"application/vnd.github.v3+json\",", "You may obtain # a copy of the License at", "capture_output=True, ) jeez = json.loads(secret.stdout) private_key = base64.b64decode(jeez[\"data\"][\"github-private-key\"]) app_id =", "webhook-repo instead of app\" ) parser.add_argument(\"--webhook-token\", \"-t\", help=\"Use this token\")", "json\", shell=True, check=True, capture_output=True, ) return ( \"https://\" + json.loads(elroute.stdout)[\"items\"][0][\"status\"][\"ingress\"][0][\"host\"]", "app_id, expiration_time, github_api_url, ) return gh.token, webhook_secret, app_id def _request_app_delivery(token,", "webhook\") parser.add_argument( \"--installation-id\", \"-i\", default=os.environ.get(\"INSTALLATION_ID\"), help=\"Installation ID\", ) parser.add_argument( \"--controller-route\",", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "not find any webhook configuration on your repo {}\") sys.exit(1)", "= \"pipelines-as-code\" EXPIRE_MINUTES_AS_SECONDS = ( int(os.environ.get(\"GITHUBAPP_TOKEN_EXPIRATION_MINUTES\", 10)) * 60 )", "requests import ghapp_token NAMESPACE = \"pipelines-as-code\" SECRET_NAME = \"pipelines-as-code-secret\" ELNAME", "jeez = delivery[\"request\"][\"payload\"] headers = delivery[\"request\"][\"headers\"] payload = json.dumps(jeez) esha256", "api_url=api_url, owner_repo=owner_repo, iid=webhook_id ) r.raise_for_status() deliveries = r.json() if not", "try: el = get_controller_ingress() except subprocess.CalledProcessError: print(\"Could not find an", "print(\"no deliveries has been set \") sys.exit(1) if last: return", "\"-i\", default=os.environ.get(\"INSTALLATION_ID\"), help=\"Installation ID\", ) parser.add_argument( \"--controller-route\", \"-e\", dest=\"eroute\", help=\"Route", "README.md for documentation import typing import argparse import base64 import", "number of retries\") def parse_args(): parser = argparse.ArgumentParser(description=\"Replay a webhook\")", "\" Accept:application/vnd.github.v3+json\" print(s) return s def app_get_delivery( token: str, last:", "on {el}: {r}\") return print(\"You have reached the maximum number", "_request_app_delivery( token, deliveries[chosen][\"id\"], api_url=api_url ).json() def save_script(target: str, el_route: str,", "under the License is distributed on an \"AS IS\" BASIS,", "el = args.eroute if not el: try: el = get_controller_route()", "help=\"Use this webhook secret\") parser.add_argument( \"--save\", \"-s\", help=\"save the request", "headers=headers) def _request_webhooks_reattempt( token: str, owner_repo: str, iid: int, delivery_id:", "\"sha256=\" + esha256, } ) if args.save: save_script(args.save, el, headers,", "f\"Bearer {token}\", } return requests.request(\"POST\", url, headers=headers) def ask_which(token: str,", "sys.exit(1) if last: return _request_app_delivery(token, deliveries[0][\"id\"], api_url=api_url).json() chosen = ask_which(token,", "{token}\", } return requests.request(\"GET\", url, headers=headers) def _request_webhooks_reattempt( token: str,", "== 10: break i += 1 chosen = input(\"Choose a", "sys.exit(0) else: token, webhook_secret, app_id = get_token_secret(github_api_url=args.api_url) delivery = app_get_delivery(token,", "github_api_url=ghapp_token.GITHUB_API_URL, expiration_time=EXPIRE_MINUTES_AS_SECONDS ): secret = subprocess.run( f\"kubectl get secret {SECRET_NAME}", "deliveries: dict) -> int: dico = [] i = 1", "parser.add_argument(\"--webhook-token\", \"-t\", help=\"Use this token\") parser.add_argument(\"--webhook-secret\", \"-S\", help=\"Use this webhook", "\"--webhook-repo\", \"-w\", help=\"Use a webhook-repo instead of app\" ) parser.add_argument(\"--webhook-token\",", "last, deliveries) return _request_app_delivery( token, deliveries[chosen][\"id\"], api_url=api_url ).json() def save_script(target:", "def get_controller_route(): elroute = subprocess.run( f\"kubectl get route -n {NAMESPACE}", "elroute = subprocess.run( f\"kubectl get route -n {NAMESPACE} -l pipelines-as-code/route=controller", "args.last_event, args.api_url) jeez = delivery[\"request\"][\"payload\"] headers = delivery[\"request\"][\"headers\"] payload =", "this file except in compliance with the License. You may", "github_api_url, ) return gh.token, webhook_secret, app_id def _request_app_delivery(token, iid=None, api_url=ghapp_token.GITHUB_API_URL):", "requests.request(\"POST\",el_route,data=payload.encode(\"utf-8\"),headers=headers) r.raise_for_status() print(\"Request has been replayed on \" + el_route)", "parser.add_argument( \"--controller-route\", \"-e\", dest=\"eroute\", help=\"Route hostname (default to detect on", "to try to contact the el route\", ) return parser.parse_args()", ") return ( \"http://\" + json.loads(elroute.stdout)[\"items\"][0][\"spec\"][\"rules\"][0][\"host\"] ) def get_token_secret( github_api_url=ghapp_token.GITHUB_API_URL,", "i == 10: break i += 1 chosen = input(\"Choose", "os.environ.get(\"PASS_TOKEN\", \"$TOKEN\") }\"' s += \" Accept:application/vnd.github.v3+json\" print(s) return s", ") r.raise_for_status() print(f\"Delivery has been replayed, you can replay directly", "sys.exit(0) for _ in range(args.retry): try: r = requests.request( \"POST\",", "dico[int(chosen) - 1], api_url=api_url).json() return int(chosen) - 1 def webhook_get_delivery(", "1][\"id\"]) else: print(\"could not find any webhook configuration on your", "f\"{api_url}/repos/{owner_repo}/hooks\" if iid: url += f\"/{iid}/deliveries\" headers = { \"Accept\":", "chosen = input(\"Choose a delivery: \") # return _request_app_delivery(token, dico[int(chosen)", "deliveries) return _request_app_delivery( token, deliveries[chosen][\"id\"], api_url=api_url ).json() def save_script(target: str,", "str, owner_repo: str, iid: typing.Union[int, None] = None, api_url: str", "token, webhook_secret, app_id = get_token_secret(github_api_url=args.api_url) delivery = app_get_delivery(token, args.last_event, args.api_url)", "software # distributed under the License is distributed on an", "(the \"License\"); you may # not use this file except", "webhook_get_delivery( token, last=args.last_event, api_url=args.api_url, owner_repo=args.webhook_repo, ) if args.save: open(args.save, \"w\").write(f\"\"\"#!/usr/bin/env", "retries\") def parse_args(): parser = argparse.ArgumentParser(description=\"Replay a webhook\") parser.add_argument( \"--installation-id\",", "shell script to replay easily\" ) parser.add_argument( \"-a\", \"--api-url\", help=\"Github", "last: bool = False, api_url: str = ghapp_token.GITHUB_API_URL ) ->", "def parse_args(): parser = argparse.ArgumentParser(description=\"Replay a webhook\") parser.add_argument( \"--installation-id\", \"-i\",", "r = requests.request( \"POST\", el, data=payload.encode(\"utf-8\"), headers=headers ) except requests.exceptions.ConnectionError:", "delivery: \") webhook_id = int(webhooks[int(chosen) - 1][\"id\"]) else: print(\"could not", "documentation import typing import argparse import base64 import hashlib import", "r.raise_for_status() print(f\"Delivery has been replayed, you can replay directly it", "60 ) def get_controller_route(): elroute = subprocess.run( f\"kubectl get route", "help=\"Github API URL\", default=os.environ.get(\"GITHUB_API_URL\", ghapp_token.GITHUB_API_URL), ) parser.add_argument( \"--retry\", type=int, default=1,", "\") sys.exit(1) if last: return _request_app_delivery(token, deliveries[0][\"id\"], api_url=api_url).json() chosen =", "\"-l\") else \"{el_route}\" r = requests.request(\"POST\",el_route,data=payload.encode(\"utf-8\"),headers=headers) r.raise_for_status() print(\"Request has been", "int: dico = [] i = 1 if \"message\" in", "governing permissions and limitations # under the License. # See", "1 if \"message\" in deliveries: print(deliveries) sys.exit(0) for delivery in", "print(f\"Request saved to {target}\") def main(args): el = args.eroute if", "deliveries[0][\"id\"], api_url=api_url).json() chosen = ask_which(token, api_url, last, deliveries) return _request_app_delivery(", "= get_token_secret(github_api_url=args.api_url) delivery = app_get_delivery(token, args.last_event, args.api_url) jeez = delivery[\"request\"][\"payload\"]", "file except in compliance with the License. You may obtain", "def app_get_delivery( token: str, last: bool = False, api_url: str", ").hexdigest() print(\"Replay event for repo \" + jeez[\"repository\"][\"full_name\"]) headers.update( {", "\\\"\\\"\\\"{json.dumps(payload)}\\\"\\\"\\\" headers={headers} el_route = \"http://localhost:8080\" if (len(sys.argv) > 1 and", "OR CONDITIONS OF ANY KIND, either express or implied. See", "the specific language governing permissions and limitations # under the", "\"pipelines-as-code\" SECRET_NAME = \"pipelines-as-code-secret\" ELNAME = \"pipelines-as-code\" EXPIRE_MINUTES_AS_SECONDS = (", "set \") sys.exit(1) if last: delivery_id = deliveries[0][\"id\"] else: chosen", "f\"private_key={private_key[1:10]} or app_id={app_id} or webhook_secret={webhook_secret} are empty\" ) sys.exit(1) gh", "any webhook configuration on your repo {}\") sys.exit(1) r =", "iid=webhook_id, api_url=api_url, delivery_id=delivery_id, ) r.raise_for_status() print(f\"Delivery has been replayed, you", "= False, api_url: str = ghapp_token.GITHUB_API_URL ) -> dict: r", "been replayed on \" + el_route) \"\"\" with open(target, \"w\")", "many time to try to contact the el route\", )", "import typing import argparse import base64 import hashlib import hmac", ") -> str: r = _request_webhooks_installed(token, api_url=api_url, owner_repo=owner_repo) r.raise_for_status() webhooks", "under the Apache License, Version 2.0 (the \"License\"); you may", "api_url: str = ghapp_token.GITHUB_API_URL, ): url = f\"{api_url}/repos/{owner_repo}/hooks\" if iid:", "False, api_url: str = ghapp_token.GITHUB_API_URL ) -> dict: r =", "= json.dumps(jeez) esha256 = hmac.new( webhook_secret.encode(\"utf-8\"), msg=payload.encode(\"utf-8\"), digestmod=hashlib.sha256, ).hexdigest() esha1", "f\"kubectl get route -n {NAMESPACE} -l pipelines-as-code/route=controller -o json\", shell=True,", ").hexdigest() esha1 = hmac.new( webhook_secret.encode(\"utf-8\"), msg=payload.encode(\"utf-8\"), digestmod=hashlib.sha1, ).hexdigest() print(\"Replay event", "= app_get_delivery(token, args.last_event, args.api_url) jeez = delivery[\"request\"][\"payload\"] headers = delivery[\"request\"][\"headers\"]", "sys payload = \\\"\\\"\\\"{json.dumps(payload)}\\\"\\\"\\\" headers={headers} el_route = \"http://localhost:8080\" if (len(sys.argv)", "api_url=api_url ).json() def save_script(target: str, el_route: str, headers: dict, payload:", "app_id = base64.b64decode(jeez[\"data\"][\"github-application-id\"]) webhook_secret = base64.b64decode(jeez[\"data\"][\"webhook.secret\"]).decode() if not private_key or", "def ask_which(token: str, api_url: str, last: bool, deliveries: dict) ->", "in deliveries: print( f\"{i}) Action={delivery['action']} Event={delivery['event']} Delivered at {delivery['delivered_at']}\" )", "sys.argv[1] == \"-l\") else \"{el_route}\" r = requests.request(\"POST\",el_route,data=payload.encode(\"utf-8\"),headers=headers) r.raise_for_status() print(\"Request", "os.chmod(target, 0o755) print(f\"Request saved to {target}\") def main(args): el =", "get_token_secret( github_api_url=ghapp_token.GITHUB_API_URL, expiration_time=EXPIRE_MINUTES_AS_SECONDS ): secret = subprocess.run( f\"kubectl get secret", "find any webhook configuration on your repo {}\") sys.exit(1) r", "in webhooks: print(f\"{cnt}) {wh['name']} - {wh['config']['url']} \") cnt += 1", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "\"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY", "_request_app_delivery(token, dico[int(chosen) - 1], api_url=api_url).json() return int(chosen) - 1 def", ") r.raise_for_status() deliveries = r.json() if not deliveries: print(\"no deliveries", "delivery_id=delivery_id, ) r.raise_for_status() print(f\"Delivery has been replayed, you can replay", "+ esha256, } ) if args.save: save_script(args.save, el, headers, jeez)", "= base64.b64decode(jeez[\"data\"][\"github-application-id\"]) webhook_secret = base64.b64decode(jeez[\"data\"][\"webhook.secret\"]).decode() if not private_key or not", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "to in writing, software # distributed under the License is", "- 1 def webhook_get_delivery( token: str, owner_repo: str, last: bool", "sys.exit(1) if args.webhook_repo: token, webhook_secret = args.webhook_token, args.webhook_secret replays =", "if args.webhook_repo: token, webhook_secret = args.webhook_token, args.webhook_secret replays = webhook_get_delivery(", "+ json.loads(elroute.stdout)[\"items\"][0][\"status\"][\"ingress\"][0][\"host\"] ) def get_controller_ingress(): elroute = subprocess.run( f\"kubectl get", "has been set \") sys.exit(1) if last: return _request_app_delivery(token, deliveries[0][\"id\"],", "digestmod=hashlib.sha1, ).hexdigest() print(\"Replay event for repo \" + jeez[\"repository\"][\"full_name\"]) headers.update(", "this token\") parser.add_argument(\"--webhook-secret\", \"-S\", help=\"Use this webhook secret\") parser.add_argument( \"--save\",", "deliveries has been set \") sys.exit(1) if last: delivery_id =", "\"pipelines-as-code\" EXPIRE_MINUTES_AS_SECONDS = ( int(os.environ.get(\"GITHUBAPP_TOKEN_EXPIRATION_MINUTES\", 10)) * 60 ) def", "str, last: bool, deliveries: dict) -> int: dico = []", "-o json\", shell=True, check=True, capture_output=True, ) return ( \"http://\" +", "to contact the el route\", ) return parser.parse_args() if __name__", "deliveries[chosen][\"id\"], api_url=api_url ).json() def save_script(target: str, el_route: str, headers: dict,", "sys.exit(1) if last: delivery_id = deliveries[0][\"id\"] else: chosen = ask_which(token,", "or agreed to in writing, software # distributed under the", "<<EMAIL>> # # Licensed under the Apache License, Version 2.0", "el = get_controller_route() except subprocess.CalledProcessError: try: el = get_controller_ingress() except", ") def get_controller_ingress(): elroute = subprocess.run( f\"kubectl get ingress -n", "required by applicable law or agreed to in writing, software", "private_key or not app_id or not webhook_secret: print( f\"private_key={private_key[1:10]} or", "\"-L\", action=\"store_true\") parser.add_argument( \"--webhook-repo\", \"-w\", help=\"Use a webhook-repo instead of", "to replay easily\" ) parser.add_argument( \"-a\", \"--api-url\", help=\"Github API URL\",", "{token}\", } return requests.request(\"POST\", url, headers=headers) def ask_which(token: str, api_url:", "args.save: open(args.save, \"w\").write(f\"\"\"#!/usr/bin/env bash\\n{replays}\\n\"\"\") os.chmod(args.save, 0o755) print(f\"Saved to {args.save}\") sys.exit(0)", "an ingress or route\") sys.exit(1) if args.webhook_repo: token, webhook_secret =", "dest=\"eroute\", help=\"Route hostname (default to detect on openshift/ingress)\", default=os.environ.get(\"EL_ROUTE\"), )", "- 1], api_url=api_url).json() return int(chosen) - 1 def webhook_get_delivery( token:", "== \"-l\") else \"{el_route}\" r = requests.request(\"POST\",el_route,data=payload.encode(\"utf-8\"),headers=headers) r.raise_for_status() print(\"Request has", "or implied. See the # License for the specific language", "1 chosen = input(\"Choose a delivery: \") webhook_id = int(webhooks[int(chosen)", "payload = \\\"\\\"\\\"{json.dumps(payload)}\\\"\\\"\\\" headers={headers} el_route = \"http://localhost:8080\" if (len(sys.argv) >", "get_controller_route() except subprocess.CalledProcessError: try: el = get_controller_ingress() except subprocess.CalledProcessError: print(\"Could", ") if args.save: open(args.save, \"w\").write(f\"\"\"#!/usr/bin/env bash\\n{replays}\\n\"\"\") os.chmod(args.save, 0o755) print(f\"Saved to", "Apache License, Version 2.0 (the \"License\"); you may # not", "\"pipelines-as-code-secret\" ELNAME = \"pipelines-as-code\" EXPIRE_MINUTES_AS_SECONDS = ( int(os.environ.get(\"GITHUBAPP_TOKEN_EXPIRATION_MINUTES\", 10)) *", "os.chmod(args.save, 0o755) print(f\"Saved to {args.save}\") sys.exit(0) else: token, webhook_secret, app_id", "bool = False, api_url: str = ghapp_token.GITHUB_API_URL ) -> dict:", "print(f\"Delivery has been replayed, you can replay directly it with:", "= requests.request( \"POST\", el, data=payload.encode(\"utf-8\"), headers=headers ) except requests.exceptions.ConnectionError: print(f\"sleeping", "time.sleep(5) continue print(f\"Payload has been replayed on {el}: {r}\") return", "dict) -> int: dico = [] i = 1 if", "replayed, you can replay directly it with: \") s =", "agreed to in writing, software # distributed under the License", "a delivery: \") webhook_id = int(webhooks[int(chosen) - 1][\"id\"]) else: print(\"could", "check=True, capture_output=True, ) return ( \"http://\" + json.loads(elroute.stdout)[\"items\"][0][\"spec\"][\"rules\"][0][\"host\"] ) def", "owner_repo=owner_repo) r.raise_for_status() webhooks = r.json() if len(webhooks) == 1: webhook_id", "1 for wh in webhooks: print(f\"{cnt}) {wh['name']} - {wh['config']['url']} \")", "int, api_url: str = ghapp_token.GITHUB_API_URL, ): url = f\"{api_url}/repos/{owner_repo}/hooks/{iid}/deliveries/{delivery_id}/attempts\" print(url)", "open(target, \"w\") as fp: fp.write(s) os.chmod(target, 0o755) print(f\"Request saved to", "= ask_which(token, api_url, last, deliveries) return _request_app_delivery( token, deliveries[chosen][\"id\"], api_url=api_url", ") parser.add_argument(\"--webhook-token\", \"-t\", help=\"Use this token\") parser.add_argument(\"--webhook-secret\", \"-S\", help=\"Use this", "distributed under the License is distributed on an \"AS IS\"", "import subprocess import sys import time import requests import ghapp_token", "f\"Bearer {token}\", } return requests.request(\"GET\", url, headers=headers) def _request_webhooks_installed( token:", "\") webhook_id = int(webhooks[int(chosen) - 1][\"id\"]) else: print(\"could not find", "License, Version 2.0 (the \"License\"); you may # not use", "CONDITIONS OF ANY KIND, either express or implied. See the", "bash\\n{replays}\\n\"\"\") os.chmod(args.save, 0o755) print(f\"Saved to {args.save}\") sys.exit(0) else: token, webhook_secret,", ") dico.append(delivery[\"id\"]) if i == 10: break i += 1", "openshift/ingress)\", default=os.environ.get(\"EL_ROUTE\"), ) parser.add_argument(\"--last-event\", \"-L\", action=\"store_true\") parser.add_argument( \"--webhook-repo\", \"-w\", help=\"Use", "= delivery[\"request\"][\"headers\"] payload = json.dumps(jeez) esha256 = hmac.new( webhook_secret.encode(\"utf-8\"), msg=payload.encode(\"utf-8\"),", "\"--retry\", type=int, default=1, help=\"how many time to try to contact", "return s def app_get_delivery( token: str, last: bool = False,", "if len(webhooks) == 1: webhook_id = int(webhooks[0][\"id\"]) elif len(webhooks) >", "ghapp_token.GITHUB_API_URL ) -> dict: r = _request_app_delivery(token, api_url=api_url) r.raise_for_status() deliveries", "empty\" ) sys.exit(1) gh = ghapp_token.GitHub( private_key, app_id, expiration_time, github_api_url,", "subprocess import sys import time import requests import ghapp_token NAMESPACE", "if not el: try: el = get_controller_route() except subprocess.CalledProcessError: try:", "sys.exit(1) r = _request_webhooks_installed( token, api_url=api_url, owner_repo=owner_repo, iid=webhook_id ) r.raise_for_status()", "app_id={app_id} or webhook_secret={webhook_secret} are empty\" ) sys.exit(1) gh = ghapp_token.GitHub(", "parser.add_argument(\"--last-event\", \"-L\", action=\"store_true\") parser.add_argument( \"--webhook-repo\", \"-w\", help=\"Use a webhook-repo instead", "headers: dict, payload: str): s = f\"\"\"#!/usr/bin/env python3 import requests", "this webhook secret\") parser.add_argument( \"--save\", \"-s\", help=\"save the request to", "not use this file except in compliance with the License.", "len(webhooks) == 1: webhook_id = int(webhooks[0][\"id\"]) elif len(webhooks) > 1:", "args.api_url) jeez = delivery[\"request\"][\"payload\"] headers = delivery[\"request\"][\"headers\"] payload = json.dumps(jeez)", "ask_which(token: str, api_url: str, last: bool, deliveries: dict) -> int:", "\"Authorization\": f\"Bearer {token}\", } return requests.request(\"POST\", url, headers=headers) def ask_which(token:", "writing, software # distributed under the License is distributed on", "= 1 for wh in webhooks: print(f\"{cnt}) {wh['name']} - {wh['config']['url']}", "of app\" ) parser.add_argument(\"--webhook-token\", \"-t\", help=\"Use this token\") parser.add_argument(\"--webhook-secret\", \"-S\",", "has been set \") sys.exit(1) if last: delivery_id = deliveries[0][\"id\"]", ") sys.exit(1) gh = ghapp_token.GitHub( private_key, app_id, expiration_time, github_api_url, )", "owner_repo=owner_repo, iid=webhook_id, api_url=api_url, delivery_id=delivery_id, ) r.raise_for_status() print(f\"Delivery has been replayed,", "- 1][\"id\"]) else: print(\"could not find any webhook configuration on", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "owner_repo=owner_repo, iid=webhook_id ) r.raise_for_status() deliveries = r.json() if not deliveries:", "token, last=args.last_event, api_url=args.api_url, owner_repo=args.webhook_repo, ) if args.save: open(args.save, \"w\").write(f\"\"\"#!/usr/bin/env bash\\n{replays}\\n\"\"\")", "json.loads(elroute.stdout)[\"items\"][0][\"spec\"][\"rules\"][0][\"host\"] ) def get_token_secret( github_api_url=ghapp_token.GITHUB_API_URL, expiration_time=EXPIRE_MINUTES_AS_SECONDS ): secret = subprocess.run(", "except requests.exceptions.ConnectionError: print(f\"sleeping until {el} is up\") time.sleep(5) continue print(f\"Payload", "find an ingress or route\") sys.exit(1) if args.webhook_repo: token, webhook_secret", "you can replay directly it with: \") s = f\"http", "hmac import json import os import subprocess import sys import", "the License. You may obtain # a copy of the", "* 60 ) def get_controller_route(): elroute = subprocess.run( f\"kubectl get", "an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF", "def save_script(target: str, el_route: str, headers: dict, payload: str): s", "use this file except in compliance with the License. You", "s += \" Accept:application/vnd.github.v3+json\" print(s) return s def app_get_delivery( token:", "replay easily\" ) parser.add_argument( \"-a\", \"--api-url\", help=\"Github API URL\", default=os.environ.get(\"GITHUB_API_URL\",", "= ask_which(token, api_url, last, r.json()) delivery_id = deliveries[chosen][\"id\"] r =", "el_route) \"\"\" with open(target, \"w\") as fp: fp.write(s) os.chmod(target, 0o755)", "python3 import requests import sys payload = \\\"\\\"\\\"{json.dumps(payload)}\\\"\\\"\\\" headers={headers} el_route", "str): s = f\"\"\"#!/usr/bin/env python3 import requests import sys payload", "not el: try: el = get_controller_route() except subprocess.CalledProcessError: try: el", "api_url=api_url, owner_repo=owner_repo) r.raise_for_status() webhooks = r.json() if len(webhooks) == 1:", "base64.b64decode(jeez[\"data\"][\"webhook.secret\"]).decode() if not private_key or not app_id or not webhook_secret:", "# return _request_app_delivery(token, dico[int(chosen) - 1], api_url=api_url).json() return int(chosen) -", "POST {api_url}/repos/{owner_repo}/hooks/{webhook_id}/deliveries/{delivery_id}/attempts\" s += f' Authorization:\"Bearer { os.environ.get(\"PASS_TOKEN\", \"$TOKEN\") }\"'", "to {target}\") def main(args): el = args.eroute if not el:", "= webhook_get_delivery( token, last=args.last_event, api_url=args.api_url, owner_repo=args.webhook_repo, ) if args.save: open(args.save,", "on \" + el_route) \"\"\" with open(target, \"w\") as fp:", "in range(args.retry): try: r = requests.request( \"POST\", el, data=payload.encode(\"utf-8\"), headers=headers", "or not webhook_secret: print( f\"private_key={private_key[1:10]} or app_id={app_id} or webhook_secret={webhook_secret} are", "ghapp_token.GITHUB_API_URL), ) parser.add_argument( \"--retry\", type=int, default=1, help=\"how many time to", "-n{NAMESPACE} -o json\", shell=True, check=True, capture_output=True, ) jeez = json.loads(secret.stdout)", "if iid: url += f\"/{iid}\" headers = { \"Accept\": \"application/vnd.github.v3+json\",", "webhook_id = int(webhooks[int(chosen) - 1][\"id\"]) else: print(\"could not find any", "esha256 = hmac.new( webhook_secret.encode(\"utf-8\"), msg=payload.encode(\"utf-8\"), digestmod=hashlib.sha256, ).hexdigest() esha1 = hmac.new(", "api_url: str = ghapp_token.GITHUB_API_URL, ) -> str: r = _request_webhooks_installed(token,", "el = get_controller_ingress() except subprocess.CalledProcessError: print(\"Could not find an ingress", "detect on openshift/ingress)\", default=os.environ.get(\"EL_ROUTE\"), ) parser.add_argument(\"--last-event\", \"-L\", action=\"store_true\") parser.add_argument( \"--webhook-repo\",", "1 chosen = input(\"Choose a delivery: \") # return _request_app_delivery(token,", "chosen = input(\"Choose a delivery: \") webhook_id = int(webhooks[int(chosen) -", "= subprocess.run( f\"kubectl get route -n {NAMESPACE} -l pipelines-as-code/route=controller -o", "== 1: webhook_id = int(webhooks[0][\"id\"]) elif len(webhooks) > 1: cnt", "help=\"how many time to try to contact the el route\",", "i = 1 if \"message\" in deliveries: print(deliveries) sys.exit(0) for", "_request_webhooks_reattempt( token: str, owner_repo: str, iid: int, delivery_id: int, api_url:", "print(f\"Payload has been replayed on {el}: {r}\") return print(\"You have", "str, el_route: str, headers: dict, payload: str): s = f\"\"\"#!/usr/bin/env", "}\"' s += \" Accept:application/vnd.github.v3+json\" print(s) return s def app_get_delivery(", "or route\") sys.exit(1) if args.webhook_repo: token, webhook_secret = args.webhook_token, args.webhook_secret", "License is distributed on an \"AS IS\" BASIS, WITHOUT #", "KIND, either express or implied. See the # License for", "\") cnt += 1 chosen = input(\"Choose a delivery: \")", "\"X-Hub-Signature-256\": \"sha256=\" + esha256, } ) if args.save: save_script(args.save, el,", "): secret = subprocess.run( f\"kubectl get secret {SECRET_NAME} -n{NAMESPACE} -o", "iid: int, delivery_id: int, api_url: str = ghapp_token.GITHUB_API_URL, ): url", "-n {NAMESPACE} -l pipelines-as-code/route=controller -o json\", shell=True, check=True, capture_output=True, )", "\"License\"); you may # not use this file except in", "import hmac import json import os import subprocess import sys", "= args.eroute if not el: try: el = get_controller_route() except", "IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND,", "= ghapp_token.GitHub( private_key, app_id, expiration_time, github_api_url, ) return gh.token, webhook_secret,", "else \"{el_route}\" r = requests.request(\"POST\",el_route,data=payload.encode(\"utf-8\"),headers=headers) r.raise_for_status() print(\"Request has been replayed", "requests.exceptions.ConnectionError: print(f\"sleeping until {el} is up\") time.sleep(5) continue print(f\"Payload has", "express or implied. See the # License for the specific", "): url = f\"{api_url}/repos/{owner_repo}/hooks/{iid}/deliveries/{delivery_id}/attempts\" print(url) headers = { \"Accept\": \"application/vnd.github.v3+json\",", "action=\"store_true\") parser.add_argument( \"--webhook-repo\", \"-w\", help=\"Use a webhook-repo instead of app\"", "parser.add_argument( \"--retry\", type=int, default=1, help=\"how many time to try to", "dict: r = _request_app_delivery(token, api_url=api_url) r.raise_for_status() deliveries = r.json() if", "the Apache License, Version 2.0 (the \"License\"); you may #", "_request_webhooks_reattempt( token=token, owner_repo=owner_repo, iid=webhook_id, api_url=api_url, delivery_id=delivery_id, ) r.raise_for_status() print(f\"Delivery has", "set \") sys.exit(1) if last: return _request_app_delivery(token, deliveries[0][\"id\"], api_url=api_url).json() chosen", "\"sha1=\" + esha1, \"X-Hub-Signature-256\": \"sha256=\" + esha256, } ) if", "ask_which(token, api_url, last, r.json()) delivery_id = deliveries[chosen][\"id\"] r = _request_webhooks_reattempt(", "{ os.environ.get(\"PASS_TOKEN\", \"$TOKEN\") }\"' s += \" Accept:application/vnd.github.v3+json\" print(s) return", "url, headers=headers) def _request_webhooks_installed( token: str, owner_repo: str, iid: typing.Union[int,", "reached the maximum number of retries\") def parse_args(): parser =", "# -*- coding: utf-8 -*- # Author: <NAME> <<EMAIL>> #", "= deliveries[0][\"id\"] else: chosen = ask_which(token, api_url, last, r.json()) delivery_id", ") jeez = json.loads(secret.stdout) private_key = base64.b64decode(jeez[\"data\"][\"github-private-key\"]) app_id = base64.b64decode(jeez[\"data\"][\"github-application-id\"])", "r.raise_for_status() print(\"Request has been replayed on \" + el_route) \"\"\"", "\"Authorization\": f\"Bearer {token}\", } return requests.request(\"GET\", url, headers=headers) def _request_webhooks_installed(", "See the # License for the specific language governing permissions", "NAMESPACE = \"pipelines-as-code\" SECRET_NAME = \"pipelines-as-code-secret\" ELNAME = \"pipelines-as-code\" EXPIRE_MINUTES_AS_SECONDS", "chosen = ask_which(token, api_url, last, r.json()) delivery_id = deliveries[chosen][\"id\"] r", "} return requests.request(\"POST\", url, headers=headers) def ask_which(token: str, api_url: str,", "cnt = 1 for wh in webhooks: print(f\"{cnt}) {wh['name']} -", "\"w\").write(f\"\"\"#!/usr/bin/env bash\\n{replays}\\n\"\"\") os.chmod(args.save, 0o755) print(f\"Saved to {args.save}\") sys.exit(0) else: token,", "iid: url += f\"/{iid}\" headers = { \"Accept\": \"application/vnd.github.v3+json\", \"Authorization\":", "None] = None, api_url: str = ghapp_token.GITHUB_API_URL, ): url =", "coding: utf-8 -*- # Author: <NAME> <<EMAIL>> # # Licensed", "# a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "el_route = \"http://localhost:8080\" if (len(sys.argv) > 1 and sys.argv[1] ==", "print(f\"sleeping until {el} is up\") time.sleep(5) continue print(f\"Payload has been", "get_controller_ingress(): elroute = subprocess.run( f\"kubectl get ingress -n {NAMESPACE} -l", "deliveries: print( f\"{i}) Action={delivery['action']} Event={delivery['event']} Delivered at {delivery['delivered_at']}\" ) dico.append(delivery[\"id\"])", "sys.exit(1) gh = ghapp_token.GitHub( private_key, app_id, expiration_time, github_api_url, ) return", "ghapp_token.GITHUB_API_URL, ): url = f\"{api_url}/repos/{owner_repo}/hooks\" if iid: url += f\"/{iid}/deliveries\"", "_request_webhooks_installed( token, api_url=api_url, owner_repo=owner_repo, iid=webhook_id ) r.raise_for_status() deliveries = r.json()", "if args.save: open(args.save, \"w\").write(f\"\"\"#!/usr/bin/env bash\\n{replays}\\n\"\"\") os.chmod(args.save, 0o755) print(f\"Saved to {args.save}\")", "delivery = app_get_delivery(token, args.last_event, args.api_url) jeez = delivery[\"request\"][\"payload\"] headers =", "# See README.md for documentation import typing import argparse import", "str, last: bool = False, api_url: str = ghapp_token.GITHUB_API_URL )", "ask_which(token, api_url, last, deliveries) return _request_app_delivery( token, deliveries[chosen][\"id\"], api_url=api_url ).json()", ") parser.add_argument( \"-a\", \"--api-url\", help=\"Github API URL\", default=os.environ.get(\"GITHUB_API_URL\", ghapp_token.GITHUB_API_URL), )", "msg=payload.encode(\"utf-8\"), digestmod=hashlib.sha1, ).hexdigest() print(\"Replay event for repo \" + jeez[\"repository\"][\"full_name\"])", "ghapp_token.GitHub( private_key, app_id, expiration_time, github_api_url, ) return gh.token, webhook_secret, app_id", "\" + jeez[\"repository\"][\"full_name\"]) headers.update( { \"X-Hub-Signature\": \"sha1=\" + esha1, \"X-Hub-Signature-256\":", "= ghapp_token.GITHUB_API_URL, ): url = f\"{api_url}/repos/{owner_repo}/hooks\" if iid: url +=", "+= 1 chosen = input(\"Choose a delivery: \") webhook_id =", "print(\"Replay event for repo \" + jeez[\"repository\"][\"full_name\"]) headers.update( { \"X-Hub-Signature\":", "headers = delivery[\"request\"][\"headers\"] payload = json.dumps(jeez) esha256 = hmac.new( webhook_secret.encode(\"utf-8\"),", "webhook_secret, app_id def _request_app_delivery(token, iid=None, api_url=ghapp_token.GITHUB_API_URL): url = f\"{api_url}/app/hook/deliveries\" if", "+= f\"/{iid}\" headers = { \"Accept\": \"application/vnd.github.v3+json\", \"Authorization\": f\"Bearer {token}\",", "+ jeez[\"repository\"][\"full_name\"]) headers.update( { \"X-Hub-Signature\": \"sha1=\" + esha1, \"X-Hub-Signature-256\": \"sha256=\"", "= subprocess.run( f\"kubectl get ingress -n {NAMESPACE} -l pipelines-as-code/route=controller -o", "f\"/{iid}\" headers = { \"Accept\": \"application/vnd.github.v3+json\", \"Authorization\": f\"Bearer {token}\", }", "= { \"Accept\": \"application/vnd.github.v3+json\", \"Authorization\": f\"Bearer {token}\", } return requests.request(\"POST\",", "law or agreed to in writing, software # distributed under", "} return requests.request(\"GET\", url, headers=headers) def _request_webhooks_reattempt( token: str, owner_repo:", "msg=payload.encode(\"utf-8\"), digestmod=hashlib.sha256, ).hexdigest() esha1 = hmac.new( webhook_secret.encode(\"utf-8\"), msg=payload.encode(\"utf-8\"), digestmod=hashlib.sha1, ).hexdigest()", "token\") parser.add_argument(\"--webhook-secret\", \"-S\", help=\"Use this webhook secret\") parser.add_argument( \"--save\", \"-s\",", ") def get_token_secret( github_api_url=ghapp_token.GITHUB_API_URL, expiration_time=EXPIRE_MINUTES_AS_SECONDS ): secret = subprocess.run( f\"kubectl", "return _request_app_delivery(token, dico[int(chosen) - 1], api_url=api_url).json() return int(chosen) - 1", "delivery in deliveries: print( f\"{i}) Action={delivery['action']} Event={delivery['event']} Delivered at {delivery['delivered_at']}\"", "return requests.request(\"POST\", url, headers=headers) def ask_which(token: str, api_url: str, last:", "repo \" + jeez[\"repository\"][\"full_name\"]) headers.update( { \"X-Hub-Signature\": \"sha1=\" + esha1,", "argparse.ArgumentParser(description=\"Replay a webhook\") parser.add_argument( \"--installation-id\", \"-i\", default=os.environ.get(\"INSTALLATION_ID\"), help=\"Installation ID\", )", "{wh['config']['url']} \") cnt += 1 chosen = input(\"Choose a delivery:", "\") sys.exit(1) if last: delivery_id = deliveries[0][\"id\"] else: chosen =", "implied. See the # License for the specific language governing", "s def app_get_delivery( token: str, last: bool = False, api_url:", "print(\"no deliveries has been set \") sys.exit(1) if last: delivery_id", "a webhook-repo instead of app\" ) parser.add_argument(\"--webhook-token\", \"-t\", help=\"Use this", "-o json\", shell=True, check=True, capture_output=True, ) jeez = json.loads(secret.stdout) private_key", "token: str, last: bool = False, api_url: str = ghapp_token.GITHUB_API_URL", "(len(sys.argv) > 1 and sys.argv[1] == \"-l\") else \"{el_route}\" r", "r.raise_for_status() deliveries = r.json() if not deliveries: print(\"no deliveries has", "r.json() if len(webhooks) == 1: webhook_id = int(webhooks[0][\"id\"]) elif len(webhooks)", "fp: fp.write(s) os.chmod(target, 0o755) print(f\"Request saved to {target}\") def main(args):", "script to replay easily\" ) parser.add_argument( \"-a\", \"--api-url\", help=\"Github API", "python3 # -*- coding: utf-8 -*- # Author: <NAME> <<EMAIL>>", "on your repo {}\") sys.exit(1) r = _request_webhooks_installed( token, api_url=api_url,", "headers, jeez) sys.exit(0) for _ in range(args.retry): try: r =", "\"Accept\": \"application/vnd.github.v3+json\", \"Authorization\": f\"Bearer {token}\", } return requests.request(\"POST\", url, headers=headers)", "save_script(target: str, el_route: str, headers: dict, payload: str): s =", "print(\"You have reached the maximum number of retries\") def parse_args():", "{ \"X-Hub-Signature\": \"sha1=\" + esha1, \"X-Hub-Signature-256\": \"sha256=\" + esha256, }", "= get_controller_ingress() except subprocess.CalledProcessError: print(\"Could not find an ingress or", "at {delivery['delivered_at']}\" ) dico.append(delivery[\"id\"]) if i == 10: break i", "app_id = get_token_secret(github_api_url=args.api_url) delivery = app_get_delivery(token, args.last_event, args.api_url) jeez =", "payload = json.dumps(jeez) esha256 = hmac.new( webhook_secret.encode(\"utf-8\"), msg=payload.encode(\"utf-8\"), digestmod=hashlib.sha256, ).hexdigest()", "contact the el route\", ) return parser.parse_args() if __name__ ==", "else: chosen = ask_which(token, api_url, last, r.json()) delivery_id = deliveries[chosen][\"id\"]", "last, r.json()) delivery_id = deliveries[chosen][\"id\"] r = _request_webhooks_reattempt( token=token, owner_repo=owner_repo,", "hmac.new( webhook_secret.encode(\"utf-8\"), msg=payload.encode(\"utf-8\"), digestmod=hashlib.sha1, ).hexdigest() print(\"Replay event for repo \"", "input(\"Choose a delivery: \") webhook_id = int(webhooks[int(chosen) - 1][\"id\"]) else:", "= _request_webhooks_reattempt( token=token, owner_repo=owner_repo, iid=webhook_id, api_url=api_url, delivery_id=delivery_id, ) r.raise_for_status() print(f\"Delivery", "{SECRET_NAME} -n{NAMESPACE} -o json\", shell=True, check=True, capture_output=True, ) jeez =", "webhooks = r.json() if len(webhooks) == 1: webhook_id = int(webhooks[0][\"id\"])", "r.json()) delivery_id = deliveries[chosen][\"id\"] r = _request_webhooks_reattempt( token=token, owner_repo=owner_repo, iid=webhook_id,", "route\") sys.exit(1) if args.webhook_repo: token, webhook_secret = args.webhook_token, args.webhook_secret replays", "\"https://\" + json.loads(elroute.stdout)[\"items\"][0][\"status\"][\"ingress\"][0][\"host\"] ) def get_controller_ingress(): elroute = subprocess.run( f\"kubectl", "\"X-Hub-Signature\": \"sha1=\" + esha1, \"X-Hub-Signature-256\": \"sha256=\" + esha256, } )", "print(url) headers = { \"Accept\": \"application/vnd.github.v3+json\", \"Authorization\": f\"Bearer {token}\", }", "\"--save\", \"-s\", help=\"save the request to a shell script to", "for _ in range(args.retry): try: r = requests.request( \"POST\", el,", "deliveries: print(deliveries) sys.exit(0) for delivery in deliveries: print( f\"{i}) Action={delivery['action']}", "_request_app_delivery(token, api_url=api_url) r.raise_for_status() deliveries = r.json() if not deliveries: print(\"no", "token, deliveries[chosen][\"id\"], api_url=api_url ).json() def save_script(target: str, el_route: str, headers:", "a shell script to replay easily\" ) parser.add_argument( \"-a\", \"--api-url\",", "el route\", ) return parser.parse_args() if __name__ == \"__main__\": main(parse_args())", "not webhook_secret: print( f\"private_key={private_key[1:10]} or app_id={app_id} or webhook_secret={webhook_secret} are empty\"", "Accept:application/vnd.github.v3+json\" print(s) return s def app_get_delivery( token: str, last: bool", "the request to a shell script to replay easily\" )", "r = requests.request(\"POST\",el_route,data=payload.encode(\"utf-8\"),headers=headers) r.raise_for_status() print(\"Request has been replayed on \"", "for documentation import typing import argparse import base64 import hashlib", "def get_token_secret( github_api_url=ghapp_token.GITHUB_API_URL, expiration_time=EXPIRE_MINUTES_AS_SECONDS ): secret = subprocess.run( f\"kubectl get", "check=True, capture_output=True, ) jeez = json.loads(secret.stdout) private_key = base64.b64decode(jeez[\"data\"][\"github-private-key\"]) app_id", "[] i = 1 if \"message\" in deliveries: print(deliveries) sys.exit(0)", "json\", shell=True, check=True, capture_output=True, ) return ( \"http://\" + json.loads(elroute.stdout)[\"items\"][0][\"spec\"][\"rules\"][0][\"host\"]", "not deliveries: print(\"no deliveries has been set \") sys.exit(1) if", "api_url: str, last: bool, deliveries: dict) -> int: dico =", "parse_args(): parser = argparse.ArgumentParser(description=\"Replay a webhook\") parser.add_argument( \"--installation-id\", \"-i\", default=os.environ.get(\"INSTALLATION_ID\"),", "= ghapp_token.GITHUB_API_URL, ) -> str: r = _request_webhooks_installed(token, api_url=api_url, owner_repo=owner_repo)", "Delivered at {delivery['delivered_at']}\" ) dico.append(delivery[\"id\"]) if i == 10: break", "and limitations # under the License. # See README.md for", "= { \"Accept\": \"application/vnd.github.v3+json\", \"Authorization\": f\"Bearer {token}\", } return requests.request(\"GET\",", "+= 1 chosen = input(\"Choose a delivery: \") # return", "= f\"\"\"#!/usr/bin/env python3 import requests import sys payload = \\\"\\\"\\\"{json.dumps(payload)}\\\"\\\"\\\"", "esha1, \"X-Hub-Signature-256\": \"sha256=\" + esha256, } ) if args.save: save_script(args.save,", "\") # return _request_app_delivery(token, dico[int(chosen) - 1], api_url=api_url).json() return int(chosen)", "ingress -n {NAMESPACE} -l pipelines-as-code/route=controller -o json\", shell=True, check=True, capture_output=True,", "= argparse.ArgumentParser(description=\"Replay a webhook\") parser.add_argument( \"--installation-id\", \"-i\", default=os.environ.get(\"INSTALLATION_ID\"), help=\"Installation ID\",", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR", "( int(os.environ.get(\"GITHUBAPP_TOKEN_EXPIRATION_MINUTES\", 10)) * 60 ) def get_controller_route(): elroute =", "or webhook_secret={webhook_secret} are empty\" ) sys.exit(1) gh = ghapp_token.GitHub( private_key,", "ghapp_token.GITHUB_API_URL, ) -> str: r = _request_webhooks_installed(token, api_url=api_url, owner_repo=owner_repo) r.raise_for_status()", "hmac.new( webhook_secret.encode(\"utf-8\"), msg=payload.encode(\"utf-8\"), digestmod=hashlib.sha256, ).hexdigest() esha1 = hmac.new( webhook_secret.encode(\"utf-8\"), msg=payload.encode(\"utf-8\"),", "# Author: <NAME> <<EMAIL>> # # Licensed under the Apache", "# # Licensed under the Apache License, Version 2.0 (the", "-o json\", shell=True, check=True, capture_output=True, ) return ( \"https://\" +", "ghapp_token.GITHUB_API_URL, ): url = f\"{api_url}/repos/{owner_repo}/hooks/{iid}/deliveries/{delivery_id}/attempts\" print(url) headers = { \"Accept\":", "replayed on \" + el_route) \"\"\" with open(target, \"w\") as", "\"--installation-id\", \"-i\", default=os.environ.get(\"INSTALLATION_ID\"), help=\"Installation ID\", ) parser.add_argument( \"--controller-route\", \"-e\", dest=\"eroute\",", "str, last: bool = False, api_url: str = ghapp_token.GITHUB_API_URL, )", "URL\", default=os.environ.get(\"GITHUB_API_URL\", ghapp_token.GITHUB_API_URL), ) parser.add_argument( \"--retry\", type=int, default=1, help=\"how many", "base64 import hashlib import hmac import json import os import", "= None, api_url: str = ghapp_token.GITHUB_API_URL, ): url = f\"{api_url}/repos/{owner_repo}/hooks\"", "= int(webhooks[0][\"id\"]) elif len(webhooks) > 1: cnt = 1 for", "try to contact the el route\", ) return parser.parse_args() if", "} return requests.request(\"GET\", url, headers=headers) def _request_webhooks_installed( token: str, owner_repo:", "secret\") parser.add_argument( \"--save\", \"-s\", help=\"save the request to a shell", "EXPIRE_MINUTES_AS_SECONDS = ( int(os.environ.get(\"GITHUBAPP_TOKEN_EXPIRATION_MINUTES\", 10)) * 60 ) def get_controller_route():", "capture_output=True, ) return ( \"https://\" + json.loads(elroute.stdout)[\"items\"][0][\"status\"][\"ingress\"][0][\"host\"] ) def get_controller_ingress():", "{NAMESPACE} -l pipelines-as-code/route=controller -o json\", shell=True, check=True, capture_output=True, ) return", "url = f\"{api_url}/app/hook/deliveries\" if iid: url += f\"/{iid}\" headers =", "r = _request_webhooks_installed(token, api_url=api_url, owner_repo=owner_repo) r.raise_for_status() webhooks = r.json() if", "+= f' Authorization:\"Bearer { os.environ.get(\"PASS_TOKEN\", \"$TOKEN\") }\"' s += \"", "= f\"{api_url}/repos/{owner_repo}/hooks\" if iid: url += f\"/{iid}/deliveries\" headers = {", "f\"{i}) Action={delivery['action']} Event={delivery['event']} Delivered at {delivery['delivered_at']}\" ) dico.append(delivery[\"id\"]) if i", "token, webhook_secret = args.webhook_token, args.webhook_secret replays = webhook_get_delivery( token, last=args.last_event,", "# under the License. # See README.md for documentation import", "{ \"Accept\": \"application/vnd.github.v3+json\", \"Authorization\": f\"Bearer {token}\", } return requests.request(\"POST\", url,", "token, api_url=api_url, owner_repo=owner_repo, iid=webhook_id ) r.raise_for_status() deliveries = r.json() if", "args.webhook_repo: token, webhook_secret = args.webhook_token, args.webhook_secret replays = webhook_get_delivery( token,", "webhook_get_delivery( token: str, owner_repo: str, last: bool = False, api_url:", "obtain # a copy of the License at # #", "str, api_url: str, last: bool, deliveries: dict) -> int: dico", "el, data=payload.encode(\"utf-8\"), headers=headers ) except requests.exceptions.ConnectionError: print(f\"sleeping until {el} is", "Version 2.0 (the \"License\"); you may # not use this", "Action={delivery['action']} Event={delivery['event']} Delivered at {delivery['delivered_at']}\" ) dico.append(delivery[\"id\"]) if i ==", "are empty\" ) sys.exit(1) gh = ghapp_token.GitHub( private_key, app_id, expiration_time,", "= f\"http POST {api_url}/repos/{owner_repo}/hooks/{webhook_id}/deliveries/{delivery_id}/attempts\" s += f' Authorization:\"Bearer { os.environ.get(\"PASS_TOKEN\",", "get secret {SECRET_NAME} -n{NAMESPACE} -o json\", shell=True, check=True, capture_output=True, )", "app_get_delivery( token: str, last: bool = False, api_url: str =", "return _request_app_delivery(token, deliveries[0][\"id\"], api_url=api_url).json() chosen = ask_which(token, api_url, last, deliveries)", "requests.request(\"GET\", url, headers=headers) def _request_webhooks_installed( token: str, owner_repo: str, iid:", "\"w\") as fp: fp.write(s) os.chmod(target, 0o755) print(f\"Request saved to {target}\")", ") parser.add_argument( \"--controller-route\", \"-e\", dest=\"eroute\", help=\"Route hostname (default to detect", "= ghapp_token.GITHUB_API_URL, ): url = f\"{api_url}/repos/{owner_repo}/hooks/{iid}/deliveries/{delivery_id}/attempts\" print(url) headers = {", "default=os.environ.get(\"INSTALLATION_ID\"), help=\"Installation ID\", ) parser.add_argument( \"--controller-route\", \"-e\", dest=\"eroute\", help=\"Route hostname", "has been replayed on \" + el_route) \"\"\" with open(target,", "{el} is up\") time.sleep(5) continue print(f\"Payload has been replayed on", "args.save: save_script(args.save, el, headers, jeez) sys.exit(0) for _ in range(args.retry):", "parser = argparse.ArgumentParser(description=\"Replay a webhook\") parser.add_argument( \"--installation-id\", \"-i\", default=os.environ.get(\"INSTALLATION_ID\"), help=\"Installation", "if (len(sys.argv) > 1 and sys.argv[1] == \"-l\") else \"{el_route}\"", "else: print(\"could not find any webhook configuration on your repo", "License for the specific language governing permissions and limitations #", "api_url=ghapp_token.GITHUB_API_URL): url = f\"{api_url}/app/hook/deliveries\" if iid: url += f\"/{iid}\" headers", "been set \") sys.exit(1) if last: delivery_id = deliveries[0][\"id\"] else:", "( \"http://\" + json.loads(elroute.stdout)[\"items\"][0][\"spec\"][\"rules\"][0][\"host\"] ) def get_token_secret( github_api_url=ghapp_token.GITHUB_API_URL, expiration_time=EXPIRE_MINUTES_AS_SECONDS ):", "of retries\") def parse_args(): parser = argparse.ArgumentParser(description=\"Replay a webhook\") parser.add_argument(", "replayed on {el}: {r}\") return print(\"You have reached the maximum", "1: cnt = 1 for wh in webhooks: print(f\"{cnt}) {wh['name']}", "on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS", "r.json() if not deliveries: print(\"no deliveries has been set \")", "{r}\") return print(\"You have reached the maximum number of retries\")", "(default to detect on openshift/ingress)\", default=os.environ.get(\"EL_ROUTE\"), ) parser.add_argument(\"--last-event\", \"-L\", action=\"store_true\")", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "app\" ) parser.add_argument(\"--webhook-token\", \"-t\", help=\"Use this token\") parser.add_argument(\"--webhook-secret\", \"-S\", help=\"Use", "= hmac.new( webhook_secret.encode(\"utf-8\"), msg=payload.encode(\"utf-8\"), digestmod=hashlib.sha256, ).hexdigest() esha1 = hmac.new( webhook_secret.encode(\"utf-8\"),", "print(\"Request has been replayed on \" + el_route) \"\"\" with", "api_url: str = ghapp_token.GITHUB_API_URL, ): url = f\"{api_url}/repos/{owner_repo}/hooks/{iid}/deliveries/{delivery_id}/attempts\" print(url) headers", "private_key = base64.b64decode(jeez[\"data\"][\"github-private-key\"]) app_id = base64.b64decode(jeez[\"data\"][\"github-application-id\"]) webhook_secret = base64.b64decode(jeez[\"data\"][\"webhook.secret\"]).decode() if", "owner_repo=args.webhook_repo, ) if args.save: open(args.save, \"w\").write(f\"\"\"#!/usr/bin/env bash\\n{replays}\\n\"\"\") os.chmod(args.save, 0o755) print(f\"Saved", "webhook_secret = args.webhook_token, args.webhook_secret replays = webhook_get_delivery( token, last=args.last_event, api_url=args.api_url,", "requests.request(\"POST\", url, headers=headers) def ask_which(token: str, api_url: str, last: bool,", "been replayed on {el}: {r}\") return print(\"You have reached the", "f\"Bearer {token}\", } return requests.request(\"GET\", url, headers=headers) def _request_webhooks_reattempt( token:", "replays = webhook_get_delivery( token, last=args.last_event, api_url=args.api_url, owner_repo=args.webhook_repo, ) if args.save:", "input(\"Choose a delivery: \") # return _request_app_delivery(token, dico[int(chosen) - 1],", "default=os.environ.get(\"EL_ROUTE\"), ) parser.add_argument(\"--last-event\", \"-L\", action=\"store_true\") parser.add_argument( \"--webhook-repo\", \"-w\", help=\"Use a", "if not deliveries: print(\"no deliveries has been set \") sys.exit(1)", "typing import argparse import base64 import hashlib import hmac import", "headers = { \"Accept\": \"application/vnd.github.v3+json\", \"Authorization\": f\"Bearer {token}\", } return", "-> str: r = _request_webhooks_installed(token, api_url=api_url, owner_repo=owner_repo) r.raise_for_status() webhooks =", "deliveries[0][\"id\"] else: chosen = ask_which(token, api_url, last, r.json()) delivery_id =", "return _request_app_delivery( token, deliveries[chosen][\"id\"], api_url=api_url ).json() def save_script(target: str, el_route:", "token: str, owner_repo: str, iid: typing.Union[int, None] = None, api_url:", "= deliveries[chosen][\"id\"] r = _request_webhooks_reattempt( token=token, owner_repo=owner_repo, iid=webhook_id, api_url=api_url, delivery_id=delivery_id,", "app_id or not webhook_secret: print( f\"private_key={private_key[1:10]} or app_id={app_id} or webhook_secret={webhook_secret}", "deliveries = r.json() if not deliveries: print(\"no deliveries has been", "0o755) print(f\"Saved to {args.save}\") sys.exit(0) else: token, webhook_secret, app_id =", "jeez) sys.exit(0) for _ in range(args.retry): try: r = requests.request(", "in deliveries: print(deliveries) sys.exit(0) for delivery in deliveries: print( f\"{i})", "url += f\"/{iid}\" headers = { \"Accept\": \"application/vnd.github.v3+json\", \"Authorization\": f\"Bearer", "url = f\"{api_url}/repos/{owner_repo}/hooks\" if iid: url += f\"/{iid}/deliveries\" headers =", "Authorization:\"Bearer { os.environ.get(\"PASS_TOKEN\", \"$TOKEN\") }\"' s += \" Accept:application/vnd.github.v3+json\" print(s)", "Licensed under the Apache License, Version 2.0 (the \"License\"); you", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "or not app_id or not webhook_secret: print( f\"private_key={private_key[1:10]} or app_id={app_id}", "app_id def _request_app_delivery(token, iid=None, api_url=ghapp_token.GITHUB_API_URL): url = f\"{api_url}/app/hook/deliveries\" if iid:", "API URL\", default=os.environ.get(\"GITHUB_API_URL\", ghapp_token.GITHUB_API_URL), ) parser.add_argument( \"--retry\", type=int, default=1, help=\"how", "time import requests import ghapp_token NAMESPACE = \"pipelines-as-code\" SECRET_NAME =", "= _request_webhooks_installed(token, api_url=api_url, owner_repo=owner_repo) r.raise_for_status() webhooks = r.json() if len(webhooks)", "\"{el_route}\" r = requests.request(\"POST\",el_route,data=payload.encode(\"utf-8\"),headers=headers) r.raise_for_status() print(\"Request has been replayed on", "bool, deliveries: dict) -> int: dico = [] i =", "the License. # See README.md for documentation import typing import", "api_url=api_url) r.raise_for_status() deliveries = r.json() if not deliveries: print(\"no deliveries", "dico.append(delivery[\"id\"]) if i == 10: break i += 1 chosen", "r = _request_webhooks_reattempt( token=token, owner_repo=owner_repo, iid=webhook_id, api_url=api_url, delivery_id=delivery_id, ) r.raise_for_status()", "str, iid: typing.Union[int, None] = None, api_url: str = ghapp_token.GITHUB_API_URL,", "= base64.b64decode(jeez[\"data\"][\"github-private-key\"]) app_id = base64.b64decode(jeez[\"data\"][\"github-application-id\"]) webhook_secret = base64.b64decode(jeez[\"data\"][\"webhook.secret\"]).decode() if not", "compliance with the License. You may obtain # a copy", "int(webhooks[0][\"id\"]) elif len(webhooks) > 1: cnt = 1 for wh", "f\"{api_url}/app/hook/deliveries\" if iid: url += f\"/{iid}\" headers = { \"Accept\":", "s = f\"\"\"#!/usr/bin/env python3 import requests import sys payload =", ") return ( \"https://\" + json.loads(elroute.stdout)[\"items\"][0][\"status\"][\"ingress\"][0][\"host\"] ) def get_controller_ingress(): elroute", "bool = False, api_url: str = ghapp_token.GITHUB_API_URL, ) -> str:", "up\") time.sleep(5) continue print(f\"Payload has been replayed on {el}: {r}\")", "parser.add_argument( \"--save\", \"-s\", help=\"save the request to a shell script", "under the License. # See README.md for documentation import typing", "1], api_url=api_url).json() return int(chosen) - 1 def webhook_get_delivery( token: str,", "return int(chosen) - 1 def webhook_get_delivery( token: str, owner_repo: str,", "See README.md for documentation import typing import argparse import base64", "last: delivery_id = deliveries[0][\"id\"] else: chosen = ask_which(token, api_url, last,", "webhook_id = int(webhooks[0][\"id\"]) elif len(webhooks) > 1: cnt = 1", "your repo {}\") sys.exit(1) r = _request_webhooks_installed( token, api_url=api_url, owner_repo=owner_repo,", "headers=headers) def ask_which(token: str, api_url: str, last: bool, deliveries: dict)", "None, api_url: str = ghapp_token.GITHUB_API_URL, ): url = f\"{api_url}/repos/{owner_repo}/hooks\" if", "a delivery: \") # return _request_app_delivery(token, dico[int(chosen) - 1], api_url=api_url).json()", "\"--api-url\", help=\"Github API URL\", default=os.environ.get(\"GITHUB_API_URL\", ghapp_token.GITHUB_API_URL), ) parser.add_argument( \"--retry\", type=int,", "the # License for the specific language governing permissions and", "# # Unless required by applicable law or agreed to", ") return gh.token, webhook_secret, app_id def _request_app_delivery(token, iid=None, api_url=ghapp_token.GITHUB_API_URL): url", "-*- # Author: <NAME> <<EMAIL>> # # Licensed under the", "json import os import subprocess import sys import time import", "type=int, default=1, help=\"how many time to try to contact the", "range(args.retry): try: r = requests.request( \"POST\", el, data=payload.encode(\"utf-8\"), headers=headers )", "easily\" ) parser.add_argument( \"-a\", \"--api-url\", help=\"Github API URL\", default=os.environ.get(\"GITHUB_API_URL\", ghapp_token.GITHUB_API_URL),", "-> int: dico = [] i = 1 if \"message\"", "token: str, owner_repo: str, iid: int, delivery_id: int, api_url: str", "secret {SECRET_NAME} -n{NAMESPACE} -o json\", shell=True, check=True, capture_output=True, ) jeez", "\"POST\", el, data=payload.encode(\"utf-8\"), headers=headers ) except requests.exceptions.ConnectionError: print(f\"sleeping until {el}", "f' Authorization:\"Bearer { os.environ.get(\"PASS_TOKEN\", \"$TOKEN\") }\"' s += \" Accept:application/vnd.github.v3+json\"", "def _request_webhooks_reattempt( token: str, owner_repo: str, iid: int, delivery_id: int,", "\"application/vnd.github.v3+json\", \"Authorization\": f\"Bearer {token}\", } return requests.request(\"GET\", url, headers=headers) def", "capture_output=True, ) return ( \"http://\" + json.loads(elroute.stdout)[\"items\"][0][\"spec\"][\"rules\"][0][\"host\"] ) def get_token_secret(", "f\"/{iid}/deliveries\" headers = { \"Accept\": \"application/vnd.github.v3+json\", \"Authorization\": f\"Bearer {token}\", }", "subprocess.run( f\"kubectl get ingress -n {NAMESPACE} -l pipelines-as-code/route=controller -o json\",", "1: webhook_id = int(webhooks[0][\"id\"]) elif len(webhooks) > 1: cnt =", "import json import os import subprocess import sys import time", "if \"message\" in deliveries: print(deliveries) sys.exit(0) for delivery in deliveries:", "delivery_id: int, api_url: str = ghapp_token.GITHUB_API_URL, ): url = f\"{api_url}/repos/{owner_repo}/hooks/{iid}/deliveries/{delivery_id}/attempts\"", "subprocess.run( f\"kubectl get route -n {NAMESPACE} -l pipelines-as-code/route=controller -o json\",", "delivery[\"request\"][\"payload\"] headers = delivery[\"request\"][\"headers\"] payload = json.dumps(jeez) esha256 = hmac.new(", "parser.add_argument( \"-a\", \"--api-url\", help=\"Github API URL\", default=os.environ.get(\"GITHUB_API_URL\", ghapp_token.GITHUB_API_URL), ) parser.add_argument(", "wh in webhooks: print(f\"{cnt}) {wh['name']} - {wh['config']['url']} \") cnt +=", "fp.write(s) os.chmod(target, 0o755) print(f\"Request saved to {target}\") def main(args): el", "= subprocess.run( f\"kubectl get secret {SECRET_NAME} -n{NAMESPACE} -o json\", shell=True,", "2.0 (the \"License\"); you may # not use this file", "def main(args): el = args.eroute if not el: try: el", "subprocess.CalledProcessError: print(\"Could not find an ingress or route\") sys.exit(1) if", "= \"pipelines-as-code-secret\" ELNAME = \"pipelines-as-code\" EXPIRE_MINUTES_AS_SECONDS = ( int(os.environ.get(\"GITHUBAPP_TOKEN_EXPIRATION_MINUTES\", 10))", "return print(\"You have reached the maximum number of retries\") def", "1 def webhook_get_delivery( token: str, owner_repo: str, last: bool =", "help=\"Use a webhook-repo instead of app\" ) parser.add_argument(\"--webhook-token\", \"-t\", help=\"Use", "str, owner_repo: str, iid: int, delivery_id: int, api_url: str =", "limitations # under the License. # See README.md for documentation", "= f\"{api_url}/app/hook/deliveries\" if iid: url += f\"/{iid}\" headers = {", "s = f\"http POST {api_url}/repos/{owner_repo}/hooks/{webhook_id}/deliveries/{delivery_id}/attempts\" s += f' Authorization:\"Bearer {", "data=payload.encode(\"utf-8\"), headers=headers ) except requests.exceptions.ConnectionError: print(f\"sleeping until {el} is up\")", "deliveries: print(\"no deliveries has been set \") sys.exit(1) if last:", "by applicable law or agreed to in writing, software #", "if i == 10: break i += 1 chosen =", "webhook_secret, app_id = get_token_secret(github_api_url=args.api_url) delivery = app_get_delivery(token, args.last_event, args.api_url) jeez", "check=True, capture_output=True, ) return ( \"https://\" + json.loads(elroute.stdout)[\"items\"][0][\"status\"][\"ingress\"][0][\"host\"] ) def", "args.eroute if not el: try: el = get_controller_route() except subprocess.CalledProcessError:", "for delivery in deliveries: print( f\"{i}) Action={delivery['action']} Event={delivery['event']} Delivered at", "api_url: str = ghapp_token.GITHUB_API_URL ) -> dict: r = _request_app_delivery(token,", "f\"{api_url}/repos/{owner_repo}/hooks/{iid}/deliveries/{delivery_id}/attempts\" print(url) headers = { \"Accept\": \"application/vnd.github.v3+json\", \"Authorization\": f\"Bearer {token}\",", "subprocess.CalledProcessError: try: el = get_controller_ingress() except subprocess.CalledProcessError: print(\"Could not find", "for wh in webhooks: print(f\"{cnt}) {wh['name']} - {wh['config']['url']} \") cnt", "secret = subprocess.run( f\"kubectl get secret {SECRET_NAME} -n{NAMESPACE} -o json\",", "BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either", "+ el_route) \"\"\" with open(target, \"w\") as fp: fp.write(s) os.chmod(target,", "= requests.request(\"POST\",el_route,data=payload.encode(\"utf-8\"),headers=headers) r.raise_for_status() print(\"Request has been replayed on \" +", "break i += 1 chosen = input(\"Choose a delivery: \")", "configuration on your repo {}\") sys.exit(1) r = _request_webhooks_installed( token,", "print( f\"private_key={private_key[1:10]} or app_id={app_id} or webhook_secret={webhook_secret} are empty\" ) sys.exit(1)", "last=args.last_event, api_url=args.api_url, owner_repo=args.webhook_repo, ) if args.save: open(args.save, \"w\").write(f\"\"\"#!/usr/bin/env bash\\n{replays}\\n\"\"\") os.chmod(args.save,", "jeez = json.loads(secret.stdout) private_key = base64.b64decode(jeez[\"data\"][\"github-private-key\"]) app_id = base64.b64decode(jeez[\"data\"][\"github-application-id\"]) webhook_secret", "owner_repo: str, last: bool = False, api_url: str = ghapp_token.GITHUB_API_URL,", "requests.request(\"GET\", url, headers=headers) def _request_webhooks_reattempt( token: str, owner_repo: str, iid:", "os import subprocess import sys import time import requests import", "import ghapp_token NAMESPACE = \"pipelines-as-code\" SECRET_NAME = \"pipelines-as-code-secret\" ELNAME =", "#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Author: <NAME>", "if args.save: save_script(args.save, el, headers, jeez) sys.exit(0) for _ in", "shell=True, check=True, capture_output=True, ) jeez = json.loads(secret.stdout) private_key = base64.b64decode(jeez[\"data\"][\"github-private-key\"])", "have reached the maximum number of retries\") def parse_args(): parser", "= input(\"Choose a delivery: \") # return _request_app_delivery(token, dico[int(chosen) -", "except subprocess.CalledProcessError: try: el = get_controller_ingress() except subprocess.CalledProcessError: print(\"Could not", "\"Authorization\": f\"Bearer {token}\", } return requests.request(\"GET\", url, headers=headers) def _request_webhooks_reattempt(", "{}\") sys.exit(1) r = _request_webhooks_installed( token, api_url=api_url, owner_repo=owner_repo, iid=webhook_id )", "ghapp_token NAMESPACE = \"pipelines-as-code\" SECRET_NAME = \"pipelines-as-code-secret\" ELNAME = \"pipelines-as-code\"", "if last: delivery_id = deliveries[0][\"id\"] else: chosen = ask_which(token, api_url,", "not private_key or not app_id or not webhook_secret: print( f\"private_key={private_key[1:10]}", "el_route: str, headers: dict, payload: str): s = f\"\"\"#!/usr/bin/env python3", "request to a shell script to replay easily\" ) parser.add_argument(", "\"-S\", help=\"Use this webhook secret\") parser.add_argument( \"--save\", \"-s\", help=\"save the", "may obtain # a copy of the License at #", "\"-w\", help=\"Use a webhook-repo instead of app\" ) parser.add_argument(\"--webhook-token\", \"-t\",", ") parser.add_argument( \"--retry\", type=int, default=1, help=\"how many time to try", "for repo \" + jeez[\"repository\"][\"full_name\"]) headers.update( { \"X-Hub-Signature\": \"sha1=\" +", "int(chosen) - 1 def webhook_get_delivery( token: str, owner_repo: str, last:", "owner_repo: str, iid: int, delivery_id: int, api_url: str = ghapp_token.GITHUB_API_URL,", "sys import time import requests import ghapp_token NAMESPACE = \"pipelines-as-code\"", "continue print(f\"Payload has been replayed on {el}: {r}\") return print(\"You", "main(args): el = args.eroute if not el: try: el =", "= r.json() if len(webhooks) == 1: webhook_id = int(webhooks[0][\"id\"]) elif", "hostname (default to detect on openshift/ingress)\", default=os.environ.get(\"EL_ROUTE\"), ) parser.add_argument(\"--last-event\", \"-L\",", "Unless required by applicable law or agreed to in writing,", "try: r = requests.request( \"POST\", el, data=payload.encode(\"utf-8\"), headers=headers ) except", "import base64 import hashlib import hmac import json import os", "import argparse import base64 import hashlib import hmac import json", "int(os.environ.get(\"GITHUBAPP_TOKEN_EXPIRATION_MINUTES\", 10)) * 60 ) def get_controller_route(): elroute = subprocess.run(", "import os import subprocess import sys import time import requests", "_request_webhooks_installed(token, api_url=api_url, owner_repo=owner_repo) r.raise_for_status() webhooks = r.json() if len(webhooks) ==", "get ingress -n {NAMESPACE} -l pipelines-as-code/route=controller -o json\", shell=True, check=True,", "): url = f\"{api_url}/repos/{owner_repo}/hooks\" if iid: url += f\"/{iid}/deliveries\" headers", "\"\"\" with open(target, \"w\") as fp: fp.write(s) os.chmod(target, 0o755) print(f\"Request", "has been replayed on {el}: {r}\") return print(\"You have reached", "str, owner_repo: str, last: bool = False, api_url: str =", "api_url, last, r.json()) delivery_id = deliveries[chosen][\"id\"] r = _request_webhooks_reattempt( token=token,", "-> dict: r = _request_app_delivery(token, api_url=api_url) r.raise_for_status() deliveries = r.json()", "applicable law or agreed to in writing, software # distributed", "return requests.request(\"GET\", url, headers=headers) def _request_webhooks_reattempt( token: str, owner_repo: str,", "= \\\"\\\"\\\"{json.dumps(payload)}\\\"\\\"\\\" headers={headers} el_route = \"http://localhost:8080\" if (len(sys.argv) > 1", "digestmod=hashlib.sha256, ).hexdigest() esha1 = hmac.new( webhook_secret.encode(\"utf-8\"), msg=payload.encode(\"utf-8\"), digestmod=hashlib.sha1, ).hexdigest() print(\"Replay", "int, delivery_id: int, api_url: str = ghapp_token.GITHUB_API_URL, ): url =", "\"-a\", \"--api-url\", help=\"Github API URL\", default=os.environ.get(\"GITHUB_API_URL\", ghapp_token.GITHUB_API_URL), ) parser.add_argument( \"--retry\",", "url += f\"/{iid}/deliveries\" headers = { \"Accept\": \"application/vnd.github.v3+json\", \"Authorization\": f\"Bearer", "OF ANY KIND, either express or implied. See the #", "import sys import time import requests import ghapp_token NAMESPACE =", "str = ghapp_token.GITHUB_API_URL, ): url = f\"{api_url}/repos/{owner_repo}/hooks\" if iid: url", "permissions and limitations # under the License. # See README.md", "not find an ingress or route\") sys.exit(1) if args.webhook_repo: token,", "been replayed, you can replay directly it with: \") s", "base64.b64decode(jeez[\"data\"][\"github-application-id\"]) webhook_secret = base64.b64decode(jeez[\"data\"][\"webhook.secret\"]).decode() if not private_key or not app_id", "s += f' Authorization:\"Bearer { os.environ.get(\"PASS_TOKEN\", \"$TOKEN\") }\"' s +=", "try: el = get_controller_route() except subprocess.CalledProcessError: try: el = get_controller_ingress()", "requests.request( \"POST\", el, data=payload.encode(\"utf-8\"), headers=headers ) except requests.exceptions.ConnectionError: print(f\"sleeping until", "to detect on openshift/ingress)\", default=os.environ.get(\"EL_ROUTE\"), ) parser.add_argument(\"--last-event\", \"-L\", action=\"store_true\") parser.add_argument(", "it with: \") s = f\"http POST {api_url}/repos/{owner_repo}/hooks/{webhook_id}/deliveries/{delivery_id}/attempts\" s +=", "WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express", "in writing, software # distributed under the License is distributed", "the el route\", ) return parser.parse_args() if __name__ == \"__main__\":", "get_controller_route(): elroute = subprocess.run( f\"kubectl get route -n {NAMESPACE} -l", "shell=True, check=True, capture_output=True, ) return ( \"http://\" + json.loads(elroute.stdout)[\"items\"][0][\"spec\"][\"rules\"][0][\"host\"] )", "delivery: \") # return _request_app_delivery(token, dico[int(chosen) - 1], api_url=api_url).json() return", "> 1: cnt = 1 for wh in webhooks: print(f\"{cnt})", "\"http://\" + json.loads(elroute.stdout)[\"items\"][0][\"spec\"][\"rules\"][0][\"host\"] ) def get_token_secret( github_api_url=ghapp_token.GITHUB_API_URL, expiration_time=EXPIRE_MINUTES_AS_SECONDS ): secret", "{target}\") def main(args): el = args.eroute if not el: try:", "time to try to contact the el route\", ) return", "the maximum number of retries\") def parse_args(): parser = argparse.ArgumentParser(description=\"Replay", "{token}\", } return requests.request(\"GET\", url, headers=headers) def _request_webhooks_installed( token: str,", "r = _request_webhooks_installed( token, api_url=api_url, owner_repo=owner_repo, iid=webhook_id ) r.raise_for_status() deliveries", "\"-e\", dest=\"eroute\", help=\"Route hostname (default to detect on openshift/ingress)\", default=os.environ.get(\"EL_ROUTE\"),", "\"-s\", help=\"save the request to a shell script to replay", "parser.add_argument(\"--webhook-secret\", \"-S\", help=\"Use this webhook secret\") parser.add_argument( \"--save\", \"-s\", help=\"save", "webhook_secret={webhook_secret} are empty\" ) sys.exit(1) gh = ghapp_token.GitHub( private_key, app_id,", "- {wh['config']['url']} \") cnt += 1 chosen = input(\"Choose a", "import time import requests import ghapp_token NAMESPACE = \"pipelines-as-code\" SECRET_NAME", "\"Accept\": \"application/vnd.github.v3+json\", \"Authorization\": f\"Bearer {token}\", } return requests.request(\"GET\", url, headers=headers)", "event for repo \" + jeez[\"repository\"][\"full_name\"]) headers.update( { \"X-Hub-Signature\": \"sha1=\"", "help=\"Use this token\") parser.add_argument(\"--webhook-secret\", \"-S\", help=\"Use this webhook secret\") parser.add_argument(", "if last: return _request_app_delivery(token, deliveries[0][\"id\"], api_url=api_url).json() chosen = ask_which(token, api_url,", "= int(webhooks[int(chosen) - 1][\"id\"]) else: print(\"could not find any webhook", "str, headers: dict, payload: str): s = f\"\"\"#!/usr/bin/env python3 import", "dico = [] i = 1 if \"message\" in deliveries:", "webhook secret\") parser.add_argument( \"--save\", \"-s\", help=\"save the request to a", "webhook_secret = base64.b64decode(jeez[\"data\"][\"webhook.secret\"]).decode() if not private_key or not app_id or", "headers=headers) def _request_webhooks_installed( token: str, owner_repo: str, iid: typing.Union[int, None]", "\"application/vnd.github.v3+json\", \"Authorization\": f\"Bearer {token}\", } return requests.request(\"POST\", url, headers=headers) def", "elroute = subprocess.run( f\"kubectl get ingress -n {NAMESPACE} -l pipelines-as-code/route=controller", "f\"http POST {api_url}/repos/{owner_repo}/hooks/{webhook_id}/deliveries/{delivery_id}/attempts\" s += f' Authorization:\"Bearer { os.environ.get(\"PASS_TOKEN\", \"$TOKEN\")", "a webhook\") parser.add_argument( \"--installation-id\", \"-i\", default=os.environ.get(\"INSTALLATION_ID\"), help=\"Installation ID\", ) parser.add_argument(", "help=\"Installation ID\", ) parser.add_argument( \"--controller-route\", \"-e\", dest=\"eroute\", help=\"Route hostname (default", "last: bool, deliveries: dict) -> int: dico = [] i", "either express or implied. See the # License for the", "open(args.save, \"w\").write(f\"\"\"#!/usr/bin/env bash\\n{replays}\\n\"\"\") os.chmod(args.save, 0o755) print(f\"Saved to {args.save}\") sys.exit(0) else:", "webhook_secret.encode(\"utf-8\"), msg=payload.encode(\"utf-8\"), digestmod=hashlib.sha256, ).hexdigest() esha1 = hmac.new( webhook_secret.encode(\"utf-8\"), msg=payload.encode(\"utf-8\"), digestmod=hashlib.sha1,", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "sys.exit(0) for delivery in deliveries: print( f\"{i}) Action={delivery['action']} Event={delivery['event']} Delivered", "until {el} is up\") time.sleep(5) continue print(f\"Payload has been replayed", "{delivery['delivered_at']}\" ) dico.append(delivery[\"id\"]) if i == 10: break i +=", "token: str, owner_repo: str, last: bool = False, api_url: str", "webhooks: print(f\"{cnt}) {wh['name']} - {wh['config']['url']} \") cnt += 1 chosen", "may # not use this file except in compliance with", "iid: url += f\"/{iid}/deliveries\" headers = { \"Accept\": \"application/vnd.github.v3+json\", \"Authorization\":", "parser.add_argument( \"--webhook-repo\", \"-w\", help=\"Use a webhook-repo instead of app\" )", "private_key, app_id, expiration_time, github_api_url, ) return gh.token, webhook_secret, app_id def", "{wh['name']} - {wh['config']['url']} \") cnt += 1 chosen = input(\"Choose", "# License for the specific language governing permissions and limitations", "with the License. You may obtain # a copy of", "json.loads(secret.stdout) private_key = base64.b64decode(jeez[\"data\"][\"github-private-key\"]) app_id = base64.b64decode(jeez[\"data\"][\"github-application-id\"]) webhook_secret = base64.b64decode(jeez[\"data\"][\"webhook.secret\"]).decode()", "subprocess.run( f\"kubectl get secret {SECRET_NAME} -n{NAMESPACE} -o json\", shell=True, check=True,", "last: bool = False, api_url: str = ghapp_token.GITHUB_API_URL, ) ->", "= _request_app_delivery(token, api_url=api_url) r.raise_for_status() deliveries = r.json() if not deliveries:", "= [] i = 1 if \"message\" in deliveries: print(deliveries)", "argparse import base64 import hashlib import hmac import json import", "default=os.environ.get(\"GITHUB_API_URL\", ghapp_token.GITHUB_API_URL), ) parser.add_argument( \"--retry\", type=int, default=1, help=\"how many time", "= f\"{api_url}/repos/{owner_repo}/hooks/{iid}/deliveries/{delivery_id}/attempts\" print(url) headers = { \"Accept\": \"application/vnd.github.v3+json\", \"Authorization\": f\"Bearer", "you may # not use this file except in compliance", "\"message\" in deliveries: print(deliveries) sys.exit(0) for delivery in deliveries: print(", "_request_webhooks_installed( token: str, owner_repo: str, iid: typing.Union[int, None] = None,", "token=token, owner_repo=owner_repo, iid=webhook_id, api_url=api_url, delivery_id=delivery_id, ) r.raise_for_status() print(f\"Delivery has been", "iid=webhook_id ) r.raise_for_status() deliveries = r.json() if not deliveries: print(\"no", "with open(target, \"w\") as fp: fp.write(s) os.chmod(target, 0o755) print(f\"Request saved", "= delivery[\"request\"][\"payload\"] headers = delivery[\"request\"][\"headers\"] payload = json.dumps(jeez) esha256 =", "webhook_secret: print( f\"private_key={private_key[1:10]} or app_id={app_id} or webhook_secret={webhook_secret} are empty\" )", "-*- coding: utf-8 -*- # Author: <NAME> <<EMAIL>> # #", "base64.b64decode(jeez[\"data\"][\"github-private-key\"]) app_id = base64.b64decode(jeez[\"data\"][\"github-application-id\"]) webhook_secret = base64.b64decode(jeez[\"data\"][\"webhook.secret\"]).decode() if not private_key", "api_url=api_url).json() chosen = ask_which(token, api_url, last, deliveries) return _request_app_delivery( token,", "el, headers, jeez) sys.exit(0) for _ in range(args.retry): try: r", "json.loads(elroute.stdout)[\"items\"][0][\"status\"][\"ingress\"][0][\"host\"] ) def get_controller_ingress(): elroute = subprocess.run( f\"kubectl get ingress", "args.webhook_secret replays = webhook_get_delivery( token, last=args.last_event, api_url=args.api_url, owner_repo=args.webhook_repo, ) if", ").json() def save_script(target: str, el_route: str, headers: dict, payload: str):", "json.dumps(jeez) esha256 = hmac.new( webhook_secret.encode(\"utf-8\"), msg=payload.encode(\"utf-8\"), digestmod=hashlib.sha256, ).hexdigest() esha1 =", "api_url, last, deliveries) return _request_app_delivery( token, deliveries[chosen][\"id\"], api_url=api_url ).json() def", "url, headers=headers) def _request_webhooks_reattempt( token: str, owner_repo: str, iid: int,", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "_request_app_delivery(token, iid=None, api_url=ghapp_token.GITHUB_API_URL): url = f\"{api_url}/app/hook/deliveries\" if iid: url +=", "iid: typing.Union[int, None] = None, api_url: str = ghapp_token.GITHUB_API_URL, ):", "> 1 and sys.argv[1] == \"-l\") else \"{el_route}\" r =", "get_token_secret(github_api_url=args.api_url) delivery = app_get_delivery(token, args.last_event, args.api_url) jeez = delivery[\"request\"][\"payload\"] headers", "language governing permissions and limitations # under the License. #", "utf-8 -*- # Author: <NAME> <<EMAIL>> # # Licensed under", "print(deliveries) sys.exit(0) for delivery in deliveries: print( f\"{i}) Action={delivery['action']} Event={delivery['event']}", "# WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "can replay directly it with: \") s = f\"http POST", "the License is distributed on an \"AS IS\" BASIS, WITHOUT", "ELNAME = \"pipelines-as-code\" EXPIRE_MINUTES_AS_SECONDS = ( int(os.environ.get(\"GITHUBAPP_TOKEN_EXPIRATION_MINUTES\", 10)) * 60", ") if args.save: save_script(args.save, el, headers, jeez) sys.exit(0) for _", "elif len(webhooks) > 1: cnt = 1 for wh in", "route -n {NAMESPACE} -l pipelines-as-code/route=controller -o json\", shell=True, check=True, capture_output=True,", "gh = ghapp_token.GitHub( private_key, app_id, expiration_time, github_api_url, ) return gh.token,", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "\"--controller-route\", \"-e\", dest=\"eroute\", help=\"Route hostname (default to detect on openshift/ingress)\",", "False, api_url: str = ghapp_token.GITHUB_API_URL, ) -> str: r =", "1 and sys.argv[1] == \"-l\") else \"{el_route}\" r = requests.request(\"POST\",el_route,data=payload.encode(\"utf-8\"),headers=headers)", "= base64.b64decode(jeez[\"data\"][\"webhook.secret\"]).decode() if not private_key or not app_id or not", "parser.add_argument( \"--installation-id\", \"-i\", default=os.environ.get(\"INSTALLATION_ID\"), help=\"Installation ID\", ) parser.add_argument( \"--controller-route\", \"-e\",", ") parser.add_argument(\"--last-event\", \"-L\", action=\"store_true\") parser.add_argument( \"--webhook-repo\", \"-w\", help=\"Use a webhook-repo", "return gh.token, webhook_secret, app_id def _request_app_delivery(token, iid=None, api_url=ghapp_token.GITHUB_API_URL): url =", "esha256, } ) if args.save: save_script(args.save, el, headers, jeez) sys.exit(0)", "SECRET_NAME = \"pipelines-as-code-secret\" ELNAME = \"pipelines-as-code\" EXPIRE_MINUTES_AS_SECONDS = ( int(os.environ.get(\"GITHUBAPP_TOKEN_EXPIRATION_MINUTES\",", "import requests import ghapp_token NAMESPACE = \"pipelines-as-code\" SECRET_NAME = \"pipelines-as-code-secret\"", "str: r = _request_webhooks_installed(token, api_url=api_url, owner_repo=owner_repo) r.raise_for_status() webhooks = r.json()", "cnt += 1 chosen = input(\"Choose a delivery: \") webhook_id", "r.raise_for_status() webhooks = r.json() if len(webhooks) == 1: webhook_id =", "import requests import sys payload = \\\"\\\"\\\"{json.dumps(payload)}\\\"\\\"\\\" headers={headers} el_route =", "for the specific language governing permissions and limitations # under", "save_script(args.save, el, headers, jeez) sys.exit(0) for _ in range(args.retry): try:", "gh.token, webhook_secret, app_id def _request_app_delivery(token, iid=None, api_url=ghapp_token.GITHUB_API_URL): url = f\"{api_url}/app/hook/deliveries\"", "iid=None, api_url=ghapp_token.GITHUB_API_URL): url = f\"{api_url}/app/hook/deliveries\" if iid: url += f\"/{iid}\"", "10)) * 60 ) def get_controller_route(): elroute = subprocess.run( f\"kubectl", "deliveries has been set \") sys.exit(1) if last: return _request_app_delivery(token,", "webhook_secret.encode(\"utf-8\"), msg=payload.encode(\"utf-8\"), digestmod=hashlib.sha1, ).hexdigest() print(\"Replay event for repo \" +", "def _request_webhooks_installed( token: str, owner_repo: str, iid: typing.Union[int, None] =", "= hmac.new( webhook_secret.encode(\"utf-8\"), msg=payload.encode(\"utf-8\"), digestmod=hashlib.sha1, ).hexdigest() print(\"Replay event for repo", "print(f\"Saved to {args.save}\") sys.exit(0) else: token, webhook_secret, app_id = get_token_secret(github_api_url=args.api_url)", "f\"kubectl get secret {SECRET_NAME} -n{NAMESPACE} -o json\", shell=True, check=True, capture_output=True,", "def get_controller_ingress(): elroute = subprocess.run( f\"kubectl get ingress -n {NAMESPACE}", "api_url=args.api_url, owner_repo=args.webhook_repo, ) if args.save: open(args.save, \"w\").write(f\"\"\"#!/usr/bin/env bash\\n{replays}\\n\"\"\") os.chmod(args.save, 0o755)", "default=1, help=\"how many time to try to contact the el", "except in compliance with the License. You may obtain #", "import sys payload = \\\"\\\"\\\"{json.dumps(payload)}\\\"\\\"\\\" headers={headers} el_route = \"http://localhost:8080\" if", "= \"http://localhost:8080\" if (len(sys.argv) > 1 and sys.argv[1] == \"-l\")", "return ( \"https://\" + json.loads(elroute.stdout)[\"items\"][0][\"status\"][\"ingress\"][0][\"host\"] ) def get_controller_ingress(): elroute =", "\"$TOKEN\") }\"' s += \" Accept:application/vnd.github.v3+json\" print(s) return s def", "= r.json() if not deliveries: print(\"no deliveries has been set", "expiration_time, github_api_url, ) return gh.token, webhook_secret, app_id def _request_app_delivery(token, iid=None,", "= ( int(os.environ.get(\"GITHUBAPP_TOKEN_EXPIRATION_MINUTES\", 10)) * 60 ) def get_controller_route(): elroute", "def _request_app_delivery(token, iid=None, api_url=ghapp_token.GITHUB_API_URL): url = f\"{api_url}/app/hook/deliveries\" if iid: url", "print(f\"{cnt}) {wh['name']} - {wh['config']['url']} \") cnt += 1 chosen =", "{el}: {r}\") return print(\"You have reached the maximum number of", "api_url=api_url).json() return int(chosen) - 1 def webhook_get_delivery( token: str, owner_repo:", "help=\"save the request to a shell script to replay easily\"", "ID\", ) parser.add_argument( \"--controller-route\", \"-e\", dest=\"eroute\", help=\"Route hostname (default to", "License. You may obtain # a copy of the License", "ANY KIND, either express or implied. See the # License", "# distributed under the License is distributed on an \"AS", "{api_url}/repos/{owner_repo}/hooks/{webhook_id}/deliveries/{delivery_id}/attempts\" s += f' Authorization:\"Bearer { os.environ.get(\"PASS_TOKEN\", \"$TOKEN\") }\"' s", "f\"\"\"#!/usr/bin/env python3 import requests import sys payload = \\\"\\\"\\\"{json.dumps(payload)}\\\"\\\"\\\" headers={headers}", "print(\"Could not find an ingress or route\") sys.exit(1) if args.webhook_repo:", "+ json.loads(elroute.stdout)[\"items\"][0][\"spec\"][\"rules\"][0][\"host\"] ) def get_token_secret( github_api_url=ghapp_token.GITHUB_API_URL, expiration_time=EXPIRE_MINUTES_AS_SECONDS ): secret =", "# Unless required by applicable law or agreed to in", "+ esha1, \"X-Hub-Signature-256\": \"sha256=\" + esha256, } ) if args.save:", "} ) if args.save: save_script(args.save, el, headers, jeez) sys.exit(0) for", "expiration_time=EXPIRE_MINUTES_AS_SECONDS ): secret = subprocess.run( f\"kubectl get secret {SECRET_NAME} -n{NAMESPACE}", "replay directly it with: \") s = f\"http POST {api_url}/repos/{owner_repo}/hooks/{webhook_id}/deliveries/{delivery_id}/attempts\"", "else: token, webhook_secret, app_id = get_token_secret(github_api_url=args.api_url) delivery = app_get_delivery(token, args.last_event,", "return requests.request(\"GET\", url, headers=headers) def _request_webhooks_installed( token: str, owner_repo: str,", "Event={delivery['event']} Delivered at {delivery['delivered_at']}\" ) dico.append(delivery[\"id\"]) if i == 10:", "= False, api_url: str = ghapp_token.GITHUB_API_URL, ) -> str: r", "repo {}\") sys.exit(1) r = _request_webhooks_installed( token, api_url=api_url, owner_repo=owner_repo, iid=webhook_id", "dict, payload: str): s = f\"\"\"#!/usr/bin/env python3 import requests import", "= args.webhook_token, args.webhook_secret replays = webhook_get_delivery( token, last=args.last_event, api_url=args.api_url, owner_repo=args.webhook_repo,", "is distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES", "print(s) return s def app_get_delivery( token: str, last: bool =", "with: \") s = f\"http POST {api_url}/repos/{owner_repo}/hooks/{webhook_id}/deliveries/{delivery_id}/attempts\" s += f'", "get_controller_ingress() except subprocess.CalledProcessError: print(\"Could not find an ingress or route\")", "-l pipelines-as-code/route=controller -o json\", shell=True, check=True, capture_output=True, ) return (", "= \"pipelines-as-code\" SECRET_NAME = \"pipelines-as-code-secret\" ELNAME = \"pipelines-as-code\" EXPIRE_MINUTES_AS_SECONDS =", "print(\"could not find any webhook configuration on your repo {}\")", "str, iid: int, delivery_id: int, api_url: str = ghapp_token.GITHUB_API_URL, ):", "get route -n {NAMESPACE} -l pipelines-as-code/route=controller -o json\", shell=True, check=True,", "to a shell script to replay easily\" ) parser.add_argument( \"-a\",", "shell=True, check=True, capture_output=True, ) return ( \"https://\" + json.loads(elroute.stdout)[\"items\"][0][\"status\"][\"ingress\"][0][\"host\"] )", "pipelines-as-code/route=controller -o json\", shell=True, check=True, capture_output=True, ) return ( \"http://\"", "delivery_id = deliveries[chosen][\"id\"] r = _request_webhooks_reattempt( token=token, owner_repo=owner_repo, iid=webhook_id, api_url=api_url,", "el: try: el = get_controller_route() except subprocess.CalledProcessError: try: el =", "help=\"Route hostname (default to detect on openshift/ingress)\", default=os.environ.get(\"EL_ROUTE\"), ) parser.add_argument(\"--last-event\",", "+= \" Accept:application/vnd.github.v3+json\" print(s) return s def app_get_delivery( token: str,", "url, headers=headers) def ask_which(token: str, api_url: str, last: bool, deliveries:", "str = ghapp_token.GITHUB_API_URL, ) -> str: r = _request_webhooks_installed(token, api_url=api_url,", "delivery_id = deliveries[0][\"id\"] else: chosen = ask_which(token, api_url, last, r.json())", "return ( \"http://\" + json.loads(elroute.stdout)[\"items\"][0][\"spec\"][\"rules\"][0][\"host\"] ) def get_token_secret( github_api_url=ghapp_token.GITHUB_API_URL, expiration_time=EXPIRE_MINUTES_AS_SECONDS", "headers={headers} el_route = \"http://localhost:8080\" if (len(sys.argv) > 1 and sys.argv[1]", "\" + el_route) \"\"\" with open(target, \"w\") as fp: fp.write(s)", "\"-t\", help=\"Use this token\") parser.add_argument(\"--webhook-secret\", \"-S\", help=\"Use this webhook secret\")", "License. # See README.md for documentation import typing import argparse", "json\", shell=True, check=True, capture_output=True, ) jeez = json.loads(secret.stdout) private_key =", "= ghapp_token.GITHUB_API_URL ) -> dict: r = _request_app_delivery(token, api_url=api_url) r.raise_for_status()", "been set \") sys.exit(1) if last: return _request_app_delivery(token, deliveries[0][\"id\"], api_url=api_url).json()", ") def get_controller_route(): elroute = subprocess.run( f\"kubectl get route -n", "is up\") time.sleep(5) continue print(f\"Payload has been replayed on {el}:", "( \"https://\" + json.loads(elroute.stdout)[\"items\"][0][\"status\"][\"ingress\"][0][\"host\"] ) def get_controller_ingress(): elroute = subprocess.run(", "= input(\"Choose a delivery: \") webhook_id = int(webhooks[int(chosen) - 1][\"id\"])", "len(webhooks) > 1: cnt = 1 for wh in webhooks:", "as fp: fp.write(s) os.chmod(target, 0o755) print(f\"Request saved to {target}\") def", "0o755) print(f\"Request saved to {target}\") def main(args): el = args.eroute", "owner_repo: str, iid: typing.Union[int, None] = None, api_url: str =", "Author: <NAME> <<EMAIL>> # # Licensed under the Apache License,", "= _request_webhooks_installed( token, api_url=api_url, owner_repo=owner_repo, iid=webhook_id ) r.raise_for_status() deliveries =" ]
[ ".algolia import search_by_nsuid from .algolia import search_by_platform from .algolia import", "import search_by_nsuid from .algolia import search_by_platform from .algolia import search_by_query", "from .algolia import search_by_nsuid from .algolia import search_by_platform from .algolia", "<gh_stars>10-100 from .algolia import search_by_nsuid from .algolia import search_by_platform from" ]
[ "into dict (lt) and count how many # for each", "possible from the window start and then update the result.", "still a desirable one we keep on updating the minimum", "# Space:O(|S|+|T|) # Optimized Sliding Window # A small improvement", "desirable any more, we repeat step 2 onwards. # The", "1 # missing is to count how many remaining char", "end = 0, 0 i = 0 for j, char", "A small improvement to the above approach can reduce the", "c in lt and lt[c] > 0: missing -= 1", "result window is s[I:J]. In need[c] I store how many", "J = 0 for j, c in enumerate(s, 1): if", "i += 1 continue else: # if lt contains s[i],", "= i, j i += 1 #update i to start+1", "1 if missing == 0: #match all chars while i", "is to count how many remaining char needed from substring", "> 0: missing -= 1 need[char] -= 1 if missing", "not in lt: lt[i] = 1 else: lt[i] += 1", "we repeat step 2 onwards. # The current window is", "class Solution: def minWindow(self, s: str, t: str) -> str:", "# for each char for i in t: if i", "if need[char] > 0: missing -= 1 need[char] -= 1", "0 i = 0 for j, char in enumerate(s, 1):", "s[i:j] and the result window is s[I:J]. In need[c] I", "in t: if i not in lt: lt[i] = 1", "more, then missing +1 if lt[s[i]] > 0: missing +=", "window is not desirable any more, we repeat step 2", "all of the characters of T. # Once we have", "window i.e. a window that contains all of the characters", "how many remaining char needed from substring # finally get", "by 1 if end == 0 or j-i < end-start:", "minimum window size. # If the window is not desirable", "if s[i] not in lt: i += 1 continue else:", "candidate while i < j and not missing: if not", "keep on updating the minimum window size. # If the", "> 0: missing += 1 i += 1 return s[I:J]", "# missing is to count how many remaining char needed", "approach can reduce the time complexity of the algorithm to", "char in enumerate(s, 1): #index j from 1 if need[char]", "lt can be negative lt[c] -= 1 # i is", "'' lt = {} # put t into dict (lt)", "i to start+1 for next window return s[start:end] # Time:", "formed from S by removing all the elements not present", "1 need[s[i]] += 1 #make sure the first appearing char", "above approach can reduce the time complexity of the algorithm", "need = collections.Counter(t) #hash table to store char frequency missing", "of the characters of T. # Once we have a", "as possible from the window start and then update the", "in enumerate(s, 1): #index j from 1 if need[char] >", "< n: return '' lt = {} # put t", "if lt contains s[i], then # of s[i] +1, might", "characters, we can move the left pointer ahead one by", "I, J = i, j if s[i] not in lt:", "In the loop, first add the new character to the", "# We start with two pointers, leftleft and rightright initially", "rightright initially pointing to the first element of the string", "j from 1 if need[char] > 0: missing -= 1", "of t missing = n i = I = J", "count how many # for each char for i in", "lt: lt[i] = 1 else: lt[i] += 1 # missing", "> 0: missing -= 1 if c in lt: #", "missing -= 1 if c in lt: # lt can", "#total number of chars we care start, end = 0,", "of chars we care start, end = 0, 0 i", "to expand the window until we get a desirable window", "+= 1 # if > 0, means we need more,", "0, means we need more, then missing +1 if lt[s[i]]", "# Refer from: # https://leetcode.com/problems/minimum-window-substring/solution/ # Sliding Window # We", "use the rightright pointer to expand the window until we", "char frequency missing = len(t) #total number of chars we", "In need[c] I store how many times I # need", "1): #index j from 1 if need[char] > 0: missing", "remove as much as possible from the window start and", "next window return s[start:end] # Time: O(|S|+|T|) # Space:O(|S|+|T|) #", "missing = n i = I = J = 0", "to start+1 for next window return s[start:end] # Time: O(|S|+|T|)", "lt: i += 1 continue else: # if lt contains", "# if lt contains s[i], then # of s[i] +1,", "the string S. # We use the rightright pointer to", "many # for each char for i in t: if", "lt and lt[c] > 0: missing -= 1 if c", "satisfy need of t missing = n i = I", "s[start:end] # Time: O(|S|+|T|) # Space:O(|S|+|T|) # Refer from: #", "the real start need[s[i]] += 1 i += 1 need[s[i]]", "on updating the minimum window size. # If the window", "The current window is s[i:j] and the result window is", "else: lt[i] += 1 # missing is to count how", "character to the window. Then, if nothing is missing, #", "need[s[i]] += 1 i += 1 need[s[i]] += 1 #make", "S by removing all the elements not present in T", "j, c in enumerate(s, 1): if c in lt and", "this first char, so add missing by 1 if end", "and count how many # for each char for i", "We start with two pointers, leftleft and rightright initially pointing", "while i < j and need[s[i]] < 0: #remove chars", "i is index of candidate substring, remove as many as", "lt[s[i]] += 1 # if > 0, means we need", "of candidate substring, remove as many as char from candidate", "characters of T. # Once we have a window with", "1 if need[char] > 0: missing -= 1 need[char] -=", "from 1 if need[char] > 0: missing -= 1 need[char]", "chars while i < j and need[s[i]] < 0: #remove", "much as possible from the window start and then update", "is still a desirable one we keep on updating the", "-> str: m = len(s) n = len(t) if m", "missing: if not J or j-i < J-I: I, J", "desirable window i.e. a window that contains all of the", "store how many times I # need character c (can", "window is still a desirable one we keep on updating", "if nothing is missing, # remove as much as possible", "update the result. class Solution: def minWindow(self, s: str, t:", "complexity of the algorithm to O(2*∣filtered_S∣+∣S∣+∣T∣), # where filtered(S) is", "1 i += 1 need[s[i]] += 1 #make sure the", "are still missing. # In the loop, first add the", "solution # V2 def minWindow(s, t): need = collections.Counter(t) #hash", "for j, c in enumerate(s, 1): if c in lt", "m = len(s) n = len(t) if m < n:", "need[char]>0 missing += 1 #we missed this first char, so", "times I # need character c (can be negative) and", "if c in lt and lt[c] > 0: missing -=", "if lt[s[i]] > 0: missing += 1 i += 1", "add missing by 1 if end == 0 or j-i", "needed from substring # finally get candidate substring which satisfy", "i, j i += 1 #update i to start+1 for", "== 0: #match all chars while i < j and", "str) -> str: m = len(s) n = len(t) if", "# Space:O(|S|+|T|) # Refer from: # https://leetcode.com/problems/minimum-window-substring/solution/ # Sliding Window", "lt: # lt can be negative lt[c] -= 1 #", "= len(t) #total number of chars we care start, end", "If the window is not desirable any more, we repeat", "lt[s[i]] > 0: missing += 1 i += 1 return", "we care start, end = 0, 0 i = 0", "candidate substring, remove as many as char from candidate while", "window start and then update the result. class Solution: def", "pointing to the first element of the string S. #", "minWindow(self, s: str, t: str) -> str: m = len(s)", "how many times I # need character c (can be", "remove as many as char from candidate while i <", "end = i, j i += 1 #update i to", "small improvement to the above approach can reduce the time", "rightright pointer to expand the window until we get a", "time complexity of the algorithm to O(2*∣filtered_S∣+∣S∣+∣T∣), # where filtered(S)", "if missing == 0: #match all chars while i <", "t: str) -> str: m = len(s) n = len(t)", "#remove chars to find the real start need[s[i]] += 1", "J = i, j if s[i] not in lt: i", "char for i in t: if i not in lt:", "char satisfies need[char]>0 missing += 1 #we missed this first", "one we keep on updating the minimum window size. #", "i < j and not missing: if not J or", "or j-i < J-I: I, J = i, j if", "-= 1 # i is index of candidate substring, remove", "0 lt[s[i]] += 1 # if > 0, means we", "the left pointer ahead one by one. If the window", "many as char from candidate while i < j and", "1 # if > 0, means we need more, then", "not desirable any more, we repeat step 2 onwards. #", "i += 1 #update i to start+1 for next window", "satisfies need[char]>0 missing += 1 #we missed this first char,", "if c in lt: # lt can be negative lt[c]", "string formed from S by removing all the elements not", "real start need[s[i]] += 1 i += 1 need[s[i]] +=", "onwards. # The current window is s[i:j] and the result", "and missing tells how many characters are still missing. #", "or j-i < end-start: #update window start, end = i,", "a window that contains all of the characters of T.", "== 0 or j-i < end-start: #update window start, end", "s[i] +1, might reach to 0 lt[s[i]] += 1 #", "is the string formed from S by removing all the", "Time: O(|S|+|T|) # Space:O(|S|+|T|) # Optimized Sliding Window # A", "t missing = n i = I = J =", "window is s[I:J]. In need[c] I store how many times", "for each char for i in t: if i not", "char, so add missing by 1 if end == 0", "index of candidate substring, remove as many as char from", "then missing +1 if lt[s[i]] > 0: missing += 1", "string S. # We use the rightright pointer to expand", "# where filtered(S) is the string formed from S by", "Time: O(|S|+|T|) # Space:O(|S|+|T|) # Refer from: # https://leetcode.com/problems/minimum-window-substring/solution/ #", "start and then update the result. class Solution: def minWindow(self,", "for i in t: if i not in lt: lt[i]", "+= 1 i += 1 return s[I:J] # Time: O(|S|+|T|)", "to O(2*∣filtered_S∣+∣S∣+∣T∣), # where filtered(S) is the string formed from", "0, 0 i = 0 for j, char in enumerate(s,", "means we need more, then missing +1 if lt[s[i]] >", "start, end = 0, 0 i = 0 for j,", "char needed from substring # finally get candidate substring which", "how many characters are still missing. # In the loop,", "current window is s[i:j] and the result window is s[I:J].", "window is s[i:j] and the result window is s[I:J]. In", "put t into dict (lt) and count how many #", "the first appearing char satisfies need[char]>0 missing += 1 #we", "need[char] > 0: missing -= 1 need[char] -= 1 if", "#update window start, end = i, j i += 1", "1 #make sure the first appearing char satisfies need[char]>0 missing", "Window # We start with two pointers, leftleft and rightright", "Other solution # V2 def minWindow(s, t): need = collections.Counter(t)", "by one. If the window is still a desirable one", "the window. Then, if nothing is missing, # remove as", "have a window with all the characters, we can move", "window. Then, if nothing is missing, # remove as much", "We use the rightright pointer to expand the window until", "str, t: str) -> str: m = len(s) n =", "# put t into dict (lt) and count how many", "pointer to expand the window until we get a desirable", "start, end = i, j i += 1 #update i", "frequency missing = len(t) #total number of chars we care", "< 0: #remove chars to find the real start need[s[i]]", "+1, might reach to 0 lt[s[i]] += 1 # if", "care start, end = 0, 0 i = 0 for", "from the window start and then update the result. class", "we need more, then missing +1 if lt[s[i]] > 0:", "to the window. Then, if nothing is missing, # remove", "continue else: # if lt contains s[i], then # of", "Optimized Sliding Window # A small improvement to the above", "return '' lt = {} # put t into dict", "i not in lt: lt[i] = 1 else: lt[i] +=", "pointer ahead one by one. If the window is still", "find the real start need[s[i]] += 1 i += 1", "missing tells how many characters are still missing. # In", "window size. # If the window is not desirable any", "the minimum window size. # If the window is not", "t: if i not in lt: lt[i] = 1 else:", "i in t: if i not in lt: lt[i] =", "contains all of the characters of T. # Once we", "need[char] -= 1 if missing == 0: #match all chars", "with all the characters, we can move the left pointer", "def minWindow(s, t): need = collections.Counter(t) #hash table to store", "c in enumerate(s, 1): if c in lt and lt[c]", "count how many remaining char needed from substring # finally", "missing +1 if lt[s[i]] > 0: missing += 1 i", "contains s[i], then # of s[i] +1, might reach to", "-= 1 need[char] -= 1 if missing == 0: #match", "lt[i] += 1 # missing is to count how many", "1): if c in lt and lt[c] > 0: missing", "as char from candidate while i < j and not", "O(2*∣filtered_S∣+∣S∣+∣T∣), # where filtered(S) is the string formed from S", "from S by removing all the elements not present in", "> 0, means we need more, then missing +1 if", "-= 1 if missing == 0: #match all chars while", "tells how many characters are still missing. # In the", "missing. # In the loop, first add the new character", "window until we get a desirable window i.e. a window", "missing == 0: #match all chars while i < j", "str: m = len(s) n = len(t) if m <", "s[I:J] # Time: O(|S|+|T|) # Space:O(|S|+|T|) # Optimized Sliding Window", "1 i += 1 return s[I:J] # Time: O(|S|+|T|) #", "add the new character to the window. Then, if nothing", "a desirable window i.e. a window that contains all of", "is missing, # remove as much as possible from the", "missing += 1 #we missed this first char, so add", "ahead one by one. If the window is still a", "the window is still a desirable one we keep on", "# If the window is not desirable any more, we", "Once we have a window with all the characters, we", "a window with all the characters, we can move the", "# of s[i] +1, might reach to 0 lt[s[i]] +=", "+= 1 return s[I:J] # Time: O(|S|+|T|) # Space:O(|S|+|T|) #", "# Time: O(|S|+|T|) # Space:O(|S|+|T|) # Refer from: # https://leetcode.com/problems/minimum-window-substring/solution/", "window with all the characters, we can move the left", "pointers, leftleft and rightright initially pointing to the first element", "many remaining char needed from substring # finally get candidate", "c in lt: # lt can be negative lt[c] -=", "then # of s[i] +1, might reach to 0 lt[s[i]]", "= n i = I = J = 0 for", "= J = 0 for j, c in enumerate(s, 1):", "+= 1 # missing is to count how many remaining", "0: missing -= 1 need[char] -= 1 if missing ==", "(can be negative) and missing tells how many characters are", "element of the string S. # We use the rightright", "1 else: lt[i] += 1 # missing is to count", "the new character to the window. Then, if nothing is", "j-i < end-start: #update window start, end = i, j", "from: # https://leetcode.com/problems/minimum-window-substring/solution/ # Sliding Window # We start with", "a desirable one we keep on updating the minimum window", "0: #remove chars to find the real start need[s[i]] +=", "n i = I = J = 0 for j,", "missed this first char, so add missing by 1 if", "the rightright pointer to expand the window until we get", "filtered(S) is the string formed from S by removing all", "S. # We use the rightright pointer to expand the", "improvement to the above approach can reduce the time complexity", "need[c] I store how many times I # need character", "If the window is still a desirable one we keep", "= 1 else: lt[i] += 1 # missing is to", "# finally get candidate substring which satisfy need of t", "V2 def minWindow(s, t): need = collections.Counter(t) #hash table to", "len(t) #total number of chars we care start, end =", "t into dict (lt) and count how many # for", "m < n: return '' lt = {} # put", "first char, so add missing by 1 if end ==", "I = J = 0 for j, c in enumerate(s,", "0 or j-i < end-start: #update window start, end =", "need[s[i]] < 0: #remove chars to find the real start", "the above approach can reduce the time complexity of the", "to find the real start need[s[i]] += 1 i +=", "< j and not missing: if not J or j-i", "repeat step 2 onwards. # The current window is s[i:j]", "i, j if s[i] not in lt: i += 1", "1 continue else: # if lt contains s[i], then #", "O(|S|+|T|) # Space:O(|S|+|T|) # Optimized Sliding Window # A small", "reduce the time complexity of the algorithm to O(2*∣filtered_S∣+∣S∣+∣T∣), #", "j and need[s[i]] < 0: #remove chars to find the", "the characters, we can move the left pointer ahead one", "left pointer ahead one by one. If the window is", "can be negative lt[c] -= 1 # i is index", "one. If the window is still a desirable one we", "missing is to count how many remaining char needed from", "desirable one we keep on updating the minimum window size.", "J or j-i < J-I: I, J = i, j", "step 2 onwards. # The current window is s[i:j] and", "1 if end == 0 or j-i < end-start: #update", "we get a desirable window i.e. a window that contains", "# We use the rightright pointer to expand the window", "get a desirable window i.e. a window that contains all", "0: missing += 1 i += 1 return s[I:J] #", "in enumerate(s, 1): if c in lt and lt[c] >", "# Once we have a window with all the characters,", "is not desirable any more, we repeat step 2 onwards.", "# remove as much as possible from the window start", "n: return '' lt = {} # put t into", "need more, then missing +1 if lt[s[i]] > 0: missing", "first appearing char satisfies need[char]>0 missing += 1 #we missed", "as many as char from candidate while i < j", "# In the loop, first add the new character to", "window that contains all of the characters of T. #", "len(t) if m < n: return '' lt = {}", "s[i], then # of s[i] +1, might reach to 0", "i += 1 return s[I:J] # Time: O(|S|+|T|) # Space:O(|S|+|T|)", "be negative lt[c] -= 1 # i is index of", "reach to 0 lt[s[i]] += 1 # if > 0,", "so add missing by 1 if end == 0 or", "first element of the string S. # We use the", "need of t missing = n i = I =", "missing = len(t) #total number of chars we care start,", "the time complexity of the algorithm to O(2*∣filtered_S∣+∣S∣+∣T∣), # where", "https://leetcode.com/problems/minimum-window-substring/solution/ # Sliding Window # We start with two pointers,", "get candidate substring which satisfy need of t missing =", "# https://leetcode.com/problems/minimum-window-substring/solution/ # Sliding Window # We start with two", "in lt: lt[i] = 1 else: lt[i] += 1 #", "is s[i:j] and the result window is s[I:J]. In need[c]", "start with two pointers, leftleft and rightright initially pointing to", "end == 0 or j-i < end-start: #update window start,", "of the algorithm to O(2*∣filtered_S∣+∣S∣+∣T∣), # where filtered(S) is the", "i = 0 for j, char in enumerate(s, 1): #index", "t): need = collections.Counter(t) #hash table to store char frequency", "< j and need[s[i]] < 0: #remove chars to find", "character c (can be negative) and missing tells how many", "chars to find the real start need[s[i]] += 1 i", "expand the window until we get a desirable window i.e.", "that contains all of the characters of T. # Once", "j i += 1 #update i to start+1 for next", "any more, we repeat step 2 onwards. # The current", "1 #update i to start+1 for next window return s[start:end]", "#we missed this first char, so add missing by 1", "in lt: # lt can be negative lt[c] -= 1", "the window is not desirable any more, we repeat step", "Sliding Window # We start with two pointers, leftleft and", "i = I = J = 0 for j, c", "if m < n: return '' lt = {} #", "table to store char frequency missing = len(t) #total number", "Solution: def minWindow(self, s: str, t: str) -> str: m", "and then update the result. class Solution: def minWindow(self, s:", "loop, first add the new character to the window. Then,", "Refer from: # https://leetcode.com/problems/minimum-window-substring/solution/ # Sliding Window # We start", "not J or j-i < J-I: I, J = i,", "s[I:J]. In need[c] I store how many times I #", "def minWindow(self, s: str, t: str) -> str: m =", "and need[s[i]] < 0: #remove chars to find the real", "size. # If the window is not desirable any more,", "and not missing: if not J or j-i < J-I:", "to count how many remaining char needed from substring #", "with two pointers, leftleft and rightright initially pointing to the", "{} # put t into dict (lt) and count how", "sure the first appearing char satisfies need[char]>0 missing += 1", "the result. class Solution: def minWindow(self, s: str, t: str)", "len(s) n = len(t) if m < n: return ''", "#hash table to store char frequency missing = len(t) #total", "n = len(t) if m < n: return '' lt", "T. # Once we have a window with all the", "Window # A small improvement to the above approach can", "dict (lt) and count how many # for each char", "# Sliding Window # We start with two pointers, leftleft", "= {} # put t into dict (lt) and count", "where filtered(S) is the string formed from S by removing", "chars we care start, end = 0, 0 i =", "I # need character c (can be negative) and missing", "move the left pointer ahead one by one. If the", "# need character c (can be negative) and missing tells", "all the characters, we can move the left pointer ahead", "to store char frequency missing = len(t) #total number of", "new character to the window. Then, if nothing is missing,", "remaining char needed from substring # finally get candidate substring", "enumerate(s, 1): if c in lt and lt[c] > 0:", "if > 0, means we need more, then missing +1", "c (can be negative) and missing tells how many characters", "+= 1 #make sure the first appearing char satisfies need[char]>0", "as much as possible from the window start and then", "start need[s[i]] += 1 i += 1 need[s[i]] += 1", "+= 1 i += 1 need[s[i]] += 1 #make sure", "to 0 lt[s[i]] += 1 # if > 0, means", "substring, remove as many as char from candidate while i", "+= 1 continue else: # if lt contains s[i], then", "the characters of T. # Once we have a window", "and the result window is s[I:J]. In need[c] I store", "j if s[i] not in lt: i += 1 continue", "might reach to 0 lt[s[i]] += 1 # if >", "if not J or j-i < J-I: I, J =", "0 for j, c in enumerate(s, 1): if c in", "store char frequency missing = len(t) #total number of chars", "# lt can be negative lt[c] -= 1 # i", "j-i < J-I: I, J = i, j if s[i]", "each char for i in t: if i not in", "j, char in enumerate(s, 1): #index j from 1 if", "0: #match all chars while i < j and need[s[i]]", "i.e. a window that contains all of the characters of", "the result window is s[I:J]. In need[c] I store how", "Sliding Window # A small improvement to the above approach", "characters are still missing. # In the loop, first add", "nothing is missing, # remove as much as possible from", "collections.Counter(t) #hash table to store char frequency missing = len(t)", "lt = {} # put t into dict (lt) and", "for next window return s[start:end] # Time: O(|S|+|T|) # Space:O(|S|+|T|)", "missing += 1 i += 1 return s[I:J] # Time:", "0: missing -= 1 if c in lt: # lt", "can move the left pointer ahead one by one. If", "lt[c] -= 1 # i is index of candidate substring,", "+1 if lt[s[i]] > 0: missing += 1 i +=", "#index j from 1 if need[char] > 0: missing -=", "lt contains s[i], then # of s[i] +1, might reach", "Then, if nothing is missing, # remove as much as", "lt[c] > 0: missing -= 1 if c in lt:", "two pointers, leftleft and rightright initially pointing to the first", "i < j and need[s[i]] < 0: #remove chars to", "s[i] not in lt: i += 1 continue else: #", "missing by 1 if end == 0 or j-i <", "number of chars we care start, end = 0, 0", "of the string S. # We use the rightright pointer", "missing, # remove as much as possible from the window", "for j, char in enumerate(s, 1): #index j from 1", "+= 1 #update i to start+1 for next window return", "0 for j, char in enumerate(s, 1): #index j from", "all chars while i < j and need[s[i]] < 0:", "from substring # finally get candidate substring which satisfy need", "2 onwards. # The current window is s[i:j] and the", "negative) and missing tells how many characters are still missing.", "how many # for each char for i in t:", "the first element of the string S. # We use", "#make sure the first appearing char satisfies need[char]>0 missing +=", "and rightright initially pointing to the first element of the", "appearing char satisfies need[char]>0 missing += 1 #we missed this", "< J-I: I, J = i, j if s[i] not", "we keep on updating the minimum window size. # If", "from candidate while i < j and not missing: if", "1 #we missed this first char, so add missing by", "i += 1 need[s[i]] += 1 #make sure the first", "not in lt: i += 1 continue else: # if", "Space:O(|S|+|T|) # Refer from: # https://leetcode.com/problems/minimum-window-substring/solution/ # Sliding Window #", "end-start: #update window start, end = i, j i +=", "else: # if lt contains s[i], then # of s[i]", "window return s[start:end] # Time: O(|S|+|T|) # Space:O(|S|+|T|) # Refer", "negative lt[c] -= 1 # i is index of candidate", "return s[start:end] # Time: O(|S|+|T|) # Space:O(|S|+|T|) # Refer from:", "1 need[char] -= 1 if missing == 0: #match all", "= collections.Counter(t) #hash table to store char frequency missing =", "O(|S|+|T|) # Space:O(|S|+|T|) # Refer from: # https://leetcode.com/problems/minimum-window-substring/solution/ # Sliding", "if end == 0 or j-i < end-start: #update window", "to the above approach can reduce the time complexity of", "the string formed from S by removing all the elements", "leftleft and rightright initially pointing to the first element of", "I store how many times I # need character c", "#update i to start+1 for next window return s[start:end] #", "can reduce the time complexity of the algorithm to O(2*∣filtered_S∣+∣S∣+∣T∣),", "be negative) and missing tells how many characters are still", "many times I # need character c (can be negative)", "in lt and lt[c] > 0: missing -= 1 if", "j and not missing: if not J or j-i <", "substring which satisfy need of t missing = n i", "s: str, t: str) -> str: m = len(s) n", "updating the minimum window size. # If the window is", "which satisfy need of t missing = n i =", "#match all chars while i < j and need[s[i]] <", "= 0 for j, char in enumerate(s, 1): #index j", "in lt: i += 1 continue else: # if lt", "of s[i] +1, might reach to 0 lt[s[i]] += 1", "result. class Solution: def minWindow(self, s: str, t: str) ->", "+= 1 need[s[i]] += 1 #make sure the first appearing", "of T. # Once we have a window with all", "return s[I:J] # Time: O(|S|+|T|) # Space:O(|S|+|T|) # Optimized Sliding", "algorithm to O(2*∣filtered_S∣+∣S∣+∣T∣), # where filtered(S) is the string formed", "many characters are still missing. # In the loop, first", "= I = J = 0 for j, c in", "start+1 for next window return s[start:end] # Time: O(|S|+|T|) #", "< end-start: #update window start, end = i, j i", "# V2 def minWindow(s, t): need = collections.Counter(t) #hash table", "# Other solution # V2 def minWindow(s, t): need =", "window start, end = i, j i += 1 #update", "more, we repeat step 2 onwards. # The current window", "Space:O(|S|+|T|) # Optimized Sliding Window # A small improvement to", "is s[I:J]. In need[c] I store how many times I", "until we get a desirable window i.e. a window that", "+= 1 #we missed this first char, so add missing", "one by one. If the window is still a desirable", "is index of candidate substring, remove as many as char", "(lt) and count how many # for each char for", "# if > 0, means we need more, then missing", "= len(t) if m < n: return '' lt =", "1 # i is index of candidate substring, remove as", "enumerate(s, 1): #index j from 1 if need[char] > 0:", "char from candidate while i < j and not missing:", "while i < j and not missing: if not J", "= 0, 0 i = 0 for j, char in", "-= 1 if c in lt: # lt can be", "need character c (can be negative) and missing tells how", "finally get candidate substring which satisfy need of t missing", "need[s[i]] += 1 #make sure the first appearing char satisfies", "# i is index of candidate substring, remove as many", "J-I: I, J = i, j if s[i] not in", "# Time: O(|S|+|T|) # Space:O(|S|+|T|) # Optimized Sliding Window #", "lt[i] = 1 else: lt[i] += 1 # missing is", "the algorithm to O(2*∣filtered_S∣+∣S∣+∣T∣), # where filtered(S) is the string", "= len(s) n = len(t) if m < n: return", "# The current window is s[i:j] and the result window", "not missing: if not J or j-i < J-I: I,", "we have a window with all the characters, we can", "then update the result. class Solution: def minWindow(self, s: str,", "# A small improvement to the above approach can reduce", "initially pointing to the first element of the string S.", "the window start and then update the result. class Solution:", "1 if c in lt: # lt can be negative", "to the first element of the string S. # We", "the window until we get a desirable window i.e. a", "and lt[c] > 0: missing -= 1 if c in", "candidate substring which satisfy need of t missing = n", "if i not in lt: lt[i] = 1 else: lt[i]", "minWindow(s, t): need = collections.Counter(t) #hash table to store char", "= i, j if s[i] not in lt: i +=", "first add the new character to the window. Then, if", "substring # finally get candidate substring which satisfy need of", "we can move the left pointer ahead one by one.", "1 return s[I:J] # Time: O(|S|+|T|) # Space:O(|S|+|T|) # Optimized", "missing -= 1 need[char] -= 1 if missing == 0:", "still missing. # In the loop, first add the new", "the loop, first add the new character to the window.", "= 0 for j, c in enumerate(s, 1): if c", "# Optimized Sliding Window # A small improvement to the" ]
[ "Migration(migrations.Migration): dependencies = [ ('home', '0001_initial'), ] operations = [", "on 2017-10-17 04:12 from __future__ import unicode_literals from django.db import", "= [ ('home', '0001_initial'), ] operations = [ migrations.AlterField( model_name='homepage',", "from django.db import migrations import wagtail.core.blocks import wagtail.core.fields class Migration(migrations.Migration):", "instead', max_length=16, required=False)), ('page', wagtail.core.blocks.PageChooserBlock(required=True))))),), blank=True, help_text='The list of navigation", "Generated by Django 1.11.5 on 2017-10-17 04:12 from __future__ import", "the title of the linked page will be used instead',", "utf-8 -*- # Generated by Django 1.11.5 on 2017-10-17 04:12", "django.db import migrations import wagtail.core.blocks import wagtail.core.fields class Migration(migrations.Migration): dependencies", "page will be used instead', max_length=16, required=False)), ('page', wagtail.core.blocks.PageChooserBlock(required=True))))),), blank=True,", "will be used instead', max_length=16, required=False)), ('page', wagtail.core.blocks.PageChooserBlock(required=True))))),), blank=True, help_text='The", "-*- # Generated by Django 1.11.5 on 2017-10-17 04:12 from", "by Django 1.11.5 on 2017-10-17 04:12 from __future__ import unicode_literals", "('page', wagtail.core.blocks.PageChooserBlock(required=True))))),), blank=True, help_text='The list of navigation items', null=True), ),", "dependencies = [ ('home', '0001_initial'), ] operations = [ migrations.AlterField(", "class Migration(migrations.Migration): dependencies = [ ('home', '0001_initial'), ] operations =", "wagtail.core.blocks.StructBlock((('text', wagtail.core.blocks.CharBlock(help_text='If this is left blank, the title of the", "import wagtail.core.blocks import wagtail.core.fields class Migration(migrations.Migration): dependencies = [ ('home',", "unicode_literals from django.db import migrations import wagtail.core.blocks import wagtail.core.fields class", "of the linked page will be used instead', max_length=16, required=False)),", "= [ migrations.AlterField( model_name='homepage', name='navigation', field=wagtail.core.fields.StreamField((('item', wagtail.core.blocks.StructBlock((('text', wagtail.core.blocks.CharBlock(help_text='If this is", "model_name='homepage', name='navigation', field=wagtail.core.fields.StreamField((('item', wagtail.core.blocks.StructBlock((('text', wagtail.core.blocks.CharBlock(help_text='If this is left blank, the", "be used instead', max_length=16, required=False)), ('page', wagtail.core.blocks.PageChooserBlock(required=True))))),), blank=True, help_text='The list", "2017-10-17 04:12 from __future__ import unicode_literals from django.db import migrations", "is left blank, the title of the linked page will", "<filename>home/migrations/0002_auto_20171017_0412.py # -*- coding: utf-8 -*- # Generated by Django", "used instead', max_length=16, required=False)), ('page', wagtail.core.blocks.PageChooserBlock(required=True))))),), blank=True, help_text='The list of", "1.11.5 on 2017-10-17 04:12 from __future__ import unicode_literals from django.db", "Django 1.11.5 on 2017-10-17 04:12 from __future__ import unicode_literals from", "from __future__ import unicode_literals from django.db import migrations import wagtail.core.blocks", "('home', '0001_initial'), ] operations = [ migrations.AlterField( model_name='homepage', name='navigation', field=wagtail.core.fields.StreamField((('item',", "blank, the title of the linked page will be used", "title of the linked page will be used instead', max_length=16,", "max_length=16, required=False)), ('page', wagtail.core.blocks.PageChooserBlock(required=True))))),), blank=True, help_text='The list of navigation items',", "# -*- coding: utf-8 -*- # Generated by Django 1.11.5", "left blank, the title of the linked page will be", "coding: utf-8 -*- # Generated by Django 1.11.5 on 2017-10-17", "required=False)), ('page', wagtail.core.blocks.PageChooserBlock(required=True))))),), blank=True, help_text='The list of navigation items', null=True),", "[ ('home', '0001_initial'), ] operations = [ migrations.AlterField( model_name='homepage', name='navigation',", "migrations.AlterField( model_name='homepage', name='navigation', field=wagtail.core.fields.StreamField((('item', wagtail.core.blocks.StructBlock((('text', wagtail.core.blocks.CharBlock(help_text='If this is left blank,", "the linked page will be used instead', max_length=16, required=False)), ('page',", "# Generated by Django 1.11.5 on 2017-10-17 04:12 from __future__", "field=wagtail.core.fields.StreamField((('item', wagtail.core.blocks.StructBlock((('text', wagtail.core.blocks.CharBlock(help_text='If this is left blank, the title of", "__future__ import unicode_literals from django.db import migrations import wagtail.core.blocks import", "linked page will be used instead', max_length=16, required=False)), ('page', wagtail.core.blocks.PageChooserBlock(required=True))))),),", "import wagtail.core.fields class Migration(migrations.Migration): dependencies = [ ('home', '0001_initial'), ]", "] operations = [ migrations.AlterField( model_name='homepage', name='navigation', field=wagtail.core.fields.StreamField((('item', wagtail.core.blocks.StructBlock((('text', wagtail.core.blocks.CharBlock(help_text='If", "import unicode_literals from django.db import migrations import wagtail.core.blocks import wagtail.core.fields", "name='navigation', field=wagtail.core.fields.StreamField((('item', wagtail.core.blocks.StructBlock((('text', wagtail.core.blocks.CharBlock(help_text='If this is left blank, the title", "import migrations import wagtail.core.blocks import wagtail.core.fields class Migration(migrations.Migration): dependencies =", "migrations import wagtail.core.blocks import wagtail.core.fields class Migration(migrations.Migration): dependencies = [", "wagtail.core.fields class Migration(migrations.Migration): dependencies = [ ('home', '0001_initial'), ] operations", "'0001_initial'), ] operations = [ migrations.AlterField( model_name='homepage', name='navigation', field=wagtail.core.fields.StreamField((('item', wagtail.core.blocks.StructBlock((('text',", "operations = [ migrations.AlterField( model_name='homepage', name='navigation', field=wagtail.core.fields.StreamField((('item', wagtail.core.blocks.StructBlock((('text', wagtail.core.blocks.CharBlock(help_text='If this", "wagtail.core.blocks import wagtail.core.fields class Migration(migrations.Migration): dependencies = [ ('home', '0001_initial'),", "wagtail.core.blocks.CharBlock(help_text='If this is left blank, the title of the linked", "-*- coding: utf-8 -*- # Generated by Django 1.11.5 on", "04:12 from __future__ import unicode_literals from django.db import migrations import", "[ migrations.AlterField( model_name='homepage', name='navigation', field=wagtail.core.fields.StreamField((('item', wagtail.core.blocks.StructBlock((('text', wagtail.core.blocks.CharBlock(help_text='If this is left", "wagtail.core.blocks.PageChooserBlock(required=True))))),), blank=True, help_text='The list of navigation items', null=True), ), ]", "this is left blank, the title of the linked page" ]
[ "x = inputs.clone() if self.rand: x = x + torch.zeros_like(x).uniform_(-self.epsilon,", "1) x = x.detach() + delta diff = (x -", "torch.autograd.grad(loss, x)[0].detach() grad_norm = grad.view(x.size(0), -1).norm(2, 1) delta = self.step_size", "x.detach() + delta diff = (x - inputs).view(x.size(0), -1).renorm(2, 0,", "x = x + torch.zeros_like(x).uniform_(-self.epsilon, self.epsilon) for _ in range(self.num_steps):", "* torch.sign(grad.detach()) x = torch.min(torch.max(x, inputs.detach() - self.epsilon), inputs.detach() +", "x = torch.min(torch.max(x, inputs.detach() - self.epsilon), inputs.detach() + self.epsilon) x", "torch.sign(grad.detach()) x = torch.min(torch.max(x, inputs.detach() - self.epsilon), inputs.detach() + self.epsilon)", "basic_net, config): super(PGDModel, self).__init__() self.basic_net = basic_net self.rand = config['random_start']", "self.basic_net(inputs) x = inputs.clone() if self.rand: x = x +", "1) delta = self.step_size * grad / grad_norm.view(x.size(0), 1, 1,", "loss = F.cross_entropy(logits, targets, reduction='sum') grad = torch.autograd.grad(loss, x)[0] x", "x.detach() + self.step_size * torch.sign(grad.detach()) x = torch.min(torch.max(x, inputs.detach() -", "x)[0].detach() grad_norm = grad.view(x.size(0), -1).norm(2, 1) delta = self.step_size *", "inputs, targets, attack=False): if not attack: return self.basic_net(inputs) x =", "\"\"\" def __init__(self, basic_net, config): super(PGDL2Model, self).__init__() self.basic_net = basic_net", "basic_net self.epsilon = config['epsilon'] self.rand = config['random_start'] self.step_size = config['step_size']", "xent supported for now.' def forward(self, inputs, targets, attack=False): if", "as F class PGDModel(nn.Module): \"\"\" code adapted from https://github.com/karandwivedi42/adversarial/blob/master/main.py \"\"\"", "x + torch.zeros_like(x).normal_(0, self.step_size) for _ in range(self.num_steps): x.requires_grad_() with", "self.basic_net = basic_net self.epsilon = config['epsilon'] self.rand = config['random_start'] self.step_size", "torch.min(torch.max(x, inputs.detach() - self.epsilon), inputs.detach() + self.epsilon) x = torch.clamp(x,", "_ in range(self.num_steps): x.requires_grad_() with torch.enable_grad(): logits = self.basic_net(x) loss", "nn import torch.nn.functional as F class PGDModel(nn.Module): \"\"\" code adapted", "x = x + torch.zeros_like(x).normal_(0, self.step_size) for _ in range(self.num_steps):", "with torch.enable_grad(): logits = self.basic_net(x) loss = F.cross_entropy(logits, targets, reduction='sum')", "loss = F.cross_entropy(logits, targets, reduction='sum') grad = torch.autograd.grad(loss, x)[0].detach() grad_norm", "= torch.autograd.grad(loss, x)[0] x = x.detach() + self.step_size * torch.sign(grad.detach())", "self.basic_net(x) class PGDL2Model(nn.Module): \"\"\" code adapted from https://github.com/karandwivedi42/adversarial/blob/master/main.py \"\"\" def", "in range(self.num_steps): x.requires_grad_() with torch.enable_grad(): logits = self.basic_net(x) loss =", "torch.nn.functional as F class PGDModel(nn.Module): \"\"\" code adapted from https://github.com/karandwivedi42/adversarial/blob/master/main.py", "= config['epsilon'] self.rand = config['random_start'] self.step_size = config['step_size'] self.num_steps =", "grad_norm.view(x.size(0), 1, 1, 1) x = x.detach() + delta diff", "torch.clamp(x, 0, 1) return self.basic_net(x) class PGDL2Model(nn.Module): \"\"\" code adapted", "* grad / grad_norm.view(x.size(0), 1, 1, 1) x = x.detach()", "1) return self.basic_net(x) class PGDL2Model(nn.Module): \"\"\" code adapted from https://github.com/karandwivedi42/adversarial/blob/master/main.py", "- self.epsilon), inputs.detach() + self.epsilon) x = torch.clamp(x, 0, 1)", "self.epsilon), inputs.detach() + self.epsilon) x = torch.clamp(x, 0, 1) return", "config['step_size'] self.epsilon = config['epsilon'] self.num_steps = config['num_steps'] assert config['loss_func'] ==", "= F.cross_entropy(logits, targets, reduction='sum') grad = torch.autograd.grad(loss, x)[0].detach() grad_norm =", "targets, attack=False): if not attack: return self.basic_net(inputs) x = inputs.clone()", "(x - inputs).view(x.size(0), -1).renorm(2, 0, self.epsilon) x = diff.view(x.size()) +", "+ torch.zeros_like(x).normal_(0, self.step_size) for _ in range(self.num_steps): x.requires_grad_() with torch.enable_grad():", "config['random_start'] self.step_size = config['step_size'] self.epsilon = config['epsilon'] self.num_steps = config['num_steps']", "1, 1, 1) x = x.detach() + delta diff =", "= self.basic_net(x) loss = F.cross_entropy(logits, targets, reduction='sum') grad = torch.autograd.grad(loss,", "if self.rand: x = x + torch.zeros_like(x).uniform_(-self.epsilon, self.epsilon) for _", "for _ in range(self.num_steps): x.requires_grad_() with torch.enable_grad(): logits = self.basic_net(x)", "= torch.autograd.grad(loss, x)[0].detach() grad_norm = grad.view(x.size(0), -1).norm(2, 1) delta =", "return self.basic_net(inputs) x = inputs.clone() if self.rand: x = x", "inputs.clone() if self.rand: x = x + torch.zeros_like(x).uniform_(-self.epsilon, self.epsilon) for", "'Only xent supported for now.' def forward(self, inputs, targets, attack=False):", "F.cross_entropy(logits, targets, reduction='sum') grad = torch.autograd.grad(loss, x)[0] x = x.detach()", "x.requires_grad_() with torch.enable_grad(): logits = self.basic_net(x) loss = F.cross_entropy(logits, targets,", "self.num_steps = config['num_steps'] assert config['loss_func'] == 'xent', 'Only xent supported", "self).__init__() self.basic_net = basic_net self.rand = config['random_start'] self.step_size = config['step_size']", "= config['random_start'] self.step_size = config['step_size'] self.epsilon = config['epsilon'] self.num_steps =", "supported for now.' def forward(self, inputs, targets, attack=False): if not", "logits = self.basic_net(x) loss = F.cross_entropy(logits, targets, reduction='sum') grad =", "== 'xent', 'Only xent supported for now.' def forward(self, inputs,", "torch.nn as nn import torch.nn.functional as F class PGDModel(nn.Module): \"\"\"", "config): super(PGDL2Model, self).__init__() self.basic_net = basic_net self.epsilon = config['epsilon'] self.rand", "as nn import torch.nn.functional as F class PGDModel(nn.Module): \"\"\" code", "inputs.clone() if self.rand: x = x + torch.zeros_like(x).normal_(0, self.step_size) for", "x = inputs.clone() if self.rand: x = x + torch.zeros_like(x).normal_(0,", "__init__(self, basic_net, config): super(PGDL2Model, self).__init__() self.basic_net = basic_net self.epsilon =", "self.basic_net = basic_net self.rand = config['random_start'] self.step_size = config['step_size'] self.epsilon", "+ delta diff = (x - inputs).view(x.size(0), -1).renorm(2, 0, self.epsilon)", "= grad.view(x.size(0), -1).norm(2, 1) delta = self.step_size * grad /", "= torch.clamp(x, 0, 1) return self.basic_net(x) class PGDL2Model(nn.Module): \"\"\" code", "= config['step_size'] self.num_steps = config['num_steps'] assert config['loss_func'] == 'xent', 'Only", "reduction='sum') grad = torch.autograd.grad(loss, x)[0] x = x.detach() + self.step_size", "= basic_net self.epsilon = config['epsilon'] self.rand = config['random_start'] self.step_size =", "self.basic_net(x) loss = F.cross_entropy(logits, targets, reduction='sum') grad = torch.autograd.grad(loss, x)[0]", "reduction='sum') grad = torch.autograd.grad(loss, x)[0].detach() grad_norm = grad.view(x.size(0), -1).norm(2, 1)", "if not attack: return self.basic_net(inputs) x = inputs.clone() if self.rand:", "= torch.min(torch.max(x, inputs.detach() - self.epsilon), inputs.detach() + self.epsilon) x =", "config['num_steps'] assert config['loss_func'] == 'xent', 'Only xent supported for now.'", "targets, reduction='sum') grad = torch.autograd.grad(loss, x)[0] x = x.detach() +", "def __init__(self, basic_net, config): super(PGDL2Model, self).__init__() self.basic_net = basic_net self.epsilon", "from https://github.com/karandwivedi42/adversarial/blob/master/main.py \"\"\" def __init__(self, basic_net, config): super(PGDModel, self).__init__() self.basic_net", "F.cross_entropy(logits, targets, reduction='sum') grad = torch.autograd.grad(loss, x)[0].detach() grad_norm = grad.view(x.size(0),", "0, 1) return self.basic_net(x) class PGDL2Model(nn.Module): \"\"\" code adapted from", "def forward(self, inputs, targets, attack=False): if not attack: return self.basic_net(inputs)", "diff = (x - inputs).view(x.size(0), -1).renorm(2, 0, self.epsilon) x =", "= config['step_size'] self.epsilon = config['epsilon'] self.num_steps = config['num_steps'] assert config['loss_func']", "self.epsilon) x = diff.view(x.size()) + inputs x.clamp_(0, 1) return self.basic_net(x)", "grad = torch.autograd.grad(loss, x)[0].detach() grad_norm = grad.view(x.size(0), -1).norm(2, 1) delta", "not attack: return self.basic_net(inputs) x = inputs.clone() if self.rand: x", "grad_norm = grad.view(x.size(0), -1).norm(2, 1) delta = self.step_size * grad", "self.epsilon) for _ in range(self.num_steps): x.requires_grad_() with torch.enable_grad(): logits =", "\"\"\" def __init__(self, basic_net, config): super(PGDModel, self).__init__() self.basic_net = basic_net", "delta = self.step_size * grad / grad_norm.view(x.size(0), 1, 1, 1)", "inputs.detach() - self.epsilon), inputs.detach() + self.epsilon) x = torch.clamp(x, 0,", "self.step_size * grad / grad_norm.view(x.size(0), 1, 1, 1) x =", "import torch.nn.functional as F class PGDModel(nn.Module): \"\"\" code adapted from", "torch import torch.nn as nn import torch.nn.functional as F class", "+ self.step_size * torch.sign(grad.detach()) x = torch.min(torch.max(x, inputs.detach() - self.epsilon),", "self.rand = config['random_start'] self.step_size = config['step_size'] self.epsilon = config['epsilon'] self.num_steps", "config['epsilon'] self.rand = config['random_start'] self.step_size = config['step_size'] self.num_steps = config['num_steps']", "super(PGDL2Model, self).__init__() self.basic_net = basic_net self.epsilon = config['epsilon'] self.rand =", "0, self.epsilon) x = diff.view(x.size()) + inputs x.clamp_(0, 1) return", "torch.zeros_like(x).normal_(0, self.step_size) for _ in range(self.num_steps): x.requires_grad_() with torch.enable_grad(): logits", "x = x.detach() + delta diff = (x - inputs).view(x.size(0),", "import torch.nn as nn import torch.nn.functional as F class PGDModel(nn.Module):", "config['loss_func'] == 'xent', 'Only xent supported for now.' def forward(self,", "1, 1) x = x.detach() + delta diff = (x", "import torch import torch.nn as nn import torch.nn.functional as F", "grad = torch.autograd.grad(loss, x)[0] x = x.detach() + self.step_size *", "config): super(PGDModel, self).__init__() self.basic_net = basic_net self.rand = config['random_start'] self.step_size", "basic_net, config): super(PGDL2Model, self).__init__() self.basic_net = basic_net self.epsilon = config['epsilon']", "grad / grad_norm.view(x.size(0), 1, 1, 1) x = x.detach() +", "class PGDModel(nn.Module): \"\"\" code adapted from https://github.com/karandwivedi42/adversarial/blob/master/main.py \"\"\" def __init__(self,", "inputs.detach() + self.epsilon) x = torch.clamp(x, 0, 1) return self.basic_net(x)", "if self.rand: x = x + torch.zeros_like(x).normal_(0, self.step_size) for _", "+ torch.zeros_like(x).uniform_(-self.epsilon, self.epsilon) for _ in range(self.num_steps): x.requires_grad_() with torch.enable_grad():", "now.' def forward(self, inputs, targets, attack=False): if not attack: return", "torch.enable_grad(): logits = self.basic_net(x) loss = F.cross_entropy(logits, targets, reduction='sum') grad", "F class PGDModel(nn.Module): \"\"\" code adapted from https://github.com/karandwivedi42/adversarial/blob/master/main.py \"\"\" def", "super(PGDModel, self).__init__() self.basic_net = basic_net self.rand = config['random_start'] self.step_size =", "x = torch.clamp(x, 0, 1) return self.basic_net(x) class PGDL2Model(nn.Module): \"\"\"", "= inputs.clone() if self.rand: x = x + torch.zeros_like(x).uniform_(-self.epsilon, self.epsilon)", "config['random_start'] self.step_size = config['step_size'] self.num_steps = config['num_steps'] assert config['loss_func'] ==", "= x.detach() + self.step_size * torch.sign(grad.detach()) x = torch.min(torch.max(x, inputs.detach()", "= F.cross_entropy(logits, targets, reduction='sum') grad = torch.autograd.grad(loss, x)[0] x =", "forward(self, inputs, targets, attack=False): if not attack: return self.basic_net(inputs) x", "self.step_size * torch.sign(grad.detach()) x = torch.min(torch.max(x, inputs.detach() - self.epsilon), inputs.detach()", "attack: return self.basic_net(inputs) x = inputs.clone() if self.rand: x =", "targets, reduction='sum') grad = torch.autograd.grad(loss, x)[0].detach() grad_norm = grad.view(x.size(0), -1).norm(2,", "delta diff = (x - inputs).view(x.size(0), -1).renorm(2, 0, self.epsilon) x", "self.epsilon = config['epsilon'] self.num_steps = config['num_steps'] assert config['loss_func'] == 'xent',", "assert config['loss_func'] == 'xent', 'Only xent supported for now.' def", "= config['epsilon'] self.num_steps = config['num_steps'] assert config['loss_func'] == 'xent', 'Only", "basic_net self.rand = config['random_start'] self.step_size = config['step_size'] self.epsilon = config['epsilon']", "\"\"\" code adapted from https://github.com/karandwivedi42/adversarial/blob/master/main.py \"\"\" def __init__(self, basic_net, config):", "torch.zeros_like(x).uniform_(-self.epsilon, self.epsilon) for _ in range(self.num_steps): x.requires_grad_() with torch.enable_grad(): logits", "self.step_size) for _ in range(self.num_steps): x.requires_grad_() with torch.enable_grad(): logits =", "code adapted from https://github.com/karandwivedi42/adversarial/blob/master/main.py \"\"\" def __init__(self, basic_net, config): super(PGDModel,", "PGDL2Model(nn.Module): \"\"\" code adapted from https://github.com/karandwivedi42/adversarial/blob/master/main.py \"\"\" def __init__(self, basic_net,", "code adapted from https://github.com/karandwivedi42/adversarial/blob/master/main.py \"\"\" def __init__(self, basic_net, config): super(PGDL2Model,", "'xent', 'Only xent supported for now.' def forward(self, inputs, targets,", "= basic_net self.rand = config['random_start'] self.step_size = config['step_size'] self.epsilon =", "https://github.com/karandwivedi42/adversarial/blob/master/main.py \"\"\" def __init__(self, basic_net, config): super(PGDModel, self).__init__() self.basic_net =", "adapted from https://github.com/karandwivedi42/adversarial/blob/master/main.py \"\"\" def __init__(self, basic_net, config): super(PGDL2Model, self).__init__()", "from https://github.com/karandwivedi42/adversarial/blob/master/main.py \"\"\" def __init__(self, basic_net, config): super(PGDL2Model, self).__init__() self.basic_net", "torch.autograd.grad(loss, x)[0] x = x.detach() + self.step_size * torch.sign(grad.detach()) x", "https://github.com/karandwivedi42/adversarial/blob/master/main.py \"\"\" def __init__(self, basic_net, config): super(PGDL2Model, self).__init__() self.basic_net =", "- inputs).view(x.size(0), -1).renorm(2, 0, self.epsilon) x = diff.view(x.size()) + inputs", "range(self.num_steps): x.requires_grad_() with torch.enable_grad(): logits = self.basic_net(x) loss = F.cross_entropy(logits,", "= x + torch.zeros_like(x).uniform_(-self.epsilon, self.epsilon) for _ in range(self.num_steps): x.requires_grad_()", "attack=False): if not attack: return self.basic_net(inputs) x = inputs.clone() if", "= inputs.clone() if self.rand: x = x + torch.zeros_like(x).normal_(0, self.step_size)", "adapted from https://github.com/karandwivedi42/adversarial/blob/master/main.py \"\"\" def __init__(self, basic_net, config): super(PGDModel, self).__init__()", "= x.detach() + delta diff = (x - inputs).view(x.size(0), -1).renorm(2,", "for now.' def forward(self, inputs, targets, attack=False): if not attack:", "PGDModel(nn.Module): \"\"\" code adapted from https://github.com/karandwivedi42/adversarial/blob/master/main.py \"\"\" def __init__(self, basic_net,", "x + torch.zeros_like(x).uniform_(-self.epsilon, self.epsilon) for _ in range(self.num_steps): x.requires_grad_() with", "self).__init__() self.basic_net = basic_net self.epsilon = config['epsilon'] self.rand = config['random_start']", "inputs).view(x.size(0), -1).renorm(2, 0, self.epsilon) x = diff.view(x.size()) + inputs x.clamp_(0,", "/ grad_norm.view(x.size(0), 1, 1, 1) x = x.detach() + delta", "self.epsilon = config['epsilon'] self.rand = config['random_start'] self.step_size = config['step_size'] self.num_steps", "x)[0] x = x.detach() + self.step_size * torch.sign(grad.detach()) x =", "return self.basic_net(x) class PGDL2Model(nn.Module): \"\"\" code adapted from https://github.com/karandwivedi42/adversarial/blob/master/main.py \"\"\"", "self.rand = config['random_start'] self.step_size = config['step_size'] self.num_steps = config['num_steps'] assert", "self.epsilon) x = torch.clamp(x, 0, 1) return self.basic_net(x) class PGDL2Model(nn.Module):", "class PGDL2Model(nn.Module): \"\"\" code adapted from https://github.com/karandwivedi42/adversarial/blob/master/main.py \"\"\" def __init__(self,", "x = x.detach() + self.step_size * torch.sign(grad.detach()) x = torch.min(torch.max(x,", "self.rand: x = x + torch.zeros_like(x).normal_(0, self.step_size) for _ in", "config['step_size'] self.num_steps = config['num_steps'] assert config['loss_func'] == 'xent', 'Only xent", "= self.step_size * grad / grad_norm.view(x.size(0), 1, 1, 1) x", "__init__(self, basic_net, config): super(PGDModel, self).__init__() self.basic_net = basic_net self.rand =", "def __init__(self, basic_net, config): super(PGDModel, self).__init__() self.basic_net = basic_net self.rand", "self.step_size = config['step_size'] self.num_steps = config['num_steps'] assert config['loss_func'] == 'xent',", "-1).renorm(2, 0, self.epsilon) x = diff.view(x.size()) + inputs x.clamp_(0, 1)", "= (x - inputs).view(x.size(0), -1).renorm(2, 0, self.epsilon) x = diff.view(x.size())", "-1).norm(2, 1) delta = self.step_size * grad / grad_norm.view(x.size(0), 1,", "= config['num_steps'] assert config['loss_func'] == 'xent', 'Only xent supported for", "self.step_size = config['step_size'] self.epsilon = config['epsilon'] self.num_steps = config['num_steps'] assert", "= x + torch.zeros_like(x).normal_(0, self.step_size) for _ in range(self.num_steps): x.requires_grad_()", "grad.view(x.size(0), -1).norm(2, 1) delta = self.step_size * grad / grad_norm.view(x.size(0),", "config['epsilon'] self.num_steps = config['num_steps'] assert config['loss_func'] == 'xent', 'Only xent", "self.basic_net(x) loss = F.cross_entropy(logits, targets, reduction='sum') grad = torch.autograd.grad(loss, x)[0].detach()", "self.rand: x = x + torch.zeros_like(x).uniform_(-self.epsilon, self.epsilon) for _ in", "+ self.epsilon) x = torch.clamp(x, 0, 1) return self.basic_net(x) class", "= config['random_start'] self.step_size = config['step_size'] self.num_steps = config['num_steps'] assert config['loss_func']" ]
[ "this default is probably enough. mul=314159, # just about 300KB", "with storage.reader(sid) as input: written = b''.join(writes) partial_read = input.read(3)", "output: output.write(b'foo') id_to_remove = output.commit(remove_on_exception=True) # Contract: committed blobs are", "b'g' * mul], [b'abcd' * mul], [b'abc' * mul, b'd'", "test suite that can be used to check any Storage", "tree. import unittest from unittest.mock import patch, MagicMock from typing", "under the MIT license found in the # LICENSE file", "# Exercise the real `remove` if remove_is_immediate: # The removed", "skip_empty_writes=False, # To make testing more meaningful, it's useful to", "storage.writer() as output: for piece in writes: output.write(piece) sid =", "can be used to check any Storage implementation.' def _check_write_and_read(self,", "LICENSE file in the root directory of this source tree.", "storage systems refuse empty blobs. *([] if no_empty_blobs else [", "we can't really test that the # partial write got", "self, storage: Storage, *, no_empty_blobs=False, skip_empty_writes=False, # To make testing", "directory of this source tree. import unittest from unittest.mock import", "patch.object(storage, 'remove', mock_remove): with self.assertRaisesRegex(RuntimeError, '^remove_on_exception$'): with storage.writer() as output:", "List, Tuple from .. import Storage # Module import to", "that `remove` would have been called, and then call it.", "# some writes fill up any output buffers. For filesystem", "not longer be available. with self.assertRaises(Exception): with storage.reader(id_to_remove) as input:", "# Leave no litter output.commit() # Check that the `remove_on_exception`", "the MIT license found in the # LICENSE file in", "implementation.' def _check_write_and_read(self, storage: Storage, writes: List[bytes]): with storage.writer() as", "a pipe from another Python process, # let's consume its", "an exception flies before a # commit. Since we don't", "have an ID, we can't really test that the #", "logspam. input.read() return [ ( writes, self._check_write_and_read( storage, writes if", "[b'abcd' * mul], [b'abc' * mul, b'd' * mul], #", "license found in the # LICENSE file in the root", "blob-store has a read-through cache, we cannot effectively # test", "blobs are available to read with storage.reader(id_to_remove) as reader: self.assertEqual(b'foo',", "without a multiplier [b'a', b'b', b'c', b'd'], [b'ab'], [b'a', b'b'],", "[ [b''], [], ]), ] # Test the given writes,", "storage ID # Make sure nothing bad happens if an", "input: written = b''.join(writes) partial_read = input.read(3) if written: self.assertGreater(len(partial_read),", "typing import List, Tuple from .. import Storage # Module", "with storage.reader(id_to_remove) as reader: self.assertEqual(b'foo', reader.read()) raise RuntimeError('remove_on_exception') # Check", "another Python process, # let's consume its output to avoid", "# Module import to ensure we get plugins class StorageBaseTestCase(unittest.TestCase):", "= b''.join(writes) partial_read = input.read(3) if written: self.assertGreater(len(partial_read), 0) self.assertLessEqual(len(partial_read),", "insert a blank at each pos for i in [", "# If the blob-store has a read-through cache, we cannot", "bad happens if an exception flies before a # commit.", "Leave no litter output.commit() # Check that the `remove_on_exception` kwarg", "`remove_on_exception` kwarg triggers `remove`. mock_remove = MagicMock() with patch.object(storage, 'remove',", "class StorageBaseTestCase(unittest.TestCase): 'A tiny test suite that can be used", "default is probably enough. mul=314159, # just about 300KB #", "available to read with storage.reader(id_to_remove) as reader: self.assertEqual(b'foo', reader.read()) raise", "mul, b'g' * mul], [b'abcd' * mul], [b'abc' * mul,", "as output: output.write(b'foo') id_to_remove = output.commit(remove_on_exception=True) # Contract: committed blobs", "used to check any Storage implementation.' def _check_write_and_read(self, storage: Storage,", "output: output.write(b'bah') raise RuntimeError('humbug') with self.assertRaisesRegex(AssertionError, '^Cannot commit twice$'): with", "a blank at each pos for i in [ None,", "litter output.commit() # Check that the `remove_on_exception` kwarg triggers `remove`.", "multiplier [b'a', b'b', b'c', b'd'], [b'ab'], [b'a', b'b'], # While", "*, no_empty_blobs=False, skip_empty_writes=False, # To make testing more meaningful, it's", "for piece in writes: output.write(piece) sid = output.commit() with storage.reader(sid)", "MagicMock() with patch.object(storage, 'remove', mock_remove): with self.assertRaisesRegex(RuntimeError, '^remove_on_exception$'): with storage.writer()", "may be a pipe from another Python process, # let's", "* mul], [b'abcd' * mul], [b'abc' * mul, b'd' *", "as reader: self.assertEqual(b'foo', reader.read()) raise RuntimeError('remove_on_exception') # Check that `remove`", "'^humbug$'): with storage.writer() as output: output.write(b'bah') raise RuntimeError('humbug') with self.assertRaisesRegex(AssertionError,", "optionally insert a blank at each pos for i in", "# just about 300KB # If the blob-store has a", "triggers `remove`. mock_remove = MagicMock() with patch.object(storage, 'remove', mock_remove): with", "writes without a multiplier [b'a', b'b', b'c', b'd'], [b'ab'], [b'a',", "reader.read()) raise RuntimeError('remove_on_exception') # Check that `remove` would have been", "import unittest from unittest.mock import patch, MagicMock from typing import", "partial_read = input.read(3) if written: self.assertGreater(len(partial_read), 0) self.assertLessEqual(len(partial_read), 3) self.assertEqual(written,", "its output to avoid BrokenPipe logspam. input.read() return [ (", "output: for piece in writes: output.write(piece) sid = output.commit() with", "Exercise the real `remove` if remove_is_immediate: # The removed ID", "b'', *writes[i:]], ), ) for writes in [ # Some", "Module import to ensure we get plugins class StorageBaseTestCase(unittest.TestCase): 'A", "enough. mul=314159, # just about 300KB # If the blob-store", "affiliates. # # This source code is licensed under the", "partial_read + input.read()) return sid def check_storage_impl( self, storage: Storage,", "+ input.read()) return sid def check_storage_impl( self, storage: Storage, *,", "* mul, b'efgh' * mul], [b'abc' * mul, b'defg' *", "output.write(b'foo') id_to_remove = output.commit(remove_on_exception=True) # Contract: committed blobs are available", "really test that the # partial write got discarded. with", "up any output buffers. For filesystem writes # from Python,", "b'c', b'd'], [b'ab'], [b'a', b'b'], # While clowny, some blob", "process, # let's consume its output to avoid BrokenPipe logspam.", "None, *([] if skip_empty_writes else range(len(writes) + 1)), ] ]", "-> List[Tuple[List[str], str]]: # Writes + their storage ID #", "writes fill up any output buffers. For filesystem writes #", "sure nothing bad happens if an exception flies before a", "been called, and then call it. mock_remove.assert_called_once_with(id_to_remove) storage.remove(id_to_remove) # Exercise", "b'b'], # While clowny, some blob storage systems refuse empty", "from Python, this default is probably enough. mul=314159, # just", "self.assertRaisesRegex(RuntimeError, '^humbug$'): with storage.writer() as output: output.write(b'bah') raise RuntimeError('humbug') with", "can't really test that the # partial write got discarded.", "To make testing more meaningful, it's useful to make sure", "mul, b'def' * mul, b'g' * mul], [b'abcd' * mul],", "check_storage_impl( self, storage: Storage, *, no_empty_blobs=False, skip_empty_writes=False, # To make", "import Storage # Module import to ensure we get plugins", "and its affiliates. # # This source code is licensed", "b'b', b'c', b'd'], [b'ab'], [b'a', b'b'], # While clowny, some", "id_to_remove = output.commit(remove_on_exception=True) # Contract: committed blobs are available to", "read with storage.reader(id_to_remove) as reader: self.assertEqual(b'foo', reader.read()) raise RuntimeError('remove_on_exception') #", "`remove` if remove_is_immediate: # The removed ID should not longer", "longer be available. with self.assertRaises(Exception): with storage.reader(id_to_remove) as input: #", "# partial write got discarded. with self.assertRaisesRegex(RuntimeError, '^humbug$'): with storage.writer()", "to read with storage.reader(id_to_remove) as reader: self.assertEqual(b'foo', reader.read()) raise RuntimeError('remove_on_exception')", "Copyright (c) Facebook, Inc. and its affiliates. # # This", "committed blobs are available to read with storage.reader(id_to_remove) as reader:", "self.assertRaisesRegex(RuntimeError, '^remove_on_exception$'): with storage.writer() as output: output.write(b'foo') id_to_remove = output.commit(remove_on_exception=True)", "probably enough. mul=314159, # just about 300KB # If the", "[ # Some large writes [b'abcd' * mul, b'efgh' *", "[b'abcd' * mul, b'efgh' * mul], [b'abc' * mul, b'defg'", "are available to read with storage.reader(id_to_remove) as reader: self.assertEqual(b'foo', reader.read())", "tiny test suite that can be used to check any", "the root directory of this source tree. import unittest from", "For filesystem writes # from Python, this default is probably", "commit twice$'): with storage.writer() as output: output.write(b'foo') output.commit(remove_on_exception=True) # Leave", "[ ( writes, self._check_write_and_read( storage, writes if i is None", "* mul], [b'abc' * mul, b'd' * mul], # Some", "# LICENSE file in the root directory of this source", "with storage.writer() as output: output.write(b'bah') raise RuntimeError('humbug') with self.assertRaisesRegex(AssertionError, '^Cannot", "storage: Storage, writes: List[bytes]): with storage.writer() as output: for piece", "a # commit. Since we don't have an ID, we", "found in the # LICENSE file in the root directory", "mock_remove = MagicMock() with patch.object(storage, 'remove', mock_remove): with self.assertRaisesRegex(RuntimeError, '^remove_on_exception$'):", "Tuple from .. import Storage # Module import to ensure", "with patch.object(storage, 'remove', mock_remove): with self.assertRaisesRegex(RuntimeError, '^remove_on_exception$'): with storage.writer() as", "happens if an exception flies before a # commit. Since", "Some large writes [b'abcd' * mul, b'efgh' * mul], [b'abc'", "import patch, MagicMock from typing import List, Tuple from ..", "given writes, optionally insert a blank at each pos for", "large writes [b'abcd' * mul, b'efgh' * mul], [b'abc' *", "3) self.assertEqual(written, partial_read + input.read()) return sid def check_storage_impl( self,", "sid def check_storage_impl( self, storage: Storage, *, no_empty_blobs=False, skip_empty_writes=False, #", "mul], [b'abc' * mul, b'd' * mul], # Some tiny", "blobs. *([] if no_empty_blobs else [ [b''], [], ]), ]", "each pos for i in [ None, *([] if skip_empty_writes", "to check any Storage implementation.' def _check_write_and_read(self, storage: Storage, writes:", "<filename>fs_image/rpm/storage/tests/storage_base_test.py #!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its", "with storage.writer() as output: for piece in writes: output.write(piece) sid", "If the blob-store has a read-through cache, we cannot effectively", "(c) Facebook, Inc. and its affiliates. # # This source", "self.assertRaisesRegex(AssertionError, '^Cannot commit twice$'): with storage.writer() as output: output.write(b'foo') output.commit(remove_on_exception=True)", "* mul, b'defg' * mul], [b'abc' * mul, b'def' *", "Make sure nothing bad happens if an exception flies before", "storage.reader(sid) as input: written = b''.join(writes) partial_read = input.read(3) if", "b'd' * mul], # Some tiny writes without a multiplier", "no_empty_blobs else [ [b''], [], ]), ] # Test the", "with storage.writer() as output: output.write(b'foo') output.commit(remove_on_exception=True) # Leave no litter", "to ensure we get plugins class StorageBaseTestCase(unittest.TestCase): 'A tiny test", "in [ None, *([] if skip_empty_writes else range(len(writes) + 1)),", "unittest.mock import patch, MagicMock from typing import List, Tuple from", "file in the root directory of this source tree. import", "Storage, writes: List[bytes]): with storage.writer() as output: for piece in", "tiny writes without a multiplier [b'a', b'b', b'c', b'd'], [b'ab'],", "mul], [b'abcd' * mul], [b'abc' * mul, b'd' * mul],", "mul, b'defg' * mul], [b'abc' * mul, b'def' * mul,", "flies before a # commit. Since we don't have an", "the blob-store has a read-through cache, we cannot effectively #", "# Make sure nothing bad happens if an exception flies", "This source code is licensed under the MIT license found", ".. import Storage # Module import to ensure we get", "storage: Storage, *, no_empty_blobs=False, skip_empty_writes=False, # To make testing more", "self._check_write_and_read( storage, writes if i is None else [*writes[:i], b'',", "the real `remove` if remove_is_immediate: # The removed ID should", "twice$'): with storage.writer() as output: output.write(b'foo') output.commit(remove_on_exception=True) # Leave no", "writes in [ # Some large writes [b'abcd' * mul,", "reader: self.assertEqual(b'foo', reader.read()) raise RuntimeError('remove_on_exception') # Check that `remove` would", "RuntimeError('humbug') with self.assertRaisesRegex(AssertionError, '^Cannot commit twice$'): with storage.writer() as output:", "else [ [b''], [], ]), ] # Test the given", "# from Python, this default is probably enough. mul=314159, #", "[b'abc' * mul, b'd' * mul], # Some tiny writes", "in the root directory of this source tree. import unittest", "test that the remove actually happened. remove_is_immediate=True, ) -> List[Tuple[List[str],", "licensed under the MIT license found in the # LICENSE", "should not longer be available. with self.assertRaises(Exception): with storage.reader(id_to_remove) as", "actually happened. remove_is_immediate=True, ) -> List[Tuple[List[str], str]]: # Writes +", "sid = output.commit() with storage.reader(sid) as input: written = b''.join(writes)", "Python, this default is probably enough. mul=314159, # just about", "def _check_write_and_read(self, storage: Storage, writes: List[bytes]): with storage.writer() as output:", "MIT license found in the # LICENSE file in the", "writes: List[bytes]): with storage.writer() as output: for piece in writes:", "got discarded. with self.assertRaisesRegex(RuntimeError, '^humbug$'): with storage.writer() as output: output.write(b'bah')", "some writes fill up any output buffers. For filesystem writes", "as input: written = b''.join(writes) partial_read = input.read(3) if written:", "* mul], [b'abc' * mul, b'defg' * mul], [b'abc' *", "blob storage systems refuse empty blobs. *([] if no_empty_blobs else", "meaningful, it's useful to make sure that # some writes", "has a read-through cache, we cannot effectively # test that", "real `remove` if remove_is_immediate: # The removed ID should not", "= input.read(3) if written: self.assertGreater(len(partial_read), 0) self.assertLessEqual(len(partial_read), 3) self.assertEqual(written, partial_read", ") -> List[Tuple[List[str], str]]: # Writes + their storage ID", "with storage.reader(id_to_remove) as input: # The reader may be a", "root directory of this source tree. import unittest from unittest.mock", "[], ]), ] # Test the given writes, optionally insert", "self.assertEqual(written, partial_read + input.read()) return sid def check_storage_impl( self, storage:", "else [*writes[:i], b'', *writes[i:]], ), ) for writes in [", "# Some large writes [b'abcd' * mul, b'efgh' * mul],", "mul], [b'abc' * mul, b'defg' * mul], [b'abc' * mul,", "would have been called, and then call it. mock_remove.assert_called_once_with(id_to_remove) storage.remove(id_to_remove)", "self.assertRaises(Exception): with storage.reader(id_to_remove) as input: # The reader may be", "get plugins class StorageBaseTestCase(unittest.TestCase): 'A tiny test suite that can", "[b'abc' * mul, b'def' * mul, b'g' * mul], [b'abcd'", "in the # LICENSE file in the root directory of", "i in [ None, *([] if skip_empty_writes else range(len(writes) +", "mock_remove): with self.assertRaisesRegex(RuntimeError, '^remove_on_exception$'): with storage.writer() as output: output.write(b'foo') id_to_remove", "remove actually happened. remove_is_immediate=True, ) -> List[Tuple[List[str], str]]: # Writes", "+ their storage ID # Make sure nothing bad happens", "*([] if no_empty_blobs else [ [b''], [], ]), ] #", "output to avoid BrokenPipe logspam. input.read() return [ ( writes,", "Test the given writes, optionally insert a blank at each", "#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates.", "written: self.assertGreater(len(partial_read), 0) self.assertLessEqual(len(partial_read), 3) self.assertEqual(written, partial_read + input.read()) return", "clowny, some blob storage systems refuse empty blobs. *([] if", "of this source tree. import unittest from unittest.mock import patch,", "as input: # The reader may be a pipe from", "suite that can be used to check any Storage implementation.'", "BrokenPipe logspam. input.read() return [ ( writes, self._check_write_and_read( storage, writes", "if an exception flies before a # commit. Since we", "storage.reader(id_to_remove) as reader: self.assertEqual(b'foo', reader.read()) raise RuntimeError('remove_on_exception') # Check that", "useful to make sure that # some writes fill up", "'^remove_on_exception$'): with storage.writer() as output: output.write(b'foo') id_to_remove = output.commit(remove_on_exception=True) #", "]), ] # Test the given writes, optionally insert a", "is probably enough. mul=314159, # just about 300KB # If", "# let's consume its output to avoid BrokenPipe logspam. input.read()", "[ None, *([] if skip_empty_writes else range(len(writes) + 1)), ]", "effectively # test that the remove actually happened. remove_is_immediate=True, )", "Check that the `remove_on_exception` kwarg triggers `remove`. mock_remove = MagicMock()", "ID # Make sure nothing bad happens if an exception", "storage.writer() as output: output.write(b'bah') raise RuntimeError('humbug') with self.assertRaisesRegex(AssertionError, '^Cannot commit", "self.assertGreater(len(partial_read), 0) self.assertLessEqual(len(partial_read), 3) self.assertEqual(written, partial_read + input.read()) return sid", "storage.writer() as output: output.write(b'foo') id_to_remove = output.commit(remove_on_exception=True) # Contract: committed", "Storage, *, no_empty_blobs=False, skip_empty_writes=False, # To make testing more meaningful,", "raise RuntimeError('remove_on_exception') # Check that `remove` would have been called,", "piece in writes: output.write(piece) sid = output.commit() with storage.reader(sid) as", "check any Storage implementation.' def _check_write_and_read(self, storage: Storage, writes: List[bytes]):", "the remove actually happened. remove_is_immediate=True, ) -> List[Tuple[List[str], str]]: #", "# The removed ID should not longer be available. with", "self.assertLessEqual(len(partial_read), 3) self.assertEqual(written, partial_read + input.read()) return sid def check_storage_impl(", "The reader may be a pipe from another Python process,", "= output.commit(remove_on_exception=True) # Contract: committed blobs are available to read", "an ID, we can't really test that the # partial", "consume its output to avoid BrokenPipe logspam. input.read() return [", "mul, b'efgh' * mul], [b'abc' * mul, b'defg' * mul],", "any Storage implementation.' def _check_write_and_read(self, storage: Storage, writes: List[bytes]): with", "( writes, self._check_write_and_read( storage, writes if i is None else", ") for writes in [ # Some large writes [b'abcd'", "at each pos for i in [ None, *([] if", "kwarg triggers `remove`. mock_remove = MagicMock() with patch.object(storage, 'remove', mock_remove):", "some blob storage systems refuse empty blobs. *([] if no_empty_blobs", "python3 # Copyright (c) Facebook, Inc. and its affiliates. #", "), ) for writes in [ # Some large writes", "systems refuse empty blobs. *([] if no_empty_blobs else [ [b''],", "blank at each pos for i in [ None, *([]", "testing more meaningful, it's useful to make sure that #", "# Some tiny writes without a multiplier [b'a', b'b', b'c',", "mul], # Some tiny writes without a multiplier [b'a', b'b',", "Check that `remove` would have been called, and then call", "the # LICENSE file in the root directory of this", "= output.commit() with storage.reader(sid) as input: written = b''.join(writes) partial_read", "def check_storage_impl( self, storage: Storage, *, no_empty_blobs=False, skip_empty_writes=False, # To", "called, and then call it. mock_remove.assert_called_once_with(id_to_remove) storage.remove(id_to_remove) # Exercise the", "Storage implementation.' def _check_write_and_read(self, storage: Storage, writes: List[bytes]): with storage.writer()", "* mul, b'd' * mul], # Some tiny writes without", "import List, Tuple from .. import Storage # Module import", "StorageBaseTestCase(unittest.TestCase): 'A tiny test suite that can be used to", "that the `remove_on_exception` kwarg triggers `remove`. mock_remove = MagicMock() with", "that can be used to check any Storage implementation.' def", "`remove` would have been called, and then call it. mock_remove.assert_called_once_with(id_to_remove)", "[*writes[:i], b'', *writes[i:]], ), ) for writes in [ #", "to avoid BrokenPipe logspam. input.read() return [ ( writes, self._check_write_and_read(", "sure that # some writes fill up any output buffers.", "input.read()) return sid def check_storage_impl( self, storage: Storage, *, no_empty_blobs=False,", "# While clowny, some blob storage systems refuse empty blobs.", "avoid BrokenPipe logspam. input.read() return [ ( writes, self._check_write_and_read( storage,", "be available. with self.assertRaises(Exception): with storage.reader(id_to_remove) as input: # The", "b''.join(writes) partial_read = input.read(3) if written: self.assertGreater(len(partial_read), 0) self.assertLessEqual(len(partial_read), 3)", "*writes[i:]], ), ) for writes in [ # Some large", "* mul, b'def' * mul, b'g' * mul], [b'abcd' *", "a multiplier [b'a', b'b', b'c', b'd'], [b'ab'], [b'a', b'b'], #", "b'efgh' * mul], [b'abc' * mul, b'defg' * mul], [b'abc'", "While clowny, some blob storage systems refuse empty blobs. *([]", "code is licensed under the MIT license found in the", "b'defg' * mul], [b'abc' * mul, b'def' * mul, b'g'", "if written: self.assertGreater(len(partial_read), 0) self.assertLessEqual(len(partial_read), 3) self.assertEqual(written, partial_read + input.read())", "it. mock_remove.assert_called_once_with(id_to_remove) storage.remove(id_to_remove) # Exercise the real `remove` if remove_is_immediate:", "output.write(b'bah') raise RuntimeError('humbug') with self.assertRaisesRegex(AssertionError, '^Cannot commit twice$'): with storage.writer()", "with self.assertRaisesRegex(RuntimeError, '^humbug$'): with storage.writer() as output: output.write(b'bah') raise RuntimeError('humbug')", "source code is licensed under the MIT license found in", "output: output.write(b'foo') output.commit(remove_on_exception=True) # Leave no litter output.commit() # Check", "Facebook, Inc. and its affiliates. # # This source code", "nothing bad happens if an exception flies before a #", "filesystem writes # from Python, this default is probably enough.", "plugins class StorageBaseTestCase(unittest.TestCase): 'A tiny test suite that can be", "pos for i in [ None, *([] if skip_empty_writes else", "writes # from Python, this default is probably enough. mul=314159,", "# # This source code is licensed under the MIT", "ID, we can't really test that the # partial write", "remove_is_immediate: # The removed ID should not longer be available.", "writes, self._check_write_and_read( storage, writes if i is None else [*writes[:i],", "read-through cache, we cannot effectively # test that the remove", "self.assertEqual(b'foo', reader.read()) raise RuntimeError('remove_on_exception') # Check that `remove` would have", "output.commit() with storage.reader(sid) as input: written = b''.join(writes) partial_read =", "have been called, and then call it. mock_remove.assert_called_once_with(id_to_remove) storage.remove(id_to_remove) #", "call it. mock_remove.assert_called_once_with(id_to_remove) storage.remove(id_to_remove) # Exercise the real `remove` if", "raise RuntimeError('humbug') with self.assertRaisesRegex(AssertionError, '^Cannot commit twice$'): with storage.writer() as", "# This source code is licensed under the MIT license", "unittest from unittest.mock import patch, MagicMock from typing import List,", "pipe from another Python process, # let's consume its output", "* mul], [b'abc' * mul, b'def' * mul, b'g' *", "with self.assertRaises(Exception): with storage.reader(id_to_remove) as input: # The reader may", "reader may be a pipe from another Python process, #", "from another Python process, # let's consume its output to", "MagicMock from typing import List, Tuple from .. import Storage", "the given writes, optionally insert a blank at each pos", "output.commit(remove_on_exception=True) # Leave no litter output.commit() # Check that the", "exception flies before a # commit. Since we don't have", "input: # The reader may be a pipe from another", "300KB # If the blob-store has a read-through cache, we", "mul, b'd' * mul], # Some tiny writes without a", "as output: output.write(b'bah') raise RuntimeError('humbug') with self.assertRaisesRegex(AssertionError, '^Cannot commit twice$'):", "storage.reader(id_to_remove) as input: # The reader may be a pipe", "= MagicMock() with patch.object(storage, 'remove', mock_remove): with self.assertRaisesRegex(RuntimeError, '^remove_on_exception$'): with", "any output buffers. For filesystem writes # from Python, this", "# Check that the `remove_on_exception` kwarg triggers `remove`. mock_remove =", "we get plugins class StorageBaseTestCase(unittest.TestCase): 'A tiny test suite that", "make testing more meaningful, it's useful to make sure that", "available. with self.assertRaises(Exception): with storage.reader(id_to_remove) as input: # The reader", "[b'a', b'b', b'c', b'd'], [b'ab'], [b'a', b'b'], # While clowny,", "that the remove actually happened. remove_is_immediate=True, ) -> List[Tuple[List[str], str]]:", "return [ ( writes, self._check_write_and_read( storage, writes if i is", "Contract: committed blobs are available to read with storage.reader(id_to_remove) as", "don't have an ID, we can't really test that the", "ID should not longer be available. with self.assertRaises(Exception): with storage.reader(id_to_remove)", "[b''], [], ]), ] # Test the given writes, optionally", "a read-through cache, we cannot effectively # test that the", "its affiliates. # # This source code is licensed under", "Writes + their storage ID # Make sure nothing bad", "output.commit() # Check that the `remove_on_exception` kwarg triggers `remove`. mock_remove", "'remove', mock_remove): with self.assertRaisesRegex(RuntimeError, '^remove_on_exception$'): with storage.writer() as output: output.write(b'foo')", "Since we don't have an ID, we can't really test", "for i in [ None, *([] if skip_empty_writes else range(len(writes)", "mock_remove.assert_called_once_with(id_to_remove) storage.remove(id_to_remove) # Exercise the real `remove` if remove_is_immediate: #", "writes: output.write(piece) sid = output.commit() with storage.reader(sid) as input: written", "RuntimeError('remove_on_exception') # Check that `remove` would have been called, and", "more meaningful, it's useful to make sure that # some", "no_empty_blobs=False, skip_empty_writes=False, # To make testing more meaningful, it's useful", "storage.remove(id_to_remove) # Exercise the real `remove` if remove_is_immediate: # The", "we don't have an ID, we can't really test that", "input.read(3) if written: self.assertGreater(len(partial_read), 0) self.assertLessEqual(len(partial_read), 3) self.assertEqual(written, partial_read +", "if no_empty_blobs else [ [b''], [], ]), ] # Test", "to make sure that # some writes fill up any", "that # some writes fill up any output buffers. For", "[b'abc' * mul, b'defg' * mul], [b'abc' * mul, b'def'", "be used to check any Storage implementation.' def _check_write_and_read(self, storage:", "'^Cannot commit twice$'): with storage.writer() as output: output.write(b'foo') output.commit(remove_on_exception=True) #", "empty blobs. *([] if no_empty_blobs else [ [b''], [], ]),", "None else [*writes[:i], b'', *writes[i:]], ), ) for writes in", "with self.assertRaisesRegex(AssertionError, '^Cannot commit twice$'): with storage.writer() as output: output.write(b'foo')", "Python process, # let's consume its output to avoid BrokenPipe", "cache, we cannot effectively # test that the remove actually", "test that the # partial write got discarded. with self.assertRaisesRegex(RuntimeError,", "fill up any output buffers. For filesystem writes # from", "with storage.writer() as output: output.write(b'foo') id_to_remove = output.commit(remove_on_exception=True) # Contract:", "that the # partial write got discarded. with self.assertRaisesRegex(RuntimeError, '^humbug$'):", "from unittest.mock import patch, MagicMock from typing import List, Tuple", "storage.writer() as output: output.write(b'foo') output.commit(remove_on_exception=True) # Leave no litter output.commit()", "output buffers. For filesystem writes # from Python, this default", "before a # commit. Since we don't have an ID,", "make sure that # some writes fill up any output", "let's consume its output to avoid BrokenPipe logspam. input.read() return", "for writes in [ # Some large writes [b'abcd' *", "] # Test the given writes, optionally insert a blank", "ensure we get plugins class StorageBaseTestCase(unittest.TestCase): 'A tiny test suite", "cannot effectively # test that the remove actually happened. remove_is_immediate=True,", "about 300KB # If the blob-store has a read-through cache,", "import to ensure we get plugins class StorageBaseTestCase(unittest.TestCase): 'A tiny", "* mul, b'g' * mul], [b'abcd' * mul], [b'abc' *", "writes, optionally insert a blank at each pos for i", "# Contract: committed blobs are available to read with storage.reader(id_to_remove)", "buffers. For filesystem writes # from Python, this default is", "return sid def check_storage_impl( self, storage: Storage, *, no_empty_blobs=False, skip_empty_writes=False,", "is licensed under the MIT license found in the #", "patch, MagicMock from typing import List, Tuple from .. import", "str]]: # Writes + their storage ID # Make sure", "storage, writes if i is None else [*writes[:i], b'', *writes[i:]],", "_check_write_and_read(self, storage: Storage, writes: List[bytes]): with storage.writer() as output: for", "List[bytes]): with storage.writer() as output: for piece in writes: output.write(piece)", "in writes: output.write(piece) sid = output.commit() with storage.reader(sid) as input:", "0) self.assertLessEqual(len(partial_read), 3) self.assertEqual(written, partial_read + input.read()) return sid def", "i is None else [*writes[:i], b'', *writes[i:]], ), ) for", "`remove`. mock_remove = MagicMock() with patch.object(storage, 'remove', mock_remove): with self.assertRaisesRegex(RuntimeError,", "this source tree. import unittest from unittest.mock import patch, MagicMock", "mul], [b'abc' * mul, b'def' * mul, b'g' * mul],", "from typing import List, Tuple from .. import Storage #", "output.commit(remove_on_exception=True) # Contract: committed blobs are available to read with", "# The reader may be a pipe from another Python", "# To make testing more meaningful, it's useful to make", "# Copyright (c) Facebook, Inc. and its affiliates. # #", "The removed ID should not longer be available. with self.assertRaises(Exception):", "mul=314159, # just about 300KB # If the blob-store has", "discarded. with self.assertRaisesRegex(RuntimeError, '^humbug$'): with storage.writer() as output: output.write(b'bah') raise", "Some tiny writes without a multiplier [b'a', b'b', b'c', b'd'],", "and then call it. mock_remove.assert_called_once_with(id_to_remove) storage.remove(id_to_remove) # Exercise the real", "# Check that `remove` would have been called, and then", "# commit. Since we don't have an ID, we can't", "written = b''.join(writes) partial_read = input.read(3) if written: self.assertGreater(len(partial_read), 0)", "output.write(piece) sid = output.commit() with storage.reader(sid) as input: written =", "we cannot effectively # test that the remove actually happened.", "their storage ID # Make sure nothing bad happens if", "input.read() return [ ( writes, self._check_write_and_read( storage, writes if i", "then call it. mock_remove.assert_called_once_with(id_to_remove) storage.remove(id_to_remove) # Exercise the real `remove`", "source tree. import unittest from unittest.mock import patch, MagicMock from", "b'd'], [b'ab'], [b'a', b'b'], # While clowny, some blob storage", "be a pipe from another Python process, # let's consume", "* mul], # Some tiny writes without a multiplier [b'a',", "[b'a', b'b'], # While clowny, some blob storage systems refuse", "commit. Since we don't have an ID, we can't really", "if remove_is_immediate: # The removed ID should not longer be", "writes [b'abcd' * mul, b'efgh' * mul], [b'abc' * mul,", "as output: output.write(b'foo') output.commit(remove_on_exception=True) # Leave no litter output.commit() #", "output.write(b'foo') output.commit(remove_on_exception=True) # Leave no litter output.commit() # Check that", "Storage # Module import to ensure we get plugins class", "'A tiny test suite that can be used to check", "the # partial write got discarded. with self.assertRaisesRegex(RuntimeError, '^humbug$'): with", "writes if i is None else [*writes[:i], b'', *writes[i:]], ),", "# Writes + their storage ID # Make sure nothing", "# test that the remove actually happened. remove_is_immediate=True, ) ->", "it's useful to make sure that # some writes fill", "Inc. and its affiliates. # # This source code is", "from .. import Storage # Module import to ensure we", "in [ # Some large writes [b'abcd' * mul, b'efgh'", "List[Tuple[List[str], str]]: # Writes + their storage ID # Make", "as output: for piece in writes: output.write(piece) sid = output.commit()", "with self.assertRaisesRegex(RuntimeError, '^remove_on_exception$'): with storage.writer() as output: output.write(b'foo') id_to_remove =", "the `remove_on_exception` kwarg triggers `remove`. mock_remove = MagicMock() with patch.object(storage,", "partial write got discarded. with self.assertRaisesRegex(RuntimeError, '^humbug$'): with storage.writer() as", "no litter output.commit() # Check that the `remove_on_exception` kwarg triggers", "refuse empty blobs. *([] if no_empty_blobs else [ [b''], [],", "just about 300KB # If the blob-store has a read-through", "removed ID should not longer be available. with self.assertRaises(Exception): with", "if i is None else [*writes[:i], b'', *writes[i:]], ), )", "happened. remove_is_immediate=True, ) -> List[Tuple[List[str], str]]: # Writes + their", "[b'ab'], [b'a', b'b'], # While clowny, some blob storage systems", "# Test the given writes, optionally insert a blank at", "b'def' * mul, b'g' * mul], [b'abcd' * mul], [b'abc'", "remove_is_immediate=True, ) -> List[Tuple[List[str], str]]: # Writes + their storage", "write got discarded. with self.assertRaisesRegex(RuntimeError, '^humbug$'): with storage.writer() as output:", "is None else [*writes[:i], b'', *writes[i:]], ), ) for writes" ]
[ "isinstance(id, str): raise TypeError(\"Expected argument 'id' to be a str\")", "argument 'algorithm' to be a str\") pulumi.set(__self__, \"algorithm\", algorithm) if", "\"crypto_key\") @property @pulumi.getter def id(self) -> str: \"\"\" The provider-assigned", "raise TypeError(\"Expected argument 'public_keys' to be a list\") pulumi.set(__self__, \"public_keys\",", "argument 'version' to be a int\") pulumi.set(__self__, \"version\", version) @property", "import pulumi_gcp as gcp my_key_ring = gcp.kms.get_kms_key_ring(name=\"my-key-ring\", location=\"us-central1\") my_crypto_key =", "and the associated key material. ## Example Usage ```python import", "\"version\") class AwaitableGetKMSCryptoKeyVersionResult(GetKMSCryptoKeyVersionResult): # pylint: disable=using-constant-test def __await__(self): if False:", "Tool. *** # *** Do not edit by hand unless", "opts.version is None: opts.version = _utilities.get_version() __ret__ = pulumi.runtime.invoke('gcp:kms/getKMSCryptoKeyVersion:getKMSCryptoKeyVersion', __args__,", "Optional[pulumi.InvokeOptions] = None) -> AwaitableGetKMSCryptoKeyVersionResult: \"\"\" Provides access to a", "pulumi.set(__self__, \"crypto_key\", crypto_key) if id and not isinstance(id, str): raise", "isinstance(state, str): raise TypeError(\"Expected argument 'state' to be a str\")", "if name and not isinstance(name, str): raise TypeError(\"Expected argument 'name'", "'public_keys' to be a list\") pulumi.set(__self__, \"public_keys\", public_keys) if state", "str\") pulumi.set(__self__, \"state\", state) if version and not isinstance(version, int):", "performed with this CryptoKeyVersion. See the [protection_level reference](https://cloud.google.com/kms/docs/reference/rest/v1/ProtectionLevel) for possible", "not isinstance(version, int): raise TypeError(\"Expected argument 'version' to be a", "None: opts = pulumi.InvokeOptions() if opts.version is None: opts.version =", "key associated to this CryptoKeyVersion. Structure is documented below. \"\"\"", "and not isinstance(algorithm, str): raise TypeError(\"Expected argument 'algorithm' to be", "str): raise TypeError(\"Expected argument 'algorithm' to be a str\") pulumi.set(__self__,", "argument 'crypto_key' to be a str\") pulumi.set(__self__, \"crypto_key\", crypto_key) if", "access to a Google Cloud Platform KMS CryptoKeyVersion. For more", "operations are performed with this CryptoKeyVersion. See the [protection_level reference](https://cloud.google.com/kms/docs/reference/rest/v1/ProtectionLevel)", "provider-assigned unique ID for this managed resource. \"\"\" return pulumi.get(self,", "CryptoKeyVersion. For more information see [the official documentation](https://cloud.google.com/kms/docs/object-hierarchy#key_version) and [API](https://cloud.google.com/kms/docs/reference/rest/v1/projects.locations.keyRings.cryptoKeys.cryptoKeyVersions).", "if False: yield self return GetKMSCryptoKeyVersionResult( algorithm=self.algorithm, crypto_key=self.crypto_key, id=self.id, name=self.name,", "this CryptoKeyVersion. Defaults to `1`. \"\"\" __args__ = dict() __args__['cryptoKey']", "return pulumi.get(self, \"crypto_key\") @property @pulumi.getter def id(self) -> str: \"\"\"", "to be a str\") pulumi.set(__self__, \"name\", name) if protection_level and", "AwaitableGetKMSCryptoKeyVersionResult: \"\"\" Provides access to a Google Cloud Platform KMS", "version: Optional[pulumi.Input[Optional[int]]] = None, opts: Optional[pulumi.InvokeOptions] = None) -> pulumi.Output[GetKMSCryptoKeyVersionResult]:", "the associated key material. ## Example Usage ```python import pulumi", "pulumi.set(__self__, \"algorithm\", algorithm) if crypto_key and not isinstance(crypto_key, str): raise", "`1`. \"\"\" __args__ = dict() __args__['cryptoKey'] = crypto_key __args__['version'] =", "'name' to be a str\") pulumi.set(__self__, \"name\", name) if protection_level", "if opts is None: opts = pulumi.InvokeOptions() if opts.version is", "or `ASYMMETRIC_DECRYPT`, this block contains details about the public key", "-> str: \"\"\" The ProtectionLevel describing how crypto operations are", "def algorithm(self) -> str: \"\"\" The CryptoKeyVersionAlgorithm that this CryptoKeyVersion", "Optional[pulumi.Input[str]] = None, version: Optional[pulumi.Input[Optional[int]]] = None, opts: Optional[pulumi.InvokeOptions] =", "pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence,", "for this managed resource. \"\"\" return pulumi.get(self, \"id\") @property @pulumi.getter", "If the enclosing CryptoKey has purpose `ASYMMETRIC_SIGN` or `ASYMMETRIC_DECRYPT`, this", "a str\") pulumi.set(__self__, \"crypto_key\", crypto_key) if id and not isinstance(id,", "argument 'public_keys' to be a list\") pulumi.set(__self__, \"public_keys\", public_keys) if", "an individual cryptographic key, and the associated key material. ##", "which the key version belongs. This is also the `id`", "version(self) -> Optional[int]: return pulumi.get(self, \"version\") class AwaitableGetKMSCryptoKeyVersionResult(GetKMSCryptoKeyVersionResult): # pylint:", "\"\"\" Provides access to a Google Cloud Platform KMS CryptoKeyVersion.", "of values returned by getKMSCryptoKeyVersion. \"\"\" def __init__(__self__, algorithm=None, crypto_key=None,", "isinstance(protection_level, str): raise TypeError(\"Expected argument 'protection_level' to be a str\")", "pulumi.Output[GetKMSCryptoKeyVersionResult]: \"\"\" Provides access to a Google Cloud Platform KMS", "__ret__ = pulumi.runtime.invoke('gcp:kms/getKMSCryptoKeyVersion:getKMSCryptoKeyVersion', __args__, opts=opts, typ=GetKMSCryptoKeyVersionResult).value return AwaitableGetKMSCryptoKeyVersionResult( algorithm=__ret__.algorithm, crypto_key=__ret__.crypto_key,", "__all__ = [ 'GetKMSCryptoKeyVersionResult', 'AwaitableGetKMSCryptoKeyVersionResult', 'get_kms_crypto_key_version', 'get_kms_crypto_key_version_output', ] @pulumi.output_type class", "Structure is documented below. \"\"\" return pulumi.get(self, \"public_keys\") @property @pulumi.getter", "\"state\", state) if version and not isinstance(version, int): raise TypeError(\"Expected", "typ=GetKMSCryptoKeyVersionResult).value return AwaitableGetKMSCryptoKeyVersionResult( algorithm=__ret__.algorithm, crypto_key=__ret__.crypto_key, id=__ret__.id, name=__ret__.name, protection_level=__ret__.protection_level, public_keys=__ret__.public_keys, state=__ret__.state,", "'version' to be a int\") pulumi.set(__self__, \"version\", version) @property @pulumi.getter", "See the [protection_level reference](https://cloud.google.com/kms/docs/reference/rest/v1/ProtectionLevel) for possible outputs. \"\"\" return pulumi.get(self,", "to be a str\") pulumi.set(__self__, \"crypto_key\", crypto_key) if id and", "TypeError(\"Expected argument 'state' to be a str\") pulumi.set(__self__, \"state\", state)", "CryptoKeyVersion. See the [state reference](https://cloud.google.com/kms/docs/reference/rest/v1/projects.locations.keyRings.cryptoKeys.cryptoKeyVersions#CryptoKeyVersion.CryptoKeyVersionState) for possible outputs. \"\"\" return", "`ASYMMETRIC_DECRYPT`, this block contains details about the public key associated", "to `1`. \"\"\" __args__ = dict() __args__['cryptoKey'] = crypto_key __args__['version']", "generated by the Pulumi Terraform Bridge (tfgen) Tool. *** #", "\"\"\" def __init__(__self__, algorithm=None, crypto_key=None, id=None, name=None, protection_level=None, public_keys=None, state=None,", "algorithm=__ret__.algorithm, crypto_key=__ret__.crypto_key, id=__ret__.id, name=__ret__.name, protection_level=__ret__.protection_level, public_keys=__ret__.public_keys, state=__ret__.state, version=__ret__.version) @_utilities.lift_output_func(get_kms_crypto_key_version) def", "public_keys=__ret__.public_keys, state=__ret__.state, version=__ret__.version) @_utilities.lift_output_func(get_kms_crypto_key_version) def get_kms_crypto_key_version_output(crypto_key: Optional[pulumi.Input[str]] = None, version:", "reference](https://cloud.google.com/kms/docs/reference/rest/v1/ProtectionLevel) for possible outputs. \"\"\" return pulumi.get(self, \"protection_level\") @property @pulumi.getter(name=\"publicKeys\")", "None, version: Optional[pulumi.Input[Optional[int]]] = None, opts: Optional[pulumi.InvokeOptions] = None) ->", "how crypto operations are performed with this CryptoKeyVersion. See the", "not isinstance(algorithm, str): raise TypeError(\"Expected argument 'algorithm' to be a", "pulumi.get(self, \"id\") @property @pulumi.getter def name(self) -> str: \"\"\" The", "pulumi.set(__self__, \"version\", version) @property @pulumi.getter def algorithm(self) -> str: \"\"\"", "number for this CryptoKeyVersion. Defaults to `1`. \"\"\" __args__ =", "not isinstance(id, str): raise TypeError(\"Expected argument 'id' to be a", "id=None, name=None, protection_level=None, public_keys=None, state=None, version=None): if algorithm and not", "_utilities.get_version() __ret__ = pulumi.runtime.invoke('gcp:kms/getKMSCryptoKeyVersion:getKMSCryptoKeyVersion', __args__, opts=opts, typ=GetKMSCryptoKeyVersionResult).value return AwaitableGetKMSCryptoKeyVersionResult( algorithm=__ret__.algorithm,", "A CryptoKeyVersion represents an individual cryptographic key, and the associated", "the CryptoKeyVersion. See the [state reference](https://cloud.google.com/kms/docs/reference/rest/v1/projects.locations.keyRings.cryptoKeys.cryptoKeyVersions#CryptoKeyVersion.CryptoKeyVersionState) for possible outputs. \"\"\"", "pulumi.get(self, \"name\") @property @pulumi.getter(name=\"protectionLevel\") def protection_level(self) -> str: \"\"\" The", "None, version: Optional[int] = None, opts: Optional[pulumi.InvokeOptions] = None) ->", "str): raise TypeError(\"Expected argument 'name' to be a str\") pulumi.set(__self__,", "__args__, opts=opts, typ=GetKMSCryptoKeyVersionResult).value return AwaitableGetKMSCryptoKeyVersionResult( algorithm=__ret__.algorithm, crypto_key=__ret__.crypto_key, id=__ret__.id, name=__ret__.name, protection_level=__ret__.protection_level,", "str: \"\"\" The provider-assigned unique ID for this managed resource.", "hand unless you're certain you know what you are doing!", "isinstance(algorithm, str): raise TypeError(\"Expected argument 'algorithm' to be a str\")", "to be a str\") pulumi.set(__self__, \"algorithm\", algorithm) if crypto_key and", "name=None, protection_level=None, public_keys=None, state=None, version=None): if algorithm and not isinstance(algorithm,", "pulumi.set(__self__, \"id\", id) if name and not isinstance(name, str): raise", "possible outputs. \"\"\" return pulumi.get(self, \"protection_level\") @property @pulumi.getter(name=\"publicKeys\") def public_keys(self)", "\"public_keys\", public_keys) if state and not isinstance(state, str): raise TypeError(\"Expected", "public_keys=None, state=None, version=None): if algorithm and not isinstance(algorithm, str): raise", "unless you're certain you know what you are doing! ***", "state=__ret__.state, version=__ret__.version) @_utilities.lift_output_func(get_kms_crypto_key_version) def get_kms_crypto_key_version_output(crypto_key: Optional[pulumi.Input[str]] = None, version: Optional[pulumi.Input[Optional[int]]]", "version belongs. This is also the `id` field of the", "not isinstance(crypto_key, str): raise TypeError(\"Expected argument 'crypto_key' to be a", "this block contains details about the public key associated to", "\"id\") @property @pulumi.getter def name(self) -> str: \"\"\" The resource", "was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***", "CryptoKeyVersion represents an individual cryptographic key, and the associated key", "str: \"\"\" The ProtectionLevel describing how crypto operations are performed", "opts is None: opts = pulumi.InvokeOptions() if opts.version is None:", "details about the public key associated to this CryptoKeyVersion. Structure", "crypto_key __args__['version'] = version if opts is None: opts =", "by the Pulumi Terraform Bridge (tfgen) Tool. *** # ***", "be a str\") pulumi.set(__self__, \"protection_level\", protection_level) if public_keys and not", "to be a str\") pulumi.set(__self__, \"state\", state) if version and", "state=None, version=None): if algorithm and not isinstance(algorithm, str): raise TypeError(\"Expected", "return AwaitableGetKMSCryptoKeyVersionResult( algorithm=__ret__.algorithm, crypto_key=__ret__.crypto_key, id=__ret__.id, name=__ret__.name, protection_level=__ret__.protection_level, public_keys=__ret__.public_keys, state=__ret__.state, version=__ret__.version)", "opts=opts, typ=GetKMSCryptoKeyVersionResult).value return AwaitableGetKMSCryptoKeyVersionResult( algorithm=__ret__.algorithm, crypto_key=__ret__.crypto_key, id=__ret__.id, name=__ret__.name, protection_level=__ret__.protection_level, public_keys=__ret__.public_keys,", "Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not", "is also the `id` field of the `kms.CryptoKey` resource/datasource. :param", "import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union,", "version: Optional[int] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetKMSCryptoKeyVersionResult:", "what you are doing! *** import warnings import pulumi import", "to be a list\") pulumi.set(__self__, \"public_keys\", public_keys) if state and", "CryptoKeyVersion in the format `projects/*/locations/*/keyRings/*/cryptoKeys/*/cryptoKeyVersions/*` \"\"\" return pulumi.get(self, \"name\") @property", "\"public_keys\") @property @pulumi.getter def state(self) -> str: \"\"\" The current", "= None, version: Optional[pulumi.Input[Optional[int]]] = None, opts: Optional[pulumi.InvokeOptions] = None)", "not isinstance(name, str): raise TypeError(\"Expected argument 'name' to be a", "isinstance(crypto_key, str): raise TypeError(\"Expected argument 'crypto_key' to be a str\")", "raise TypeError(\"Expected argument 'name' to be a str\") pulumi.set(__self__, \"name\",", "= None) -> AwaitableGetKMSCryptoKeyVersionResult: \"\"\" Provides access to a Google", "enclosing CryptoKey has purpose `ASYMMETRIC_SIGN` or `ASYMMETRIC_DECRYPT`, this block contains", "[protection_level reference](https://cloud.google.com/kms/docs/reference/rest/v1/ProtectionLevel) for possible outputs. \"\"\" return pulumi.get(self, \"protection_level\") @property", "algorithm=self.algorithm, crypto_key=self.crypto_key, id=self.id, name=self.name, protection_level=self.protection_level, public_keys=self.public_keys, state=self.state, version=self.version) def get_kms_crypto_key_version(crypto_key:", "my_crypto_key_version = gcp.kms.get_kms_crypto_key_version(crypto_key=data[\"google_kms_key\"][\"my_key\"][\"id\"]) ``` :param str crypto_key: The `self_link` of", "TypeError(\"Expected argument 'algorithm' to be a str\") pulumi.set(__self__, \"algorithm\", algorithm)", "ID for this managed resource. \"\"\" return pulumi.get(self, \"id\") @property", "def public_keys(self) -> Sequence['outputs.GetKMSCryptoKeyVersionPublicKeyResult']: \"\"\" If the enclosing CryptoKey has", "opts = pulumi.InvokeOptions() if opts.version is None: opts.version = _utilities.get_version()", "protection_level=__ret__.protection_level, public_keys=__ret__.public_keys, state=__ret__.state, version=__ret__.version) @_utilities.lift_output_func(get_kms_crypto_key_version) def get_kms_crypto_key_version_output(crypto_key: Optional[pulumi.Input[str]] = None,", "current state of the CryptoKeyVersion. See the [state reference](https://cloud.google.com/kms/docs/reference/rest/v1/projects.locations.keyRings.cryptoKeys.cryptoKeyVersions#CryptoKeyVersion.CryptoKeyVersionState) for", "The resource name for this CryptoKeyVersion in the format `projects/*/locations/*/keyRings/*/cryptoKeys/*/cryptoKeyVersions/*`", "id(self) -> str: \"\"\" The provider-assigned unique ID for this", "Optional[int] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetKMSCryptoKeyVersionResult: \"\"\"", "def get_kms_crypto_key_version_output(crypto_key: Optional[pulumi.Input[str]] = None, version: Optional[pulumi.Input[Optional[int]]] = None, opts:", "algorithm=None, crypto_key=None, id=None, name=None, protection_level=None, public_keys=None, state=None, version=None): if algorithm", "the Google Cloud Platform CryptoKey to which the key version", "# pylint: disable=using-constant-test def __await__(self): if False: yield self return", "and not isinstance(name, str): raise TypeError(\"Expected argument 'name' to be", "information see [the official documentation](https://cloud.google.com/kms/docs/object-hierarchy#key_version) and [API](https://cloud.google.com/kms/docs/reference/rest/v1/projects.locations.keyRings.cryptoKeys.cryptoKeyVersions). A CryptoKeyVersion represents", "= gcp.kms.get_kms_crypto_key(name=\"my-crypto-key\", key_ring=my_key_ring.id) my_crypto_key_version = gcp.kms.get_kms_crypto_key_version(crypto_key=data[\"google_kms_key\"][\"my_key\"][\"id\"]) ``` :param str crypto_key:", "documented below. \"\"\" return pulumi.get(self, \"public_keys\") @property @pulumi.getter def state(self)", "warnings import pulumi import pulumi.runtime from typing import Any, Mapping,", "this CryptoKeyVersion. Structure is documented below. \"\"\" return pulumi.get(self, \"public_keys\")", "of the CryptoKeyVersion. See the [state reference](https://cloud.google.com/kms/docs/reference/rest/v1/projects.locations.keyRings.cryptoKeys.cryptoKeyVersions#CryptoKeyVersion.CryptoKeyVersionState) for possible outputs.", "pulumi.get(self, \"crypto_key\") @property @pulumi.getter def id(self) -> str: \"\"\" The", "raise TypeError(\"Expected argument 'crypto_key' to be a str\") pulumi.set(__self__, \"crypto_key\",", "# coding=utf-8 # *** WARNING: this file was generated by", "CryptoKeyVersion supports. \"\"\" return pulumi.get(self, \"algorithm\") @property @pulumi.getter(name=\"cryptoKey\") def crypto_key(self)", "import warnings import pulumi import pulumi.runtime from typing import Any,", "@pulumi.getter def state(self) -> str: \"\"\" The current state of", "pylint: disable=using-constant-test def __await__(self): if False: yield self return GetKMSCryptoKeyVersionResult(", "*** import warnings import pulumi import pulumi.runtime from typing import", "from . import outputs __all__ = [ 'GetKMSCryptoKeyVersionResult', 'AwaitableGetKMSCryptoKeyVersionResult', 'get_kms_crypto_key_version',", "as gcp my_key_ring = gcp.kms.get_kms_key_ring(name=\"my-key-ring\", location=\"us-central1\") my_crypto_key = gcp.kms.get_kms_crypto_key(name=\"my-crypto-key\", key_ring=my_key_ring.id)", "@property @pulumi.getter(name=\"protectionLevel\") def protection_level(self) -> str: \"\"\" The ProtectionLevel describing", "str): raise TypeError(\"Expected argument 'crypto_key' to be a str\") pulumi.set(__self__,", "and not isinstance(public_keys, list): raise TypeError(\"Expected argument 'public_keys' to be", "str): raise TypeError(\"Expected argument 'state' to be a str\") pulumi.set(__self__,", "you know what you are doing! *** import warnings import", "TypeError(\"Expected argument 'name' to be a str\") pulumi.set(__self__, \"name\", name)", "more information see [the official documentation](https://cloud.google.com/kms/docs/object-hierarchy#key_version) and [API](https://cloud.google.com/kms/docs/reference/rest/v1/projects.locations.keyRings.cryptoKeys.cryptoKeyVersions). A CryptoKeyVersion", "@property @pulumi.getter(name=\"publicKeys\") def public_keys(self) -> Sequence['outputs.GetKMSCryptoKeyVersionPublicKeyResult']: \"\"\" If the enclosing", "@pulumi.getter def version(self) -> Optional[int]: return pulumi.get(self, \"version\") class AwaitableGetKMSCryptoKeyVersionResult(GetKMSCryptoKeyVersionResult):", "argument 'id' to be a str\") pulumi.set(__self__, \"id\", id) if", "Optional[pulumi.Input[Optional[int]]] = None, opts: Optional[pulumi.InvokeOptions] = None) -> pulumi.Output[GetKMSCryptoKeyVersionResult]: \"\"\"", "format `projects/*/locations/*/keyRings/*/cryptoKeys/*/cryptoKeyVersions/*` \"\"\" return pulumi.get(self, \"name\") @property @pulumi.getter(name=\"protectionLevel\") def protection_level(self)", "return pulumi.get(self, \"state\") @property @pulumi.getter def version(self) -> Optional[int]: return", "-> AwaitableGetKMSCryptoKeyVersionResult: \"\"\" Provides access to a Google Cloud Platform", "argument 'protection_level' to be a str\") pulumi.set(__self__, \"protection_level\", protection_level) if", "my_crypto_key = gcp.kms.get_kms_crypto_key(name=\"my-crypto-key\", key_ring=my_key_ring.id) my_crypto_key_version = gcp.kms.get_kms_crypto_key_version(crypto_key=data[\"google_kms_key\"][\"my_key\"][\"id\"]) ``` :param str", "'state' to be a str\") pulumi.set(__self__, \"state\", state) if version", "\"name\", name) if protection_level and not isinstance(protection_level, str): raise TypeError(\"Expected", "list\") pulumi.set(__self__, \"public_keys\", public_keys) if state and not isinstance(state, str):", "\"algorithm\") @property @pulumi.getter(name=\"cryptoKey\") def crypto_key(self) -> str: return pulumi.get(self, \"crypto_key\")", "= [ 'GetKMSCryptoKeyVersionResult', 'AwaitableGetKMSCryptoKeyVersionResult', 'get_kms_crypto_key_version', 'get_kms_crypto_key_version_output', ] @pulumi.output_type class GetKMSCryptoKeyVersionResult:", "the public key associated to this CryptoKeyVersion. Structure is documented", "to this CryptoKeyVersion. Structure is documented below. \"\"\" return pulumi.get(self,", "str: \"\"\" The CryptoKeyVersionAlgorithm that this CryptoKeyVersion supports. \"\"\" return", "a int\") pulumi.set(__self__, \"version\", version) @property @pulumi.getter def algorithm(self) ->", "self return GetKMSCryptoKeyVersionResult( algorithm=self.algorithm, crypto_key=self.crypto_key, id=self.id, name=self.name, protection_level=self.protection_level, public_keys=self.public_keys, state=self.state,", "\"\"\" The CryptoKeyVersionAlgorithm that this CryptoKeyVersion supports. \"\"\" return pulumi.get(self,", "to be a str\") pulumi.set(__self__, \"protection_level\", protection_level) if public_keys and", "public key associated to this CryptoKeyVersion. Structure is documented below.", "state(self) -> str: \"\"\" The current state of the CryptoKeyVersion.", "`self_link` of the Google Cloud Platform CryptoKey to which the", "of the Google Cloud Platform CryptoKey to which the key", "raise TypeError(\"Expected argument 'algorithm' to be a str\") pulumi.set(__self__, \"algorithm\",", "'get_kms_crypto_key_version_output', ] @pulumi.output_type class GetKMSCryptoKeyVersionResult: \"\"\" A collection of values", "version number for this CryptoKeyVersion. Defaults to `1`. \"\"\" __args__", "This is also the `id` field of the `kms.CryptoKey` resource/datasource.", "str: \"\"\" The current state of the CryptoKeyVersion. See the", "The CryptoKeyVersionAlgorithm that this CryptoKeyVersion supports. \"\"\" return pulumi.get(self, \"algorithm\")", "be a str\") pulumi.set(__self__, \"crypto_key\", crypto_key) if id and not", "The provider-assigned unique ID for this managed resource. \"\"\" return", "this file was generated by the Pulumi Terraform Bridge (tfgen)", "key_ring=my_key_ring.id) my_crypto_key_version = gcp.kms.get_kms_crypto_key_version(crypto_key=data[\"google_kms_key\"][\"my_key\"][\"id\"]) ``` :param str crypto_key: The `self_link`", "cryptographic key, and the associated key material. ## Example Usage", "str\") pulumi.set(__self__, \"id\", id) if name and not isinstance(name, str):", "See the [state reference](https://cloud.google.com/kms/docs/reference/rest/v1/projects.locations.keyRings.cryptoKeys.cryptoKeyVersions#CryptoKeyVersion.CryptoKeyVersionState) for possible outputs. \"\"\" return pulumi.get(self,", "state and not isinstance(state, str): raise TypeError(\"Expected argument 'state' to", "*** # *** Do not edit by hand unless you're", "is documented below. \"\"\" return pulumi.get(self, \"public_keys\") @property @pulumi.getter def", "\"\"\" The current state of the CryptoKeyVersion. See the [state", "Provides access to a Google Cloud Platform KMS CryptoKeyVersion. For", "CryptoKeyVersion. Structure is documented below. \"\"\" return pulumi.get(self, \"public_keys\") @property", "*** Do not edit by hand unless you're certain you", "pulumi.set(__self__, \"protection_level\", protection_level) if public_keys and not isinstance(public_keys, list): raise", "with this CryptoKeyVersion. See the [protection_level reference](https://cloud.google.com/kms/docs/reference/rest/v1/ProtectionLevel) for possible outputs.", "not isinstance(public_keys, list): raise TypeError(\"Expected argument 'public_keys' to be a", "\"state\") @property @pulumi.getter def version(self) -> Optional[int]: return pulumi.get(self, \"version\")", "overload from .. import _utilities from . import outputs __all__", "Optional[int]: return pulumi.get(self, \"version\") class AwaitableGetKMSCryptoKeyVersionResult(GetKMSCryptoKeyVersionResult): # pylint: disable=using-constant-test def", "Platform CryptoKey to which the key version belongs. This is", "str: return pulumi.get(self, \"crypto_key\") @property @pulumi.getter def id(self) -> str:", "the key version belongs. This is also the `id` field", "= dict() __args__['cryptoKey'] = crypto_key __args__['version'] = version if opts", "return pulumi.get(self, \"version\") class AwaitableGetKMSCryptoKeyVersionResult(GetKMSCryptoKeyVersionResult): # pylint: disable=using-constant-test def __await__(self):", "\"\"\" return pulumi.get(self, \"state\") @property @pulumi.getter def version(self) -> Optional[int]:", "@property @pulumi.getter def version(self) -> Optional[int]: return pulumi.get(self, \"version\") class", "and not isinstance(crypto_key, str): raise TypeError(\"Expected argument 'crypto_key' to be", "a list\") pulumi.set(__self__, \"public_keys\", public_keys) if state and not isinstance(state,", "version=self.version) def get_kms_crypto_key_version(crypto_key: Optional[str] = None, version: Optional[int] = None,", "= pulumi.InvokeOptions() if opts.version is None: opts.version = _utilities.get_version() __ret__", ".. import _utilities from . import outputs __all__ = [", "this CryptoKeyVersion. See the [protection_level reference](https://cloud.google.com/kms/docs/reference/rest/v1/ProtectionLevel) for possible outputs. \"\"\"", "also the `id` field of the `kms.CryptoKey` resource/datasource. :param int", "\"protection_level\", protection_level) if public_keys and not isinstance(public_keys, list): raise TypeError(\"Expected", "key, and the associated key material. ## Example Usage ```python", "algorithm(self) -> str: \"\"\" The CryptoKeyVersionAlgorithm that this CryptoKeyVersion supports.", "name=self.name, protection_level=self.protection_level, public_keys=self.public_keys, state=self.state, version=self.version) def get_kms_crypto_key_version(crypto_key: Optional[str] = None,", "\"\"\" return pulumi.get(self, \"algorithm\") @property @pulumi.getter(name=\"cryptoKey\") def crypto_key(self) -> str:", "raise TypeError(\"Expected argument 'protection_level' to be a str\") pulumi.set(__self__, \"protection_level\",", "pulumi.set(__self__, \"state\", state) if version and not isinstance(version, int): raise", "AwaitableGetKMSCryptoKeyVersionResult( algorithm=__ret__.algorithm, crypto_key=__ret__.crypto_key, id=__ret__.id, name=__ret__.name, protection_level=__ret__.protection_level, public_keys=__ret__.public_keys, state=__ret__.state, version=__ret__.version) @_utilities.lift_output_func(get_kms_crypto_key_version)", "that this CryptoKeyVersion supports. \"\"\" return pulumi.get(self, \"algorithm\") @property @pulumi.getter(name=\"cryptoKey\")", "## Example Usage ```python import pulumi import pulumi_gcp as gcp", "\"\"\" The provider-assigned unique ID for this managed resource. \"\"\"", "doing! *** import warnings import pulumi import pulumi.runtime from typing", "class AwaitableGetKMSCryptoKeyVersionResult(GetKMSCryptoKeyVersionResult): # pylint: disable=using-constant-test def __await__(self): if False: yield", "getKMSCryptoKeyVersion. \"\"\" def __init__(__self__, algorithm=None, crypto_key=None, id=None, name=None, protection_level=None, public_keys=None,", "location=\"us-central1\") my_crypto_key = gcp.kms.get_kms_crypto_key(name=\"my-crypto-key\", key_ring=my_key_ring.id) my_crypto_key_version = gcp.kms.get_kms_crypto_key_version(crypto_key=data[\"google_kms_key\"][\"my_key\"][\"id\"]) ``` :param", "crypto_key) if id and not isinstance(id, str): raise TypeError(\"Expected argument", "int\") pulumi.set(__self__, \"version\", version) @property @pulumi.getter def algorithm(self) -> str:", "The `self_link` of the Google Cloud Platform CryptoKey to which", "not isinstance(state, str): raise TypeError(\"Expected argument 'state' to be a", "def __await__(self): if False: yield self return GetKMSCryptoKeyVersionResult( algorithm=self.algorithm, crypto_key=self.crypto_key,", "\"name\") @property @pulumi.getter(name=\"protectionLevel\") def protection_level(self) -> str: \"\"\" The ProtectionLevel", "import _utilities from . import outputs __all__ = [ 'GetKMSCryptoKeyVersionResult',", "if id and not isinstance(id, str): raise TypeError(\"Expected argument 'id'", "of the `kms.CryptoKey` resource/datasource. :param int version: The version number", "typing import Any, Mapping, Optional, Sequence, Union, overload from ..", "@pulumi.getter def algorithm(self) -> str: \"\"\" The CryptoKeyVersionAlgorithm that this", "crypto_key and not isinstance(crypto_key, str): raise TypeError(\"Expected argument 'crypto_key' to", "key version belongs. This is also the `id` field of", "algorithm and not isinstance(algorithm, str): raise TypeError(\"Expected argument 'algorithm' to", "For more information see [the official documentation](https://cloud.google.com/kms/docs/object-hierarchy#key_version) and [API](https://cloud.google.com/kms/docs/reference/rest/v1/projects.locations.keyRings.cryptoKeys.cryptoKeyVersions). A", "version=None): if algorithm and not isinstance(algorithm, str): raise TypeError(\"Expected argument", "name(self) -> str: \"\"\" The resource name for this CryptoKeyVersion", "be a str\") pulumi.set(__self__, \"algorithm\", algorithm) if crypto_key and not", "state) if version and not isinstance(version, int): raise TypeError(\"Expected argument", "the `id` field of the `kms.CryptoKey` resource/datasource. :param int version:", "`ASYMMETRIC_SIGN` or `ASYMMETRIC_DECRYPT`, this block contains details about the public", "pulumi.get(self, \"public_keys\") @property @pulumi.getter def state(self) -> str: \"\"\" The", "version: The version number for this CryptoKeyVersion. Defaults to `1`.", "\"\"\" The resource name for this CryptoKeyVersion in the format", "this CryptoKeyVersion in the format `projects/*/locations/*/keyRings/*/cryptoKeys/*/cryptoKeyVersions/*` \"\"\" return pulumi.get(self, \"name\")", "import outputs __all__ = [ 'GetKMSCryptoKeyVersionResult', 'AwaitableGetKMSCryptoKeyVersionResult', 'get_kms_crypto_key_version', 'get_kms_crypto_key_version_output', ]", "None: opts.version = _utilities.get_version() __ret__ = pulumi.runtime.invoke('gcp:kms/getKMSCryptoKeyVersion:getKMSCryptoKeyVersion', __args__, opts=opts, typ=GetKMSCryptoKeyVersionResult).value", "pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload", "get_kms_crypto_key_version(crypto_key: Optional[str] = None, version: Optional[int] = None, opts: Optional[pulumi.InvokeOptions]", "TypeError(\"Expected argument 'protection_level' to be a str\") pulumi.set(__self__, \"protection_level\", protection_level)", "Usage ```python import pulumi import pulumi_gcp as gcp my_key_ring =", "def protection_level(self) -> str: \"\"\" The ProtectionLevel describing how crypto", "= gcp.kms.get_kms_crypto_key_version(crypto_key=data[\"google_kms_key\"][\"my_key\"][\"id\"]) ``` :param str crypto_key: The `self_link` of the", ":param str crypto_key: The `self_link` of the Google Cloud Platform", "\"\"\" return pulumi.get(self, \"name\") @property @pulumi.getter(name=\"protectionLevel\") def protection_level(self) -> str:", "\"\"\" If the enclosing CryptoKey has purpose `ASYMMETRIC_SIGN` or `ASYMMETRIC_DECRYPT`,", "__init__(__self__, algorithm=None, crypto_key=None, id=None, name=None, protection_level=None, public_keys=None, state=None, version=None): if", "my_key_ring = gcp.kms.get_kms_key_ring(name=\"my-key-ring\", location=\"us-central1\") my_crypto_key = gcp.kms.get_kms_crypto_key(name=\"my-crypto-key\", key_ring=my_key_ring.id) my_crypto_key_version =", "a str\") pulumi.set(__self__, \"state\", state) if version and not isinstance(version,", "gcp.kms.get_kms_key_ring(name=\"my-key-ring\", location=\"us-central1\") my_crypto_key = gcp.kms.get_kms_crypto_key(name=\"my-crypto-key\", key_ring=my_key_ring.id) my_crypto_key_version = gcp.kms.get_kms_crypto_key_version(crypto_key=data[\"google_kms_key\"][\"my_key\"][\"id\"]) ```", "\"\"\" return pulumi.get(self, \"id\") @property @pulumi.getter def name(self) -> str:", "__args__['cryptoKey'] = crypto_key __args__['version'] = version if opts is None:", "yield self return GetKMSCryptoKeyVersionResult( algorithm=self.algorithm, crypto_key=self.crypto_key, id=self.id, name=self.name, protection_level=self.protection_level, public_keys=self.public_keys,", "if version and not isinstance(version, int): raise TypeError(\"Expected argument 'version'", "__args__ = dict() __args__['cryptoKey'] = crypto_key __args__['version'] = version if", "KMS CryptoKeyVersion. For more information see [the official documentation](https://cloud.google.com/kms/docs/object-hierarchy#key_version) and", "protection_level and not isinstance(protection_level, str): raise TypeError(\"Expected argument 'protection_level' to", "associated to this CryptoKeyVersion. Structure is documented below. \"\"\" return", "Union, overload from .. import _utilities from . import outputs", "CryptoKey to which the key version belongs. This is also", "= None) -> pulumi.Output[GetKMSCryptoKeyVersionResult]: \"\"\" Provides access to a Google", "`kms.CryptoKey` resource/datasource. :param int version: The version number for this", "if state and not isinstance(state, str): raise TypeError(\"Expected argument 'state'", "from typing import Any, Mapping, Optional, Sequence, Union, overload from", "def get_kms_crypto_key_version(crypto_key: Optional[str] = None, version: Optional[int] = None, opts:", "@property @pulumi.getter def name(self) -> str: \"\"\" The resource name", "'crypto_key' to be a str\") pulumi.set(__self__, \"crypto_key\", crypto_key) if id", "pulumi.get(self, \"state\") @property @pulumi.getter def version(self) -> Optional[int]: return pulumi.get(self,", "\"algorithm\", algorithm) if crypto_key and not isinstance(crypto_key, str): raise TypeError(\"Expected", "id=self.id, name=self.name, protection_level=self.protection_level, public_keys=self.public_keys, state=self.state, version=self.version) def get_kms_crypto_key_version(crypto_key: Optional[str] =", "to a Google Cloud Platform KMS CryptoKeyVersion. For more information", "name=__ret__.name, protection_level=__ret__.protection_level, public_keys=__ret__.public_keys, state=__ret__.state, version=__ret__.version) @_utilities.lift_output_func(get_kms_crypto_key_version) def get_kms_crypto_key_version_output(crypto_key: Optional[pulumi.Input[str]] =", "know what you are doing! *** import warnings import pulumi", "argument 'state' to be a str\") pulumi.set(__self__, \"state\", state) if", "-> str: \"\"\" The current state of the CryptoKeyVersion. See", "= None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetKMSCryptoKeyVersionResult: \"\"\" Provides", "Any, Mapping, Optional, Sequence, Union, overload from .. import _utilities", "TypeError(\"Expected argument 'version' to be a int\") pulumi.set(__self__, \"version\", version)", "certain you know what you are doing! *** import warnings", "-> Sequence['outputs.GetKMSCryptoKeyVersionPublicKeyResult']: \"\"\" If the enclosing CryptoKey has purpose `ASYMMETRIC_SIGN`", "get_kms_crypto_key_version_output(crypto_key: Optional[pulumi.Input[str]] = None, version: Optional[pulumi.Input[Optional[int]]] = None, opts: Optional[pulumi.InvokeOptions]", "\"\"\" The ProtectionLevel describing how crypto operations are performed with", "Terraform Bridge (tfgen) Tool. *** # *** Do not edit", "@pulumi.getter(name=\"protectionLevel\") def protection_level(self) -> str: \"\"\" The ProtectionLevel describing how", "@pulumi.getter(name=\"cryptoKey\") def crypto_key(self) -> str: return pulumi.get(self, \"crypto_key\") @property @pulumi.getter", "\"\"\" A collection of values returned by getKMSCryptoKeyVersion. \"\"\" def", "a Google Cloud Platform KMS CryptoKeyVersion. For more information see", "str): raise TypeError(\"Expected argument 'protection_level' to be a str\") pulumi.set(__self__,", "you're certain you know what you are doing! *** import", "None) -> AwaitableGetKMSCryptoKeyVersionResult: \"\"\" Provides access to a Google Cloud", "coding=utf-8 # *** WARNING: this file was generated by the", "(tfgen) Tool. *** # *** Do not edit by hand", "pulumi import pulumi_gcp as gcp my_key_ring = gcp.kms.get_kms_key_ring(name=\"my-key-ring\", location=\"us-central1\") my_crypto_key", "not isinstance(protection_level, str): raise TypeError(\"Expected argument 'protection_level' to be a", "for this CryptoKeyVersion in the format `projects/*/locations/*/keyRings/*/cryptoKeys/*/cryptoKeyVersions/*` \"\"\" return pulumi.get(self,", "\"\"\" return pulumi.get(self, \"protection_level\") @property @pulumi.getter(name=\"publicKeys\") def public_keys(self) -> Sequence['outputs.GetKMSCryptoKeyVersionPublicKeyResult']:", "@pulumi.getter def name(self) -> str: \"\"\" The resource name for", "The ProtectionLevel describing how crypto operations are performed with this", "= crypto_key __args__['version'] = version if opts is None: opts", "@property @pulumi.getter(name=\"cryptoKey\") def crypto_key(self) -> str: return pulumi.get(self, \"crypto_key\") @property", "The current state of the CryptoKeyVersion. See the [state reference](https://cloud.google.com/kms/docs/reference/rest/v1/projects.locations.keyRings.cryptoKeys.cryptoKeyVersions#CryptoKeyVersion.CryptoKeyVersionState)", "opts.version = _utilities.get_version() __ret__ = pulumi.runtime.invoke('gcp:kms/getKMSCryptoKeyVersion:getKMSCryptoKeyVersion', __args__, opts=opts, typ=GetKMSCryptoKeyVersionResult).value return", "'protection_level' to be a str\") pulumi.set(__self__, \"protection_level\", protection_level) if public_keys", "if algorithm and not isinstance(algorithm, str): raise TypeError(\"Expected argument 'algorithm'", "outputs. \"\"\" return pulumi.get(self, \"protection_level\") @property @pulumi.getter(name=\"publicKeys\") def public_keys(self) ->", "and not isinstance(state, str): raise TypeError(\"Expected argument 'state' to be", "None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetKMSCryptoKeyVersionResult: \"\"\" Provides access", "id=__ret__.id, name=__ret__.name, protection_level=__ret__.protection_level, public_keys=__ret__.public_keys, state=__ret__.state, version=__ret__.version) @_utilities.lift_output_func(get_kms_crypto_key_version) def get_kms_crypto_key_version_output(crypto_key: Optional[pulumi.Input[str]]", "not edit by hand unless you're certain you know what", "] @pulumi.output_type class GetKMSCryptoKeyVersionResult: \"\"\" A collection of values returned", "possible outputs. \"\"\" return pulumi.get(self, \"state\") @property @pulumi.getter def version(self)", "and [API](https://cloud.google.com/kms/docs/reference/rest/v1/projects.locations.keyRings.cryptoKeys.cryptoKeyVersions). A CryptoKeyVersion represents an individual cryptographic key, and", "to be a str\") pulumi.set(__self__, \"id\", id) if name and", "@property @pulumi.getter def id(self) -> str: \"\"\" The provider-assigned unique", "'get_kms_crypto_key_version', 'get_kms_crypto_key_version_output', ] @pulumi.output_type class GetKMSCryptoKeyVersionResult: \"\"\" A collection of", "Google Cloud Platform CryptoKey to which the key version belongs.", "TypeError(\"Expected argument 'crypto_key' to be a str\") pulumi.set(__self__, \"crypto_key\", crypto_key)", "name for this CryptoKeyVersion in the format `projects/*/locations/*/keyRings/*/cryptoKeys/*/cryptoKeyVersions/*` \"\"\" return", "and not isinstance(id, str): raise TypeError(\"Expected argument 'id' to be", "id) if name and not isinstance(name, str): raise TypeError(\"Expected argument", "Cloud Platform KMS CryptoKeyVersion. For more information see [the official", "= version if opts is None: opts = pulumi.InvokeOptions() if", "int version: The version number for this CryptoKeyVersion. Defaults to", "# *** WARNING: this file was generated by the Pulumi", "CryptoKeyVersionAlgorithm that this CryptoKeyVersion supports. \"\"\" return pulumi.get(self, \"algorithm\") @property", "-> pulumi.Output[GetKMSCryptoKeyVersionResult]: \"\"\" Provides access to a Google Cloud Platform", "CryptoKeyVersion. See the [protection_level reference](https://cloud.google.com/kms/docs/reference/rest/v1/ProtectionLevel) for possible outputs. \"\"\" return", "has purpose `ASYMMETRIC_SIGN` or `ASYMMETRIC_DECRYPT`, this block contains details about", "Cloud Platform CryptoKey to which the key version belongs. This", "str\") pulumi.set(__self__, \"protection_level\", protection_level) if public_keys and not isinstance(public_keys, list):", "_utilities from . import outputs __all__ = [ 'GetKMSCryptoKeyVersionResult', 'AwaitableGetKMSCryptoKeyVersionResult',", "\"\"\" return pulumi.get(self, \"public_keys\") @property @pulumi.getter def state(self) -> str:", "def state(self) -> str: \"\"\" The current state of the", "algorithm) if crypto_key and not isinstance(crypto_key, str): raise TypeError(\"Expected argument", "crypto_key(self) -> str: return pulumi.get(self, \"crypto_key\") @property @pulumi.getter def id(self)", "this managed resource. \"\"\" return pulumi.get(self, \"id\") @property @pulumi.getter def", "= _utilities.get_version() __ret__ = pulumi.runtime.invoke('gcp:kms/getKMSCryptoKeyVersion:getKMSCryptoKeyVersion', __args__, opts=opts, typ=GetKMSCryptoKeyVersionResult).value return AwaitableGetKMSCryptoKeyVersionResult(", "gcp.kms.get_kms_crypto_key_version(crypto_key=data[\"google_kms_key\"][\"my_key\"][\"id\"]) ``` :param str crypto_key: The `self_link` of the Google", "a str\") pulumi.set(__self__, \"id\", id) if name and not isinstance(name,", "by hand unless you're certain you know what you are", "crypto_key=None, id=None, name=None, protection_level=None, public_keys=None, state=None, version=None): if algorithm and", "\"protection_level\") @property @pulumi.getter(name=\"publicKeys\") def public_keys(self) -> Sequence['outputs.GetKMSCryptoKeyVersionPublicKeyResult']: \"\"\" If the", "pulumi.get(self, \"algorithm\") @property @pulumi.getter(name=\"cryptoKey\") def crypto_key(self) -> str: return pulumi.get(self,", "the [protection_level reference](https://cloud.google.com/kms/docs/reference/rest/v1/ProtectionLevel) for possible outputs. \"\"\" return pulumi.get(self, \"protection_level\")", "def crypto_key(self) -> str: return pulumi.get(self, \"crypto_key\") @property @pulumi.getter def", "```python import pulumi import pulumi_gcp as gcp my_key_ring = gcp.kms.get_kms_key_ring(name=\"my-key-ring\",", "@_utilities.lift_output_func(get_kms_crypto_key_version) def get_kms_crypto_key_version_output(crypto_key: Optional[pulumi.Input[str]] = None, version: Optional[pulumi.Input[Optional[int]]] = None,", "individual cryptographic key, and the associated key material. ## Example", "= gcp.kms.get_kms_key_ring(name=\"my-key-ring\", location=\"us-central1\") my_crypto_key = gcp.kms.get_kms_crypto_key(name=\"my-crypto-key\", key_ring=my_key_ring.id) my_crypto_key_version = gcp.kms.get_kms_crypto_key_version(crypto_key=data[\"google_kms_key\"][\"my_key\"][\"id\"])", "block contains details about the public key associated to this", "CryptoKey has purpose `ASYMMETRIC_SIGN` or `ASYMMETRIC_DECRYPT`, this block contains details", "version and not isinstance(version, int): raise TypeError(\"Expected argument 'version' to", "public_keys=self.public_keys, state=self.state, version=self.version) def get_kms_crypto_key_version(crypto_key: Optional[str] = None, version: Optional[int]", "the format `projects/*/locations/*/keyRings/*/cryptoKeys/*/cryptoKeyVersions/*` \"\"\" return pulumi.get(self, \"name\") @property @pulumi.getter(name=\"protectionLevel\") def", "Google Cloud Platform KMS CryptoKeyVersion. For more information see [the", "[API](https://cloud.google.com/kms/docs/reference/rest/v1/projects.locations.keyRings.cryptoKeys.cryptoKeyVersions). A CryptoKeyVersion represents an individual cryptographic key, and the", "Platform KMS CryptoKeyVersion. For more information see [the official documentation](https://cloud.google.com/kms/docs/object-hierarchy#key_version)", "you are doing! *** import warnings import pulumi import pulumi.runtime", "\"id\", id) if name and not isinstance(name, str): raise TypeError(\"Expected", "Optional[str] = None, version: Optional[int] = None, opts: Optional[pulumi.InvokeOptions] =", "-> Optional[int]: return pulumi.get(self, \"version\") class AwaitableGetKMSCryptoKeyVersionResult(GetKMSCryptoKeyVersionResult): # pylint: disable=using-constant-test", "None, opts: Optional[pulumi.InvokeOptions] = None) -> pulumi.Output[GetKMSCryptoKeyVersionResult]: \"\"\" Provides access", "Example Usage ```python import pulumi import pulumi_gcp as gcp my_key_ring", "\"version\", version) @property @pulumi.getter def algorithm(self) -> str: \"\"\" The", "TypeError(\"Expected argument 'id' to be a str\") pulumi.set(__self__, \"id\", id)", "gcp my_key_ring = gcp.kms.get_kms_key_ring(name=\"my-key-ring\", location=\"us-central1\") my_crypto_key = gcp.kms.get_kms_crypto_key(name=\"my-crypto-key\", key_ring=my_key_ring.id) my_crypto_key_version", "Bridge (tfgen) Tool. *** # *** Do not edit by", "reference](https://cloud.google.com/kms/docs/reference/rest/v1/projects.locations.keyRings.cryptoKeys.cryptoKeyVersions#CryptoKeyVersion.CryptoKeyVersionState) for possible outputs. \"\"\" return pulumi.get(self, \"state\") @property @pulumi.getter", "@property @pulumi.getter def state(self) -> str: \"\"\" The current state", "and not isinstance(version, int): raise TypeError(\"Expected argument 'version' to be", "WARNING: this file was generated by the Pulumi Terraform Bridge", "represents an individual cryptographic key, and the associated key material.", "return pulumi.get(self, \"id\") @property @pulumi.getter def name(self) -> str: \"\"\"", "for possible outputs. \"\"\" return pulumi.get(self, \"protection_level\") @property @pulumi.getter(name=\"publicKeys\") def", "str\") pulumi.set(__self__, \"name\", name) if protection_level and not isinstance(protection_level, str):", "ProtectionLevel describing how crypto operations are performed with this CryptoKeyVersion.", "*** WARNING: this file was generated by the Pulumi Terraform", "associated key material. ## Example Usage ```python import pulumi import", "purpose `ASYMMETRIC_SIGN` or `ASYMMETRIC_DECRYPT`, this block contains details about the", "crypto_key: The `self_link` of the Google Cloud Platform CryptoKey to", "= None, version: Optional[int] = None, opts: Optional[pulumi.InvokeOptions] = None)", ":param int version: The version number for this CryptoKeyVersion. Defaults", "the enclosing CryptoKey has purpose `ASYMMETRIC_SIGN` or `ASYMMETRIC_DECRYPT`, this block", "belongs. This is also the `id` field of the `kms.CryptoKey`", "crypto operations are performed with this CryptoKeyVersion. See the [protection_level", "the `kms.CryptoKey` resource/datasource. :param int version: The version number for", "'GetKMSCryptoKeyVersionResult', 'AwaitableGetKMSCryptoKeyVersionResult', 'get_kms_crypto_key_version', 'get_kms_crypto_key_version_output', ] @pulumi.output_type class GetKMSCryptoKeyVersionResult: \"\"\" A", "def name(self) -> str: \"\"\" The resource name for this", "@pulumi.getter def id(self) -> str: \"\"\" The provider-assigned unique ID", "str): raise TypeError(\"Expected argument 'id' to be a str\") pulumi.set(__self__,", "class GetKMSCryptoKeyVersionResult: \"\"\" A collection of values returned by getKMSCryptoKeyVersion.", "be a list\") pulumi.set(__self__, \"public_keys\", public_keys) if state and not", "def id(self) -> str: \"\"\" The provider-assigned unique ID for", "official documentation](https://cloud.google.com/kms/docs/object-hierarchy#key_version) and [API](https://cloud.google.com/kms/docs/reference/rest/v1/projects.locations.keyRings.cryptoKeys.cryptoKeyVersions). A CryptoKeyVersion represents an individual cryptographic", "protection_level=self.protection_level, public_keys=self.public_keys, state=self.state, version=self.version) def get_kms_crypto_key_version(crypto_key: Optional[str] = None, version:", "Mapping, Optional, Sequence, Union, overload from .. import _utilities from", "are performed with this CryptoKeyVersion. See the [protection_level reference](https://cloud.google.com/kms/docs/reference/rest/v1/ProtectionLevel) for", "see [the official documentation](https://cloud.google.com/kms/docs/object-hierarchy#key_version) and [API](https://cloud.google.com/kms/docs/reference/rest/v1/projects.locations.keyRings.cryptoKeys.cryptoKeyVersions). A CryptoKeyVersion represents an", "import pulumi import pulumi.runtime from typing import Any, Mapping, Optional,", "Sequence, Union, overload from .. import _utilities from . import", "@pulumi.getter(name=\"publicKeys\") def public_keys(self) -> Sequence['outputs.GetKMSCryptoKeyVersionPublicKeyResult']: \"\"\" If the enclosing CryptoKey", "Defaults to `1`. \"\"\" __args__ = dict() __args__['cryptoKey'] = crypto_key", "isinstance(version, int): raise TypeError(\"Expected argument 'version' to be a int\")", "TypeError(\"Expected argument 'public_keys' to be a list\") pulumi.set(__self__, \"public_keys\", public_keys)", "returned by getKMSCryptoKeyVersion. \"\"\" def __init__(__self__, algorithm=None, crypto_key=None, id=None, name=None,", "False: yield self return GetKMSCryptoKeyVersionResult( algorithm=self.algorithm, crypto_key=self.crypto_key, id=self.id, name=self.name, protection_level=self.protection_level,", "@property @pulumi.getter def algorithm(self) -> str: \"\"\" The CryptoKeyVersionAlgorithm that", "if crypto_key and not isinstance(crypto_key, str): raise TypeError(\"Expected argument 'crypto_key'", "import pulumi import pulumi_gcp as gcp my_key_ring = gcp.kms.get_kms_key_ring(name=\"my-key-ring\", location=\"us-central1\")", "protection_level=None, public_keys=None, state=None, version=None): if algorithm and not isinstance(algorithm, str):", "-> str: return pulumi.get(self, \"crypto_key\") @property @pulumi.getter def id(self) ->", "GetKMSCryptoKeyVersionResult: \"\"\" A collection of values returned by getKMSCryptoKeyVersion. \"\"\"", "the [state reference](https://cloud.google.com/kms/docs/reference/rest/v1/projects.locations.keyRings.cryptoKeys.cryptoKeyVersions#CryptoKeyVersion.CryptoKeyVersionState) for possible outputs. \"\"\" return pulumi.get(self, \"state\")", "[ 'GetKMSCryptoKeyVersionResult', 'AwaitableGetKMSCryptoKeyVersionResult', 'get_kms_crypto_key_version', 'get_kms_crypto_key_version_output', ] @pulumi.output_type class GetKMSCryptoKeyVersionResult: \"\"\"", "public_keys and not isinstance(public_keys, list): raise TypeError(\"Expected argument 'public_keys' to", "str\") pulumi.set(__self__, \"crypto_key\", crypto_key) if id and not isinstance(id, str):", "-> str: \"\"\" The provider-assigned unique ID for this managed", "protection_level) if public_keys and not isinstance(public_keys, list): raise TypeError(\"Expected argument", "version number for this CryptoKeyVersion. Defaults to `1`. \"\"\" ...", "= pulumi.runtime.invoke('gcp:kms/getKMSCryptoKeyVersion:getKMSCryptoKeyVersion', __args__, opts=opts, typ=GetKMSCryptoKeyVersionResult).value return AwaitableGetKMSCryptoKeyVersionResult( algorithm=__ret__.algorithm, crypto_key=__ret__.crypto_key, id=__ret__.id,", "be a int\") pulumi.set(__self__, \"version\", version) @property @pulumi.getter def algorithm(self)", "-> str: \"\"\" The CryptoKeyVersionAlgorithm that this CryptoKeyVersion supports. \"\"\"", "managed resource. \"\"\" return pulumi.get(self, \"id\") @property @pulumi.getter def name(self)", "crypto_key=__ret__.crypto_key, id=__ret__.id, name=__ret__.name, protection_level=__ret__.protection_level, public_keys=__ret__.public_keys, state=__ret__.state, version=__ret__.version) @_utilities.lift_output_func(get_kms_crypto_key_version) def get_kms_crypto_key_version_output(crypto_key:", "be a str\") pulumi.set(__self__, \"name\", name) if protection_level and not", "list): raise TypeError(\"Expected argument 'public_keys' to be a list\") pulumi.set(__self__,", "pulumi_gcp as gcp my_key_ring = gcp.kms.get_kms_key_ring(name=\"my-key-ring\", location=\"us-central1\") my_crypto_key = gcp.kms.get_kms_crypto_key(name=\"my-crypto-key\",", "protection_level(self) -> str: \"\"\" The ProtectionLevel describing how crypto operations", "import Any, Mapping, Optional, Sequence, Union, overload from .. import", "and not isinstance(protection_level, str): raise TypeError(\"Expected argument 'protection_level' to be", "return pulumi.get(self, \"name\") @property @pulumi.getter(name=\"protectionLevel\") def protection_level(self) -> str: \"\"\"", "\"\"\" __args__ = dict() __args__['cryptoKey'] = crypto_key __args__['version'] = version", "state of the CryptoKeyVersion. See the [state reference](https://cloud.google.com/kms/docs/reference/rest/v1/projects.locations.keyRings.cryptoKeys.cryptoKeyVersions#CryptoKeyVersion.CryptoKeyVersionState) for possible", "to be a int\") pulumi.set(__self__, \"version\", version) @property @pulumi.getter def", "outputs __all__ = [ 'GetKMSCryptoKeyVersionResult', 'AwaitableGetKMSCryptoKeyVersionResult', 'get_kms_crypto_key_version', 'get_kms_crypto_key_version_output', ] @pulumi.output_type", "if opts.version is None: opts.version = _utilities.get_version() __ret__ = pulumi.runtime.invoke('gcp:kms/getKMSCryptoKeyVersion:getKMSCryptoKeyVersion',", "the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do", "by getKMSCryptoKeyVersion. \"\"\" def __init__(__self__, algorithm=None, crypto_key=None, id=None, name=None, protection_level=None,", "name) if protection_level and not isinstance(protection_level, str): raise TypeError(\"Expected argument", "to which the key version belongs. This is also the", "crypto_key=self.crypto_key, id=self.id, name=self.name, protection_level=self.protection_level, public_keys=self.public_keys, state=self.state, version=self.version) def get_kms_crypto_key_version(crypto_key: Optional[str]", "str\") pulumi.set(__self__, \"algorithm\", algorithm) if crypto_key and not isinstance(crypto_key, str):", "supports. \"\"\" return pulumi.get(self, \"algorithm\") @property @pulumi.getter(name=\"cryptoKey\") def crypto_key(self) ->", "int): raise TypeError(\"Expected argument 'version' to be a int\") pulumi.set(__self__,", "argument 'name' to be a str\") pulumi.set(__self__, \"name\", name) if", "str crypto_key: The `self_link` of the Google Cloud Platform CryptoKey", "[state reference](https://cloud.google.com/kms/docs/reference/rest/v1/projects.locations.keyRings.cryptoKeys.cryptoKeyVersions#CryptoKeyVersion.CryptoKeyVersionState) for possible outputs. \"\"\" return pulumi.get(self, \"state\") @property", "A collection of values returned by getKMSCryptoKeyVersion. \"\"\" def __init__(__self__,", "are doing! *** import warnings import pulumi import pulumi.runtime from", "isinstance(public_keys, list): raise TypeError(\"Expected argument 'public_keys' to be a list\")", "-> str: \"\"\" The resource name for this CryptoKeyVersion in", "Sequence['outputs.GetKMSCryptoKeyVersionPublicKeyResult']: \"\"\" If the enclosing CryptoKey has purpose `ASYMMETRIC_SIGN` or", "describing how crypto operations are performed with this CryptoKeyVersion. See", "a str\") pulumi.set(__self__, \"protection_level\", protection_level) if public_keys and not isinstance(public_keys,", "__await__(self): if False: yield self return GetKMSCryptoKeyVersionResult( algorithm=self.algorithm, crypto_key=self.crypto_key, id=self.id,", "pulumi.InvokeOptions() if opts.version is None: opts.version = _utilities.get_version() __ret__ =", "isinstance(name, str): raise TypeError(\"Expected argument 'name' to be a str\")", "for this CryptoKeyVersion. Defaults to `1`. \"\"\" __args__ = dict()", "__args__['version'] = version if opts is None: opts = pulumi.InvokeOptions()", "'algorithm' to be a str\") pulumi.set(__self__, \"algorithm\", algorithm) if crypto_key", "disable=using-constant-test def __await__(self): if False: yield self return GetKMSCryptoKeyVersionResult( algorithm=self.algorithm,", "[the official documentation](https://cloud.google.com/kms/docs/object-hierarchy#key_version) and [API](https://cloud.google.com/kms/docs/reference/rest/v1/projects.locations.keyRings.cryptoKeys.cryptoKeyVersions). A CryptoKeyVersion represents an individual", "edit by hand unless you're certain you know what you", "collection of values returned by getKMSCryptoKeyVersion. \"\"\" def __init__(__self__, algorithm=None,", "this CryptoKeyVersion supports. \"\"\" return pulumi.get(self, \"algorithm\") @property @pulumi.getter(name=\"cryptoKey\") def", "be a str\") pulumi.set(__self__, \"state\", state) if version and not", "resource name for this CryptoKeyVersion in the format `projects/*/locations/*/keyRings/*/cryptoKeys/*/cryptoKeyVersions/*` \"\"\"", "= None, opts: Optional[pulumi.InvokeOptions] = None) -> pulumi.Output[GetKMSCryptoKeyVersionResult]: \"\"\" Provides", "if public_keys and not isinstance(public_keys, list): raise TypeError(\"Expected argument 'public_keys'", "pulumi.set(__self__, \"name\", name) if protection_level and not isinstance(protection_level, str): raise", "pulumi.get(self, \"version\") class AwaitableGetKMSCryptoKeyVersionResult(GetKMSCryptoKeyVersionResult): # pylint: disable=using-constant-test def __await__(self): if", "CryptoKeyVersion. Defaults to `1`. \"\"\" __args__ = dict() __args__['cryptoKey'] =", "Do not edit by hand unless you're certain you know", "None) -> pulumi.Output[GetKMSCryptoKeyVersionResult]: \"\"\" Provides access to a Google Cloud", "a str\") pulumi.set(__self__, \"name\", name) if protection_level and not isinstance(protection_level,", "version) @property @pulumi.getter def algorithm(self) -> str: \"\"\" The CryptoKeyVersionAlgorithm", "unique ID for this managed resource. \"\"\" return pulumi.get(self, \"id\")", "return GetKMSCryptoKeyVersionResult( algorithm=self.algorithm, crypto_key=self.crypto_key, id=self.id, name=self.name, protection_level=self.protection_level, public_keys=self.public_keys, state=self.state, version=self.version)", "def __init__(__self__, algorithm=None, crypto_key=None, id=None, name=None, protection_level=None, public_keys=None, state=None, version=None):", "return pulumi.get(self, \"algorithm\") @property @pulumi.getter(name=\"cryptoKey\") def crypto_key(self) -> str: return", "opts: Optional[pulumi.InvokeOptions] = None) -> pulumi.Output[GetKMSCryptoKeyVersionResult]: \"\"\" Provides access to", "raise TypeError(\"Expected argument 'state' to be a str\") pulumi.set(__self__, \"state\",", "a str\") pulumi.set(__self__, \"algorithm\", algorithm) if crypto_key and not isinstance(crypto_key,", "Optional[pulumi.InvokeOptions] = None) -> pulumi.Output[GetKMSCryptoKeyVersionResult]: \"\"\" Provides access to a", "version if opts is None: opts = pulumi.InvokeOptions() if opts.version", "``` :param str crypto_key: The `self_link` of the Google Cloud", "from .. import _utilities from . import outputs __all__ =", "# *** Do not edit by hand unless you're certain", "if protection_level and not isinstance(protection_level, str): raise TypeError(\"Expected argument 'protection_level'", "@pulumi.output_type class GetKMSCryptoKeyVersionResult: \"\"\" A collection of values returned by", "in the format `projects/*/locations/*/keyRings/*/cryptoKeys/*/cryptoKeyVersions/*` \"\"\" return pulumi.get(self, \"name\") @property @pulumi.getter(name=\"protectionLevel\")", "raise TypeError(\"Expected argument 'version' to be a int\") pulumi.set(__self__, \"version\",", "state=self.state, version=self.version) def get_kms_crypto_key_version(crypto_key: Optional[str] = None, version: Optional[int] =", "return pulumi.get(self, \"protection_level\") @property @pulumi.getter(name=\"publicKeys\") def public_keys(self) -> Sequence['outputs.GetKMSCryptoKeyVersionPublicKeyResult']: \"\"\"", "is None: opts.version = _utilities.get_version() __ret__ = pulumi.runtime.invoke('gcp:kms/getKMSCryptoKeyVersion:getKMSCryptoKeyVersion', __args__, opts=opts,", "contains details about the public key associated to this CryptoKeyVersion.", "'AwaitableGetKMSCryptoKeyVersionResult', 'get_kms_crypto_key_version', 'get_kms_crypto_key_version_output', ] @pulumi.output_type class GetKMSCryptoKeyVersionResult: \"\"\" A collection", "public_keys) if state and not isinstance(state, str): raise TypeError(\"Expected argument", "AwaitableGetKMSCryptoKeyVersionResult(GetKMSCryptoKeyVersionResult): # pylint: disable=using-constant-test def __await__(self): if False: yield self", "resource/datasource. :param int version: The version number for this CryptoKeyVersion.", "is None: opts = pulumi.InvokeOptions() if opts.version is None: opts.version", "resource. \"\"\" return pulumi.get(self, \"id\") @property @pulumi.getter def name(self) ->", "opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetKMSCryptoKeyVersionResult: \"\"\" Provides access to", "about the public key associated to this CryptoKeyVersion. Structure is", "gcp.kms.get_kms_crypto_key(name=\"my-crypto-key\", key_ring=my_key_ring.id) my_crypto_key_version = gcp.kms.get_kms_crypto_key_version(crypto_key=data[\"google_kms_key\"][\"my_key\"][\"id\"]) ``` :param str crypto_key: The", "pulumi.runtime.invoke('gcp:kms/getKMSCryptoKeyVersion:getKMSCryptoKeyVersion', __args__, opts=opts, typ=GetKMSCryptoKeyVersionResult).value return AwaitableGetKMSCryptoKeyVersionResult( algorithm=__ret__.algorithm, crypto_key=__ret__.crypto_key, id=__ret__.id, name=__ret__.name,", "The version number for this CryptoKeyVersion. Defaults to `1`. \"\"\"", "pulumi.get(self, \"protection_level\") @property @pulumi.getter(name=\"publicKeys\") def public_keys(self) -> Sequence['outputs.GetKMSCryptoKeyVersionPublicKeyResult']: \"\"\" If", "below. \"\"\" return pulumi.get(self, \"public_keys\") @property @pulumi.getter def state(self) ->", "def version(self) -> Optional[int]: return pulumi.get(self, \"version\") class AwaitableGetKMSCryptoKeyVersionResult(GetKMSCryptoKeyVersionResult): #", "raise TypeError(\"Expected argument 'id' to be a str\") pulumi.set(__self__, \"id\",", "version=__ret__.version) @_utilities.lift_output_func(get_kms_crypto_key_version) def get_kms_crypto_key_version_output(crypto_key: Optional[pulumi.Input[str]] = None, version: Optional[pulumi.Input[Optional[int]]] =", "Optional, Sequence, Union, overload from .. import _utilities from .", "field of the `kms.CryptoKey` resource/datasource. :param int version: The version", "dict() __args__['cryptoKey'] = crypto_key __args__['version'] = version if opts is", "file was generated by the Pulumi Terraform Bridge (tfgen) Tool.", "documentation](https://cloud.google.com/kms/docs/object-hierarchy#key_version) and [API](https://cloud.google.com/kms/docs/reference/rest/v1/projects.locations.keyRings.cryptoKeys.cryptoKeyVersions). A CryptoKeyVersion represents an individual cryptographic key,", "id and not isinstance(id, str): raise TypeError(\"Expected argument 'id' to", "`id` field of the `kms.CryptoKey` resource/datasource. :param int version: The", "outputs. \"\"\" return pulumi.get(self, \"state\") @property @pulumi.getter def version(self) ->", "`projects/*/locations/*/keyRings/*/cryptoKeys/*/cryptoKeyVersions/*` \"\"\" return pulumi.get(self, \"name\") @property @pulumi.getter(name=\"protectionLevel\") def protection_level(self) ->", "public_keys(self) -> Sequence['outputs.GetKMSCryptoKeyVersionPublicKeyResult']: \"\"\" If the enclosing CryptoKey has purpose", "GetKMSCryptoKeyVersionResult( algorithm=self.algorithm, crypto_key=self.crypto_key, id=self.id, name=self.name, protection_level=self.protection_level, public_keys=self.public_keys, state=self.state, version=self.version) def", "pulumi.set(__self__, \"public_keys\", public_keys) if state and not isinstance(state, str): raise", "name and not isinstance(name, str): raise TypeError(\"Expected argument 'name' to", "str: \"\"\" The resource name for this CryptoKeyVersion in the", ". import outputs __all__ = [ 'GetKMSCryptoKeyVersionResult', 'AwaitableGetKMSCryptoKeyVersionResult', 'get_kms_crypto_key_version', 'get_kms_crypto_key_version_output',", "key material. ## Example Usage ```python import pulumi import pulumi_gcp", "for possible outputs. \"\"\" return pulumi.get(self, \"state\") @property @pulumi.getter def", "values returned by getKMSCryptoKeyVersion. \"\"\" def __init__(__self__, algorithm=None, crypto_key=None, id=None,", "material. ## Example Usage ```python import pulumi import pulumi_gcp as", "\"crypto_key\", crypto_key) if id and not isinstance(id, str): raise TypeError(\"Expected", "be a str\") pulumi.set(__self__, \"id\", id) if name and not", "'id' to be a str\") pulumi.set(__self__, \"id\", id) if name", "return pulumi.get(self, \"public_keys\") @property @pulumi.getter def state(self) -> str: \"\"\"" ]
[ "= range(0, 10) # Main Execution def main(): count =", "0: count += 1 print(count) if __name__ == '__main__': main()", "if sum(subset) % 3 == 0: count += 1 print(count)", "sum(subset) % 3 == 0: count += 1 print(count) if", "def main(): count = 0 for length in range(0, len(NUMBERS)", "1): for subset in itertools.combinations(NUMBERS, length): if sum(subset) % 3", "length in range(0, len(NUMBERS) + 1): for subset in itertools.combinations(NUMBERS,", "Constants NUMBERS = range(0, 10) # Main Execution def main():", "len(NUMBERS) + 1): for subset in itertools.combinations(NUMBERS, length): if sum(subset)", "10) # Main Execution def main(): count = 0 for", "Main Execution def main(): count = 0 for length in", "range(0, len(NUMBERS) + 1): for subset in itertools.combinations(NUMBERS, length): if", "0 for length in range(0, len(NUMBERS) + 1): for subset", "count = 0 for length in range(0, len(NUMBERS) + 1):", "# Main Execution def main(): count = 0 for length", "in range(0, len(NUMBERS) + 1): for subset in itertools.combinations(NUMBERS, length):", "3 == 0: count += 1 print(count) if __name__ ==", "+ 1): for subset in itertools.combinations(NUMBERS, length): if sum(subset) %", "for subset in itertools.combinations(NUMBERS, length): if sum(subset) % 3 ==", "range(0, 10) # Main Execution def main(): count = 0", "main(): count = 0 for length in range(0, len(NUMBERS) +", "= 0 for length in range(0, len(NUMBERS) + 1): for", "python3 import itertools # Constants NUMBERS = range(0, 10) #", "for length in range(0, len(NUMBERS) + 1): for subset in", "#!/usr/bin/env python3 import itertools # Constants NUMBERS = range(0, 10)", "in itertools.combinations(NUMBERS, length): if sum(subset) % 3 == 0: count", "length): if sum(subset) % 3 == 0: count += 1", "% 3 == 0: count += 1 print(count) if __name__", "itertools # Constants NUMBERS = range(0, 10) # Main Execution", "# Constants NUMBERS = range(0, 10) # Main Execution def", "Execution def main(): count = 0 for length in range(0,", "NUMBERS = range(0, 10) # Main Execution def main(): count", "import itertools # Constants NUMBERS = range(0, 10) # Main", "subset in itertools.combinations(NUMBERS, length): if sum(subset) % 3 == 0:", "== 0: count += 1 print(count) if __name__ == '__main__':", "itertools.combinations(NUMBERS, length): if sum(subset) % 3 == 0: count +=" ]
[ "been terminated. This allows for the possibility of a new", "of the job. 0 implies successful. EXIT_STATUS_UNAVAILABLE_VALUE is used when", "\"\"\" Kills the given job IDs. After returning, the killed", "detail: str = '') -> None: \"\"\" Check resource request", "resources are actually being used by the Jobs. The workers", "an environment variable for the worker process before it is", "temporary directory by setting TMPDIR.') else: msg = (f'{R}equesting {requested}", "add code to that script to get parameters for your", "2.0 (the \"License\"); # you may not use this file", "_ArgumentGroup from contextlib import contextmanager from typing import (Any, Callable,", "report what resource is the limiting factor when scheduling jobs,", "the maximum of ' f'{available} {unit}{resource} that {batch_system} was configured", "map of jobs as jobIDs that are currently running (not", "the filtering after node termination is done. :param method: This", "should not be depended upon. \"\"\" raise NotImplementedError() @abstractmethod def", "this batch system invokes :meth:`BatchSystemSupport.workerCleanup` after the last job for", "('onSuccess', 'onError') and workflowDirContents in ([], [cacheDirName(info.workflowID)])): shutil.rmtree(workflowDir, ignore_errors=True) class", "disk space being requested, in bytes :param str job_name: Name", "None and the name cannot be found in the environment", "Each such job will be returned exactly once. Does not", "means that you would typically need to copy the variables", "node identifiers of preemptable or non-preemptable nodes to NodeInfo objects,", "of node to ignore. \"\"\" raise NotImplementedError() @abstractmethod def unignoreNode(self,", "= workers class AbstractScalableBatchSystem(AbstractBatchSystem): \"\"\" A batch system that supports", "ABC, abstractmethod from argparse import ArgumentParser, _ArgumentGroup from contextlib import", "= coresUsed self.memoryUsed = memoryUsed self.coresTotal = coresTotal self.memoryTotal =", "import ABC, abstractmethod from argparse import ArgumentParser, _ArgumentGroup from contextlib", "address, presumably after a node with this address has been", "list of IDs of jobs to kill \"\"\" raise NotImplementedError()", "to set up the environment of a job. A call", "returns True here, it should also override \"\"\" raise NotImplementedError()", "ready to terminate a node, but jobs are still running.", "the user script for this workflow. This method must be", "issued job \"\"\" raise NotImplementedError() @abstractmethod def killBatchJobs(self, jobIDs: List[int])", "to the same nodes 3) scaler terminates nodes, resulting in", "worker threads. \"\"\" raise NotImplementedError() def setEnv(self, name: str, value:", "value will be used as the value on the worker", "class NodeInfo: \"\"\" The coresUsed attribute is a floating point", "killed by killBatchJobs, although they may cause None to be", "killed before finishing. ERROR: int = 5 # Internal error.", "None: \"\"\" If this batch system provides any command line", "UpdatedBatchJobInfo.exitStatus when status is not available. EXIT_STATUS_UNAVAILABLE_VALUE = 255 class", "(where the cache would go)\"\"\" workflowID: str \"\"\"used to identify", "relevant to this batch system. :param setOption: A function with", "attribute is an integer reflecting the number of workers currently", "scale the number of worker nodes in the cluster up", "\"\"\" Returns a dictionary mapping node identifiers of preemptable or", "different interface (generator?) pass def getWorkerContexts(self) -> List[ContextManager[Any]]: \"\"\" Get", "jobs 2) scaler decides to terminate these nodes. In parallel", "worker node on batch system shutdown. Also see :meth:`supportsWorkerCleanup`. :param", "node termination to ensure that nodes being considered for termination", "being requested, in bytes :param str job_name: Name of the", "str] = {} self.workerCleanupInfo = WorkerCleanupInfo(workDir=self.config.workDir, workflowID=self.config.workflowID, cleanWorkDir=self.config.cleanWorkDir) def checkResourceRequest(self,", "the error. :raise InsufficientSystemResources: raised when a resource is requested", "on but this method makes it possible to override specific", "to ask the Toil worker to do things in-process (such", "the autoscaler as having no jobs 2) scaler decides to", "nodes have reported to the autoscaler as having no jobs", "went away). KILLED: int = 4 # Job killed before", "License for the specific language governing permissions and # limitations", ":rtype: string : Formatted filename; however if self.config.noStdOutErr is true,", "node's resources, not just the used resources The requestedCores and", "Batch-system-specific message to include in the error. :raise InsufficientSystemResources: raised", "def add_options(cls, parser: Union[ArgumentParser, _ArgumentGroup]) -> None: \"\"\" If this", "exitStatus in UpdatedBatchJobInfo.exitStatus when status is not available. EXIT_STATUS_UNAVAILABLE_VALUE =", "workflowDirContents = os.listdir(workflowDir) AbstractFileStore.shutdownFileStore(workflowDir, info.workflowID) if (info.cleanWorkDir == 'always' or", "value is provided it will be looked up from the", "base temporary directory by setting TMPDIR.') else: msg = (f'{R}equesting", "the resources that Toil Jobs have reserved on the node,", "system invokes :meth:`BatchSystemSupport.workerCleanup` after the last job for a particular", "use as exitStatus in UpdatedBatchJobInfo.exitStatus when status is not available.", "config: object is setup by the toilSetup script and has", "requested, in bytes :param float cores: number of cores being", "with, or enforced ' f'by --max{resource.capitalize()}. Try setting/changing the toil", "of cores the batch system can request for any one", "('disk', disk, self.maxDisk)]: assert requested is not None if requested", "terminates. \"\"\" raise NotImplementedError() def setUserScript(self, userScript: Resource) -> None:", "for jobs killed by killBatchJobs, although they may cause None", "def setOptions(cls, setOption: Callable[[str, Optional[Callable[[Any], OptionType]], Optional[Callable[[OptionType], None]], Optional[OptionType], Optional[List[str]]],", "all worker threads. \"\"\" raise NotImplementedError() def setEnv(self, name: str,", "Toil. \"\"\" @classmethod @abstractmethod def supportsAutoDeployment(cls) -> bool: \"\"\" Whether", "batch system is said to *shut down* after the last", "status (integer value) of the job. 0 implies successful. EXIT_STATUS_UNAVAILABLE_VALUE", "config self.maxCores = maxCores self.maxMemory = maxMemory self.maxDisk = maxDisk", "(f'{R}equesting {requested} {unit}{resource}, more than the maximum of ' f'{available}", "to be returned earlier than maxWait. :param maxWait: the number", "one job, in bytes :param int maxDisk: the maximum amount", "return os.devnull fileName: str = f'toil_{self.config.workflowID}.{toil_job_id}.{cluster_job_id}.{std}.log' workDir: str = Toil.getToilWorkDir(self.config.workDir)", "DeferredFunctionManager.cleanupWorker(workflowDir) workflowDirContents = os.listdir(workflowDir) AbstractFileStore.shutdownFileStore(workflowDir, info.workflowID) if (info.cleanWorkDir == 'always'", "self.maxDisk)]: assert requested is not None if requested > available:", "worker node, for the same workflow. The batch system is", "f'toil_{self.config.workflowID}.{toil_job_id}.{cluster_job_id}.{std}.log' workDir: str = Toil.getToilWorkDir(self.config.workDir) return os.path.join(workDir, fileName) @staticmethod def", "system job IDs, for ease of debugging job failures. :param:", "name will be set to this value. if None, the", "can be invoked to set the resource object representing the", "job_environment: Optional[Dict[str, str]] = None) -> int: \"\"\" Issues a", "class UpdatedBatchJobInfo(NamedTuple): jobID: int exitStatus: int \"\"\" The exit status", "tracking wall time. \"\"\" raise NotImplementedError() def getSchedulingStatusMessage(self) -> Optional[str]:", "jobs issued after this method returns. Note to implementors: This", "available or allowed. :param int memory: amount of memory being", "memory used) and 1 (all memory used), reflecting the memory", "limiting factor when scheduling jobs, for example. If the leader", "or cleaning up a node) that would otherwise require a", "result :return: If a result is available, returns UpdatedBatchJobInfo. Otherwise", "= '', detail: str = '') -> None: \"\"\" Check", "except KeyError: raise RuntimeError(f\"{name} does not exist in current environment\")", "that the term *worker* refers to an entire node, not", "representing the user script or module and the modules it", "has updated its status (i.e. ceased running, either successfully or", "internally to set up the environment of a job. A", "resource in ('disk', 'memory') else '' R = f'The job", "for worker cleanup on shutdown of the batch system. class", "Set the user script for this workflow. This method must", "int, job_name: str = '', detail: str = '') ->", "files generated by the batch system itself. Files will be", "number of worker nodes. Used by :class:`toil. provisioners.clusterScaler.ClusterScaler` to scale", "by the toilSetup script and has configuration parameters for the", "NotImplementedError() @abstractmethod def getUpdatedBatchJob(self, maxWait: int) -> Optional[UpdatedBatchJobInfo]: \"\"\" Returns", "upon. \"\"\" raise NotImplementedError() @abstractmethod def getRunningBatchJobIDs(self) -> Dict[int, float]:", "The worker process will typically inherit the environment of the", "implementors: This means that you would typically need to copy", "used to report what resource is the limiting factor when", "'', detail: str = '') -> None: \"\"\" Check resource", "or non-preemptable nodes to NodeInfo objects, one for each node.", "worker nodes private IP address :return: True if the worker", "job with the specified command to the batch system and", "the worker. :param str value: if given, the environment variable", "OF ANY KIND, either express or implied. # See the", "add them to the given parser. \"\"\" pass OptionType =", "(then also fix the tests) @abstractmethod def getIssuedBatchJobIDs(self) -> List[int]:", "See the License for the specific language governing permissions and", "import JobDescription from toil.resource import Resource logger = logging.getLogger(__name__) #", ":return: dictionary with currently running jobID keys and how many", "space being requested, in bytes :param str job_name: Name of", "NotImplementedError() @abstractmethod def nodeInUse(self, nodeIP: str) -> bool: \"\"\" Can", "batch system itself. Files will be written to the Toil", "to in writing, software # distributed under the License is", "the workflow is stuck, the message can be displayed to", "maximum of {available} {unit}{resource} of free space on ' f'{self.config.workDir}", "\"\"\" Partial implementation of AbstractBatchSystem, support methods. \"\"\" def __init__(self,", "be depended upon. \"\"\" raise NotImplementedError() @abstractmethod def getRunningBatchJobIDs(self) ->", "def nodeInUse(self, nodeIP: str) -> bool: \"\"\" Can be used", "# Preemptable failure (job's executing host went away). KILLED: int", "or agreed to in writing, software # distributed under the", "many seconds they have been running as the value \"\"\"", "space on ' f'{self.config.workDir} that {batch_system} was configured with, or", "this context manager exits the filter should be removed \"\"\"", "current jobs have finished. :param nodeAddress: IP address of node", "= f'The job {job_name} is r' if job_name else 'R'", "in autoscaling when the autoscaler is ready to terminate a", "# different interface (generator?) pass def getWorkerContexts(self) -> List[ContextManager[Any]]: \"\"\"", "the name cannot be found in the environment \"\"\" if", "seconds to block, waiting for a result :return: If a", "Optional[OptionType], Optional[List[str]]], None]) -> None: \"\"\" Process command line or", "autoscaling where 1) nodes have reported to the autoscaler as", "the University of California # # Licensed under the Apache", "they may cause None to be returned earlier than maxWait.", "method returns. Note to implementors: This means that you would", "worker process may exist on a worker node, for the", "compliance with the License. # You may obtain a copy", "is the number of seconds (a strictly positive float) in", "1) nodes have reported to the autoscaler as having no", "other files generated by the batch system itself. Files will", "and returns a unique jobID. :param jobDesc a toil.job.JobDescription :param", "issued any tasks, else False \"\"\" raise NotImplementedError() # TODO:", "Toil and batch system job IDs, for ease of debugging", "wallTime is the number of seconds (a strictly positive float)", "the worker process before it is launched. The worker process", "in ('disk', 'memory') else '' R = f'The job {job_name}", "strictly positive float) in wall-clock time the job ran for,", "([], [cacheDirName(info.workflowID)])): shutil.rmtree(workflowDir, ignore_errors=True) class NodeInfo: \"\"\" The coresUsed attribute", "the batch system can request for any one job, in", "msg = (f'{R}equesting {requested} {unit}{resource} for temporary space, ' f'more", "on batch system shutdown. Also see :meth:`supportsWorkerCleanup`. :param WorkerCleanupInfo info:", "written to the Toil work directory (which may be on", "The killed job will not be returned from getUpdatedBatchJob. :param", "jobIDs) currently issued (may be running, or may be waiting", "variable for the worker process before it is launched. The", "assigns jobs to the same nodes 3) scaler terminates nodes,", "not use this file except in compliance with the License.", "-> None: \"\"\" Stop ignoring this address, presumably after a", "Dict[int, float]: \"\"\" Gets a map of jobs as jobIDs", "than the maximum of ' f'{available} {unit}{resource} that {batch_system} was", "job_environment: a collection of job-specific environment variables to be set", "None]) -> None: \"\"\" Process command line or configuration options", "you may not use this file except in compliance with", "parser. \"\"\" pass OptionType = TypeVar('OptionType') @classmethod def setOptions(cls, setOption:", "to be set on the worker. :param str value: if", "node termination is done. :param method: This will be used", "example: 'err' for 'stderr' or 'out' for 'stdout') :rtype: string", "line or configuration options relevant to this batch system. :param", "a map of jobs as jobIDs that are currently running", "list, the ordering should not be depended upon. \"\"\" raise", "is stuck, the message can be displayed to the user", "provide to Toil. \"\"\" @classmethod @abstractmethod def supportsAutoDeployment(cls) -> bool:", ":param WorkerCleanupInfo info: A named tuple consisting of all the", "failure (job's executing host went away). KILLED: int = 4", "is running any tasks. If the node is doesn't exist,", "true, returns '/dev/null' or equivalent. \"\"\" if self.config.noStdOutErr: return os.devnull", "far as Python currently allows) base class to represent the", "NotImplementedError() def getSchedulingStatusMessage(self) -> Optional[str]: \"\"\" Get a log message", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "job. A call to this method affects all jobs issued", "None as the filter to disable the filtering after node", "nodeAddress: str) -> None: \"\"\" Stop sending jobs to this", "'bytes of ' if resource in ('disk', 'memory') else ''", "This means that you would typically need to copy the", "than allowed \"\"\" batch_system = self.__class__.__name__ or 'this batch system'", "before the first job is issued to this batch system,", "running (not just waiting) and how long they have been", "node on batch system shutdown. Also see :meth:`supportsWorkerCleanup`. :param WorkerCleanupInfo", "if (info.cleanWorkDir == 'always' or info.cleanWorkDir in ('onSuccess', 'onError') and", "-> None: \"\"\" Process command line or configuration options relevant", "raise NotImplementedError() @abstractmethod def ignoreNode(self, nodeAddress: str) -> None: \"\"\"", "would go)\"\"\" workflowID: str \"\"\"used to identify files specific to", "system. :param float maxCores: the maximum number of cores the", "all the relevant information for cleaning up the worker. \"\"\"", "After this context manager exits the filter should be removed", "from toil.common import Toil, cacheDirName, Config from toil.deferred import DeferredFunctionManager", "InsufficientSystemResources: raised when a resource is requested in an amount", "as its internal job id. :param: string std : The", "that has updated its status (i.e. ceased running, either successfully", "float]: \"\"\" Gets a map of jobs as jobIDs that", "positive float) in wall-clock time the job ran for, or", "to override specific variables in that inherited environment before the", "a log message fragment for the user about anything that", "for temporary space, ' f'more than the maximum of {available}", "raise NotImplementedError() def setEnv(self, name: str, value: Optional[str] = None)", "copy the variables before enqueuing a job. If no value", "a job. If no value is provided it will be", "of the user script itself. If it does, the :meth:`.setUserScript`", "names containing both the Toil and batch system job IDs,", "workDir: str \"\"\"workdir path (where the cache would go)\"\"\" workflowID:", "The workers attribute is an integer reflecting the number of", "report. :param str detail: Batch-system-specific message to include in the", "typically need to copy the variables before enqueuing a job.", "The unique id that Toil gives a job. :param: cluster_job_id", "support tracking wall time. \"\"\" raise NotImplementedError() def getSchedulingStatusMessage(self) ->", "os.environ[name] except KeyError: raise RuntimeError(f\"{name} does not exist in current", "may cause None to be returned earlier than maxWait. :param", "user scripts, or cleaning up a node) that would otherwise", "\"\"\" raise NotImplementedError() @classmethod @abstractmethod def supportsWorkerCleanup(cls) -> bool: \"\"\"", "str = '', detail: str = '') -> None: \"\"\"", "not exist in current environment\") self.environment[name] = value def formatStdOutErrPath(self,", "environment variables to be set on the worker. :return: a", "as exitStatus in UpdatedBatchJobInfo.exitStatus when status is not available. EXIT_STATUS_UNAVAILABLE_VALUE", "getIssuedBatchJobIDs(self) -> List[int]: \"\"\" Gets all currently issued jobs :return:", "self.workers = workers class AbstractScalableBatchSystem(AbstractBatchSystem): \"\"\" A batch system that", "str) -> bool: \"\"\" Can be used to determine if", "looked up from the current environment. \"\"\" raise NotImplementedError() @classmethod", "\"\"\" Format path for batch system standard output/error and other", "is not None if requested > available: unit = 'bytes", "str) -> None: \"\"\" Stop sending jobs to this node.", "resources, not just the used resources The requestedCores and requestedMemory", "after this method returns. Note to implementors: This means that", "\"\"\" Whether this batch system supports auto-deployment of the user", "in that inherited environment before the worker is launched. Note", "' f'\"--workDir\" or changing the base temporary directory by setting", "for ease of debugging job failures. :param: int toil_job_id :", "the CPU load of the node. The memoryUsed attribute is", ":class:`toil. provisioners.clusterScaler.ClusterScaler` to scale the number of worker nodes in", "-> Dict[int, float]: \"\"\" Gets a map of jobs as", "This can be used to report what resource is the", "be written to the Toil work directory (which may be", "that this mechanism is different to the one used by", "or 'out' for 'stdout') :rtype: string : Formatted filename; however", "-> None: \"\"\" Cleans up the worker node on batch", "itself. If it does, the :meth:`.setUserScript` can be invoked to", "Default implementation returns None. # Override to provide scheduling status", "to this node. Used in autoscaling when the autoscaler is", "is launched. The worker process will typically inherit the environment", "killed jobs will not appear in the results of getRunningBatchJobIDs.", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "\"\"\" The coresUsed attribute is a floating point value between", "they have been running, in seconds. :return: dictionary with currently", "to help them diagnose why it might be stuck. :return:", "shutil from abc import ABC, abstractmethod from argparse import ArgumentParser,", "\"\"\" raise NotImplementedError() @abstractmethod def getRunningBatchJobIDs(self) -> Dict[int, float]: \"\"\"", "script for this workflow. This method must be called before", "invocation finishes. Note that the term *worker* refers to an", "The requestedCores and requestedMemory attributes are all the resources that", "def getWorkerContexts(self) -> List[ContextManager[Any]]: \"\"\" Get a list of picklable", "returned exactly once. Does not return info for jobs killed", "to an entire node, not just a worker process. A", "from toil.fileStores.abstractFileStore import AbstractFileStore from toil.job import JobDescription from toil.resource", "Toil worker to do things in-process (such as configuring environment", "workflow invocation finishes. Note that the term *worker* refers to", "'memory') else '' R = f'The job {job_name} is r'", "however if self.config.noStdOutErr is true, returns '/dev/null' or equivalent. \"\"\"", "Optional[bool] = None) -> Dict[str, NodeInfo]: \"\"\" Returns a dictionary", "batch system imposed memory limit class UpdatedBatchJobInfo(NamedTuple): jobID: int exitStatus:", "system. class WorkerCleanupInfo(NamedTuple): workDir: str \"\"\"workdir path (where the cache", "sequentially, and more than one concurrent worker process may exist", "file except in compliance with the License. # You may", "diagnose why it might be stuck. :return: User-directed message about", "supportsWorkerCleanup(cls) -> bool: \"\"\" Indicates whether this batch system invokes", "more than one concurrent worker process may exist on a", "address has been terminated. This allows for the possibility of", "error. MEMLIMIT: int = 6 # Job hit batch system", "\"\"\" An abstract (as far as Python currently allows) base", "nodes to NodeInfo objects, one for each node. :param preemptable:", "might be going wrong in the batch system, if available.", "and other files generated by the batch system itself. Files", "raised when a resource is requested in an amount greater", "None: \"\"\" Kills the given job IDs. After returning, the", "it might be stuck. :return: User-directed message about scheduling state.", "0 (all cores idle) and 1 (all cores busy), reflecting", "jobID. :param jobDesc a toil.job.JobDescription :param job_environment: a collection of", "Partial implementation of AbstractBatchSystem, support methods. \"\"\" def __init__(self, config:", "node to ignore. \"\"\" raise NotImplementedError() @abstractmethod def unignoreNode(self, nodeAddress:", "configured with, or enforced ' f'by --max{resource.capitalize()}. Try setting/changing the", "why it might be stuck. :return: User-directed message about scheduling", "@staticmethod def workerCleanup(info: WorkerCleanupInfo) -> None: \"\"\" Cleans up the", "than one concurrent worker process may exist on a worker", "self.memoryTotal = memoryTotal self.requestedCores = requestedCores self.requestedMemory = requestedMemory self.workers", "invoked to set the resource object representing the user script.", "f'or enforced by --max{resource.capitalize()}.') if detail: msg += detail raise", "node, but jobs are still running. This allows the node", "message is available, return None. This can be used to", "maxWait. :param maxWait: the number of seconds to block, waiting", "\"\"\" Get a list of picklable context manager objects to", "stuck, the message can be displayed to the user to", "a list of picklable context manager objects to wrap worker", "job, in bytes :param int maxDisk: the maximum amount of", "Called at the completion of a toil invocation. Should cleanly", "the node. \"\"\" def __init__(self, coresUsed: float, memoryUsed: float, coresTotal:", "shutil.rmtree(workflowDir, ignore_errors=True) class NodeInfo: \"\"\" The coresUsed attribute is a", "language governing permissions and # limitations under the License. import", "(all cores idle) and 1 (all cores busy), reflecting the", "raise NotImplementedError() @abstractmethod def killBatchJobs(self, jobIDs: List[int]) -> None: \"\"\"", "all jobs on that node. Call this method prior to", "the user about anything that might be going wrong in", "all jobs issued after this method returns. Note to implementors:", "bytes :param str job_name: Name of the job being checked,", "to identify files specific to this workflow\"\"\" cleanWorkDir: str class", "if given, the environment variable given by name will be", "\"\"\" Gets a map of jobs as jobIDs that are", "update run configuration as a side effect. \"\"\" # TODO:", "the value \"\"\" raise NotImplementedError() @abstractmethod def getUpdatedBatchJob(self, maxWait: int)", "bool: \"\"\" Can be used to determine if a worker", "the given parser. \"\"\" pass OptionType = TypeVar('OptionType') @classmethod def", "job IDs. After returning, the killed jobs will not appear", "that {batch_system} was configured with, or enforced ' f'by --max{resource.capitalize()}.", "is provided it will be looked up from the current", "any tasks, else False \"\"\" raise NotImplementedError() # TODO: May", "autoscaler is ready to terminate a node, but jobs are", "KIND, either express or implied. # See the License for", "6 # Job hit batch system imposed memory limit class", "-> None: \"\"\" Set the user script for this workflow.", "batch system supports auto-deployment of the user script itself. If", "only if :meth:`.supportsAutoDeployment` returns True, otherwise it will raise an", "of disk space the batch system can request for any", "otherwise require a wrapping \"executor\" process. \"\"\" return [] class", "List[int]) -> None: \"\"\" Kills the given job IDs. After", "environment\") self.environment[name] = value def formatStdOutErrPath(self, toil_job_id: int, cluster_job_id: str,", ":meth:`.setUserScript` can be invoked to set the resource object representing", "abstractmethod from argparse import ArgumentParser, _ArgumentGroup from contextlib import contextmanager", "one job :param int maxMemory: the maximum amount of memory", "The batch system is said to *shut down* after the", "Resource) -> None: \"\"\" Set the user script for this", "cannot be found in the environment \"\"\" if value is", "the ordering should not be depended upon. \"\"\" raise NotImplementedError()", "for any one job, in bytes :param int maxDisk: the", "directory by setting TMPDIR.') else: msg = (f'{R}equesting {requested} {unit}{resource},", "= memoryTotal self.requestedCores = requestedCores self.requestedMemory = requestedMemory self.workers =", "preemptable or non-preemptable nodes to NodeInfo objects, one for each", "else: msg = (f'{R}equesting {requested} {unit}{resource}, more than the maximum", "self.maxMemory), ('disk', disk, self.maxDisk)]: assert requested is not None if", "Check resource request is not greater than that available or", "up the worker node on batch system shutdown. Also see", "(the \"License\"); # you may not use this file except", "anything that might be going wrong in the batch system,", ":param jobIDs: list of IDs of jobs to kill \"\"\"", "uses as its internal job id. :param: string std :", "done. :param method: This will be used as a filter", "unused! @abstractmethod @contextmanager def nodeFiltering(self, filter: Optional[Callable[[NodeInfo], bool]]) -> Iterator[None]:", "variables to be set on the worker. :return: a unique", "import (Any, Callable, ContextManager, Dict, Iterator, List, Optional, Tuple, Type,", "such job will be returned exactly once. Does not return", "\"\"\" pass OptionType = TypeVar('OptionType') @classmethod def setOptions(cls, setOption: Callable[[str,", "system. :param setOption: A function with signature setOption(option_name, parsing_function=None, check_function=None,", "TypeVar, Union, NamedTuple) from toil.common import Toil, cacheDirName, Config from", "\"\"\" If this batch system provides any command line options,", "Returns a dictionary mapping node identifiers of preemptable or non-preemptable", "the node to be terminated after the current jobs have", "The provenance of the stream (for example: 'err' for 'stderr'", "the possibility of a new node having the same address", "be used to determine if a worker node is running", "environment. \"\"\" raise NotImplementedError() @classmethod def add_options(cls, parser: Union[ArgumentParser, _ArgumentGroup])", "this workflow. This method must be called before the first", "# # Unless required by applicable law or agreed to", "raise NotImplementedError() # FIXME: Return value should be a set", "amount of disk space being requested, in bytes :param str", "= (f'{R}equesting {requested} {unit}{resource} for temporary space, ' f'more than", "from typing import (Any, Callable, ContextManager, Dict, Iterator, List, Optional,", "depends on. \"\"\" raise NotImplementedError() @abstractmethod def issueBatchJob(self, jobDesc: JobDescription,", "them diagnose why it might be stuck. :return: User-directed message", "to include in the error. :raise InsufficientSystemResources: raised when a", "either successfully or with an error). Each such job will", "if resource in ('disk', 'memory') else '' R = f'The", "cluster_job_id: str, std: str) -> str: \"\"\" Format path for", "job. :param: cluster_job_id : What the cluster, for example, GridEngine,", "-> List[ContextManager[Any]]: \"\"\" Get a list of picklable context manager", "objects to wrap worker work in, in order. Can be", "and memoryTotal attributes are the node's resources, not just the", "Files will be written to the Toil work directory (which", "newly issued job \"\"\" raise NotImplementedError() @abstractmethod def killBatchJobs(self, jobIDs:", "amount greater than allowed \"\"\" batch_system = self.__class__.__name__ or 'this", "value between 0 (no memory used) and 1 (all memory", "batch system can request for any one job :param int", "the job. 0 implies successful. EXIT_STATUS_UNAVAILABLE_VALUE is used when the", "be used to report what resource is the limiting factor", "FAILED: int = 2 # Job finished, but failed. LOST:", "implied. # See the License for the specific language governing", "nodes considered when assigning new jobs. After this context manager", "setUserScript(self, userScript: Resource) -> None: \"\"\" Set the user script", "reference the newly issued job \"\"\" raise NotImplementedError() @abstractmethod def", "setting/changing the toil option ' f'\"--workDir\" or changing the base", "cores: float, disk: int, job_name: str = '', detail: str", ":return: a unique jobID that can be used to reference", "nodes private IP address :return: True if the worker node", "IDs. After returning, the killed jobs will not appear in", "class WorkerCleanupInfo(NamedTuple): workDir: str \"\"\"workdir path (where the cache would", ":param int memory: amount of memory being requested, in bytes", "--max{resource.capitalize()}.') if detail: msg += detail raise InsufficientSystemResources(msg) def setEnv(self,", "possible to override specific variables in that inherited environment before", "and the name cannot be found in the environment \"\"\"", "used to ask the Toil worker to do things in-process", "getRunningBatchJobIDs(self) -> Dict[int, float]: \"\"\" Gets a map of jobs", "workers attribute is an integer reflecting the number of workers", "can add code to that script to get parameters for", "\"\"\" if self.config.noStdOutErr: return os.devnull fileName: str = f'toil_{self.config.workflowID}.{toil_job_id}.{cluster_job_id}.{std}.log' workDir:", "exit status is not available (e.g. job is lost). \"\"\"", "BatchSystemSupport(AbstractBatchSystem): \"\"\" Partial implementation of AbstractBatchSystem, support methods. \"\"\" def", "-> str: \"\"\" Format path for batch system standard output/error", "nodeIP: The worker nodes private IP address :return: True if", "Optional, Tuple, Type, TypeVar, Union, NamedTuple) from toil.common import Toil,", "running jobID keys and how many seconds they have been", "try: value = os.environ[name] except KeyError: raise RuntimeError(f\"{name} does not", "when assigning new jobs. After this context manager exits the", "the number of worker nodes in the cluster up or", "{available} {unit}{resource} of free space on ' f'{self.config.workDir} that {batch_system}", "if None, the variable's current value will be used as", "env=None) returning nothing, used to update run configuration as a", "to this workflow\"\"\" cleanWorkDir: str class AbstractBatchSystem(ABC): \"\"\" An abstract", "method must be called before the first job is issued", "this node. Used in autoscaling when the autoscaler is ready", "amount of memory being requested, in bytes :param float cores:", "useful message is available, return None. This can be used", "job is issued to this batch system, and only if", "that are currently running (not just waiting) and how long", "def setEnv(self, name: str, value: Optional[str] = None) -> None:", "None, all nodes will be returned. \"\"\" raise NotImplementedError() @abstractmethod", "Unless required by applicable law or agreed to in writing,", "busy), reflecting the CPU load of the node. The memoryUsed", "node has been issued any tasks, else False \"\"\" raise", "an amount greater than allowed \"\"\" batch_system = self.__class__.__name__ or", "toil.job import JobDescription from toil.resource import Resource logger = logging.getLogger(__name__)", "method prior to node termination to ensure that nodes being", "of the node. The memoryUsed attribute is a floating point", "float, requestedMemory: int, workers: int) -> None: self.coresUsed = coresUsed", "Note to implementors: This means that you would typically need", "the specific language governing permissions and # limitations under the", "might be stuck. :return: User-directed message about scheduling state. \"\"\"", "requested, in bytes :param str job_name: Name of the job", "inherit the environment of the machine it is running on", "return [] class BatchSystemSupport(AbstractBatchSystem): \"\"\" Partial implementation of AbstractBatchSystem, support", "used by the Jobs. The workers attribute is an integer", "a collection of job-specific environment variables to be set on", "node. The memoryUsed attribute is a floating point value between", "it will raise an exception. :param userScript: the resource object", "@abstractmethod def shutdown(self) -> None: \"\"\" Called at the completion", "= 255 class BatchJobExitReason(enum.Enum): FINISHED: int = 1 # Successfully", "= Toil.getToilWorkDir(self.config.workDir) return os.path.join(workDir, fileName) @staticmethod def workerCleanup(info: WorkerCleanupInfo) ->", "job_name: Name of the job being checked, for generating a", "node. :param preemptable: If True (False) only (non-)preemptable nodes will", "of a job. A call to this method affects all", "number of cores being requested :param int disk: amount of", "an integer reflecting the number of workers currently active workers", "to set the resource object representing the user script. Note", "system imposed memory limit class UpdatedBatchJobInfo(NamedTuple): jobID: int exitStatus: int", "the filter to disable the filtering after node termination is", "RuntimeError: if value is None and the name cannot be", "a useful error report. :param str detail: Batch-system-specific message to", "NotImplementedError() @abstractmethod def ignoreNode(self, nodeAddress: str) -> None: \"\"\" Stop", "@abstractmethod def killBatchJobs(self, jobIDs: List[int]) -> None: \"\"\" Kills the", ": The unique id that Toil gives a job. :param:", "str class AbstractBatchSystem(ABC): \"\"\" An abstract (as far as Python", "\"\"\" Set an environment variable for the worker process before", "' f'{self.config.workDir} that {batch_system} was configured with, or enforced '", "be unused! @abstractmethod @contextmanager def nodeFiltering(self, filter: Optional[Callable[[NodeInfo], bool]]) ->", "Optional[str]: \"\"\" Get a log message fragment for the user", "Override to provide scheduling status information. return None @abstractmethod def", "any one job :param int maxMemory: the maximum amount of", "the modules it depends on. \"\"\" raise NotImplementedError() @abstractmethod def", "TODO: change type to a Protocol to express kwarg names,", "resource == 'disk': msg = (f'{R}equesting {requested} {unit}{resource} for temporary", "Config from toil.deferred import DeferredFunctionManager from toil.fileStores.abstractFileStore import AbstractFileStore from", "of all the relevant information for cleaning up the worker.", "parser: Union[ArgumentParser, _ArgumentGroup]) -> None: \"\"\" If this batch system", "should be removed \"\"\" raise NotImplementedError() @abstractmethod def ignoreNode(self, nodeAddress:", "California # # Licensed under the Apache License, Version 2.0", "in bytes :param int maxDisk: the maximum amount of disk", "the jobtree. You can add code to that script to", "self.maxMemory = maxMemory self.maxDisk = maxDisk self.environment: Dict[str, str] =", "the same nodes 3) scaler terminates nodes, resulting in job", "@abstractmethod def issueBatchJob(self, jobDesc: JobDescription, job_environment: Optional[Dict[str, str]] = None)", "@abstractmethod def supportsAutoDeployment(cls) -> bool: \"\"\" Whether this batch system", "\"\"\" super().__init__() self.config = config self.maxCores = maxCores self.maxMemory =", "int disk: amount of disk space being requested, in bytes", "on overall load. \"\"\" @abstractmethod def getNodes(self, preemptable: Optional[bool] =", "will be returned. \"\"\" raise NotImplementedError() @abstractmethod def nodeInUse(self, nodeIP:", "the worker node has been issued any tasks, else False", "Stop sending jobs to this node. Used in autoscaling when", "IP address :return: True if the worker node has been", "@contextmanager def nodeFiltering(self, filter: Optional[Callable[[NodeInfo], bool]]) -> Iterator[None]: \"\"\" Used", "one concurrent worker process may exist on a worker node,", "user to help them diagnose why it might be stuck.", "Jobs have reserved on the node, regardless of whether the", "from argparse import ArgumentParser, _ArgumentGroup from contextlib import contextmanager from", "cleanly terminate all worker threads. \"\"\" raise NotImplementedError() def setEnv(self,", "removed \"\"\" raise NotImplementedError() @abstractmethod def ignoreNode(self, nodeAddress: str) ->", "them to the given parser. \"\"\" pass OptionType = TypeVar('OptionType')", "NodeInfo objects, one for each node. :param preemptable: If True", "return info for jobs killed by killBatchJobs, although they may", "None: try: value = os.environ[name] except KeyError: raise RuntimeError(f\"{name} does", "getUpdatedBatchJob(self, maxWait: int) -> Optional[UpdatedBatchJobInfo]: \"\"\" Returns information about job", "killBatchJobs(self, jobIDs: List[int]) -> None: \"\"\" Kills the given job", "considered for termination are not assigned new jobs. Call the", "request for any one job, in bytes \"\"\" super().__init__() self.config", "running, either successfully or with an error). Each such job", "for 'stdout') :rtype: string : Formatted filename; however if self.config.noStdOutErr", "bool]]) -> Iterator[None]: \"\"\" Used to prevent races in autoscaling", "in ([], [cacheDirName(info.workflowID)])): shutil.rmtree(workflowDir, ignore_errors=True) class NodeInfo: \"\"\" The coresUsed", "is setup by the toilSetup script and has configuration parameters", "does not support tracking wall time. \"\"\" raise NotImplementedError() def", "\"\"\" Process command line or configuration options relevant to this", "any command line options, add them to the given parser.", "disk: int, job_name: str = '', detail: str = '')", "or changing the base temporary directory by setting TMPDIR.') else:", "set up the environment of a job. A call to", "when a resource is requested in an amount greater than", "if :meth:`.supportsAutoDeployment` returns True, otherwise it will raise an exception.", "scheduling status information. return None @abstractmethod def shutdown(self) -> None:", "after a node with this address has been terminated. This", "node is doesn't exist, this function should simply return False.", "Used in autoscaling when the autoscaler is ready to terminate", "worker to do things in-process (such as configuring environment variables,", "coresUsed attribute is a floating point value between 0 (all", "If a result is available, returns UpdatedBatchJobInfo. Otherwise it returns", "terminate all worker threads. \"\"\" raise NotImplementedError() def setEnv(self, name:", "the used resources The requestedCores and requestedMemory attributes are all", "5 # Internal error. MEMLIMIT: int = 6 # Job", "{unit}{resource} that {batch_system} was configured with, ' f'or enforced by", "jobtree. You can add code to that script to get", "raise NotImplementedError() @abstractmethod def nodeInUse(self, nodeIP: str) -> bool: \"\"\"", "def unignoreNode(self, nodeAddress: str) -> None: \"\"\" Stop ignoring this", "issued (may be running, or may be waiting to be", "nodeIP: str) -> bool: \"\"\" Can be used to determine", "id that Toil gives a job. :param: cluster_job_id : What", "a unique jobID that can be used to reference the", "used), reflecting the memory pressure on the node. The coresTotal", "If the leader thinks the workflow is stuck, the message", "{requested} {unit}{resource}, more than the maximum of ' f'{available} {unit}{resource}", "up from the current environment. \"\"\" raise NotImplementedError() @classmethod def", "Format path for batch system standard output/error and other files", "command line or configuration options relevant to this batch system.", "of the University of California # # Licensed under the", "NotImplementedError() def setUserScript(self, userScript: Resource) -> None: \"\"\" Set the", "returns None. wallTime is the number of seconds (a strictly", "and has configuration parameters for the jobtree. You can add", "exist in current environment\") self.environment[name] = value def formatStdOutErrPath(self, toil_job_id:", "possibility of a new node having the same address as", "from toil.resource import Resource logger = logging.getLogger(__name__) # Value to", "You may obtain a copy of the License at #", "float, disk: int, job_name: str = '', detail: str =", "{batch_system} was configured with, or enforced ' f'by --max{resource.capitalize()}. Try", "returns UpdatedBatchJobInfo. Otherwise it returns None. wallTime is the number", "autoscaling when the autoscaler is ready to terminate a node,", "\"\"\" def __init__(self, coresUsed: float, memoryUsed: float, coresTotal: float, memoryTotal:", "system must provide to Toil. \"\"\" @classmethod @abstractmethod def supportsAutoDeployment(cls)", "'/dev/null' or equivalent. \"\"\" if self.config.noStdOutErr: return os.devnull fileName: str", "jobs. Call the method again passing None as the filter", "for the user about anything that might be going wrong", "module and the modules it depends on. \"\"\" raise NotImplementedError()", "str, std: str) -> str: \"\"\" Format path for batch", "pressure on the node. The coresTotal and memoryTotal attributes are", "not just a worker process. A worker process may run", "int maxMemory: the maximum amount of memory the batch system", "manager exits the filter should be removed \"\"\" raise NotImplementedError()", "the user to help them diagnose why it might be", "be looked up from the current environment. \"\"\" raise NotImplementedError()", "be used to ask the Toil worker to do things", "batch_system = self.__class__.__name__ or 'this batch system' for resource, requested,", "issueBatchJob(self, jobDesc: JobDescription, job_environment: Optional[Dict[str, str]] = None) -> int:", "file system) with names containing both the Toil and batch", "List[ContextManager[Any]]: \"\"\" Get a list of picklable context manager objects", "attributes are the node's resources, not just the used resources", "that {batch_system} was configured with, ' f'or enforced by --max{resource.capitalize()}.')", "toil.fileStores.abstractFileStore import AbstractFileStore from toil.job import JobDescription from toil.resource import", "user script itself. If it does, the :meth:`.setUserScript` can be", "provided it will be looked up from the current environment.", "DeferredFunctionManager from toil.fileStores.abstractFileStore import AbstractFileStore from toil.job import JobDescription from", "is true, returns '/dev/null' or equivalent. \"\"\" if self.config.noStdOutErr: return", "AbstractFileStore from toil.job import JobDescription from toil.resource import Resource logger", "to express kwarg names, or else use a # different", "int, cluster_job_id: str, std: str) -> str: \"\"\" Format path", "options relevant to this batch system. :param setOption: A function", "cluster up or down depending on overall load. \"\"\" @abstractmethod", "in, in order. Can be used to ask the Toil", "than one job sequentially, and more than one concurrent worker", "races in autoscaling where 1) nodes have reported to the", "kill \"\"\" raise NotImplementedError() # FIXME: Return value should be", "batch system, if available. If no useful message is available,", "address of node to ignore. \"\"\" raise NotImplementedError() @abstractmethod def", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "the first job is issued to this batch system, and", "and the modules it depends on. \"\"\" raise NotImplementedError() @abstractmethod", "named tuple consisting of all the relevant information for cleaning", "with names containing both the Toil and batch system job", "from the current environment. :param str name: the environment variable", "appear in the results of getRunningBatchJobIDs. The killed job will", "\"\"\" # TODO: change type to a Protocol to express", "\"\"\" Called at the completion of a toil invocation. Should", "not greater than that available or allowed. :param int memory:", "assigning new jobs. After this context manager exits the filter", "a filter on nodes considered when assigning new jobs. After", "import enum import logging import os import shutil from abc", "if self.config.noStdOutErr: return os.devnull fileName: str = f'toil_{self.config.workflowID}.{toil_job_id}.{cluster_job_id}.{std}.log' workDir: str", "simply return False. :param nodeIP: The worker nodes private IP", "all the resources that Toil Jobs have reserved on the", "f'{self.config.workDir} that {batch_system} was configured with, or enforced ' f'by", "2) scaler decides to terminate these nodes. In parallel the", "by the worker internally to set up the environment of", "(Any, Callable, ContextManager, Dict, Iterator, List, Optional, Tuple, Type, TypeVar,", "must be called before the first job is issued to", "' f'more than the maximum of {available} {unit}{resource} of free", "to this batch system. :param setOption: A function with signature", "Iterator[None]: \"\"\" Used to prevent races in autoscaling where 1)", "to the autoscaler as having no jobs 2) scaler decides", "os import shutil from abc import ABC, abstractmethod from argparse", "\"\"\" raise NotImplementedError() def setEnv(self, name: str, value: Optional[str] =", "and how long they have been running, in seconds. :return:", "def supportsAutoDeployment(cls) -> bool: \"\"\" Whether this batch system supports", "coresTotal and memoryTotal attributes are the node's resources, not just", "-> None: \"\"\" Kills the given job IDs. After returning,", "node. Used in autoscaling when the autoscaler is ready to", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "License. # You may obtain a copy of the License", "specific to this workflow\"\"\" cleanWorkDir: str class AbstractBatchSystem(ABC): \"\"\" An", "def getRunningBatchJobIDs(self) -> Dict[int, float]: \"\"\" Gets a map of", "Note that this mechanism is different to the one used", "the maximum amount of disk space the batch system can", "\"\"\" Stop sending jobs to this node. Used in autoscaling", "space the batch system can request for any one job,", "batch system can request for any one job, in bytes", "completion of a toil invocation. Should cleanly terminate all worker", "unignoreNode(self, nodeAddress: str) -> None: \"\"\" Stop ignoring this address,", "to NodeInfo objects, one for each node. :param preemptable: If", "seconds (a strictly positive float) in wall-clock time the job", "WorkerCleanupInfo) -> None: \"\"\" Cleans up the worker node on", "status is not available (e.g. job is lost). \"\"\" exitReason:", "on the node. \"\"\" def __init__(self, coresUsed: float, memoryUsed: float,", "This allows for the possibility of a new node having", "finishing. ERROR: int = 5 # Internal error. MEMLIMIT: int", "to be set on the worker. :return: a unique jobID", "the job being checked, for generating a useful error report.", "regardless of whether the resources are actually being used by", "and batch system job IDs, for ease of debugging job", "None) -> Dict[str, NodeInfo]: \"\"\" Returns a dictionary mapping node", "to node termination to ensure that nodes being considered for", "ordering should not be depended upon. \"\"\" raise NotImplementedError() @abstractmethod", "jobIDs that are currently running (not just waiting) and how", "workflowID: str \"\"\"used to identify files specific to this workflow\"\"\"", "== 'disk': msg = (f'{R}equesting {requested} {unit}{resource} for temporary space,", "be returned. If None, all nodes will be returned. \"\"\"", "with, ' f'or enforced by --max{resource.capitalize()}.') if detail: msg +=", "@classmethod def add_options(cls, parser: Union[ArgumentParser, _ArgumentGroup]) -> None: \"\"\" If", "def workerCleanup(info: WorkerCleanupInfo) -> None: \"\"\" Cleans up the worker", "raise an exception. :param userScript: the resource object representing the", "script and has configuration parameters for the jobtree. You can", "help them diagnose why it might be stuck. :return: User-directed", "about anything that might be going wrong in the batch", "prevent races in autoscaling where 1) nodes have reported to", "allows for the possibility of a new node having the", "message to include in the error. :raise InsufficientSystemResources: raised when", "available. EXIT_STATUS_UNAVAILABLE_VALUE = 255 class BatchJobExitReason(enum.Enum): FINISHED: int = 1", "names, or else use a # different interface (generator?) pass", "job-specific environment variables to be set on the worker. :return:", "requested, available in [('cores', cores, self.maxCores), ('memory', memory, self.maxMemory), ('disk',", "int = 3 # Preemptable failure (job's executing host went", "from the current environment. \"\"\" raise NotImplementedError() @classmethod def add_options(cls,", "is None: try: value = os.environ[name] except KeyError: raise RuntimeError(f\"{name}", "and 1 (all cores busy), reflecting the CPU load of", "None. wallTime is the number of seconds (a strictly positive", "initial state of the object :param toil.common.Config config: object is", "time. \"\"\" raise NotImplementedError() def getSchedulingStatusMessage(self) -> Optional[str]: \"\"\" Get", "nodes in the cluster up or down depending on overall", "base class to represent the interface the batch system must", "and requestedMemory attributes are all the resources that Toil Jobs", "same nodes 3) scaler terminates nodes, resulting in job failures", "std : The provenance of the stream (for example: 'err'", "\"\"\" Can be used to determine if a worker node", "workDir: str = Toil.getToilWorkDir(self.config.workDir) return os.path.join(workDir, fileName) @staticmethod def workerCleanup(info:", "makes it possible to override specific variables in that inherited", "the message can be displayed to the user to help", "on ' f'{self.config.workDir} that {batch_system} was configured with, or enforced", "getNodes(self, preemptable: Optional[bool] = None) -> Dict[str, NodeInfo]: \"\"\" Returns", "(info.cleanWorkDir == 'always' or info.cleanWorkDir in ('onSuccess', 'onError') and workflowDirContents", "After returning, the killed jobs will not appear in the", "being requested, in bytes :param float cores: number of cores", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "value) of the job. 0 implies successful. EXIT_STATUS_UNAVAILABLE_VALUE is used", "getUpdatedBatchJob. :param jobIDs: list of IDs of jobs to kill", "abstract (as far as Python currently allows) base class to", "path for batch system standard output/error and other files generated", "of the stream (for example: 'err' for 'stderr' or 'out'", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "for the specific language governing permissions and # limitations under", "f'by --max{resource.capitalize()}. Try setting/changing the toil option ' f'\"--workDir\" or", "node. \"\"\" def __init__(self, coresUsed: float, memoryUsed: float, coresTotal: float,", "disk space the batch system can request for any one", "command line options, add them to the given parser. \"\"\"", "getRunningBatchJobIDs. The killed job will not be returned from getUpdatedBatchJob.", "new node having the same address as a terminated one.", "@classmethod @abstractmethod def supportsAutoDeployment(cls) -> bool: \"\"\" Whether this batch", "required by applicable law or agreed to in writing, software", "lost). \"\"\" exitReason: Optional[BatchJobExitReason] wallTime: Union[float, int, None] # Information", "= 1 # Successfully finished. FAILED: int = 2 #", "toil.deferred import DeferredFunctionManager from toil.fileStores.abstractFileStore import AbstractFileStore from toil.job import", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "tasks. If the node is doesn't exist, this function should", "(such as configuring environment variables, hot-deploying user scripts, or cleaning", "not return info for jobs killed by killBatchJobs, although they", "\"\"\" raise NotImplementedError() @abstractmethod def ignoreNode(self, nodeAddress: str) -> None:", "shared file system) with names containing both the Toil and", "error). Each such job will be returned exactly once. Does", "the maximum of {available} {unit}{resource} of free space on '", "enforced ' f'by --max{resource.capitalize()}. Try setting/changing the toil option '", "the one used by the worker internally to set up", "that supports a variable number of worker nodes. Used by", "agreed to in writing, software # distributed under the License", "raise NotImplementedError() def setUserScript(self, userScript: Resource) -> None: \"\"\" Set", "in an amount greater than allowed \"\"\" batch_system = self.__class__.__name__", "generating a useful error report. :param str detail: Batch-system-specific message", "<reponame>Hexotical/toil<gh_stars>100-1000 # Copyright (C) 2015-2021 Regents of the University of", "distributed under the License is distributed on an \"AS IS\"", "attribute is a floating point value between 0 (no memory", "system can request for any one job :param int maxMemory:", "methods. \"\"\" def __init__(self, config: Config, maxCores: float, maxMemory: int,", "on a shared file system) with names containing both the", ":param str value: if given, the environment variable given by", "no useful message is available, return None. This can be", "any one job, in bytes :param int maxDisk: the maximum", "node having the same address as a terminated one. \"\"\"", "jobDesc: JobDescription, job_environment: Optional[Dict[str, str]] = None) -> int: \"\"\"", "1 (all memory used), reflecting the memory pressure on the", "filter on nodes considered when assigning new jobs. After this", "None: \"\"\" Cleans up the worker node on batch system", "the user script itself. If it does, the :meth:`.setUserScript` can", "side effect. \"\"\" # TODO: change type to a Protocol", "= self.__class__.__name__ or 'this batch system' for resource, requested, available", "number of seconds (a strictly positive float) in wall-clock time", "-> None: \"\"\" Stop sending jobs to this node. Used", "-> bool: \"\"\" Can be used to determine if a", "environment variables, hot-deploying user scripts, or cleaning up a node)", ": What the cluster, for example, GridEngine, uses as its", "{} self.workerCleanupInfo = WorkerCleanupInfo(workDir=self.config.workDir, workflowID=self.config.workflowID, cleanWorkDir=self.config.cleanWorkDir) def checkResourceRequest(self, memory: int,", "jobIDs: list of IDs of jobs to kill \"\"\" raise", "Job finished, but failed. LOST: int = 3 # Preemptable", "last job for a particular workflow invocation finishes. Note that", "TODO: May be unused! @abstractmethod @contextmanager def nodeFiltering(self, filter: Optional[Callable[[NodeInfo],", "inherited environment before the worker is launched. Note that this", "scripts, or cleaning up a node) that would otherwise require", "worker process may run more than one job sequentially, and", "Gets a map of jobs as jobIDs that are currently", "Cleans up the worker node on batch system shutdown. Also", "filtering after node termination is done. :param method: This will", "class AbstractBatchSystem(ABC): \"\"\" An abstract (as far as Python currently", "from contextlib import contextmanager from typing import (Any, Callable, ContextManager,", "from toil.job import JobDescription from toil.resource import Resource logger =", "info.cleanWorkDir in ('onSuccess', 'onError') and workflowDirContents in ([], [cacheDirName(info.workflowID)])): shutil.rmtree(workflowDir,", "the current jobs have finished. :param nodeAddress: IP address of", "maxDisk self.environment: Dict[str, str] = {} self.workerCleanupInfo = WorkerCleanupInfo(workDir=self.config.workDir, workflowID=self.config.workflowID,", "Toil.getToilWorkDir(self.config.workDir) return os.path.join(workDir, fileName) @staticmethod def workerCleanup(info: WorkerCleanupInfo) -> None:", "actually being used by the Jobs. The workers attribute is", "of worker nodes. Used by :class:`toil. provisioners.clusterScaler.ClusterScaler` to scale the", "the last worker process terminates. \"\"\" raise NotImplementedError() def setUserScript(self,", "Job hit batch system imposed memory limit class UpdatedBatchJobInfo(NamedTuple): jobID:", "{requested} {unit}{resource} for temporary space, ' f'more than the maximum", "on the worker. :param str value: if given, the environment", "filename; however if self.config.noStdOutErr is true, returns '/dev/null' or equivalent.", "reflecting the memory pressure on the node. The coresTotal and", "batch system and returns a unique jobID. :param jobDesc a", "will not appear in the results of getRunningBatchJobIDs. The killed", "to terminate these nodes. In parallel the batch system assigns", "int = 2 # Job finished, but failed. LOST: int", "work directory (which may be on a shared file system)", "ensure that nodes being considered for termination are not assigned", "@classmethod def setOptions(cls, setOption: Callable[[str, Optional[Callable[[Any], OptionType]], Optional[Callable[[OptionType], None]], Optional[OptionType],", "will be used as the value on the worker :raise", "workflow. The batch system is said to *shut down* after", "OR CONDITIONS OF ANY KIND, either express or implied. #", "batch system does not support tracking wall time. \"\"\" raise", "process before it is launched. The worker process will typically", "picklable context manager objects to wrap worker work in, in", "the License is distributed on an \"AS IS\" BASIS, #", "workers class AbstractScalableBatchSystem(AbstractBatchSystem): \"\"\" A batch system that supports a", "batch system invokes :meth:`BatchSystemSupport.workerCleanup` after the last job for a", "termination to ensure that nodes being considered for termination are", "pass OptionType = TypeVar('OptionType') @classmethod def setOptions(cls, setOption: Callable[[str, Optional[Callable[[Any],", "Return value should be a set (then also fix the", "an error). Each such job will be returned exactly once.", "machine it is running on but this method makes it", "a node with this address has been terminated. This allows", "will be written to the Toil work directory (which may", "point value between 0 (no memory used) and 1 (all", "of AbstractBatchSystem, support methods. \"\"\" def __init__(self, config: Config, maxCores:", "is not greater than that available or allowed. :param int", "str: \"\"\" Format path for batch system standard output/error and", "The coresUsed attribute is a floating point value between 0", "job that has updated its status (i.e. ceased running, either", "checked, for generating a useful error report. :param str detail:", "has been issued any tasks, else False \"\"\" raise NotImplementedError()", "raise NotImplementedError() @abstractmethod def getUpdatedBatchJob(self, maxWait: int) -> Optional[UpdatedBatchJobInfo]: \"\"\"", "resource, requested, available in [('cores', cores, self.maxCores), ('memory', memory, self.maxMemory),", "it is launched. The worker process will typically inherit the", "bytes \"\"\" super().__init__() self.config = config self.maxCores = maxCores self.maxMemory", "law or agreed to in writing, software # distributed under", "a list, the ordering should not be depended upon. \"\"\"", "greater than that available or allowed. :param int memory: amount", "'' R = f'The job {job_name} is r' if job_name", "more than one job sequentially, and more than one concurrent", "NotImplementedError() @abstractmethod def killBatchJobs(self, jobIDs: List[int]) -> None: \"\"\" Kills", "given, the environment variable given by name will be set", "preemptable: Optional[bool] = None) -> Dict[str, NodeInfo]: \"\"\" Returns a", "worker node has been issued any tasks, else False \"\"\"", "self.environment: Dict[str, str] = {} self.workerCleanupInfo = WorkerCleanupInfo(workDir=self.config.workDir, workflowID=self.config.workflowID, cleanWorkDir=self.config.cleanWorkDir)", "Union[float, int, None] # Information required for worker cleanup on", "for generating a useful error report. :param str detail: Batch-system-specific", "Iterator, List, Optional, Tuple, Type, TypeVar, Union, NamedTuple) from toil.common", "be returned exactly once. Does not return info for jobs", "process. \"\"\" return [] class BatchSystemSupport(AbstractBatchSystem): \"\"\" Partial implementation of", "NamedTuple) from toil.common import Toil, cacheDirName, Config from toil.deferred import", "raise NotImplementedError() @abstractmethod def issueBatchJob(self, jobDesc: JobDescription, job_environment: Optional[Dict[str, str]]", "(job's executing host went away). KILLED: int = 4 #", "will be looked up from the current environment. :param str", "script to get parameters for your batch system. :param float", "\"\"\" A batch system that supports a variable number of", "to update run configuration as a side effect. \"\"\" #", "scaler terminates nodes, resulting in job failures for all jobs", "# TODO: May be unused! @abstractmethod @contextmanager def nodeFiltering(self, filter:", "may obtain a copy of the License at # #", "parsing_function=None, check_function=None, default=None, env=None) returning nothing, used to update run", "this batch system supports auto-deployment of the user script itself.", "You can add code to that script to get parameters", "running as the value \"\"\" raise NotImplementedError() @abstractmethod def getUpdatedBatchJob(self,", "the worker internally to set up the environment of a", "available, return None. This can be used to report what", "of IDs of jobs to kill \"\"\" raise NotImplementedError() #", "also fix the tests) @abstractmethod def getIssuedBatchJobIDs(self) -> List[int]: \"\"\"", "wrong in the batch system, if available. If no useful", "although they may cause None to be returned earlier than", "= memoryUsed self.coresTotal = coresTotal self.memoryTotal = memoryTotal self.requestedCores =", "this batch system provides any command line options, add them", "may not use this file except in compliance with the", "debugging job failures. :param: int toil_job_id : The unique id", "killBatchJobs, although they may cause None to be returned earlier", "jobs will not appear in the results of getRunningBatchJobIDs. The", "is running on but this method makes it possible to", "allows) base class to represent the interface the batch system", "= 6 # Job hit batch system imposed memory limit", "job. 0 implies successful. EXIT_STATUS_UNAVAILABLE_VALUE is used when the exit", "this file except in compliance with the License. # You", "is ready to terminate a node, but jobs are still", "Jobs. The workers attribute is an integer reflecting the number", "just waiting) and how long they have been running, in", "NotImplementedError() @abstractmethod def getRunningBatchJobIDs(self) -> Dict[int, float]: \"\"\" Gets a", "variables in that inherited environment before the worker is launched.", "def getIssuedBatchJobIDs(self) -> List[int]: \"\"\" Gets all currently issued jobs", "toil.job.JobDescription :param job_environment: a collection of job-specific environment variables to", "Dict[str, str] = {} self.workerCleanupInfo = WorkerCleanupInfo(workDir=self.config.workDir, workflowID=self.config.workflowID, cleanWorkDir=self.config.cleanWorkDir) def", "is None and the name cannot be found in the", "are not assigned new jobs. Call the method again passing", "# # Licensed under the Apache License, Version 2.0 (the", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "thinks the workflow is stuck, the message can be displayed", "disable the filtering after node termination is done. :param method:", "process may run more than one job sequentially, and more", "int = 5 # Internal error. MEMLIMIT: int = 6", "(C) 2015-2021 Regents of the University of California # #", "scheduling state. \"\"\" # Default implementation returns None. # Override", "status information. return None @abstractmethod def shutdown(self) -> None: \"\"\"", "float maxCores: the maximum number of cores the batch system", "of cores being requested :param int disk: amount of disk", "worker work in, in order. Can be used to ask", "this batch system, and only if :meth:`.supportsAutoDeployment` returns True, otherwise", "be looked up from the current environment. :param str name:", "the environment of the machine it is running on but", "memory: int, cores: float, disk: int, job_name: str = '',", "to *shut down* after the last worker process terminates. \"\"\"", "from toil.deferred import DeferredFunctionManager from toil.fileStores.abstractFileStore import AbstractFileStore from toil.job", "permissions and # limitations under the License. import enum import", "displayed to the user to help them diagnose why it", "is not available (e.g. job is lost). \"\"\" exitReason: Optional[BatchJobExitReason]", "@abstractmethod def getRunningBatchJobIDs(self) -> Dict[int, float]: \"\"\" Gets a map", "is said to *shut down* after the last worker process", "detail raise InsufficientSystemResources(msg) def setEnv(self, name: str, value: Optional[str] =", "available in [('cores', cores, self.maxCores), ('memory', memory, self.maxMemory), ('disk', disk,", "cores, self.maxCores), ('memory', memory, self.maxMemory), ('disk', disk, self.maxDisk)]: assert requested", "1 (all cores busy), reflecting the CPU load of the", "currently issued jobs :return: A list of jobs (as jobIDs)", "message can be displayed to the user to help them", "workflow. This method must be called before the first job", "resource request is not greater than that available or allowed.", "depending on overall load. \"\"\" @abstractmethod def getNodes(self, preemptable: Optional[bool]", "of jobs as jobIDs that are currently running (not just", "shutdown. Also see :meth:`supportsWorkerCleanup`. :param WorkerCleanupInfo info: A named tuple", "= os.listdir(workflowDir) AbstractFileStore.shutdownFileStore(workflowDir, info.workflowID) if (info.cleanWorkDir == 'always' or info.cleanWorkDir", "workflow is stuck, the message can be displayed to the", "== 'always' or info.cleanWorkDir in ('onSuccess', 'onError') and workflowDirContents in", "resource is requested in an amount greater than allowed \"\"\"", "Initializes initial state of the object :param toil.common.Config config: object", "user script for this workflow. This method must be called", "the variables before enqueuing a job. If no value is", "returned earlier than maxWait. :param maxWait: the number of seconds", ":return: A list of jobs (as jobIDs) currently issued (may", "include in the error. :raise InsufficientSystemResources: raised when a resource", "argparse import ArgumentParser, _ArgumentGroup from contextlib import contextmanager from typing", "\"\"\"used to identify files specific to this workflow\"\"\" cleanWorkDir: str", "None. # Override to provide scheduling status information. return None", "in the environment \"\"\" if value is None: try: value", "or implied. # See the License for the specific language", "factor when scheduling jobs, for example. If the leader thinks", "\"executor\" process. \"\"\" return [] class BatchSystemSupport(AbstractBatchSystem): \"\"\" Partial implementation", "Kills the given job IDs. After returning, the killed jobs", "fragment for the user about anything that might be going", "looked up from the current environment. :param str name: the", "assert isinstance(info, WorkerCleanupInfo) workflowDir = Toil.getLocalWorkflowDir(info.workflowID, info.workDir) DeferredFunctionManager.cleanupWorker(workflowDir) workflowDirContents =", "A call to this method affects all jobs issued after", "exactly once. Does not return info for jobs killed by", "formatStdOutErrPath(self, toil_job_id: int, cluster_job_id: str, std: str) -> str: \"\"\"", "any tasks. If the node is doesn't exist, this function", "the variable's current value will be used as the value", "process may exist on a worker node, for the same", "jobIDs: List[int]) -> None: \"\"\" Kills the given job IDs.", "allowed \"\"\" batch_system = self.__class__.__name__ or 'this batch system' for", "the resource object representing the user script or module and", "getSchedulingStatusMessage(self) -> Optional[str]: \"\"\" Get a log message fragment for", "all currently issued jobs :return: A list of jobs (as", "after node termination is done. :param method: This will be", ":param job_environment: a collection of job-specific environment variables to be", "is a floating point value between 0 (all cores idle)", "system can request for any one job, in bytes \"\"\"", "info: A named tuple consisting of all the relevant information", "will not be returned from getUpdatedBatchJob. :param jobIDs: list of", "worker. \"\"\" assert isinstance(info, WorkerCleanupInfo) workflowDir = Toil.getLocalWorkflowDir(info.workflowID, info.workDir) DeferredFunctionManager.cleanupWorker(workflowDir)", "given job IDs. After returning, the killed jobs will not", "job is lost). \"\"\" exitReason: Optional[BatchJobExitReason] wallTime: Union[float, int, None]", "JobDescription from toil.resource import Resource logger = logging.getLogger(__name__) # Value", "a worker node, for the same workflow. The batch system", "int = 4 # Job killed before finishing. ERROR: int", "# limitations under the License. import enum import logging import", "jobs on that node. Call this method prior to node", "a set (then also fix the tests) @abstractmethod def getIssuedBatchJobIDs(self)", "Despite the result being a list, the ordering should not", "in order. Can be used to ask the Toil worker", "Indicates whether this batch system invokes :meth:`BatchSystemSupport.workerCleanup` after the last", "if a worker node is running any tasks. If the", "current environment. \"\"\" raise NotImplementedError() @classmethod def add_options(cls, parser: Union[ArgumentParser,", "finishes. Note that the term *worker* refers to an entire", "running any tasks. If the node is doesn't exist, this", "is launched. Note that this mechanism is different to the", "[cacheDirName(info.workflowID)])): shutil.rmtree(workflowDir, ignore_errors=True) class NodeInfo: \"\"\" The coresUsed attribute is", "coresTotal self.memoryTotal = memoryTotal self.requestedCores = requestedCores self.requestedMemory = requestedMemory", "\"\"\" raise NotImplementedError() @abstractmethod def getUpdatedBatchJob(self, maxWait: int) -> Optional[UpdatedBatchJobInfo]:", "to be run). Despite the result being a list, the", "None) -> None: \"\"\" Set an environment variable for the", "not support tracking wall time. \"\"\" raise NotImplementedError() def getSchedulingStatusMessage(self)", "'always' or info.cleanWorkDir in ('onSuccess', 'onError') and workflowDirContents in ([],", "be terminated after the current jobs have finished. :param nodeAddress:", "whether this batch system invokes :meth:`BatchSystemSupport.workerCleanup` after the last job", "'R' if resource == 'disk': msg = (f'{R}equesting {requested} {unit}{resource}", "hit batch system imposed memory limit class UpdatedBatchJobInfo(NamedTuple): jobID: int", "memoryUsed attribute is a floating point value between 0 (no", "depended upon. \"\"\" raise NotImplementedError() @abstractmethod def getRunningBatchJobIDs(self) -> Dict[int,", "disk: amount of disk space being requested, in bytes :param", "resource object representing the user script. Note to implementors: If", "abc import ABC, abstractmethod from argparse import ArgumentParser, _ArgumentGroup from", "when the autoscaler is ready to terminate a node, but", "of the batch system. class WorkerCleanupInfo(NamedTuple): workDir: str \"\"\"workdir path", "for example. If the leader thinks the workflow is stuck,", "-> None: \"\"\" Initializes initial state of the object :param", "True (False) only (non-)preemptable nodes will be returned. If None,", "the cluster, for example, GridEngine, uses as its internal job", "the node is doesn't exist, this function should simply return", "system, and only if :meth:`.supportsAutoDeployment` returns True, otherwise it will", "issued after this method returns. Note to implementors: This means", "The worker nodes private IP address :return: True if the", "-> None: \"\"\" If this batch system provides any command", ":param float cores: number of cores being requested :param int", "set on the worker. :return: a unique jobID that can", "change type to a Protocol to express kwarg names, or", "affects all jobs issued after this method returns. Note to", "currently active workers on the node. \"\"\" def __init__(self, coresUsed:", "nodes, resulting in job failures for all jobs on that", "example, GridEngine, uses as its internal job id. :param: string", "it possible to override specific variables in that inherited environment", "exist on a worker node, for the same workflow. The", "between 0 (all cores idle) and 1 (all cores busy),", "are currently running (not just waiting) and how long they", "the batch system assigns jobs to the same nodes 3)", "this method makes it possible to override specific variables in", "amount of disk space the batch system can request for", "FIXME: Return value should be a set (then also fix", "None: self.coresUsed = coresUsed self.memoryUsed = memoryUsed self.coresTotal = coresTotal", "used when the exit status is not available (e.g. job", "f'more than the maximum of {available} {unit}{resource} of free space", "If it does, the :meth:`.setUserScript` can be invoked to set", "float cores: number of cores being requested :param int disk:", "just the used resources The requestedCores and requestedMemory attributes are", ":param nodeIP: The worker nodes private IP address :return: True", "= None) -> int: \"\"\" Issues a job with the", "unique jobID that can be used to reference the newly", "have finished. :param nodeAddress: IP address of node to ignore.", "process will typically inherit the environment of the machine it", "work in, in order. Can be used to ask the", "the batch system and returns a unique jobID. :param jobDesc", "__init__(self, coresUsed: float, memoryUsed: float, coresTotal: float, memoryTotal: int, requestedCores:", "This allows the node to be terminated after the current", "found in the environment \"\"\" if value is None: try:", "a wrapping \"executor\" process. \"\"\" return [] class BatchSystemSupport(AbstractBatchSystem): \"\"\"", "object is setup by the toilSetup script and has configuration", "job, in bytes \"\"\" super().__init__() self.config = config self.maxCores =", "_ArgumentGroup]) -> None: \"\"\" If this batch system provides any", "int, maxDisk: int) -> None: \"\"\" Initializes initial state of", "support methods. \"\"\" def __init__(self, config: Config, maxCores: float, maxMemory:", "option ' f'\"--workDir\" or changing the base temporary directory by", "@abstractmethod def ignoreNode(self, nodeAddress: str) -> None: \"\"\" Stop sending", "import DeferredFunctionManager from toil.fileStores.abstractFileStore import AbstractFileStore from toil.job import JobDescription", "logging import os import shutil from abc import ABC, abstractmethod", "in job failures for all jobs on that node. Call", "the limiting factor when scheduling jobs, for example. If the", "May be unused! @abstractmethod @contextmanager def nodeFiltering(self, filter: Optional[Callable[[NodeInfo], bool]])", "float, memoryTotal: int, requestedCores: float, requestedMemory: int, workers: int) ->", "more than the maximum of ' f'{available} {unit}{resource} that {batch_system}", "Optional[str] = None) -> None: \"\"\" Set an environment variable", "@abstractmethod def unignoreNode(self, nodeAddress: str) -> None: \"\"\" Stop ignoring", "os.devnull fileName: str = f'toil_{self.config.workflowID}.{toil_job_id}.{cluster_job_id}.{std}.log' workDir: str = Toil.getToilWorkDir(self.config.workDir) return", "for resource, requested, available in [('cores', cores, self.maxCores), ('memory', memory,", "this batch system. :param setOption: A function with signature setOption(option_name,", "maxMemory: int, maxDisk: int) -> None: \"\"\" Initializes initial state", "Optional[BatchJobExitReason] wallTime: Union[float, int, None] # Information required for worker", "available: unit = 'bytes of ' if resource in ('disk',", "Call the method again passing None as the filter to", "to a Protocol to express kwarg names, or else use", "raise InsufficientSystemResources(msg) def setEnv(self, name: str, value: Optional[str] = None)", "terminated. This allows for the possibility of a new node", ": The provenance of the stream (for example: 'err' for", "they have been running as the value \"\"\" raise NotImplementedError()", "to the batch system and returns a unique jobID. :param", "ease of debugging job failures. :param: int toil_job_id : The", "1 # Successfully finished. FAILED: int = 2 # Job", "(for example: 'err' for 'stderr' or 'out' for 'stdout') :rtype:", "contextmanager from typing import (Any, Callable, ContextManager, Dict, Iterator, List,", "system itself. Files will be written to the Toil work", "in writing, software # distributed under the License is distributed", "Regents of the University of California # # Licensed under", "system shutdown. Also see :meth:`supportsWorkerCleanup`. :param WorkerCleanupInfo info: A named", "function should simply return False. :param nodeIP: The worker nodes", "for 'stderr' or 'out' for 'stdout') :rtype: string : Formatted", "returned from getUpdatedBatchJob. :param jobIDs: list of IDs of jobs", "number of seconds to block, waiting for a result :return:", "toil_job_id : The unique id that Toil gives a job.", ":param: cluster_job_id : What the cluster, for example, GridEngine, uses", ": Formatted filename; however if self.config.noStdOutErr is true, returns '/dev/null'", "collection of job-specific environment variables to be set on the", "raise NotImplementedError() def getSchedulingStatusMessage(self) -> Optional[str]: \"\"\" Get a log", "in UpdatedBatchJobInfo.exitStatus when status is not available. EXIT_STATUS_UNAVAILABLE_VALUE = 255", "the number of workers currently active workers on the node.", "unit = 'bytes of ' if resource in ('disk', 'memory')", "result being a list, the ordering should not be depended", "before enqueuing a job. If no value is provided it", "at the completion of a toil invocation. Should cleanly terminate", "idle) and 1 (all cores busy), reflecting the CPU load", "cluster, for example, GridEngine, uses as its internal job id.", "License is distributed on an \"AS IS\" BASIS, # WITHOUT", "of job-specific environment variables to be set on the worker.", "License, Version 2.0 (the \"License\"); # you may not use", "should simply return False. :param nodeIP: The worker nodes private", "If no value is provided it will be looked up", "class AbstractScalableBatchSystem(AbstractBatchSystem): \"\"\" A batch system that supports a variable", "shutdown of the batch system. class WorkerCleanupInfo(NamedTuple): workDir: str \"\"\"workdir", "setOption(option_name, parsing_function=None, check_function=None, default=None, env=None) returning nothing, used to update", "self.requestedCores = requestedCores self.requestedMemory = requestedMemory self.workers = workers class", "the number of seconds (a strictly positive float) in wall-clock", "Optional[Callable[[Any], OptionType]], Optional[Callable[[OptionType], None]], Optional[OptionType], Optional[List[str]]], None]) -> None: \"\"\"", "be stuck. :return: User-directed message about scheduling state. \"\"\" #", "'this batch system' for resource, requested, available in [('cores', cores,", "not None if requested > available: unit = 'bytes of", "memory pressure on the node. The coresTotal and memoryTotal attributes", "about job that has updated its status (i.e. ceased running,", "True here, it should also override \"\"\" raise NotImplementedError() @classmethod", "the maximum amount of memory the batch system can request", "def checkResourceRequest(self, memory: int, cores: float, disk: int, job_name: str", "of memory being requested, in bytes :param float cores: number", "the leader thinks the workflow is stuck, the message can", "@abstractmethod def nodeInUse(self, nodeIP: str) -> bool: \"\"\" Can be", "memoryTotal: int, requestedCores: float, requestedMemory: int, workers: int) -> None:", "the License for the specific language governing permissions and #", "Otherwise it returns None. wallTime is the number of seconds", "context manager exits the filter should be removed \"\"\" raise", "string std : The provenance of the stream (for example:", "maxMemory: the maximum amount of memory the batch system can", "to use as exitStatus in UpdatedBatchJobInfo.exitStatus when status is not", "may exist on a worker node, for the same workflow.", "maxMemory self.maxDisk = maxDisk self.environment: Dict[str, str] = {} self.workerCleanupInfo", "jobs, for example. If the leader thinks the workflow is", "list of picklable context manager objects to wrap worker work", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "workflowDirContents in ([], [cacheDirName(info.workflowID)])): shutil.rmtree(workflowDir, ignore_errors=True) class NodeInfo: \"\"\" The", "auto-deployment of the user script itself. If it does, the", "just a worker process. A worker process may run more", "to get parameters for your batch system. :param float maxCores:", "refers to an entire node, not just a worker process.", "tasks, else False \"\"\" raise NotImplementedError() # TODO: May be", "WorkerCleanupInfo(NamedTuple): workDir: str \"\"\"workdir path (where the cache would go)\"\"\"", "= f'toil_{self.config.workflowID}.{toil_job_id}.{cluster_job_id}.{std}.log' workDir: str = Toil.getToilWorkDir(self.config.workDir) return os.path.join(workDir, fileName) @staticmethod", "you would typically need to copy the variables before enqueuing", "(non-)preemptable nodes will be returned. If None, all nodes will", "implementation returns True here, it should also override \"\"\" raise", "nodeFiltering(self, filter: Optional[Callable[[NodeInfo], bool]]) -> Iterator[None]: \"\"\" Used to prevent", "KeyError: raise RuntimeError(f\"{name} does not exist in current environment\") self.environment[name]", "failed. LOST: int = 3 # Preemptable failure (job's executing", "memory being requested, in bytes :param float cores: number of", "allows the node to be terminated after the current jobs", "(which may be on a shared file system) with names", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "effect. \"\"\" # TODO: change type to a Protocol to", "@abstractmethod def getNodes(self, preemptable: Optional[bool] = None) -> Dict[str, NodeInfo]:", "of preemptable or non-preemptable nodes to NodeInfo objects, one for", "or configuration options relevant to this batch system. :param setOption:", "add_options(cls, parser: Union[ArgumentParser, _ArgumentGroup]) -> None: \"\"\" If this batch", "different to the one used by the worker internally to", "worker nodes in the cluster up or down depending on", "amount of memory the batch system can request for any", "the worker node on batch system shutdown. Also see :meth:`supportsWorkerCleanup`.", "are actually being used by the Jobs. The workers attribute", "requestedCores: float, requestedMemory: int, workers: int) -> None: self.coresUsed =", "required for worker cleanup on shutdown of the batch system.", "if self.config.noStdOutErr is true, returns '/dev/null' or equivalent. \"\"\" if", "worker node is running any tasks. If the node is", "int \"\"\" The exit status (integer value) of the job.", "'err' for 'stderr' or 'out' for 'stdout') :rtype: string :", "(all cores busy), reflecting the CPU load of the node.", "the tests) @abstractmethod def getIssuedBatchJobIDs(self) -> List[int]: \"\"\" Gets all", "value. if None, the variable's current value will be used", "= coresTotal self.memoryTotal = memoryTotal self.requestedCores = requestedCores self.requestedMemory =", "def supportsWorkerCleanup(cls) -> bool: \"\"\" Indicates whether this batch system", "config: Config, maxCores: float, maxMemory: int, maxDisk: int) -> None:", "maximum of ' f'{available} {unit}{resource} that {batch_system} was configured with,", "Get a log message fragment for the user about anything", "the object :param toil.common.Config config: object is setup by the", "nodeAddress: str) -> None: \"\"\" Stop ignoring this address, presumably", "Dict, Iterator, List, Optional, Tuple, Type, TypeVar, Union, NamedTuple) from", "options, add them to the given parser. \"\"\" pass OptionType", "# distributed under the License is distributed on an \"AS", "worker cleanup on shutdown of the batch system. class WorkerCleanupInfo(NamedTuple):", "Python currently allows) base class to represent the interface the", "# Unless required by applicable law or agreed to in", "has configuration parameters for the jobtree. You can add code", "command to the batch system and returns a unique jobID.", "currently running jobID keys and how many seconds they have", "Config, maxCores: float, maxMemory: int, maxDisk: int) -> None: \"\"\"", "enum import logging import os import shutil from abc import", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "for this workflow. This method must be called before the", "If True (False) only (non-)preemptable nodes will be returned. If", "worker. :return: a unique jobID that can be used to", "-> Optional[UpdatedBatchJobInfo]: \"\"\" Returns information about job that has updated", "(as far as Python currently allows) base class to represent", "Job killed before finishing. ERROR: int = 5 # Internal", "info.workflowID) if (info.cleanWorkDir == 'always' or info.cleanWorkDir in ('onSuccess', 'onError')", "in the cluster up or down depending on overall load.", "it does, the :meth:`.setUserScript` can be invoked to set the", "be called before the first job is issued to this", "self.maxCores), ('memory', memory, self.maxMemory), ('disk', disk, self.maxDisk)]: assert requested is", "results of getRunningBatchJobIDs. The killed job will not be returned", "launched. The worker process will typically inherit the environment of", "# Information required for worker cleanup on shutdown of the", "the environment of a job. A call to this method", "resulting in job failures for all jobs on that node.", "nodes being considered for termination are not assigned new jobs.", "returns. Note to implementors: This means that you would typically", "the Apache License, Version 2.0 (the \"License\"); # you may", "new jobs. Call the method again passing None as the", "system and returns a unique jobID. :param jobDesc a toil.job.JobDescription", "a particular workflow invocation finishes. Note that the term *worker*", "Successfully finished. FAILED: int = 2 # Job finished, but", "variables, hot-deploying user scripts, or cleaning up a node) that", "whether the resources are actually being used by the Jobs.", "requestedMemory: int, workers: int) -> None: self.coresUsed = coresUsed self.memoryUsed", "jobs :return: A list of jobs (as jobIDs) currently issued", "Toil.getLocalWorkflowDir(info.workflowID, info.workDir) DeferredFunctionManager.cleanupWorker(workflowDir) workflowDirContents = os.listdir(workflowDir) AbstractFileStore.shutdownFileStore(workflowDir, info.workflowID) if (info.cleanWorkDir", "None, the variable's current value will be used as the", "of jobs to kill \"\"\" raise NotImplementedError() # FIXME: Return", "again passing None as the filter to disable the filtering", "failures. :param: int toil_job_id : The unique id that Toil", "system is said to *shut down* after the last worker", "in bytes :param float cores: number of cores being requested", "new jobs. After this context manager exits the filter should", "maxCores: the maximum number of cores the batch system can", "= Toil.getLocalWorkflowDir(info.workflowID, info.workDir) DeferredFunctionManager.cleanupWorker(workflowDir) workflowDirContents = os.listdir(workflowDir) AbstractFileStore.shutdownFileStore(workflowDir, info.workflowID) if", "string : Formatted filename; however if self.config.noStdOutErr is true, returns", "mechanism is different to the one used by the worker", "(no memory used) and 1 (all memory used), reflecting the", "If no useful message is available, return None. This can", "be running, or may be waiting to be run). Despite", "that can be used to reference the newly issued job", "@classmethod @abstractmethod def supportsWorkerCleanup(cls) -> bool: \"\"\" Indicates whether this", "state of the object :param toil.common.Config config: object is setup", "when the exit status is not available (e.g. job is", "set (then also fix the tests) @abstractmethod def getIssuedBatchJobIDs(self) ->", "If the node is doesn't exist, this function should simply", "NodeInfo: \"\"\" The coresUsed attribute is a floating point value", "by killBatchJobs, although they may cause None to be returned", "logger = logging.getLogger(__name__) # Value to use as exitStatus in", "the number of seconds to block, waiting for a result", "value is None and the name cannot be found in", "process. A worker process may run more than one job", "batch system. class WorkerCleanupInfo(NamedTuple): workDir: str \"\"\"workdir path (where the", "raise NotImplementedError() @abstractmethod def unignoreNode(self, nodeAddress: str) -> None: \"\"\"", "workerCleanup(info: WorkerCleanupInfo) -> None: \"\"\" Cleans up the worker node", "gives a job. :param: cluster_job_id : What the cluster, for", "not available (e.g. job is lost). \"\"\" exitReason: Optional[BatchJobExitReason] wallTime:", "super().__init__() self.config = config self.maxCores = maxCores self.maxMemory = maxMemory", "IDs, for ease of debugging job failures. :param: int toil_job_id", "of the job being checked, for generating a useful error", "Value to use as exitStatus in UpdatedBatchJobInfo.exitStatus when status is", "the Toil and batch system job IDs, for ease of", "user script. Note to implementors: If your implementation returns True", "be displayed to the user to help them diagnose why", "worker is launched. Note that this mechanism is different to", "job failures for all jobs on that node. Call this", "for any one job :param int maxMemory: the maximum amount", "of seconds (a strictly positive float) in wall-clock time the", "available (e.g. job is lost). \"\"\" exitReason: Optional[BatchJobExitReason] wallTime: Union[float,", "int memory: amount of memory being requested, in bytes :param", "requestedCores self.requestedMemory = requestedMemory self.workers = workers class AbstractScalableBatchSystem(AbstractBatchSystem): \"\"\"", "run more than one job sequentially, and more than one", "or info.cleanWorkDir in ('onSuccess', 'onError') and workflowDirContents in ([], [cacheDirName(info.workflowID)])):", "environment variable to be set on the worker. :param str", "if value is None and the name cannot be found", "return None. This can be used to report what resource", "a result :return: If a result is available, returns UpdatedBatchJobInfo.", "if requested > available: unit = 'bytes of ' if", "the node. The coresTotal and memoryTotal attributes are the node's", "limit class UpdatedBatchJobInfo(NamedTuple): jobID: int exitStatus: int \"\"\" The exit", "keys and how many seconds they have been running as", "int) -> Optional[UpdatedBatchJobInfo]: \"\"\" Returns information about job that has", "of ' f'{available} {unit}{resource} that {batch_system} was configured with, '", "state. \"\"\" # Default implementation returns None. # Override to", "None if requested > available: unit = 'bytes of '", "should also override \"\"\" raise NotImplementedError() @classmethod @abstractmethod def supportsWorkerCleanup(cls)", "invocation. Should cleanly terminate all worker threads. \"\"\" raise NotImplementedError()", "self.__class__.__name__ or 'this batch system' for resource, requested, available in", "implies successful. EXIT_STATUS_UNAVAILABLE_VALUE is used when the exit status is", "also override \"\"\" raise NotImplementedError() @classmethod @abstractmethod def supportsWorkerCleanup(cls) ->", "= WorkerCleanupInfo(workDir=self.config.workDir, workflowID=self.config.workflowID, cleanWorkDir=self.config.cleanWorkDir) def checkResourceRequest(self, memory: int, cores: float,", "-> None: self.coresUsed = coresUsed self.memoryUsed = memoryUsed self.coresTotal =", "representing the user script. Note to implementors: If your implementation", "--max{resource.capitalize()}. Try setting/changing the toil option ' f'\"--workDir\" or changing", "can be used to reference the newly issued job \"\"\"", "the given job IDs. After returning, the killed jobs will", "under the License is distributed on an \"AS IS\" BASIS,", "a resource is requested in an amount greater than allowed", "A batch system that supports a variable number of worker", "self.maxDisk = maxDisk self.environment: Dict[str, str] = {} self.workerCleanupInfo =", "system, if available. If no useful message is available, return", "A list of jobs (as jobIDs) currently issued (may be", "ignoring this address, presumably after a node with this address", "Should cleanly terminate all worker threads. \"\"\" raise NotImplementedError() def", "int, workers: int) -> None: self.coresUsed = coresUsed self.memoryUsed =", "None if this batch system does not support tracking wall", "returns None. # Override to provide scheduling status information. return", "on shutdown of the batch system. class WorkerCleanupInfo(NamedTuple): workDir: str", "as the value on the worker :raise RuntimeError: if value", "called before the first job is issued to this batch", "result is available, returns UpdatedBatchJobInfo. Otherwise it returns None. wallTime", "can request for any one job, in bytes :param int", "[('cores', cores, self.maxCores), ('memory', memory, self.maxMemory), ('disk', disk, self.maxDisk)]: assert", "'disk': msg = (f'{R}equesting {requested} {unit}{resource} for temporary space, '", "(all memory used), reflecting the memory pressure on the node.", "is not available. EXIT_STATUS_UNAVAILABLE_VALUE = 255 class BatchJobExitReason(enum.Enum): FINISHED: int", "maxDisk: int) -> None: \"\"\" Initializes initial state of the", "may be on a shared file system) with names containing", "coresTotal: float, memoryTotal: int, requestedCores: float, requestedMemory: int, workers: int)", "\"\"\" Used to prevent races in autoscaling where 1) nodes", "\"\"\" raise NotImplementedError() @abstractmethod def killBatchJobs(self, jobIDs: List[int]) -> None:", "enqueuing a job. If no value is provided it will", "to this value. if None, the variable's current value will", "shutdown(self) -> None: \"\"\" Called at the completion of a", "executing host went away). KILLED: int = 4 # Job", "255 class BatchJobExitReason(enum.Enum): FINISHED: int = 1 # Successfully finished.", "been running, in seconds. :return: dictionary with currently running jobID", "int: \"\"\" Issues a job with the specified command to", "is a floating point value between 0 (no memory used)", "a dictionary mapping node identifiers of preemptable or non-preemptable nodes", "info.workDir) DeferredFunctionManager.cleanupWorker(workflowDir) workflowDirContents = os.listdir(workflowDir) AbstractFileStore.shutdownFileStore(workflowDir, info.workflowID) if (info.cleanWorkDir ==", "returning nothing, used to update run configuration as a side", "be set to this value. if None, the variable's current", "scheduling jobs, for example. If the leader thinks the workflow", "where 1) nodes have reported to the autoscaler as having", "assert requested is not None if requested > available: unit", "as jobIDs that are currently running (not just waiting) and", "process terminates. \"\"\" raise NotImplementedError() def setUserScript(self, userScript: Resource) ->", "request for any one job, in bytes :param int maxDisk:", "= maxCores self.maxMemory = maxMemory self.maxDisk = maxDisk self.environment: Dict[str,", "Optional[Callable[[OptionType], None]], Optional[OptionType], Optional[List[str]]], None]) -> None: \"\"\" Process command", "system standard output/error and other files generated by the batch", "memory limit class UpdatedBatchJobInfo(NamedTuple): jobID: int exitStatus: int \"\"\" The", "int = 6 # Job hit batch system imposed memory", "variable's current value will be used as the value on", "coresUsed: float, memoryUsed: float, coresTotal: float, memoryTotal: int, requestedCores: float,", "workers: int) -> None: self.coresUsed = coresUsed self.memoryUsed = memoryUsed", "An abstract (as far as Python currently allows) base class", "of a toil invocation. Should cleanly terminate all worker threads.", "relevant information for cleaning up the worker. \"\"\" assert isinstance(info,", "= value def formatStdOutErrPath(self, toil_job_id: int, cluster_job_id: str, std: str)", "jobs to the same nodes 3) scaler terminates nodes, resulting", "order. Can be used to ask the Toil worker to", ":return: If a result is available, returns UpdatedBatchJobInfo. Otherwise it", "Union[ArgumentParser, _ArgumentGroup]) -> None: \"\"\" If this batch system provides", "worker process. A worker process may run more than one", "the result being a list, the ordering should not be", "ANY KIND, either express or implied. # See the License", ":raise RuntimeError: if value is None and the name cannot", "reflecting the number of workers currently active workers on the", "Toil Jobs have reserved on the node, regardless of whether", "def getNodes(self, preemptable: Optional[bool] = None) -> Dict[str, NodeInfo]: \"\"\"", "the License. # You may obtain a copy of the", "be found in the environment \"\"\" if value is None:", "KILLED: int = 4 # Job killed before finishing. ERROR:", "get parameters for your batch system. :param float maxCores: the", "override \"\"\" raise NotImplementedError() @classmethod @abstractmethod def supportsWorkerCleanup(cls) -> bool:", "a floating point value between 0 (all cores idle) and", "# See the License for the specific language governing permissions", "str = Toil.getToilWorkDir(self.config.workDir) return os.path.join(workDir, fileName) @staticmethod def workerCleanup(info: WorkerCleanupInfo)", "cache would go)\"\"\" workflowID: str \"\"\"used to identify files specific", "# Successfully finished. FAILED: int = 2 # Job finished,", "the same workflow. The batch system is said to *shut", "that node. Call this method prior to node termination to", "on. \"\"\" raise NotImplementedError() @abstractmethod def issueBatchJob(self, jobDesc: JobDescription, job_environment:", "as the filter to disable the filtering after node termination", ":param userScript: the resource object representing the user script or", "name: the environment variable to be set on the worker.", "LOST: int = 3 # Preemptable failure (job's executing host", "the term *worker* refers to an entire node, not just", "Used by :class:`toil. provisioners.clusterScaler.ClusterScaler` to scale the number of worker", "a Protocol to express kwarg names, or else use a", "nodes. In parallel the batch system assigns jobs to the", "bytes :param float cores: number of cores being requested :param", "the current environment. :param str name: the environment variable to", "dictionary mapping node identifiers of preemptable or non-preemptable nodes to", "the base temporary directory by setting TMPDIR.') else: msg =", "(as jobIDs) currently issued (may be running, or may be", "greater than allowed \"\"\" batch_system = self.__class__.__name__ or 'this batch", "value should be a set (then also fix the tests)", "the current environment. \"\"\" raise NotImplementedError() @classmethod def add_options(cls, parser:", "its internal job id. :param: string std : The provenance", "resource object representing the user script or module and the", "OptionType = TypeVar('OptionType') @classmethod def setOptions(cls, setOption: Callable[[str, Optional[Callable[[Any], OptionType]],", "finished, but failed. LOST: int = 3 # Preemptable failure", "that might be going wrong in the batch system, if", "Preemptable failure (job's executing host went away). KILLED: int =", "What the cluster, for example, GridEngine, uses as its internal", "Can be used to determine if a worker node is", "information for cleaning up the worker. \"\"\" assert isinstance(info, WorkerCleanupInfo)", "when scheduling jobs, for example. If the leader thinks the", ":meth:`BatchSystemSupport.workerCleanup` after the last job for a particular workflow invocation", "to ignore. \"\"\" raise NotImplementedError() @abstractmethod def unignoreNode(self, nodeAddress: str)", "be set on the worker. :param str value: if given,", "wallTime: Union[float, int, None] # Information required for worker cleanup", "use a # different interface (generator?) pass def getWorkerContexts(self) ->", "nodes 3) scaler terminates nodes, resulting in job failures for", "str value: if given, the environment variable given by name", "this method returns. Note to implementors: This means that you", "consisting of all the relevant information for cleaning up the", "Licensed under the Apache License, Version 2.0 (the \"License\"); #", "job :param int maxMemory: the maximum amount of memory the", "be used to reference the newly issued job \"\"\" raise", "specified command to the batch system and returns a unique", "r' if job_name else 'R' if resource == 'disk': msg", "memory, self.maxMemory), ('disk', disk, self.maxDisk)]: assert requested is not None", "writing, software # distributed under the License is distributed on", "name cannot be found in the environment \"\"\" if value", ":meth:`supportsWorkerCleanup`. :param WorkerCleanupInfo info: A named tuple consisting of all", "None) -> int: \"\"\" Issues a job with the specified", "to kill \"\"\" raise NotImplementedError() # FIXME: Return value should", "msg += detail raise InsufficientSystemResources(msg) def setEnv(self, name: str, value:", "resource is the limiting factor when scheduling jobs, for example.", ":param method: This will be used as a filter on", "int, cores: float, disk: int, job_name: str = '', detail:", "by the Jobs. The workers attribute is an integer reflecting", "not assigned new jobs. Call the method again passing None", "nodeInUse(self, nodeIP: str) -> bool: \"\"\" Can be used to", "that Toil gives a job. :param: cluster_job_id : What the", "issued jobs :return: A list of jobs (as jobIDs) currently", "\"\"\" Indicates whether this batch system invokes :meth:`BatchSystemSupport.workerCleanup` after the", "None: \"\"\" Called at the completion of a toil invocation.", "toil.common import Toil, cacheDirName, Config from toil.deferred import DeferredFunctionManager from", "memoryUsed self.coresTotal = coresTotal self.memoryTotal = memoryTotal self.requestedCores = requestedCores", "a worker node is running any tasks. If the node", "determine if a worker node is running any tasks. If", "requestedMemory attributes are all the resources that Toil Jobs have", "of worker nodes in the cluster up or down depending", "of getRunningBatchJobIDs. The killed job will not be returned from", "-> None: \"\"\" Check resource request is not greater than", "the batch system must provide to Toil. \"\"\" @classmethod @abstractmethod", "environment. :param str name: the environment variable to be set", "int toil_job_id : The unique id that Toil gives a", "\"\"\" raise NotImplementedError() @classmethod def add_options(cls, parser: Union[ArgumentParser, _ArgumentGroup]) ->", "self.environment[name] = value def formatStdOutErrPath(self, toil_job_id: int, cluster_job_id: str, std:", "TypeVar('OptionType') @classmethod def setOptions(cls, setOption: Callable[[str, Optional[Callable[[Any], OptionType]], Optional[Callable[[OptionType], None]],", "batch system shutdown. Also see :meth:`supportsWorkerCleanup`. :param WorkerCleanupInfo info: A", "\"\"\" raise NotImplementedError() # FIXME: Return value should be a", "InsufficientSystemResources(msg) def setEnv(self, name: str, value: Optional[str] = None) ->", "environment of a job. A call to this method affects", "a side effect. \"\"\" # TODO: change type to a", "the job ran for, or None if this batch system", "allowed. :param int memory: amount of memory being requested, in", "path (where the cache would go)\"\"\" workflowID: str \"\"\"used to", "it should also override \"\"\" raise NotImplementedError() @classmethod @abstractmethod def", "jobID that can be used to reference the newly issued", "self.config = config self.maxCores = maxCores self.maxMemory = maxMemory self.maxDisk", "before the worker is launched. Note that this mechanism is", "requestedMemory self.workers = workers class AbstractScalableBatchSystem(AbstractBatchSystem): \"\"\" A batch system", "exitStatus: int \"\"\" The exit status (integer value) of the", "not just the used resources The requestedCores and requestedMemory attributes", "setOption: A function with signature setOption(option_name, parsing_function=None, check_function=None, default=None, env=None)", "the newly issued job \"\"\" raise NotImplementedError() @abstractmethod def killBatchJobs(self,", "or else use a # different interface (generator?) pass def", "resources that Toil Jobs have reserved on the node, regardless", "Copyright (C) 2015-2021 Regents of the University of California #", "system can request for any one job, in bytes :param", "= maxMemory self.maxDisk = maxDisk self.environment: Dict[str, str] = {}", "(e.g. job is lost). \"\"\" exitReason: Optional[BatchJobExitReason] wallTime: Union[float, int,", "configuration parameters for the jobtree. You can add code to", "number of workers currently active workers on the node. \"\"\"", "currently running (not just waiting) and how long they have", "before finishing. ERROR: int = 5 # Internal error. MEMLIMIT:", "std: str) -> str: \"\"\" Format path for batch system", ":param float maxCores: the maximum number of cores the batch", "in seconds. :return: dictionary with currently running jobID keys and", "request is not greater than that available or allowed. :param", "\"\"\" Stop ignoring this address, presumably after a node with", "to this batch system, and only if :meth:`.supportsAutoDeployment` returns True,", "\"\"\" Initializes initial state of the object :param toil.common.Config config:", "userScript: the resource object representing the user script or module", "a floating point value between 0 (no memory used) and", "cleaning up the worker. \"\"\" assert isinstance(info, WorkerCleanupInfo) workflowDir =", "a variable number of worker nodes. Used by :class:`toil. provisioners.clusterScaler.ClusterScaler`", "= os.environ[name] except KeyError: raise RuntimeError(f\"{name} does not exist in", "to the one used by the worker internally to set", "example. If the leader thinks the workflow is stuck, the", "environment of the machine it is running on but this", "number of worker nodes in the cluster up or down", "log message fragment for the user about anything that might", "one used by the worker internally to set up the", "a # different interface (generator?) pass def getWorkerContexts(self) -> List[ContextManager[Any]]:", "isinstance(info, WorkerCleanupInfo) workflowDir = Toil.getLocalWorkflowDir(info.workflowID, info.workDir) DeferredFunctionManager.cleanupWorker(workflowDir) workflowDirContents = os.listdir(workflowDir)", "import Resource logger = logging.getLogger(__name__) # Value to use as", "class to represent the interface the batch system must provide", "used resources The requestedCores and requestedMemory attributes are all the", "@abstractmethod def getUpdatedBatchJob(self, maxWait: int) -> Optional[UpdatedBatchJobInfo]: \"\"\" Returns information", ":param maxWait: the number of seconds to block, waiting for", "MEMLIMIT: int = 6 # Job hit batch system imposed", "and # limitations under the License. import enum import logging", "the specified command to the batch system and returns a", "Call this method prior to node termination to ensure that", "to be terminated after the current jobs have finished. :param", "to do things in-process (such as configuring environment variables, hot-deploying", "os.path.join(workDir, fileName) @staticmethod def workerCleanup(info: WorkerCleanupInfo) -> None: \"\"\" Cleans", "of jobs (as jobIDs) currently issued (may be running, or", "are still running. This allows the node to be terminated", "= logging.getLogger(__name__) # Value to use as exitStatus in UpdatedBatchJobInfo.exitStatus", "an entire node, not just a worker process. A worker", "worker internally to set up the environment of a job.", "a toil.job.JobDescription :param job_environment: a collection of job-specific environment variables", "toil.common.Config config: object is setup by the toilSetup script and", "batch system. :param setOption: A function with signature setOption(option_name, parsing_function=None,", "WorkerCleanupInfo(workDir=self.config.workDir, workflowID=self.config.workflowID, cleanWorkDir=self.config.cleanWorkDir) def checkResourceRequest(self, memory: int, cores: float, disk:", "-> bool: \"\"\" Indicates whether this batch system invokes :meth:`BatchSystemSupport.workerCleanup`", "of a new node having the same address as a", "the toil option ' f'\"--workDir\" or changing the base temporary", "-> List[int]: \"\"\" Gets all currently issued jobs :return: A", "the results of getRunningBatchJobIDs. The killed job will not be", "> available: unit = 'bytes of ' if resource in", "to reference the newly issued job \"\"\" raise NotImplementedError() @abstractmethod", "configured with, ' f'or enforced by --max{resource.capitalize()}.') if detail: msg", "for the possibility of a new node having the same", "Issues a job with the specified command to the batch", "CPU load of the node. The memoryUsed attribute is a", "logging.getLogger(__name__) # Value to use as exitStatus in UpdatedBatchJobInfo.exitStatus when", "the worker. :return: a unique jobID that can be used", "= 4 # Job killed before finishing. ERROR: int =", "batch system standard output/error and other files generated by the", "to provide scheduling status information. return None @abstractmethod def shutdown(self)", "resources The requestedCores and requestedMemory attributes are all the resources", "if this batch system does not support tracking wall time.", "worker nodes. Used by :class:`toil. provisioners.clusterScaler.ClusterScaler` to scale the number", "to report what resource is the limiting factor when scheduling", "this mechanism is different to the one used by the", "active workers on the node. \"\"\" def __init__(self, coresUsed: float,", "None: \"\"\" Stop sending jobs to this node. Used in", "of memory the batch system can request for any one", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "# TODO: change type to a Protocol to express kwarg", "maximum number of cores the batch system can request for", "self.maxCores = maxCores self.maxMemory = maxMemory self.maxDisk = maxDisk self.environment:", "+= detail raise InsufficientSystemResources(msg) def setEnv(self, name: str, value: Optional[str]", "Optional[Callable[[NodeInfo], bool]]) -> Iterator[None]: \"\"\" Used to prevent races in", "\"\"\" Get a log message fragment for the user about", "to the Toil work directory (which may be on a", "not be depended upon. \"\"\" raise NotImplementedError() @abstractmethod def getRunningBatchJobIDs(self)", "fileName: str = f'toil_{self.config.workflowID}.{toil_job_id}.{cluster_job_id}.{std}.log' workDir: str = Toil.getToilWorkDir(self.config.workDir) return os.path.join(workDir,", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "up the environment of a job. A call to this", "for, or None if this batch system does not support", "preemptable: If True (False) only (non-)preemptable nodes will be returned.", "Get a list of picklable context manager objects to wrap", "In parallel the batch system assigns jobs to the same", "provisioners.clusterScaler.ClusterScaler` to scale the number of worker nodes in the", "that available or allowed. :param int memory: amount of memory", "in [('cores', cores, self.maxCores), ('memory', memory, self.maxMemory), ('disk', disk, self.maxDisk)]:", "from abc import ABC, abstractmethod from argparse import ArgumentParser, _ArgumentGroup", "def issueBatchJob(self, jobDesc: JobDescription, job_environment: Optional[Dict[str, str]] = None) ->", "waiting) and how long they have been running, in seconds.", "return os.path.join(workDir, fileName) @staticmethod def workerCleanup(info: WorkerCleanupInfo) -> None: \"\"\"", "filter: Optional[Callable[[NodeInfo], bool]]) -> Iterator[None]: \"\"\" Used to prevent races", "NotImplementedError() # FIXME: Return value should be a set (then", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "None: \"\"\" Initializes initial state of the object :param toil.common.Config", "for all jobs on that node. Call this method prior", "threads. \"\"\" raise NotImplementedError() def setEnv(self, name: str, value: Optional[str]", "variable number of worker nodes. Used by :class:`toil. provisioners.clusterScaler.ClusterScaler` to", "R = f'The job {job_name} is r' if job_name else", "import shutil from abc import ABC, abstractmethod from argparse import", "in the results of getRunningBatchJobIDs. The killed job will not", "BatchJobExitReason(enum.Enum): FINISHED: int = 1 # Successfully finished. FAILED: int", "invokes :meth:`BatchSystemSupport.workerCleanup` after the last job for a particular workflow", "jobs as jobIDs that are currently running (not just waiting)", "is r' if job_name else 'R' if resource == 'disk':", "to scale the number of worker nodes in the cluster", "mapping node identifiers of preemptable or non-preemptable nodes to NodeInfo", "terminated after the current jobs have finished. :param nodeAddress: IP", "object representing the user script. Note to implementors: If your", "modules it depends on. \"\"\" raise NotImplementedError() @abstractmethod def issueBatchJob(self,", "the machine it is running on but this method makes", "for your batch system. :param float maxCores: the maximum number", "value: if given, the environment variable given by name will", "returns True, otherwise it will raise an exception. :param userScript:", "('disk', 'memory') else '' R = f'The job {job_name} is", "or None if this batch system does not support tracking", "as the value \"\"\" raise NotImplementedError() @abstractmethod def getUpdatedBatchJob(self, maxWait:", "by :class:`toil. provisioners.clusterScaler.ClusterScaler` to scale the number of worker nodes", "or allowed. :param int memory: amount of memory being requested,", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "NotImplementedError() @classmethod def add_options(cls, parser: Union[ArgumentParser, _ArgumentGroup]) -> None: \"\"\"", "def formatStdOutErrPath(self, toil_job_id: int, cluster_job_id: str, std: str) -> str:", "to ensure that nodes being considered for termination are not", "need to copy the variables before enqueuing a job. If", "before it is launched. The worker process will typically inherit", "useful error report. :param str detail: Batch-system-specific message to include", "Internal error. MEMLIMIT: int = 6 # Job hit batch", "-> Dict[str, NodeInfo]: \"\"\" Returns a dictionary mapping node identifiers", "fix the tests) @abstractmethod def getIssuedBatchJobIDs(self) -> List[int]: \"\"\" Gets", "returns '/dev/null' or equivalent. \"\"\" if self.config.noStdOutErr: return os.devnull fileName:", ":param preemptable: If True (False) only (non-)preemptable nodes will be", ":param jobDesc a toil.job.JobDescription :param job_environment: a collection of job-specific", "non-preemptable nodes to NodeInfo objects, one for each node. :param", "finished. :param nodeAddress: IP address of node to ignore. \"\"\"", "ignore. \"\"\" raise NotImplementedError() @abstractmethod def unignoreNode(self, nodeAddress: str) ->", "method makes it possible to override specific variables in that", "specific language governing permissions and # limitations under the License.", "that would otherwise require a wrapping \"executor\" process. \"\"\" return", "maxCores self.maxMemory = maxMemory self.maxDisk = maxDisk self.environment: Dict[str, str]", "by setting TMPDIR.') else: msg = (f'{R}equesting {requested} {unit}{resource}, more", "\"\"\" raise NotImplementedError() @abstractmethod def issueBatchJob(self, jobDesc: JobDescription, job_environment: Optional[Dict[str,", "script or module and the modules it depends on. \"\"\"", "a node) that would otherwise require a wrapping \"executor\" process.", "{unit}{resource}, more than the maximum of ' f'{available} {unit}{resource} that", "\"\"\" if value is None: try: value = os.environ[name] except", "\"\"\" raise NotImplementedError() def getSchedulingStatusMessage(self) -> Optional[str]: \"\"\" Get a", "job id. :param: string std : The provenance of the", "things in-process (such as configuring environment variables, hot-deploying user scripts,", "return False. :param nodeIP: The worker nodes private IP address", "interface (generator?) pass def getWorkerContexts(self) -> List[ContextManager[Any]]: \"\"\" Get a", "set on the worker. :param str value: if given, the", "{unit}{resource} for temporary space, ' f'more than the maximum of", "after the last worker process terminates. \"\"\" raise NotImplementedError() def", "once. Does not return info for jobs killed by killBatchJobs,", "2015-2021 Regents of the University of California # # Licensed", "def killBatchJobs(self, jobIDs: List[int]) -> None: \"\"\" Kills the given", "Note to implementors: If your implementation returns True here, it", "# you may not use this file except in compliance", "implementors: If your implementation returns True here, it should also", "(a strictly positive float) in wall-clock time the job ran", "the resource object representing the user script. Note to implementors:", "str job_name: Name of the job being checked, for generating", "jobs (as jobIDs) currently issued (may be running, or may", "successfully or with an error). Each such job will be", "does, the :meth:`.setUserScript` can be invoked to set the resource", "and how many seconds they have been running as the", "on a worker node, for the same workflow. The batch", "objects, one for each node. :param preemptable: If True (False)", "is lost). \"\"\" exitReason: Optional[BatchJobExitReason] wallTime: Union[float, int, None] #", "= requestedCores self.requestedMemory = requestedMemory self.workers = workers class AbstractScalableBatchSystem(AbstractBatchSystem):", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "the environment variable to be set on the worker. :param", "user about anything that might be going wrong in the", "EXIT_STATUS_UNAVAILABLE_VALUE = 255 class BatchJobExitReason(enum.Enum): FINISHED: int = 1 #", "AbstractBatchSystem(ABC): \"\"\" An abstract (as far as Python currently allows)", "equivalent. \"\"\" if self.config.noStdOutErr: return os.devnull fileName: str = f'toil_{self.config.workflowID}.{toil_job_id}.{cluster_job_id}.{std}.log'", "\"\"\"workdir path (where the cache would go)\"\"\" workflowID: str \"\"\"used", "ArgumentParser, _ArgumentGroup from contextlib import contextmanager from typing import (Any,", "of disk space being requested, in bytes :param str job_name:", "workers currently active workers on the node. \"\"\" def __init__(self,", "environment before the worker is launched. Note that this mechanism", "by --max{resource.capitalize()}.') if detail: msg += detail raise InsufficientSystemResources(msg) def", "for example, GridEngine, uses as its internal job id. :param:", "under the Apache License, Version 2.0 (the \"License\"); # you", "cacheDirName, Config from toil.deferred import DeferredFunctionManager from toil.fileStores.abstractFileStore import AbstractFileStore", "-> Optional[str]: \"\"\" Get a log message fragment for the", "raise RuntimeError(f\"{name} does not exist in current environment\") self.environment[name] =", "userScript: Resource) -> None: \"\"\" Set the user script for", "to prevent races in autoscaling where 1) nodes have reported", "batch system assigns jobs to the same nodes 3) scaler", "Toil gives a job. :param: cluster_job_id : What the cluster,", "value def formatStdOutErrPath(self, toil_job_id: int, cluster_job_id: str, std: str) ->", "\"\"\" Cleans up the worker node on batch system shutdown.", "A named tuple consisting of all the relevant information for", "one job, in bytes \"\"\" super().__init__() self.config = config self.maxCores", "= 3 # Preemptable failure (job's executing host went away).", "supportsAutoDeployment(cls) -> bool: \"\"\" Whether this batch system supports auto-deployment", "'out' for 'stdout') :rtype: string : Formatted filename; however if", "or equivalent. \"\"\" if self.config.noStdOutErr: return os.devnull fileName: str =", "setting TMPDIR.') else: msg = (f'{R}equesting {requested} {unit}{resource}, more than", "check_function=None, default=None, env=None) returning nothing, used to update run configuration", "maximum amount of disk space the batch system can request", "changing the base temporary directory by setting TMPDIR.') else: msg", "to copy the variables before enqueuing a job. If no", "being a list, the ordering should not be depended upon.", "a job. :param: cluster_job_id : What the cluster, for example,", "memory used), reflecting the memory pressure on the node. The", "both the Toil and batch system job IDs, for ease", "{unit}{resource} of free space on ' f'{self.config.workDir} that {batch_system} was", "passing None as the filter to disable the filtering after", "the filter should be removed \"\"\" raise NotImplementedError() @abstractmethod def", "4 # Job killed before finishing. ERROR: int = 5", "reserved on the node, regardless of whether the resources are", "environment \"\"\" if value is None: try: value = os.environ[name]", "OptionType]], Optional[Callable[[OptionType], None]], Optional[OptionType], Optional[List[str]]], None]) -> None: \"\"\" Process", "doesn't exist, this function should simply return False. :param nodeIP:", "TMPDIR.') else: msg = (f'{R}equesting {requested} {unit}{resource}, more than the", "None] # Information required for worker cleanup on shutdown of", "unique jobID. :param jobDesc a toil.job.JobDescription :param job_environment: a collection", "\"\"\" batch_system = self.__class__.__name__ or 'this batch system' for resource,", "0 implies successful. EXIT_STATUS_UNAVAILABLE_VALUE is used when the exit status", "value on the worker :raise RuntimeError: if value is None", "job. If no value is provided it will be looked", "given by name will be set to this value. if", "an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "no value is provided it will be looked up from", "setup by the toilSetup script and has configuration parameters for", "autoscaler as having no jobs 2) scaler decides to terminate", "available, returns UpdatedBatchJobInfo. Otherwise it returns None. wallTime is the", "may run more than one job sequentially, and more than", "killed job will not be returned from getUpdatedBatchJob. :param jobIDs:", "node, for the same workflow. The batch system is said", "int exitStatus: int \"\"\" The exit status (integer value) of", "name: str, value: Optional[str] = None) -> None: \"\"\" Set", "is issued to this batch system, and only if :meth:`.supportsAutoDeployment`", "the batch system. class WorkerCleanupInfo(NamedTuple): workDir: str \"\"\"workdir path (where", "= {} self.workerCleanupInfo = WorkerCleanupInfo(workDir=self.config.workDir, workflowID=self.config.workflowID, cleanWorkDir=self.config.cleanWorkDir) def checkResourceRequest(self, memory:", "this address, presumably after a node with this address has", "the relevant information for cleaning up the worker. \"\"\" assert", "free space on ' f'{self.config.workDir} that {batch_system} was configured with,", "parallel the batch system assigns jobs to the same nodes", "NotImplementedError() def setEnv(self, name: str, value: Optional[str] = None) ->", "term *worker* refers to an entire node, not just a", "leader thinks the workflow is stuck, the message can be", "otherwise it will raise an exception. :param userScript: the resource", "not appear in the results of getRunningBatchJobIDs. The killed job", "\"\"\" @abstractmethod def getNodes(self, preemptable: Optional[bool] = None) -> Dict[str,", "self.config.noStdOutErr is true, returns '/dev/null' or equivalent. \"\"\" if self.config.noStdOutErr:", "job failures. :param: int toil_job_id : The unique id that", "of workers currently active workers on the node. \"\"\" def", "AbstractScalableBatchSystem(AbstractBatchSystem): \"\"\" A batch system that supports a variable number", "tuple consisting of all the relevant information for cleaning up", "to represent the interface the batch system must provide to", "The coresTotal and memoryTotal attributes are the node's resources, not", "' f'by --max{resource.capitalize()}. Try setting/changing the toil option ' f'\"--workDir\"", "worker process before it is launched. The worker process will", "launched. Note that this mechanism is different to the one", "context manager objects to wrap worker work in, in order.", "be set on the worker. :return: a unique jobID that", "jobs. After this context manager exits the filter should be", "these nodes. In parallel the batch system assigns jobs to", "Try setting/changing the toil option ' f'\"--workDir\" or changing the", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "bytes :param int maxDisk: the maximum amount of disk space", "worker. :param str value: if given, the environment variable given", "object representing the user script or module and the modules", "the node. The memoryUsed attribute is a floating point value", "memoryTotal attributes are the node's resources, not just the used", "no jobs 2) scaler decides to terminate these nodes. In", "variables before enqueuing a job. If no value is provided", "maxCores: float, maxMemory: int, maxDisk: int) -> None: \"\"\" Initializes", "decides to terminate these nodes. In parallel the batch system", "the node, regardless of whether the resources are actually being", "a unique jobID. :param jobDesc a toil.job.JobDescription :param job_environment: a", "toil invocation. Should cleanly terminate all worker threads. \"\"\" raise", "else use a # different interface (generator?) pass def getWorkerContexts(self)", "RuntimeError(f\"{name} does not exist in current environment\") self.environment[name] = value", "be run). Despite the result being a list, the ordering", "*shut down* after the last worker process terminates. \"\"\" raise", "used to reference the newly issued job \"\"\" raise NotImplementedError()", "Toil, cacheDirName, Config from toil.deferred import DeferredFunctionManager from toil.fileStores.abstractFileStore import", "# Internal error. MEMLIMIT: int = 6 # Job hit", "float, coresTotal: float, memoryTotal: int, requestedCores: float, requestedMemory: int, workers:", "with signature setOption(option_name, parsing_function=None, check_function=None, default=None, env=None) returning nothing, used", "how many seconds they have been running as the value", "Used to prevent races in autoscaling where 1) nodes have", "Apache License, Version 2.0 (the \"License\"); # you may not", "the worker :raise RuntimeError: if value is None and the", "either express or implied. # See the License for the", "in bytes :param str job_name: Name of the job being", "if job_name else 'R' if resource == 'disk': msg =", "contextlib import contextmanager from typing import (Any, Callable, ContextManager, Dict,", "user script or module and the modules it depends on.", "must provide to Toil. \"\"\" @classmethod @abstractmethod def supportsAutoDeployment(cls) ->", "for termination are not assigned new jobs. Call the method", "in ('onSuccess', 'onError') and workflowDirContents in ([], [cacheDirName(info.workflowID)])): shutil.rmtree(workflowDir, ignore_errors=True)", "ignoreNode(self, nodeAddress: str) -> None: \"\"\" Stop sending jobs to", "ask the Toil worker to do things in-process (such as", "than maxWait. :param maxWait: the number of seconds to block,", "(integer value) of the job. 0 implies successful. EXIT_STATUS_UNAVAILABLE_VALUE is", "\"\"\" The exit status (integer value) of the job. 0", "job being checked, for generating a useful error report. :param", "will be looked up from the current environment. \"\"\" raise", "Optional[List[str]]], None]) -> None: \"\"\" Process command line or configuration", "exit status (integer value) of the job. 0 implies successful.", "do things in-process (such as configuring environment variables, hot-deploying user", "was configured with, ' f'or enforced by --max{resource.capitalize()}.') if detail:", "this address has been terminated. This allows for the possibility", "terminates nodes, resulting in job failures for all jobs on", "that inherited environment before the worker is launched. Note that", "generated by the batch system itself. Files will be written", "used to determine if a worker node is running any", "Callable, ContextManager, Dict, Iterator, List, Optional, Tuple, Type, TypeVar, Union,", "will be set to this value. if None, the variable's", "ignore_errors=True) class NodeInfo: \"\"\" The coresUsed attribute is a floating", "provide scheduling status information. return None @abstractmethod def shutdown(self) ->", "\"\"\" raise NotImplementedError() # TODO: May be unused! @abstractmethod @contextmanager", "import AbstractFileStore from toil.job import JobDescription from toil.resource import Resource", "bool: \"\"\" Whether this batch system supports auto-deployment of the", "-> None: \"\"\" Called at the completion of a toil", "or down depending on overall load. \"\"\" @abstractmethod def getNodes(self,", "first job is issued to this batch system, and only", "Name of the job being checked, for generating a useful", "set the resource object representing the user script. Note to", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "earlier than maxWait. :param maxWait: the number of seconds to", "exist, this function should simply return False. :param nodeIP: The", "\"\"\" raise NotImplementedError() @abstractmethod def unignoreNode(self, nodeAddress: str) -> None:", ":param str name: the environment variable to be set on", "cleanup on shutdown of the batch system. class WorkerCleanupInfo(NamedTuple): workDir:", "available. If no useful message is available, return None. This", "will typically inherit the environment of the machine it is", "import logging import os import shutil from abc import ABC,", "termination are not assigned new jobs. Call the method again", "the :meth:`.setUserScript` can be invoked to set the resource object", "used as a filter on nodes considered when assigning new", "interface the batch system must provide to Toil. \"\"\" @classmethod", "been issued any tasks, else False \"\"\" raise NotImplementedError() #", "be a set (then also fix the tests) @abstractmethod def", "= 'bytes of ' if resource in ('disk', 'memory') else", "seconds they have been running as the value \"\"\" raise", "as configuring environment variables, hot-deploying user scripts, or cleaning up", "issued to this batch system, and only if :meth:`.supportsAutoDeployment` returns", "for the same workflow. The batch system is said to", "str) -> str: \"\"\" Format path for batch system standard", "on the worker. :return: a unique jobID that can be", "is used when the exit status is not available (e.g.", "float) in wall-clock time the job ran for, or None", "on the node. The coresTotal and memoryTotal attributes are the", "maxWait: the number of seconds to block, waiting for a", "termination is done. :param method: This will be used as", "in wall-clock time the job ran for, or None if", "output/error and other files generated by the batch system itself.", "dictionary with currently running jobID keys and how many seconds", "value between 0 (all cores idle) and 1 (all cores", "as a terminated one. \"\"\" raise NotImplementedError() class InsufficientSystemResources(Exception): pass", "was configured with, or enforced ' f'by --max{resource.capitalize()}. Try setting/changing", "worker process terminates. \"\"\" raise NotImplementedError() def setUserScript(self, userScript: Resource)", "# FIXME: Return value should be a set (then also", "see :meth:`supportsWorkerCleanup`. :param WorkerCleanupInfo info: A named tuple consisting of", "3) scaler terminates nodes, resulting in job failures for all", "implementation of AbstractBatchSystem, support methods. \"\"\" def __init__(self, config: Config,", "maxDisk: the maximum amount of disk space the batch system", "enforced by --max{resource.capitalize()}.') if detail: msg += detail raise InsufficientSystemResources(msg)", "checkResourceRequest(self, memory: int, cores: float, disk: int, job_name: str =", "wrap worker work in, in order. Can be used to", "kwarg names, or else use a # different interface (generator?)", "when status is not available. EXIT_STATUS_UNAVAILABLE_VALUE = 255 class BatchJobExitReason(enum.Enum):", "@abstractmethod def getIssuedBatchJobIDs(self) -> List[int]: \"\"\" Gets all currently issued", "it depends on. \"\"\" raise NotImplementedError() @abstractmethod def issueBatchJob(self, jobDesc:", "said to *shut down* after the last worker process terminates.", "requested in an amount greater than allowed \"\"\" batch_system =", "str \"\"\"used to identify files specific to this workflow\"\"\" cleanWorkDir:", "manager objects to wrap worker work in, in order. Can", ":raise InsufficientSystemResources: raised when a resource is requested in an", "can be displayed to the user to help them diagnose", "batch system. :param float maxCores: the maximum number of cores", "List[int]: \"\"\" Gets all currently issued jobs :return: A list", "of {available} {unit}{resource} of free space on ' f'{self.config.workDir} that", "User-directed message about scheduling state. \"\"\" # Default implementation returns", "requested :param int disk: amount of disk space being requested,", "(not just waiting) and how long they have been running,", "cleaning up a node) that would otherwise require a wrapping", "raise NotImplementedError() @abstractmethod def getRunningBatchJobIDs(self) -> Dict[int, float]: \"\"\" Gets", "AbstractFileStore.shutdownFileStore(workflowDir, info.workflowID) if (info.cleanWorkDir == 'always' or info.cleanWorkDir in ('onSuccess',", "the last job for a particular workflow invocation finishes. Note", "this batch system does not support tracking wall time. \"\"\"", "the autoscaler is ready to terminate a node, but jobs", "A worker process may run more than one job sequentially,", "it is running on but this method makes it possible", "run configuration as a side effect. \"\"\" # TODO: change", "governing permissions and # limitations under the License. import enum", "seconds. :return: dictionary with currently running jobID keys and how", "still running. This allows the node to be terminated after", "import ArgumentParser, _ArgumentGroup from contextlib import contextmanager from typing import", "can be used to report what resource is the limiting", "Protocol to express kwarg names, or else use a #", "overall load. \"\"\" @abstractmethod def getNodes(self, preemptable: Optional[bool] = None)", "on the worker :raise RuntimeError: if value is None and", "use this file except in compliance with the License. #", "ran for, or None if this batch system does not", ":param str job_name: Name of the job being checked, for", "UpdatedBatchJobInfo. Otherwise it returns None. wallTime is the number of", "message about scheduling state. \"\"\" # Default implementation returns None.", "be removed \"\"\" raise NotImplementedError() @abstractmethod def ignoreNode(self, nodeAddress: str)", "information about job that has updated its status (i.e. ceased", "configuring environment variables, hot-deploying user scripts, or cleaning up a", ":param int maxDisk: the maximum amount of disk space the", "a worker process. A worker process may run more than", "system does not support tracking wall time. \"\"\" raise NotImplementedError()", "typically inherit the environment of the machine it is running", "would typically need to copy the variables before enqueuing a", "Dict[str, NodeInfo]: \"\"\" Returns a dictionary mapping node identifiers of", "it will be looked up from the current environment. :param", "def __init__(self, coresUsed: float, memoryUsed: float, coresTotal: float, memoryTotal: int,", "batch system job IDs, for ease of debugging job failures.", "as Python currently allows) base class to represent the interface", "terminate these nodes. In parallel the batch system assigns jobs", "to that script to get parameters for your batch system.", "Type, TypeVar, Union, NamedTuple) from toil.common import Toil, cacheDirName, Config", "in bytes \"\"\" super().__init__() self.config = config self.maxCores = maxCores", ":param: int toil_job_id : The unique id that Toil gives", "specific variables in that inherited environment before the worker is", "or module and the modules it depends on. \"\"\" raise", "function with signature setOption(option_name, parsing_function=None, check_function=None, default=None, env=None) returning nothing,", ":param: string std : The provenance of the stream (for", "list of jobs (as jobIDs) currently issued (may be running,", "FINISHED: int = 1 # Successfully finished. FAILED: int =", "the environment variable given by name will be set to", "' if resource in ('disk', 'memory') else '' R =", "code to that script to get parameters for your batch", "os.listdir(workflowDir) AbstractFileStore.shutdownFileStore(workflowDir, info.workflowID) if (info.cleanWorkDir == 'always' or info.cleanWorkDir in", "\"\"\" raise NotImplementedError() @abstractmethod def nodeInUse(self, nodeIP: str) -> bool:", "provides any command line options, add them to the given", "been running as the value \"\"\" raise NotImplementedError() @abstractmethod def", "block, waiting for a result :return: If a result is", "unique id that Toil gives a job. :param: cluster_job_id :", "message fragment for the user about anything that might be", "as a side effect. \"\"\" # TODO: change type to", "id. :param: string std : The provenance of the stream", "None. This can be used to report what resource is", "hot-deploying user scripts, or cleaning up a node) that would", "is available, return None. This can be used to report", "and only if :meth:`.supportsAutoDeployment` returns True, otherwise it will raise", "method: This will be used as a filter on nodes", "self.memoryUsed = memoryUsed self.coresTotal = coresTotal self.memoryTotal = memoryTotal self.requestedCores", "by name will be set to this value. if None,", "supports auto-deployment of the user script itself. If it does,", "pass def getWorkerContexts(self) -> List[ContextManager[Any]]: \"\"\" Get a list of", "it returns None. wallTime is the number of seconds (a", "Gets all currently issued jobs :return: A list of jobs", "disk, self.maxDisk)]: assert requested is not None if requested >", "the environment \"\"\" if value is None: try: value =", "nodes will be returned. \"\"\" raise NotImplementedError() @abstractmethod def nodeInUse(self,", "str]] = None) -> int: \"\"\" Issues a job with", "in compliance with the License. # You may obtain a", "from getUpdatedBatchJob. :param jobIDs: list of IDs of jobs to", "software # distributed under the License is distributed on an", "\"\"\" assert isinstance(info, WorkerCleanupInfo) workflowDir = Toil.getLocalWorkflowDir(info.workflowID, info.workDir) DeferredFunctionManager.cleanupWorker(workflowDir) workflowDirContents", "for each node. :param preemptable: If True (False) only (non-)preemptable", "detail: Batch-system-specific message to include in the error. :raise InsufficientSystemResources:", "set to this value. if None, the variable's current value", "def __init__(self, config: Config, maxCores: float, maxMemory: int, maxDisk: int)", "Information required for worker cleanup on shutdown of the batch", "concurrent worker process may exist on a worker node, for", "the node's resources, not just the used resources The requestedCores", "[] class BatchSystemSupport(AbstractBatchSystem): \"\"\" Partial implementation of AbstractBatchSystem, support methods.", "have reported to the autoscaler as having no jobs 2)", "the memory pressure on the node. The coresTotal and memoryTotal", "The memoryUsed attribute is a floating point value between 0", "toilSetup script and has configuration parameters for the jobtree. You", "are all the resources that Toil Jobs have reserved on", "\"\"\" Gets all currently issued jobs :return: A list of", "job ran for, or None if this batch system does", "attributes are all the resources that Toil Jobs have reserved", "workflow\"\"\" cleanWorkDir: str class AbstractBatchSystem(ABC): \"\"\" An abstract (as far", "None to be returned earlier than maxWait. :param maxWait: the", "address as a terminated one. \"\"\" raise NotImplementedError() class InsufficientSystemResources(Exception):", "the cluster up or down depending on overall load. \"\"\"", "= '') -> None: \"\"\" Check resource request is not", "successful. EXIT_STATUS_UNAVAILABLE_VALUE is used when the exit status is not", "but this method makes it possible to override specific variables", "a new node having the same address as a terminated", "this value. if None, the variable's current value will be", "being checked, for generating a useful error report. :param str", "node. Call this method prior to node termination to ensure", "used) and 1 (all memory used), reflecting the memory pressure", "and more than one concurrent worker process may exist on", "f'\"--workDir\" or changing the base temporary directory by setting TMPDIR.')", "script. Note to implementors: If your implementation returns True here,", "identifiers of preemptable or non-preemptable nodes to NodeInfo objects, one", "job \"\"\" raise NotImplementedError() @abstractmethod def killBatchJobs(self, jobIDs: List[int]) ->", "same address as a terminated one. \"\"\" raise NotImplementedError() class", "if available. If no useful message is available, return None.", "NodeInfo]: \"\"\" Returns a dictionary mapping node identifiers of preemptable", "signature setOption(option_name, parsing_function=None, check_function=None, default=None, env=None) returning nothing, used to", "a toil invocation. Should cleanly terminate all worker threads. \"\"\"", "up the worker. \"\"\" assert isinstance(info, WorkerCleanupInfo) workflowDir = Toil.getLocalWorkflowDir(info.workflowID,", "value = os.environ[name] except KeyError: raise RuntimeError(f\"{name} does not exist", "to implementors: If your implementation returns True here, it should", "memory the batch system can request for any one job,", "go)\"\"\" workflowID: str \"\"\"used to identify files specific to this", "worker process will typically inherit the environment of the machine", "ERROR: int = 5 # Internal error. MEMLIMIT: int =", "If None, all nodes will be returned. \"\"\" raise NotImplementedError()", "is available, returns UpdatedBatchJobInfo. Otherwise it returns None. wallTime is", "jobID: int exitStatus: int \"\"\" The exit status (integer value)", "for a particular workflow invocation finishes. Note that the term", "to implementors: This means that you would typically need to", "the value on the worker :raise RuntimeError: if value is", "configuration options relevant to this batch system. :param setOption: A", "the batch system itself. Files will be written to the", "environment variable for the worker process before it is launched.", "f'The job {job_name} is r' if job_name else 'R' if", "-> bool: \"\"\" Whether this batch system supports auto-deployment of", "status (i.e. ceased running, either successfully or with an error).", "NotImplementedError() # TODO: May be unused! @abstractmethod @contextmanager def nodeFiltering(self,", "is an integer reflecting the number of workers currently active", "None: \"\"\" Set an environment variable for the worker process", "= TypeVar('OptionType') @classmethod def setOptions(cls, setOption: Callable[[str, Optional[Callable[[Any], OptionType]], Optional[Callable[[OptionType],", "having the same address as a terminated one. \"\"\" raise", "import contextmanager from typing import (Any, Callable, ContextManager, Dict, Iterator,", "default=None, env=None) returning nothing, used to update run configuration as", "with the License. # You may obtain a copy of", "identify files specific to this workflow\"\"\" cleanWorkDir: str class AbstractBatchSystem(ABC):", "2 # Job finished, but failed. LOST: int = 3", "jobDesc a toil.job.JobDescription :param job_environment: a collection of job-specific environment", "exitReason: Optional[BatchJobExitReason] wallTime: Union[float, int, None] # Information required for", "itself. Files will be written to the Toil work directory", "str detail: Batch-system-specific message to include in the error. :raise", "would otherwise require a wrapping \"executor\" process. \"\"\" return []", "current value will be used as the value on the", "Toil work directory (which may be on a shared file", "with this address has been terminated. This allows for the", "coresUsed self.memoryUsed = memoryUsed self.coresTotal = coresTotal self.memoryTotal = memoryTotal", "nodes. Used by :class:`toil. provisioners.clusterScaler.ClusterScaler` to scale the number of", "exception. :param userScript: the resource object representing the user script", "to this method affects all jobs issued after this method", "after the last job for a particular workflow invocation finishes.", "the user script. Note to implementors: If your implementation returns", "License. import enum import logging import os import shutil from", "only (non-)preemptable nodes will be returned. If None, all nodes", "AbstractBatchSystem, support methods. \"\"\" def __init__(self, config: Config, maxCores: float,", "setOption: Callable[[str, Optional[Callable[[Any], OptionType]], Optional[Callable[[OptionType], None]], Optional[OptionType], Optional[List[str]]], None]) ->", "if the worker node has been issued any tasks, else", "considered when assigning new jobs. After this context manager exits", "batch system, and only if :meth:`.supportsAutoDeployment` returns True, otherwise it", "value \"\"\" raise NotImplementedError() @abstractmethod def getUpdatedBatchJob(self, maxWait: int) ->", "in autoscaling where 1) nodes have reported to the autoscaler", "3 # Preemptable failure (job's executing host went away). KILLED:", "node is running any tasks. If the node is doesn't", "given parser. \"\"\" pass OptionType = TypeVar('OptionType') @classmethod def setOptions(cls,", "waiting for a result :return: If a result is available,", "\"\"\" raise NotImplementedError() def setUserScript(self, userScript: Resource) -> None: \"\"\"", "ContextManager, Dict, Iterator, List, Optional, Tuple, Type, TypeVar, Union, NamedTuple)", "toil.resource import Resource logger = logging.getLogger(__name__) # Value to use", "(may be running, or may be waiting to be run).", "express or implied. # See the License for the specific", "GridEngine, uses as its internal job id. :param: string std", "floating point value between 0 (no memory used) and 1", "except in compliance with the License. # You may obtain", "= (f'{R}equesting {requested} {unit}{resource}, more than the maximum of '", "' f'or enforced by --max{resource.capitalize()}.') if detail: msg += detail", "batch system provides any command line options, add them to", "import Toil, cacheDirName, Config from toil.deferred import DeferredFunctionManager from toil.fileStores.abstractFileStore", "and 1 (all memory used), reflecting the memory pressure on", "{batch_system} was configured with, ' f'or enforced by --max{resource.capitalize()}.') if", "assigned new jobs. Call the method again passing None as", "None: \"\"\" Set the user script for this workflow. This", "line options, add them to the given parser. \"\"\" pass", "have reserved on the node, regardless of whether the resources", "parameters for your batch system. :param float maxCores: the maximum", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "= None) -> None: \"\"\" Set an environment variable for", "after the current jobs have finished. :param nodeAddress: IP address", "temporary space, ' f'more than the maximum of {available} {unit}{resource}", "to wrap worker work in, in order. Can be used", "scaler decides to terminate these nodes. In parallel the batch", "exits the filter should be removed \"\"\" raise NotImplementedError() @abstractmethod", "system' for resource, requested, available in [('cores', cores, self.maxCores), ('memory',", "the License. import enum import logging import os import shutil", "workers on the node. \"\"\" def __init__(self, coresUsed: float, memoryUsed:", "current environment. :param str name: the environment variable to be", "of ' if resource in ('disk', 'memory') else '' R", "fileName) @staticmethod def workerCleanup(info: WorkerCleanupInfo) -> None: \"\"\" Cleans up", "\"\"\" return [] class BatchSystemSupport(AbstractBatchSystem): \"\"\" Partial implementation of AbstractBatchSystem,", "the interface the batch system must provide to Toil. \"\"\"", "the exit status is not available (e.g. job is lost).", "or may be waiting to be run). Despite the result", "parameters for the jobtree. You can add code to that", "CONDITIONS OF ANY KIND, either express or implied. # See", "('memory', memory, self.maxMemory), ('disk', disk, self.maxDisk)]: assert requested is not", "'stdout') :rtype: string : Formatted filename; however if self.config.noStdOutErr is", "NotImplementedError() @abstractmethod def issueBatchJob(self, jobDesc: JobDescription, job_environment: Optional[Dict[str, str]] =", "def setUserScript(self, userScript: Resource) -> None: \"\"\" Set the user", "should be a set (then also fix the tests) @abstractmethod", "private IP address :return: True if the worker node has", "setOptions(cls, setOption: Callable[[str, Optional[Callable[[Any], OptionType]], Optional[Callable[[OptionType], None]], Optional[OptionType], Optional[List[str]]], None])", "the Jobs. The workers attribute is an integer reflecting the", "to Toil. \"\"\" @classmethod @abstractmethod def supportsAutoDeployment(cls) -> bool: \"\"\"", "running on but this method makes it possible to override", "filter should be removed \"\"\" raise NotImplementedError() @abstractmethod def ignoreNode(self,", "= None) -> Dict[str, NodeInfo]: \"\"\" Returns a dictionary mapping", "'') -> None: \"\"\" Check resource request is not greater", "in-process (such as configuring environment variables, hot-deploying user scripts, or", "but jobs are still running. This allows the node to", "job for a particular workflow invocation finishes. Note that the", "False. :param nodeIP: The worker nodes private IP address :return:", "used as the value on the worker :raise RuntimeError: if", "being considered for termination are not assigned new jobs. Call", "\"\"\" Issues a job with the specified command to the", "the batch system, if available. If no useful message is", "-> Iterator[None]: \"\"\" Used to prevent races in autoscaling where", "up a node) that would otherwise require a wrapping \"executor\"", "space, ' f'more than the maximum of {available} {unit}{resource} of", "prior to node termination to ensure that nodes being considered", "can request for any one job :param int maxMemory: the", "msg = (f'{R}equesting {requested} {unit}{resource}, more than the maximum of", "what resource is the limiting factor when scheduling jobs, for", "-> None: \"\"\" Set an environment variable for the worker", "load. \"\"\" @abstractmethod def getNodes(self, preemptable: Optional[bool] = None) ->", "requestedCores and requestedMemory attributes are all the resources that Toil", "*worker* refers to an entire node, not just a worker", "for a result :return: If a result is available, returns", "cores idle) and 1 (all cores busy), reflecting the CPU", "= 5 # Internal error. MEMLIMIT: int = 6 #", "will be returned. If None, all nodes will be returned.", ":param toil.common.Config config: object is setup by the toilSetup script", "a node, but jobs are still running. This allows the", "tests) @abstractmethod def getIssuedBatchJobIDs(self) -> List[int]: \"\"\" Gets all currently", "the resources are actually being used by the Jobs. The", "sending jobs to this node. Used in autoscaling when the", "not be returned from getUpdatedBatchJob. :param jobIDs: list of IDs", "This method must be called before the first job is", "__init__(self, config: Config, maxCores: float, maxMemory: int, maxDisk: int) ->", "Stop ignoring this address, presumably after a node with this", "JobDescription, job_environment: Optional[Dict[str, str]] = None) -> int: \"\"\" Issues", "Returns information about job that has updated its status (i.e.", "= requestedMemory self.workers = workers class AbstractScalableBatchSystem(AbstractBatchSystem): \"\"\" A batch", "jobID keys and how many seconds they have been running", "the worker is launched. Note that this mechanism is different", "def getUpdatedBatchJob(self, maxWait: int) -> Optional[UpdatedBatchJobInfo]: \"\"\" Returns information about", "run). Despite the result being a list, the ordering should", "import os import shutil from abc import ABC, abstractmethod from", "True, otherwise it will raise an exception. :param userScript: the", "= maxDisk self.environment: Dict[str, str] = {} self.workerCleanupInfo = WorkerCleanupInfo(workDir=self.config.workDir,", "of free space on ' f'{self.config.workDir} that {batch_system} was configured", "int, requestedCores: float, requestedMemory: int, workers: int) -> None: self.coresUsed", "This will be used as a filter on nodes considered", "the killed jobs will not appear in the results of", "job sequentially, and more than one concurrent worker process may", "with the specified command to the batch system and returns", "or enforced ' f'by --max{resource.capitalize()}. Try setting/changing the toil option", "currently issued (may be running, or may be waiting to", "else False \"\"\" raise NotImplementedError() # TODO: May be unused!", "jobs to this node. Used in autoscaling when the autoscaler", "to disable the filtering after node termination is done. :param", "None: \"\"\" Check resource request is not greater than that", "on nodes considered when assigning new jobs. After this context", "finished. FAILED: int = 2 # Job finished, but failed.", "about scheduling state. \"\"\" # Default implementation returns None. #", "\"\"\" # Default implementation returns None. # Override to provide", "jobs have finished. :param nodeAddress: IP address of node to", "The exit status (integer value) of the job. 0 implies", "attribute is a floating point value between 0 (all cores", "to the given parser. \"\"\" pass OptionType = TypeVar('OptionType') @classmethod", "job {job_name} is r' if job_name else 'R' if resource", "def nodeFiltering(self, filter: Optional[Callable[[NodeInfo], bool]]) -> Iterator[None]: \"\"\" Used to", ":param str detail: Batch-system-specific message to include in the error.", "is the limiting factor when scheduling jobs, for example. If", "away). KILLED: int = 4 # Job killed before finishing.", "of picklable context manager objects to wrap worker work in,", "maxWait: int) -> Optional[UpdatedBatchJobInfo]: \"\"\" Returns information about job that", "workflowID=self.config.workflowID, cleanWorkDir=self.config.cleanWorkDir) def checkResourceRequest(self, memory: int, cores: float, disk: int,", "address :return: True if the worker node has been issued", "require a wrapping \"executor\" process. \"\"\" return [] class BatchSystemSupport(AbstractBatchSystem):", ":param setOption: A function with signature setOption(option_name, parsing_function=None, check_function=None, default=None,", "of the machine it is running on but this method", "batch system must provide to Toil. \"\"\" @classmethod @abstractmethod def", "job IDs, for ease of debugging job failures. :param: int", "cause None to be returned earlier than maxWait. :param maxWait:", "the method again passing None as the filter to disable", "self.coresTotal = coresTotal self.memoryTotal = memoryTotal self.requestedCores = requestedCores self.requestedMemory", "in the error. :raise InsufficientSystemResources: raised when a resource is", "be on a shared file system) with names containing both", "type to a Protocol to express kwarg names, or else", "self.workerCleanupInfo = WorkerCleanupInfo(workDir=self.config.workDir, workflowID=self.config.workflowID, cleanWorkDir=self.config.cleanWorkDir) def checkResourceRequest(self, memory: int, cores:", "variable to be set on the worker. :param str value:", "value is None: try: value = os.environ[name] except KeyError: raise", "the Toil worker to do things in-process (such as configuring", "memoryTotal self.requestedCores = requestedCores self.requestedMemory = requestedMemory self.workers = workers", "-> int: \"\"\" Issues a job with the specified command", "None: \"\"\" Stop ignoring this address, presumably after a node", "node, not just a worker process. A worker process may", "with currently running jobID keys and how many seconds they", "to block, waiting for a result :return: If a result", "nodes will be returned. If None, all nodes will be", "class BatchJobExitReason(enum.Enum): FINISHED: int = 1 # Successfully finished. FAILED:", "configuration as a side effect. \"\"\" # TODO: change type", "variable given by name will be set to this value.", "your batch system. :param float maxCores: the maximum number of", "by the batch system itself. Files will be written to", "long they have been running, in seconds. :return: dictionary with", "else '' R = f'The job {job_name} is r' if", "Whether this batch system supports auto-deployment of the user script", "(False) only (non-)preemptable nodes will be returned. If None, all", "cleanWorkDir: str class AbstractBatchSystem(ABC): \"\"\" An abstract (as far as", "being requested :param int disk: amount of disk space being", "List, Optional, Tuple, Type, TypeVar, Union, NamedTuple) from toil.common import", "one job sequentially, and more than one concurrent worker process", "with an error). Each such job will be returned exactly", "environment variable given by name will be set to this", "cores: number of cores being requested :param int disk: amount", "memoryUsed: float, coresTotal: float, memoryTotal: int, requestedCores: float, requestedMemory: int,", "as a filter on nodes considered when assigning new jobs.", "system supports auto-deployment of the user script itself. If it", "bool: \"\"\" Indicates whether this batch system invokes :meth:`BatchSystemSupport.workerCleanup` after", "returns a unique jobID. :param jobDesc a toil.job.JobDescription :param job_environment:", "ceased running, either successfully or with an error). Each such", "float, memoryUsed: float, coresTotal: float, memoryTotal: int, requestedCores: float, requestedMemory:", "entire node, not just a worker process. A worker process", "implementation returns None. # Override to provide scheduling status information.", "int maxDisk: the maximum amount of disk space the batch", "in current environment\") self.environment[name] = value def formatStdOutErrPath(self, toil_job_id: int,", "for cleaning up the worker. \"\"\" assert isinstance(info, WorkerCleanupInfo) workflowDir", "cluster_job_id : What the cluster, for example, GridEngine, uses as", "class BatchSystemSupport(AbstractBatchSystem): \"\"\" Partial implementation of AbstractBatchSystem, support methods. \"\"\"", "can request for any one job, in bytes \"\"\" super().__init__()", ":meth:`.supportsAutoDeployment` returns True, otherwise it will raise an exception. :param", "\"\"\" def __init__(self, config: Config, maxCores: float, maxMemory: int, maxDisk:", "# Copyright (C) 2015-2021 Regents of the University of California", "request for any one job :param int maxMemory: the maximum", "in the batch system, if available. If no useful message", "this function should simply return False. :param nodeIP: The worker", "workflowDir = Toil.getLocalWorkflowDir(info.workflowID, info.workDir) DeferredFunctionManager.cleanupWorker(workflowDir) workflowDirContents = os.listdir(workflowDir) AbstractFileStore.shutdownFileStore(workflowDir, info.workflowID)", "Can be used to ask the Toil worker to do", "limitations under the License. import enum import logging import os", "@abstractmethod @contextmanager def nodeFiltering(self, filter: Optional[Callable[[NodeInfo], bool]]) -> Iterator[None]: \"\"\"", "typing import (Any, Callable, ContextManager, Dict, Iterator, List, Optional, Tuple,", "have been running, in seconds. :return: dictionary with currently running", "object :param toil.common.Config config: object is setup by the toilSetup", "being used by the Jobs. The workers attribute is an", "node with this address has been terminated. This allows for", "the toilSetup script and has configuration parameters for the jobtree.", "reported to the autoscaler as having no jobs 2) scaler", "raise NotImplementedError() # TODO: May be unused! @abstractmethod @contextmanager def", "down depending on overall load. \"\"\" @abstractmethod def getNodes(self, preemptable:", "if value is None: try: value = os.environ[name] except KeyError:", "# Value to use as exitStatus in UpdatedBatchJobInfo.exitStatus when status", "it will be looked up from the current environment. \"\"\"", "job_name else 'R' if resource == 'disk': msg = (f'{R}equesting", "a job with the specified command to the batch system", "\"\"\" @classmethod @abstractmethod def supportsAutoDeployment(cls) -> bool: \"\"\" Whether this", "or 'this batch system' for resource, requested, available in [('cores',", ":return: User-directed message about scheduling state. \"\"\" # Default implementation", "int) -> None: self.coresUsed = coresUsed self.memoryUsed = memoryUsed self.coresTotal", "IP address of node to ignore. \"\"\" raise NotImplementedError() @abstractmethod", "worker :raise RuntimeError: if value is None and the name", "WorkerCleanupInfo) workflowDir = Toil.getLocalWorkflowDir(info.workflowID, info.workDir) DeferredFunctionManager.cleanupWorker(workflowDir) workflowDirContents = os.listdir(workflowDir) AbstractFileStore.shutdownFileStore(workflowDir,", "job will be returned exactly once. Does not return info", "EXIT_STATUS_UNAVAILABLE_VALUE is used when the exit status is not available", "terminate a node, but jobs are still running. This allows", "for any one job, in bytes \"\"\" super().__init__() self.config =", "down* after the last worker process terminates. \"\"\" raise NotImplementedError()", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "str = f'toil_{self.config.workflowID}.{toil_job_id}.{cluster_job_id}.{std}.log' workDir: str = Toil.getToilWorkDir(self.config.workDir) return os.path.join(workDir, fileName)", "system that supports a variable number of worker nodes. Used", "str \"\"\"workdir path (where the cache would go)\"\"\" workflowID: str", "A function with signature setOption(option_name, parsing_function=None, check_function=None, default=None, env=None) returning", "express kwarg names, or else use a # different interface", "wrapping \"executor\" process. \"\"\" return [] class BatchSystemSupport(AbstractBatchSystem): \"\"\" Partial", "' f'{available} {unit}{resource} that {batch_system} was configured with, ' f'or", "a job. A call to this method affects all jobs", "# Job finished, but failed. LOST: int = 3 #", "wall time. \"\"\" raise NotImplementedError() def getSchedulingStatusMessage(self) -> Optional[str]: \"\"\"", "time the job ran for, or None if this batch", "WorkerCleanupInfo info: A named tuple consisting of all the relevant", "# Override to provide scheduling status information. return None @abstractmethod", "be returned from getUpdatedBatchJob. :param jobIDs: list of IDs of", "will raise an exception. :param userScript: the resource object representing", "of debugging job failures. :param: int toil_job_id : The unique", "cleanWorkDir=self.config.cleanWorkDir) def checkResourceRequest(self, memory: int, cores: float, disk: int, job_name:", "but failed. LOST: int = 3 # Preemptable failure (job's", "this method affects all jobs issued after this method returns.", "than that available or allowed. :param int memory: amount of", "call to this method affects all jobs issued after this", "provenance of the stream (for example: 'err' for 'stderr' or", "@abstractmethod def supportsWorkerCleanup(cls) -> bool: \"\"\" Indicates whether this batch", "job will not be returned from getUpdatedBatchJob. :param jobIDs: list", "floating point value between 0 (all cores idle) and 1", "Callable[[str, Optional[Callable[[Any], OptionType]], Optional[Callable[[OptionType], None]], Optional[OptionType], Optional[List[str]]], None]) -> None:", "def ignoreNode(self, nodeAddress: str) -> None: \"\"\" Stop sending jobs", "is requested in an amount greater than allowed \"\"\" batch_system", "of California # # Licensed under the Apache License, Version", "the stream (for example: 'err' for 'stderr' or 'out' for", "Version 2.0 (the \"License\"); # you may not use this", "any one job, in bytes \"\"\" super().__init__() self.config = config", "that script to get parameters for your batch system. :param", "nothing, used to update run configuration as a side effect.", "for batch system standard output/error and other files generated by", "Optional[Dict[str, str]] = None) -> int: \"\"\" Issues a job", "that nodes being considered for termination are not assigned new", "cores the batch system can request for any one job", "override specific variables in that inherited environment before the worker", "one for each node. :param preemptable: If True (False) only", "a shared file system) with names containing both the Toil", "f'{available} {unit}{resource} that {batch_system} was configured with, ' f'or enforced", "waiting to be run). Despite the result being a list,", "a result is available, returns UpdatedBatchJobInfo. Otherwise it returns None.", "False \"\"\" raise NotImplementedError() # TODO: May be unused! @abstractmethod", "Process command line or configuration options relevant to this batch", "number of cores the batch system can request for any", "the same address as a terminated one. \"\"\" raise NotImplementedError()", "presumably after a node with this address has been terminated.", "same workflow. The batch system is said to *shut down*", "running. This allows the node to be terminated after the", "the batch system can request for any one job :param", "be invoked to set the resource object representing the user", "filter to disable the filtering after node termination is done.", "by applicable law or agreed to in writing, software #", ":param nodeAddress: IP address of node to ignore. \"\"\" raise", "all nodes will be returned. \"\"\" raise NotImplementedError() @abstractmethod def", "the completion of a toil invocation. Should cleanly terminate all", "that you would typically need to copy the variables before", "# Job hit batch system imposed memory limit class UpdatedBatchJobInfo(NamedTuple):", "cores busy), reflecting the CPU load of the node. The", "0 (no memory used) and 1 (all memory used), reflecting", "jobs killed by killBatchJobs, although they may cause None to", "{job_name} is r' if job_name else 'R' if resource ==", "the maximum number of cores the batch system can request", "return None @abstractmethod def shutdown(self) -> None: \"\"\" Called at", "NotImplementedError() @classmethod @abstractmethod def supportsWorkerCleanup(cls) -> bool: \"\"\" Indicates whether", "error. :raise InsufficientSystemResources: raised when a resource is requested in", "maximum amount of memory the batch system can request for", "for the jobtree. You can add code to that script", "method affects all jobs issued after this method returns. Note", "of the object :param toil.common.Config config: object is setup by", "'onError') and workflowDirContents in ([], [cacheDirName(info.workflowID)])): shutil.rmtree(workflowDir, ignore_errors=True) class NodeInfo:", "may be waiting to be run). Despite the result being", "(generator?) pass def getWorkerContexts(self) -> List[ContextManager[Any]]: \"\"\" Get a list", "str, value: Optional[str] = None) -> None: \"\"\" Set an", "int, None] # Information required for worker cleanup on shutdown", "running, or may be waiting to be run). Despite the", "going wrong in the batch system, if available. If no", "toil_job_id: int, cluster_job_id: str, std: str) -> str: \"\"\" Format", "system assigns jobs to the same nodes 3) scaler terminates", "script itself. If it does, the :meth:`.setUserScript` can be invoked", "None: \"\"\" Process command line or configuration options relevant to", "If this batch system provides any command line options, add", "the cache would go)\"\"\" workflowID: str \"\"\"used to identify files", "up from the current environment. :param str name: the environment", "batch system' for resource, requested, available in [('cores', cores, self.maxCores),", "system provides any command line options, add them to the", "current environment\") self.environment[name] = value def formatStdOutErrPath(self, toil_job_id: int, cluster_job_id:", "to terminate a node, but jobs are still running. This", "containing both the Toil and batch system job IDs, for", "to determine if a worker node is running any tasks.", "last worker process terminates. \"\"\" raise NotImplementedError() def setUserScript(self, userScript:", "the Toil work directory (which may be on a shared", "error report. :param str detail: Batch-system-specific message to include in", "this method prior to node termination to ensure that nodes", "if resource == 'disk': msg = (f'{R}equesting {requested} {unit}{resource} for", "node. The coresTotal and memoryTotal attributes are the node's resources,", "Tuple, Type, TypeVar, Union, NamedTuple) from toil.common import Toil, cacheDirName,", "str name: the environment variable to be set on the", "raise NotImplementedError() @classmethod def add_options(cls, parser: Union[ArgumentParser, _ArgumentGroup]) -> None:", "be returned earlier than maxWait. :param maxWait: the number of", "is doesn't exist, this function should simply return False. :param", "NotImplementedError() @abstractmethod def unignoreNode(self, nodeAddress: str) -> None: \"\"\" Stop", "stream (for example: 'err' for 'stderr' or 'out' for 'stdout')", "memory: amount of memory being requested, in bytes :param float", "system) with names containing both the Toil and batch system", "that Toil Jobs have reserved on the node, regardless of", "else 'R' if resource == 'disk': msg = (f'{R}equesting {requested}", "applicable law or agreed to in writing, software # distributed", "used by the worker internally to set up the environment", "True if the worker node has been issued any tasks,", "to the user to help them diagnose why it might", "# Default implementation returns None. # Override to provide scheduling", "have been running as the value \"\"\" raise NotImplementedError() @abstractmethod", "or with an error). Each such job will be returned", "each node. :param preemptable: If True (False) only (non-)preemptable nodes", "returned. If None, all nodes will be returned. \"\"\" raise", "will be used as a filter on nodes considered when", "files specific to this workflow\"\"\" cleanWorkDir: str class AbstractBatchSystem(ABC): \"\"\"", "be waiting to be run). Despite the result being a", "'stderr' or 'out' for 'stdout') :rtype: string : Formatted filename;", "batch system that supports a variable number of worker nodes.", "supports a variable number of worker nodes. Used by :class:`toil.", "(i.e. ceased running, either successfully or with an error). Each", "under the License. import enum import logging import os import", "will be returned exactly once. Does not return info for", "an exception. :param userScript: the resource object representing the user", "your implementation returns True here, it should also override \"\"\"", "cores being requested :param int disk: amount of disk space", "= config self.maxCores = maxCores self.maxMemory = maxMemory self.maxDisk =", "the user script or module and the modules it depends", "the worker. \"\"\" assert isinstance(info, WorkerCleanupInfo) workflowDir = Toil.getLocalWorkflowDir(info.workflowID, info.workDir)", "internal job id. :param: string std : The provenance of", "Optional[UpdatedBatchJobInfo]: \"\"\" Returns information about job that has updated its", "has been terminated. This allows for the possibility of a", "be used as a filter on nodes considered when assigning", "IDs of jobs to kill \"\"\" raise NotImplementedError() # FIXME:", "None]], Optional[OptionType], Optional[List[str]]], None]) -> None: \"\"\" Process command line", "running, in seconds. :return: dictionary with currently running jobID keys", "on that node. Call this method prior to node termination", "# You may obtain a copy of the License at", "\"\"\" Set the user script for this workflow. This method", "str) -> None: \"\"\" Stop ignoring this address, presumably after", "be used as the value on the worker :raise RuntimeError:", "represent the interface the batch system must provide to Toil.", "used to update run configuration as a side effect. \"\"\"", "University of California # # Licensed under the Apache License,", "Formatted filename; however if self.config.noStdOutErr is true, returns '/dev/null' or", "UpdatedBatchJobInfo(NamedTuple): jobID: int exitStatus: int \"\"\" The exit status (integer", "getWorkerContexts(self) -> List[ContextManager[Any]]: \"\"\" Get a list of picklable context", "requested > available: unit = 'bytes of ' if resource", "host went away). KILLED: int = 4 # Job killed", "up or down depending on overall load. \"\"\" @abstractmethod def", "imposed memory limit class UpdatedBatchJobInfo(NamedTuple): jobID: int exitStatus: int \"\"\"", "method again passing None as the filter to disable the", "standard output/error and other files generated by the batch system", "integer reflecting the number of workers currently active workers on", "on the node, regardless of whether the resources are actually", "= 2 # Job finished, but failed. LOST: int =", "having no jobs 2) scaler decides to terminate these nodes.", "toil option ' f'\"--workDir\" or changing the base temporary directory", "jobs to kill \"\"\" raise NotImplementedError() # FIXME: Return value", ":param int maxMemory: the maximum amount of memory the batch", "updated its status (i.e. ceased running, either successfully or with", "here, it should also override \"\"\" raise NotImplementedError() @classmethod @abstractmethod", "node) that would otherwise require a wrapping \"executor\" process. \"\"\"", "and workflowDirContents in ([], [cacheDirName(info.workflowID)])): shutil.rmtree(workflowDir, ignore_errors=True) class NodeInfo: \"\"\"", "its status (i.e. ceased running, either successfully or with an", "Note that the term *worker* refers to an entire node,", "this workflow\"\"\" cleanWorkDir: str class AbstractBatchSystem(ABC): \"\"\" An abstract (as", "Resource logger = logging.getLogger(__name__) # Value to use as exitStatus", "# Job killed before finishing. ERROR: int = 5 #", "is different to the one used by the worker internally", "int = 1 # Successfully finished. FAILED: int = 2", "reflecting the CPU load of the node. The memoryUsed attribute", "Does not return info for jobs killed by killBatchJobs, although", "Union, NamedTuple) from toil.common import Toil, cacheDirName, Config from toil.deferred", "point value between 0 (all cores idle) and 1 (all", "returned. \"\"\" raise NotImplementedError() @abstractmethod def nodeInUse(self, nodeIP: str) ->", "failures for all jobs on that node. Call this method", "for the worker process before it is launched. The worker", "def getSchedulingStatusMessage(self) -> Optional[str]: \"\"\" Get a log message fragment", "of whether the resources are actually being used by the", "information. return None @abstractmethod def shutdown(self) -> None: \"\"\" Called", "Set an environment variable for the worker process before it", "If your implementation returns True here, it should also override", "def shutdown(self) -> None: \"\"\" Called at the completion of", "wall-clock time the job ran for, or None if this", ":return: True if the worker node has been issued any", "job_name: str = '', detail: str = '') -> None:", "\"\"\" Check resource request is not greater than that available", "how long they have been running, in seconds. :return: dictionary", "str = '') -> None: \"\"\" Check resource request is", "is done. :param method: This will be used as a", "detail: msg += detail raise InsufficientSystemResources(msg) def setEnv(self, name: str,", "currently allows) base class to represent the interface the batch", "not available. EXIT_STATUS_UNAVAILABLE_VALUE = 255 class BatchJobExitReason(enum.Enum): FINISHED: int =", "info for jobs killed by killBatchJobs, although they may cause", "if detail: msg += detail raise InsufficientSystemResources(msg) def setEnv(self, name:", "\"\"\" Returns information about job that has updated its status", "(f'{R}equesting {requested} {unit}{resource} for temporary space, ' f'more than the", "\"License\"); # you may not use this file except in", "self.coresUsed = coresUsed self.memoryUsed = memoryUsed self.coresTotal = coresTotal self.memoryTotal", "returning, the killed jobs will not appear in the results", "does not exist in current environment\") self.environment[name] = value def", "stuck. :return: User-directed message about scheduling state. \"\"\" # Default", "raise NotImplementedError() @classmethod @abstractmethod def supportsWorkerCleanup(cls) -> bool: \"\"\" Indicates", ":param int disk: amount of disk space being requested, in", "jobs are still running. This allows the node to be", "node to be terminated after the current jobs have finished.", "self.requestedMemory = requestedMemory self.workers = workers class AbstractScalableBatchSystem(AbstractBatchSystem): \"\"\" A", "None @abstractmethod def shutdown(self) -> None: \"\"\" Called at the", "be going wrong in the batch system, if available. If", "setEnv(self, name: str, value: Optional[str] = None) -> None: \"\"\"", "are the node's resources, not just the used resources The", "node, regardless of whether the resources are actually being used", "self.config.noStdOutErr: return os.devnull fileName: str = f'toil_{self.config.workflowID}.{toil_job_id}.{cluster_job_id}.{std}.log' workDir: str =", "status is not available. EXIT_STATUS_UNAVAILABLE_VALUE = 255 class BatchJobExitReason(enum.Enum): FINISHED:", "nodeAddress: IP address of node to ignore. \"\"\" raise NotImplementedError()", "directory (which may be on a shared file system) with", "requested is not None if requested > available: unit =", "of seconds to block, waiting for a result :return: If", "load of the node. The memoryUsed attribute is a floating", "be returned. \"\"\" raise NotImplementedError() @abstractmethod def nodeInUse(self, nodeIP: str)", "float, maxMemory: int, maxDisk: int) -> None: \"\"\" Initializes initial", "than the maximum of {available} {unit}{resource} of free space on", "\"\"\" exitReason: Optional[BatchJobExitReason] wallTime: Union[float, int, None] # Information required", "particular workflow invocation finishes. Note that the term *worker* refers", "Also see :meth:`supportsWorkerCleanup`. :param WorkerCleanupInfo info: A named tuple consisting", "as having no jobs 2) scaler decides to terminate these", "value: Optional[str] = None) -> None: \"\"\" Set an environment", "int) -> None: \"\"\" Initializes initial state of the object", "between 0 (no memory used) and 1 (all memory used)," ]
[ "# -*- coding: utf-8 -*- from lite_tools import get_md5, get_sha,", "b'dGVzdF9pbmZvcm1hdGlvbg==' res_b32_encode = get_b64e(s, mode=32) # default mode=64 // mode:", "mode=256 // mode: 224 256 384 512 print(get_sha3(s, mode=384)) #", "64 85 print(res_b32_encode) # ORSXG5C7NFXGM33SNVQXI2LPNY====== res_b64_decode = get_b64d(res_b64_encode) print(res_b64_decode) #", "1 224 256 384 512 print(get_sha3(s)) # 9c539ca35c6719f546e67837ff37fe7791e53fe40715cd4da0167c78c9adc2e8 print(get_sha3(s, to_bin=True))", "about hashlib ==> get_md5, get_sha, get_sha3 || default mode=256 s", "= get_b64e(s) print(res_b64_encode) # dGVzdF9pbmZvcm1hdGlvbg== res_b64_bin = get_b64e(s, to_bin=True) print(res_b64_bin)", "print(get_sha3(s, mode=1)) # return \"\" // SUPPORT: sha3_224 sha3_256 sha3_384", "384 512 print(get_sha3(s, mode=384)) # 95c09e20a139843eae877a64cd95d6a629b3c9ff383b5460557aab2612682d4228d05fe41606a79acf5ae1c4de35160c # about base64 ==>", "224 256 384 512 # default mode=256 // mode: 224", "mode=32) # default mode=64 // mode: 16 32 64 85", "s = \"test_information\" # 这里只能丢字符串 print(get_md5(s)) # 5414ffd88fcb58417e64ecec51bb3a6b print(get_md5(s, upper=True))", "SUPPORT: sha3_224 sha3_256 sha3_384 sha3_512// only need inputting: 224 256", "coding: utf-8 -*- from lite_tools import get_md5, get_sha, get_sha3, get_b64e,", "\"test_information\" # 这里只能丢字符串 print(get_md5(s)) # 5414ffd88fcb58417e64ecec51bb3a6b print(get_md5(s, upper=True)) # 5414FFD88FCB58417E64ECEC51BB3A6B", "default mode=256 // mode: 1 224 256 384 512 print(get_sha3(s))", "# 5414ffd88fcb58417e64ecec51bb3a6b print(get_md5(s, upper=True)) # 5414FFD88FCB58417E64ECEC51BB3A6B print(get_md5(s, to_bin=True)) # b'T\\x14\\xff\\xd8\\x8f\\xcbXA~d\\xec\\xecQ\\xbb:k'", "sha3_256 sha3_384 sha3_512// only need inputting: 224 256 384 512", "print(res_b64_decode) # test_information res_b32_decode = get_b64d(res_b32_encode, mode=32) # default mode=64", "res_b64_decode = get_b64d(res_b64_encode) print(res_b64_decode) # test_information res_b32_decode = get_b64d(res_b32_encode, mode=32)", "// SUPPORT: sha3_224 sha3_256 sha3_384 sha3_512// only need inputting: 224", "sha3_384 sha3_512// only need inputting: 224 256 384 512 #", "# about base64 ==> get_b64e, get_b64d res_b64_encode = get_b64e(s) print(res_b64_encode)", "// mode: 16 32 64 85 print(res_b32_encode) # ORSXG5C7NFXGM33SNVQXI2LPNY====== res_b64_decode", "print(res_b64_bin) # b'dGVzdF9pbmZvcm1hdGlvbg==' res_b32_encode = get_b64e(s, mode=32) # default mode=64", "default mode=64 // mode: 16 32 64 85 print(res_b32_encode) #", "sha3_224 sha3_256 sha3_384 sha3_512// only need inputting: 224 256 384", "95c09e20a139843eae877a64cd95d6a629b3c9ff383b5460557aab2612682d4228d05fe41606a79acf5ae1c4de35160c # about base64 ==> get_b64e, get_b64d res_b64_encode = get_b64e(s)", "384 512 print(get_sha3(s)) # 9c539ca35c6719f546e67837ff37fe7791e53fe40715cd4da0167c78c9adc2e8 print(get_sha3(s, to_bin=True)) # b'\\x9cS\\x9c\\xa3\\\\g\\x19\\xf5F\\xe6x7\\xff7\\xfew\\x91\\xe5?\\xe4\\x07\\x15\\xcdM\\xa0\\x16|x\\xc9\\xad\\xc2\\xe8' print(get_sha3(s,", "get_b64e(s, to_bin=True) print(res_b64_bin) # b'dGVzdF9pbmZvcm1hdGlvbg==' res_b32_encode = get_b64e(s, mode=32) #", "inputting: 224 256 384 512 # default mode=256 // mode:", "only need inputting: 224 256 384 512 # default mode=256", "# 95c09e20a139843eae877a64cd95d6a629b3c9ff383b5460557aab2612682d4228d05fe41606a79acf5ae1c4de35160c # about base64 ==> get_b64e, get_b64d res_b64_encode =", "print(get_sha(s, to_bin=True)) # b'\\xd0\\x98i\\xfd\\xf9\\x01F\\\\\\x85f\\xf0\\xe2\\xde\\xbf\\xa3\\xf6\\xa3\\xd8x\\xa8\\x15~\\x19\\x9c|Lm\\xd7Ua\\x7f3' print(get_sha(s, mode=1)) # ada5dfdf0c9a76a84958310b838a70b6fd6d01f6 # default", "return \"\" // SUPPORT: sha3_224 sha3_256 sha3_384 sha3_512// only need", "utf-8 -*- from lite_tools import get_md5, get_sha, get_sha3, get_b64e, get_b64d", "get_b64e, get_b64d res_b64_encode = get_b64e(s) print(res_b64_encode) # dGVzdF9pbmZvcm1hdGlvbg== res_b64_bin =", "-*- from lite_tools import get_md5, get_sha, get_sha3, get_b64e, get_b64d #", "转成二进制的需求没什么用但是可以保留 print(get_sha(s)) # d09869fdf901465c8566f0e2debfa3f6a3d878a8157e199c7c4c6dd755617f33 print(get_sha(s, to_bin=True)) # b'\\xd0\\x98i\\xfd\\xf9\\x01F\\\\\\x85f\\xf0\\xe2\\xde\\xbf\\xa3\\xf6\\xa3\\xd8x\\xa8\\x15~\\x19\\x9c|Lm\\xd7Ua\\x7f3' print(get_sha(s, mode=1))", "# default mode=64 // mode: 16 32 64 85 print(res_b32_encode)", "mode=256 s = \"test_information\" # 这里只能丢字符串 print(get_md5(s)) # 5414ffd88fcb58417e64ecec51bb3a6b print(get_md5(s,", "512 print(get_sha3(s, mode=384)) # 95c09e20a139843eae877a64cd95d6a629b3c9ff383b5460557aab2612682d4228d05fe41606a79acf5ae1c4de35160c # about base64 ==> get_b64e,", "-*- coding: utf-8 -*- from lite_tools import get_md5, get_sha, get_sha3,", "get_sha3 || default mode=256 s = \"test_information\" # 这里只能丢字符串 print(get_md5(s))", "mode=256 // mode: 1 224 256 384 512 print(get_sha3(s)) #", "# b'dGVzdF9pbmZvcm1hdGlvbg==' res_b32_encode = get_b64e(s, mode=32) # default mode=64 //", "print(get_md5(s, to_bin=True)) # b'T\\x14\\xff\\xd8\\x8f\\xcbXA~d\\xec\\xecQ\\xbb:k' # 转成二进制的需求没什么用但是可以保留 print(get_sha(s)) # d09869fdf901465c8566f0e2debfa3f6a3d878a8157e199c7c4c6dd755617f33 print(get_sha(s,", "print(get_sha3(s, to_bin=True)) # b'\\x9cS\\x9c\\xa3\\\\g\\x19\\xf5F\\xe6x7\\xff7\\xfew\\x91\\xe5?\\xe4\\x07\\x15\\xcdM\\xa0\\x16|x\\xc9\\xad\\xc2\\xe8' print(get_sha3(s, mode=1)) # return \"\" //", "mode=384)) # 95c09e20a139843eae877a64cd95d6a629b3c9ff383b5460557aab2612682d4228d05fe41606a79acf5ae1c4de35160c # about base64 ==> get_b64e, get_b64d res_b64_encode", "# default mode=64 // mode: 16 32 64 85 print(res_b32_decode)", "9c539ca35c6719f546e67837ff37fe7791e53fe40715cd4da0167c78c9adc2e8 print(get_sha3(s, to_bin=True)) # b'\\x9cS\\x9c\\xa3\\\\g\\x19\\xf5F\\xe6x7\\xff7\\xfew\\x91\\xe5?\\xe4\\x07\\x15\\xcdM\\xa0\\x16|x\\xc9\\xad\\xc2\\xe8' print(get_sha3(s, mode=1)) # return \"\"", "32 64 85 print(res_b32_encode) # ORSXG5C7NFXGM33SNVQXI2LPNY====== res_b64_decode = get_b64d(res_b64_encode) print(res_b64_decode)", "这里只能丢字符串 print(get_md5(s)) # 5414ffd88fcb58417e64ecec51bb3a6b print(get_md5(s, upper=True)) # 5414FFD88FCB58417E64ECEC51BB3A6B print(get_md5(s, to_bin=True))", "lite_tools import get_md5, get_sha, get_sha3, get_b64e, get_b64d # about hashlib", "256 384 512 print(get_sha3(s)) # 9c539ca35c6719f546e67837ff37fe7791e53fe40715cd4da0167c78c9adc2e8 print(get_sha3(s, to_bin=True)) # b'\\x9cS\\x9c\\xa3\\\\g\\x19\\xf5F\\xe6x7\\xff7\\xfew\\x91\\xe5?\\xe4\\x07\\x15\\xcdM\\xa0\\x16|x\\xc9\\xad\\xc2\\xe8'", "upper=True)) # 5414FFD88FCB58417E64ECEC51BB3A6B print(get_md5(s, to_bin=True)) # b'T\\x14\\xff\\xd8\\x8f\\xcbXA~d\\xec\\xecQ\\xbb:k' # 转成二进制的需求没什么用但是可以保留 print(get_sha(s))", "print(get_sha3(s, mode=384)) # 95c09e20a139843eae877a64cd95d6a629b3c9ff383b5460557aab2612682d4228d05fe41606a79acf5ae1c4de35160c # about base64 ==> get_b64e, get_b64d", "256 384 512 print(get_sha3(s, mode=384)) # 95c09e20a139843eae877a64cd95d6a629b3c9ff383b5460557aab2612682d4228d05fe41606a79acf5ae1c4de35160c # about base64", "get_b64e, get_b64d # about hashlib ==> get_md5, get_sha, get_sha3 ||", "mode=1)) # return \"\" // SUPPORT: sha3_224 sha3_256 sha3_384 sha3_512//", "get_b64e(s, mode=32) # default mode=64 // mode: 16 32 64", "res_b32_encode = get_b64e(s, mode=32) # default mode=64 // mode: 16", "# b'T\\x14\\xff\\xd8\\x8f\\xcbXA~d\\xec\\xecQ\\xbb:k' # 转成二进制的需求没什么用但是可以保留 print(get_sha(s)) # d09869fdf901465c8566f0e2debfa3f6a3d878a8157e199c7c4c6dd755617f33 print(get_sha(s, to_bin=True)) #", "# b'\\xd0\\x98i\\xfd\\xf9\\x01F\\\\\\x85f\\xf0\\xe2\\xde\\xbf\\xa3\\xf6\\xa3\\xd8x\\xa8\\x15~\\x19\\x9c|Lm\\xd7Ua\\x7f3' print(get_sha(s, mode=1)) # ada5dfdf0c9a76a84958310b838a70b6fd6d01f6 # default mode=256 //", "get_sha3, get_b64e, get_b64d # about hashlib ==> get_md5, get_sha, get_sha3", "# ada5dfdf0c9a76a84958310b838a70b6fd6d01f6 # default mode=256 // mode: 1 224 256", "512 print(get_sha3(s)) # 9c539ca35c6719f546e67837ff37fe7791e53fe40715cd4da0167c78c9adc2e8 print(get_sha3(s, to_bin=True)) # b'\\x9cS\\x9c\\xa3\\\\g\\x19\\xf5F\\xe6x7\\xff7\\xfew\\x91\\xe5?\\xe4\\x07\\x15\\xcdM\\xa0\\x16|x\\xc9\\xad\\xc2\\xe8' print(get_sha3(s, mode=1))", "to_bin=True)) # b'\\x9cS\\x9c\\xa3\\\\g\\x19\\xf5F\\xe6x7\\xff7\\xfew\\x91\\xe5?\\xe4\\x07\\x15\\xcdM\\xa0\\x16|x\\xc9\\xad\\xc2\\xe8' print(get_sha3(s, mode=1)) # return \"\" // SUPPORT:", "= \"test_information\" # 这里只能丢字符串 print(get_md5(s)) # 5414ffd88fcb58417e64ecec51bb3a6b print(get_md5(s, upper=True)) #", "default mode=256 s = \"test_information\" # 这里只能丢字符串 print(get_md5(s)) # 5414ffd88fcb58417e64ecec51bb3a6b", "b'T\\x14\\xff\\xd8\\x8f\\xcbXA~d\\xec\\xecQ\\xbb:k' # 转成二进制的需求没什么用但是可以保留 print(get_sha(s)) # d09869fdf901465c8566f0e2debfa3f6a3d878a8157e199c7c4c6dd755617f33 print(get_sha(s, to_bin=True)) # b'\\xd0\\x98i\\xfd\\xf9\\x01F\\\\\\x85f\\xf0\\xe2\\xde\\xbf\\xa3\\xf6\\xa3\\xd8x\\xa8\\x15~\\x19\\x9c|Lm\\xd7Ua\\x7f3'", "get_b64d res_b64_encode = get_b64e(s) print(res_b64_encode) # dGVzdF9pbmZvcm1hdGlvbg== res_b64_bin = get_b64e(s,", "5414FFD88FCB58417E64ECEC51BB3A6B print(get_md5(s, to_bin=True)) # b'T\\x14\\xff\\xd8\\x8f\\xcbXA~d\\xec\\xecQ\\xbb:k' # 转成二进制的需求没什么用但是可以保留 print(get_sha(s)) # d09869fdf901465c8566f0e2debfa3f6a3d878a8157e199c7c4c6dd755617f33", "get_md5, get_sha, get_sha3, get_b64e, get_b64d # about hashlib ==> get_md5,", "# 9c539ca35c6719f546e67837ff37fe7791e53fe40715cd4da0167c78c9adc2e8 print(get_sha3(s, to_bin=True)) # b'\\x9cS\\x9c\\xa3\\\\g\\x19\\xf5F\\xe6x7\\xff7\\xfew\\x91\\xe5?\\xe4\\x07\\x15\\xcdM\\xa0\\x16|x\\xc9\\xad\\xc2\\xe8' print(get_sha3(s, mode=1)) # return", "print(res_b64_encode) # dGVzdF9pbmZvcm1hdGlvbg== res_b64_bin = get_b64e(s, to_bin=True) print(res_b64_bin) # b'dGVzdF9pbmZvcm1hdGlvbg=='", "mode=1)) # ada5dfdf0c9a76a84958310b838a70b6fd6d01f6 # default mode=256 // mode: 1 224", "ORSXG5C7NFXGM33SNVQXI2LPNY====== res_b64_decode = get_b64d(res_b64_encode) print(res_b64_decode) # test_information res_b32_decode = get_b64d(res_b32_encode,", "print(get_sha(s, mode=1)) # ada5dfdf0c9a76a84958310b838a70b6fd6d01f6 # default mode=256 // mode: 1", "d09869fdf901465c8566f0e2debfa3f6a3d878a8157e199c7c4c6dd755617f33 print(get_sha(s, to_bin=True)) # b'\\xd0\\x98i\\xfd\\xf9\\x01F\\\\\\x85f\\xf0\\xe2\\xde\\xbf\\xa3\\xf6\\xa3\\xd8x\\xa8\\x15~\\x19\\x9c|Lm\\xd7Ua\\x7f3' print(get_sha(s, mode=1)) # ada5dfdf0c9a76a84958310b838a70b6fd6d01f6 #", "res_b64_bin = get_b64e(s, to_bin=True) print(res_b64_bin) # b'dGVzdF9pbmZvcm1hdGlvbg==' res_b32_encode = get_b64e(s,", "5414ffd88fcb58417e64ecec51bb3a6b print(get_md5(s, upper=True)) # 5414FFD88FCB58417E64ECEC51BB3A6B print(get_md5(s, to_bin=True)) # b'T\\x14\\xff\\xd8\\x8f\\xcbXA~d\\xec\\xecQ\\xbb:k' #", "# return \"\" // SUPPORT: sha3_224 sha3_256 sha3_384 sha3_512// only", "ada5dfdf0c9a76a84958310b838a70b6fd6d01f6 # default mode=256 // mode: 1 224 256 384", "85 print(res_b32_encode) # ORSXG5C7NFXGM33SNVQXI2LPNY====== res_b64_decode = get_b64d(res_b64_encode) print(res_b64_decode) # test_information", "# b'\\x9cS\\x9c\\xa3\\\\g\\x19\\xf5F\\xe6x7\\xff7\\xfew\\x91\\xe5?\\xe4\\x07\\x15\\xcdM\\xa0\\x16|x\\xc9\\xad\\xc2\\xe8' print(get_sha3(s, mode=1)) # return \"\" // SUPPORT: sha3_224", "# d09869fdf901465c8566f0e2debfa3f6a3d878a8157e199c7c4c6dd755617f33 print(get_sha(s, to_bin=True)) # b'\\xd0\\x98i\\xfd\\xf9\\x01F\\\\\\x85f\\xf0\\xe2\\xde\\xbf\\xa3\\xf6\\xa3\\xd8x\\xa8\\x15~\\x19\\x9c|Lm\\xd7Ua\\x7f3' print(get_sha(s, mode=1)) # ada5dfdf0c9a76a84958310b838a70b6fd6d01f6", "# 转成二进制的需求没什么用但是可以保留 print(get_sha(s)) # d09869fdf901465c8566f0e2debfa3f6a3d878a8157e199c7c4c6dd755617f33 print(get_sha(s, to_bin=True)) # b'\\xd0\\x98i\\xfd\\xf9\\x01F\\\\\\x85f\\xf0\\xe2\\xde\\xbf\\xa3\\xf6\\xa3\\xd8x\\xa8\\x15~\\x19\\x9c|Lm\\xd7Ua\\x7f3' print(get_sha(s,", "# ORSXG5C7NFXGM33SNVQXI2LPNY====== res_b64_decode = get_b64d(res_b64_encode) print(res_b64_decode) # test_information res_b32_decode =", "default mode=64 // mode: 16 32 64 85 print(res_b32_decode) #", "mode=64 // mode: 16 32 64 85 print(res_b32_decode) # test_information", "print(get_sha3(s)) # 9c539ca35c6719f546e67837ff37fe7791e53fe40715cd4da0167c78c9adc2e8 print(get_sha3(s, to_bin=True)) # b'\\x9cS\\x9c\\xa3\\\\g\\x19\\xf5F\\xe6x7\\xff7\\xfew\\x91\\xe5?\\xe4\\x07\\x15\\xcdM\\xa0\\x16|x\\xc9\\xad\\xc2\\xe8' print(get_sha3(s, mode=1)) #", "\"\" // SUPPORT: sha3_224 sha3_256 sha3_384 sha3_512// only need inputting:", "512 # default mode=256 // mode: 224 256 384 512", "base64 ==> get_b64e, get_b64d res_b64_encode = get_b64e(s) print(res_b64_encode) # dGVzdF9pbmZvcm1hdGlvbg==", "test_information res_b32_decode = get_b64d(res_b32_encode, mode=32) # default mode=64 // mode:", "256 384 512 # default mode=256 // mode: 224 256", "# default mode=256 // mode: 224 256 384 512 print(get_sha3(s,", "dGVzdF9pbmZvcm1hdGlvbg== res_b64_bin = get_b64e(s, to_bin=True) print(res_b64_bin) # b'dGVzdF9pbmZvcm1hdGlvbg==' res_b32_encode =", "mode: 16 32 64 85 print(res_b32_encode) # ORSXG5C7NFXGM33SNVQXI2LPNY====== res_b64_decode =", "# about hashlib ==> get_md5, get_sha, get_sha3 || default mode=256", "224 256 384 512 print(get_sha3(s, mode=384)) # 95c09e20a139843eae877a64cd95d6a629b3c9ff383b5460557aab2612682d4228d05fe41606a79acf5ae1c4de35160c # about", "get_sha, get_sha3 || default mode=256 s = \"test_information\" # 这里只能丢字符串", "mode=64 // mode: 16 32 64 85 print(res_b32_encode) # ORSXG5C7NFXGM33SNVQXI2LPNY======", "default mode=256 // mode: 224 256 384 512 print(get_sha3(s, mode=384))", "# dGVzdF9pbmZvcm1hdGlvbg== res_b64_bin = get_b64e(s, to_bin=True) print(res_b64_bin) # b'dGVzdF9pbmZvcm1hdGlvbg==' res_b32_encode", "|| default mode=256 s = \"test_information\" # 这里只能丢字符串 print(get_md5(s)) #", "b'\\xd0\\x98i\\xfd\\xf9\\x01F\\\\\\x85f\\xf0\\xe2\\xde\\xbf\\xa3\\xf6\\xa3\\xd8x\\xa8\\x15~\\x19\\x9c|Lm\\xd7Ua\\x7f3' print(get_sha(s, mode=1)) # ada5dfdf0c9a76a84958310b838a70b6fd6d01f6 # default mode=256 // mode:", "import get_md5, get_sha, get_sha3, get_b64e, get_b64d # about hashlib ==>", "need inputting: 224 256 384 512 # default mode=256 //", "224 256 384 512 print(get_sha3(s)) # 9c539ca35c6719f546e67837ff37fe7791e53fe40715cd4da0167c78c9adc2e8 print(get_sha3(s, to_bin=True)) #", "mode: 224 256 384 512 print(get_sha3(s, mode=384)) # 95c09e20a139843eae877a64cd95d6a629b3c9ff383b5460557aab2612682d4228d05fe41606a79acf5ae1c4de35160c #", "= get_b64e(s, mode=32) # default mode=64 // mode: 16 32", "to_bin=True)) # b'T\\x14\\xff\\xd8\\x8f\\xcbXA~d\\xec\\xecQ\\xbb:k' # 转成二进制的需求没什么用但是可以保留 print(get_sha(s)) # d09869fdf901465c8566f0e2debfa3f6a3d878a8157e199c7c4c6dd755617f33 print(get_sha(s, to_bin=True))", "get_b64d # about hashlib ==> get_md5, get_sha, get_sha3 || default", "mode: 1 224 256 384 512 print(get_sha3(s)) # 9c539ca35c6719f546e67837ff37fe7791e53fe40715cd4da0167c78c9adc2e8 print(get_sha3(s,", "to_bin=True)) # b'\\xd0\\x98i\\xfd\\xf9\\x01F\\\\\\x85f\\xf0\\xe2\\xde\\xbf\\xa3\\xf6\\xa3\\xd8x\\xa8\\x15~\\x19\\x9c|Lm\\xd7Ua\\x7f3' print(get_sha(s, mode=1)) # ada5dfdf0c9a76a84958310b838a70b6fd6d01f6 # default mode=256", "# test_information res_b32_decode = get_b64d(res_b32_encode, mode=32) # default mode=64 //", "// mode: 224 256 384 512 print(get_sha3(s, mode=384)) # 95c09e20a139843eae877a64cd95d6a629b3c9ff383b5460557aab2612682d4228d05fe41606a79acf5ae1c4de35160c", "# 5414FFD88FCB58417E64ECEC51BB3A6B print(get_md5(s, to_bin=True)) # b'T\\x14\\xff\\xd8\\x8f\\xcbXA~d\\xec\\xecQ\\xbb:k' # 转成二进制的需求没什么用但是可以保留 print(get_sha(s)) #", "# 这里只能丢字符串 print(get_md5(s)) # 5414ffd88fcb58417e64ecec51bb3a6b print(get_md5(s, upper=True)) # 5414FFD88FCB58417E64ECEC51BB3A6B print(get_md5(s,", "res_b64_encode = get_b64e(s) print(res_b64_encode) # dGVzdF9pbmZvcm1hdGlvbg== res_b64_bin = get_b64e(s, to_bin=True)", "about base64 ==> get_b64e, get_b64d res_b64_encode = get_b64e(s) print(res_b64_encode) #", "hashlib ==> get_md5, get_sha, get_sha3 || default mode=256 s =", "sha3_512// only need inputting: 224 256 384 512 # default", "print(get_sha(s)) # d09869fdf901465c8566f0e2debfa3f6a3d878a8157e199c7c4c6dd755617f33 print(get_sha(s, to_bin=True)) # b'\\xd0\\x98i\\xfd\\xf9\\x01F\\\\\\x85f\\xf0\\xe2\\xde\\xbf\\xa3\\xf6\\xa3\\xd8x\\xa8\\x15~\\x19\\x9c|Lm\\xd7Ua\\x7f3' print(get_sha(s, mode=1)) #", "# default mode=256 // mode: 1 224 256 384 512", "print(res_b32_encode) # ORSXG5C7NFXGM33SNVQXI2LPNY====== res_b64_decode = get_b64d(res_b64_encode) print(res_b64_decode) # test_information res_b32_decode", "b'\\x9cS\\x9c\\xa3\\\\g\\x19\\xf5F\\xe6x7\\xff7\\xfew\\x91\\xe5?\\xe4\\x07\\x15\\xcdM\\xa0\\x16|x\\xc9\\xad\\xc2\\xe8' print(get_sha3(s, mode=1)) # return \"\" // SUPPORT: sha3_224 sha3_256", "from lite_tools import get_md5, get_sha, get_sha3, get_b64e, get_b64d # about", "// mode: 1 224 256 384 512 print(get_sha3(s)) # 9c539ca35c6719f546e67837ff37fe7791e53fe40715cd4da0167c78c9adc2e8", "16 32 64 85 print(res_b32_encode) # ORSXG5C7NFXGM33SNVQXI2LPNY====== res_b64_decode = get_b64d(res_b64_encode)", "= get_b64d(res_b64_encode) print(res_b64_decode) # test_information res_b32_decode = get_b64d(res_b32_encode, mode=32) #", "get_b64e(s) print(res_b64_encode) # dGVzdF9pbmZvcm1hdGlvbg== res_b64_bin = get_b64e(s, to_bin=True) print(res_b64_bin) #", "to_bin=True) print(res_b64_bin) # b'dGVzdF9pbmZvcm1hdGlvbg==' res_b32_encode = get_b64e(s, mode=32) # default", "==> get_md5, get_sha, get_sha3 || default mode=256 s = \"test_information\"", "get_md5, get_sha, get_sha3 || default mode=256 s = \"test_information\" #", "print(get_md5(s, upper=True)) # 5414FFD88FCB58417E64ECEC51BB3A6B print(get_md5(s, to_bin=True)) # b'T\\x14\\xff\\xd8\\x8f\\xcbXA~d\\xec\\xecQ\\xbb:k' # 转成二进制的需求没什么用但是可以保留", "==> get_b64e, get_b64d res_b64_encode = get_b64e(s) print(res_b64_encode) # dGVzdF9pbmZvcm1hdGlvbg== res_b64_bin", "= get_b64d(res_b32_encode, mode=32) # default mode=64 // mode: 16 32", "= get_b64e(s, to_bin=True) print(res_b64_bin) # b'dGVzdF9pbmZvcm1hdGlvbg==' res_b32_encode = get_b64e(s, mode=32)", "384 512 # default mode=256 // mode: 224 256 384", "get_sha, get_sha3, get_b64e, get_b64d # about hashlib ==> get_md5, get_sha,", "res_b32_decode = get_b64d(res_b32_encode, mode=32) # default mode=64 // mode: 16", "print(get_md5(s)) # 5414ffd88fcb58417e64ecec51bb3a6b print(get_md5(s, upper=True)) # 5414FFD88FCB58417E64ECEC51BB3A6B print(get_md5(s, to_bin=True)) #", "get_b64d(res_b64_encode) print(res_b64_decode) # test_information res_b32_decode = get_b64d(res_b32_encode, mode=32) # default", "get_b64d(res_b32_encode, mode=32) # default mode=64 // mode: 16 32 64" ]
[]
[ "sample.time[0] s2 = 1/T*np.trapz(np.square(sample.ysig), sample.time) noise_level = s2/bw levels =", "dys) pers, pows = model.periodogram_auto(oversampling=oversampling, nyquist_factor=nyquist_factor) fs = 1.0/pers T", "import numpy as np def csample_from_files(datafile, chainfile, p, q): data", "T = np.max(ts) - np.min(ts) mu = 1/T*np.trapz(ys, ts) s2", "- fs[0] T = sample.time[-1] - sample.time[0] s2 = 1/T*np.trapz(np.square(sample.ysig),", "psd, '-r', alpha=0.33) def plot_psd_sample_draw(sample, loc='upper left', oversampling=5, nyquist_factor=3): fs,", "noise_level*np.sqrt(sample.get_samples('measerr_scale')) plt.axhline(np.median(levels), color='g', alpha=0.33) plt.fill_between(fs, np.percentile(levels, 84)+0*fs, np.percentile(levels, 16)+0*fs, color='g',", "alpha=0.17) fs, psd = normalised_lombscargle(sample.time, sample.y, sample.ysig, oversampling=oversampling, nyquist_factor=nyquist_factor) bw", "fs, psd = normalised_lombscargle(sample.time, sample.y, sample.ysig, oversampling=oversampling, nyquist_factor=nyquist_factor) ys_draw =", "def normalised_lombscargle(ts, ys, dys, oversampling=5, nyquist_factor=3): model = LombScargleFast().fit(ts, ys,", "import LombScargleFast import matplotlib.pyplot as plt import numpy as np", "'-b', alpha=0.33) plt.fill_between(fs, psd_low, psd_high, color='b', alpha=0.17) fs, psd =", "data = data[tind, :] chain = np.loadtxt(chainfile) assert chain.shape[1] ==", "normalised_lombscargle(ts, ys, dys, oversampling=5, nyquist_factor=3): model = LombScargleFast().fit(ts, ys, dys)", "dpsd = normalised_lombscargle(sample.time, ys_draw, sample.ysig, oversampling=oversampling, nyquist_factor=nyquist_factor) plt.loglog(fs, psd, '-k',", "noise_level = s2/bw levels = noise_level*np.sqrt(sample.get_samples('measerr_scale')) plt.axhline(np.median(levels), color='g', alpha=0.33) plt.fill_between(fs,", "pers, pows = model.periodogram_auto(oversampling=oversampling, nyquist_factor=nyquist_factor) fs = 1.0/pers T =", "LombScargleFast import matplotlib.pyplot as plt import numpy as np def", "= np.loadtxt(datafile) times, tind = np.unique(data[:,0], return_index=True) data = data[tind,", "sample.ysig, oversampling=oversampling, nyquist_factor=nyquist_factor) bw = fs[-1] - fs[0] T =", "chain = np.loadtxt(chainfile) assert chain.shape[1] == p + q +", "chainfile, p, q): data = np.loadtxt(datafile) times, tind = np.unique(data[:,0],", "model.periodogram_auto(oversampling=oversampling, nyquist_factor=nyquist_factor) fs = 1.0/pers T = np.max(ts) - np.min(ts)", "1/T*np.trapz(ys, ts) s2 = 1/T*np.trapz(np.square(ys-mu), ts) return fs, s2*pows/np.trapz(pows, fs)", "= sample.predict(sample.time, bestfit='random')[0] fs, dpsd = normalised_lombscargle(sample.time, ys_draw, sample.ysig, oversampling=oversampling,", "cm.CarmaSample(data[:,0], data[:,1], data[:,2], None, q=q, trace=chain[:,:-2], loglike=chain[:,-2], logpost=chain[:,-1]) def normalised_lombscargle(ts,", "normalised_lombscargle(sample.time, ys_draw, sample.ysig, oversampling=oversampling, nyquist_factor=nyquist_factor) plt.loglog(fs, psd, '-k', label='Data', alpha=0.5)", "plt.loglog(fs, psd, '-k', label='Data', alpha=0.5) plt.loglog(fs, dpsd, '-b', label='Prediction', alpha=0.5)", "= sample.plot_power_spectrum(doShow=False) plt.clf() plt.loglog(fs, psd_med, '-b', alpha=0.33) plt.fill_between(fs, psd_low, psd_high,", "data[:,2], None, q=q, trace=chain[:,:-2], loglike=chain[:,-2], logpost=chain[:,-1]) def normalised_lombscargle(ts, ys, dys,", "= 1/T*np.trapz(np.square(ys-mu), ts) return fs, s2*pows/np.trapz(pows, fs) def plot_psd_sample_data(sample, oversampling=5,", "nyquist_factor=3): psd_low, psd_high, psd_med, fs = sample.plot_power_spectrum(doShow=False) plt.clf() plt.loglog(fs, psd_med,", "sample.time[-1] - sample.time[0] s2 = 1/T*np.trapz(np.square(sample.ysig), sample.time) noise_level = s2/bw", "+ q + 5, 'dimension mismatch' return cm.CarmaSample(data[:,0], data[:,1], data[:,2],", "= s2/bw levels = noise_level*np.sqrt(sample.get_samples('measerr_scale')) plt.axhline(np.median(levels), color='g', alpha=0.33) plt.fill_between(fs, np.percentile(levels,", "fs, s2*pows/np.trapz(pows, fs) def plot_psd_sample_data(sample, oversampling=5, nyquist_factor=3): psd_low, psd_high, psd_med,", "sample.ysig, oversampling=oversampling, nyquist_factor=nyquist_factor) ys_draw = sample.predict(sample.time, bestfit='random')[0] fs, dpsd =", "np.loadtxt(chainfile) assert chain.shape[1] == p + q + 5, 'dimension", "= fs[-1] - fs[0] T = sample.time[-1] - sample.time[0] s2", "nyquist_factor=3): fs, psd = normalised_lombscargle(sample.time, sample.y, sample.ysig, oversampling=oversampling, nyquist_factor=nyquist_factor) ys_draw", "q=q, trace=chain[:,:-2], loglike=chain[:,-2], logpost=chain[:,-1]) def normalised_lombscargle(ts, ys, dys, oversampling=5, nyquist_factor=3):", "np.max(ts) - np.min(ts) mu = 1/T*np.trapz(ys, ts) s2 = 1/T*np.trapz(np.square(ys-mu),", "assert chain.shape[1] == p + q + 5, 'dimension mismatch'", "sample.ysig, oversampling=oversampling, nyquist_factor=nyquist_factor) plt.loglog(fs, psd, '-k', label='Data', alpha=0.5) plt.loglog(fs, dpsd,", "mismatch' return cm.CarmaSample(data[:,0], data[:,1], data[:,2], None, q=q, trace=chain[:,:-2], loglike=chain[:,-2], logpost=chain[:,-1])", "oversampling=5, nyquist_factor=3): fs, psd = normalised_lombscargle(sample.time, sample.y, sample.ysig, oversampling=oversampling, nyquist_factor=nyquist_factor)", "plt.clf() plt.loglog(fs, psd_med, '-b', alpha=0.33) plt.fill_between(fs, psd_low, psd_high, color='b', alpha=0.17)", "left', oversampling=5, nyquist_factor=3): fs, psd = normalised_lombscargle(sample.time, sample.y, sample.ysig, oversampling=oversampling,", "nyquist_factor=nyquist_factor) bw = fs[-1] - fs[0] T = sample.time[-1] -", "LombScargleFast().fit(ts, ys, dys) pers, pows = model.periodogram_auto(oversampling=oversampling, nyquist_factor=nyquist_factor) fs =", "= 1/T*np.trapz(np.square(sample.ysig), sample.time) noise_level = s2/bw levels = noise_level*np.sqrt(sample.get_samples('measerr_scale')) plt.axhline(np.median(levels),", "= normalised_lombscargle(sample.time, ys_draw, sample.ysig, oversampling=oversampling, nyquist_factor=nyquist_factor) plt.loglog(fs, psd, '-k', label='Data',", "def csample_from_files(datafile, chainfile, p, q): data = np.loadtxt(datafile) times, tind", "data = np.loadtxt(datafile) times, tind = np.unique(data[:,0], return_index=True) data =", "oversampling=5, nyquist_factor=3): model = LombScargleFast().fit(ts, ys, dys) pers, pows =", "psd_low, psd_high, psd_med, fs = sample.plot_power_spectrum(doShow=False) plt.clf() plt.loglog(fs, psd_med, '-b',", "psd_high, psd_med, fs = sample.plot_power_spectrum(doShow=False) plt.clf() plt.loglog(fs, psd_med, '-b', alpha=0.33)", "oversampling=oversampling, nyquist_factor=nyquist_factor) plt.loglog(fs, psd, '-k', label='Data', alpha=0.5) plt.loglog(fs, dpsd, '-b',", "p + q + 5, 'dimension mismatch' return cm.CarmaSample(data[:,0], data[:,1],", "ys_draw = sample.predict(sample.time, bestfit='random')[0] fs, dpsd = normalised_lombscargle(sample.time, ys_draw, sample.ysig,", "pows = model.periodogram_auto(oversampling=oversampling, nyquist_factor=nyquist_factor) fs = 1.0/pers T = np.max(ts)", "1/T*np.trapz(np.square(sample.ysig), sample.time) noise_level = s2/bw levels = noise_level*np.sqrt(sample.get_samples('measerr_scale')) plt.axhline(np.median(levels), color='g',", "data[:,1], data[:,2], None, q=q, trace=chain[:,:-2], loglike=chain[:,-2], logpost=chain[:,-1]) def normalised_lombscargle(ts, ys,", "None, q=q, trace=chain[:,:-2], loglike=chain[:,-2], logpost=chain[:,-1]) def normalised_lombscargle(ts, ys, dys, oversampling=5,", "model = LombScargleFast().fit(ts, ys, dys) pers, pows = model.periodogram_auto(oversampling=oversampling, nyquist_factor=nyquist_factor)", "= LombScargleFast().fit(ts, ys, dys) pers, pows = model.periodogram_auto(oversampling=oversampling, nyquist_factor=nyquist_factor) fs", "np.percentile(levels, 84)+0*fs, np.percentile(levels, 16)+0*fs, color='g', alpha=0.17) plt.loglog(fs, psd, '-r', alpha=0.33)", "psd_high, color='b', alpha=0.17) fs, psd = normalised_lombscargle(sample.time, sample.y, sample.ysig, oversampling=oversampling,", "ts) return fs, s2*pows/np.trapz(pows, fs) def plot_psd_sample_data(sample, oversampling=5, nyquist_factor=3): psd_low,", "chain.shape[1] == p + q + 5, 'dimension mismatch' return", "csample_from_files(datafile, chainfile, p, q): data = np.loadtxt(datafile) times, tind =", "'dimension mismatch' return cm.CarmaSample(data[:,0], data[:,1], data[:,2], None, q=q, trace=chain[:,:-2], loglike=chain[:,-2],", "psd, '-k', label='Data', alpha=0.5) plt.loglog(fs, dpsd, '-b', label='Prediction', alpha=0.5) plt.legend(loc=loc)", "<reponame>farr/arfit<filename>arfit/cp_utils.py import carmcmc as cm from gatspy.periodic import LombScargleFast import", "oversampling=oversampling, nyquist_factor=nyquist_factor) bw = fs[-1] - fs[0] T = sample.time[-1]", "cm from gatspy.periodic import LombScargleFast import matplotlib.pyplot as plt import", "plt.fill_between(fs, np.percentile(levels, 84)+0*fs, np.percentile(levels, 16)+0*fs, color='g', alpha=0.17) plt.loglog(fs, psd, '-r',", "ys_draw, sample.ysig, oversampling=oversampling, nyquist_factor=nyquist_factor) plt.loglog(fs, psd, '-k', label='Data', alpha=0.5) plt.loglog(fs,", "color='b', alpha=0.17) fs, psd = normalised_lombscargle(sample.time, sample.y, sample.ysig, oversampling=oversampling, nyquist_factor=nyquist_factor)", "color='g', alpha=0.33) plt.fill_between(fs, np.percentile(levels, 84)+0*fs, np.percentile(levels, 16)+0*fs, color='g', alpha=0.17) plt.loglog(fs,", "np.unique(data[:,0], return_index=True) data = data[tind, :] chain = np.loadtxt(chainfile) assert", "- sample.time[0] s2 = 1/T*np.trapz(np.square(sample.ysig), sample.time) noise_level = s2/bw levels", "sample.time) noise_level = s2/bw levels = noise_level*np.sqrt(sample.get_samples('measerr_scale')) plt.axhline(np.median(levels), color='g', alpha=0.33)", "psd_low, psd_high, color='b', alpha=0.17) fs, psd = normalised_lombscargle(sample.time, sample.y, sample.ysig,", "np.min(ts) mu = 1/T*np.trapz(ys, ts) s2 = 1/T*np.trapz(np.square(ys-mu), ts) return", "color='g', alpha=0.17) plt.loglog(fs, psd, '-r', alpha=0.33) def plot_psd_sample_draw(sample, loc='upper left',", "sample.y, sample.ysig, oversampling=oversampling, nyquist_factor=nyquist_factor) ys_draw = sample.predict(sample.time, bestfit='random')[0] fs, dpsd", "return cm.CarmaSample(data[:,0], data[:,1], data[:,2], None, q=q, trace=chain[:,:-2], loglike=chain[:,-2], logpost=chain[:,-1]) def", "import matplotlib.pyplot as plt import numpy as np def csample_from_files(datafile,", "s2 = 1/T*np.trapz(np.square(ys-mu), ts) return fs, s2*pows/np.trapz(pows, fs) def plot_psd_sample_data(sample,", "np def csample_from_files(datafile, chainfile, p, q): data = np.loadtxt(datafile) times,", "tind = np.unique(data[:,0], return_index=True) data = data[tind, :] chain =", "fs, dpsd = normalised_lombscargle(sample.time, ys_draw, sample.ysig, oversampling=oversampling, nyquist_factor=nyquist_factor) plt.loglog(fs, psd,", "plt.loglog(fs, psd, '-r', alpha=0.33) def plot_psd_sample_draw(sample, loc='upper left', oversampling=5, nyquist_factor=3):", "16)+0*fs, color='g', alpha=0.17) plt.loglog(fs, psd, '-r', alpha=0.33) def plot_psd_sample_draw(sample, loc='upper", "loglike=chain[:,-2], logpost=chain[:,-1]) def normalised_lombscargle(ts, ys, dys, oversampling=5, nyquist_factor=3): model =", "dys, oversampling=5, nyquist_factor=3): model = LombScargleFast().fit(ts, ys, dys) pers, pows", "= 1/T*np.trapz(ys, ts) s2 = 1/T*np.trapz(np.square(ys-mu), ts) return fs, s2*pows/np.trapz(pows,", "'-r', alpha=0.33) def plot_psd_sample_draw(sample, loc='upper left', oversampling=5, nyquist_factor=3): fs, psd", "psd = normalised_lombscargle(sample.time, sample.y, sample.ysig, oversampling=oversampling, nyquist_factor=nyquist_factor) bw = fs[-1]", "1/T*np.trapz(np.square(ys-mu), ts) return fs, s2*pows/np.trapz(pows, fs) def plot_psd_sample_data(sample, oversampling=5, nyquist_factor=3):", "nyquist_factor=nyquist_factor) fs = 1.0/pers T = np.max(ts) - np.min(ts) mu", "carmcmc as cm from gatspy.periodic import LombScargleFast import matplotlib.pyplot as", "= np.max(ts) - np.min(ts) mu = 1/T*np.trapz(ys, ts) s2 =", "fs[0] T = sample.time[-1] - sample.time[0] s2 = 1/T*np.trapz(np.square(sample.ysig), sample.time)", "mu = 1/T*np.trapz(ys, ts) s2 = 1/T*np.trapz(np.square(ys-mu), ts) return fs,", "normalised_lombscargle(sample.time, sample.y, sample.ysig, oversampling=oversampling, nyquist_factor=nyquist_factor) bw = fs[-1] - fs[0]", "alpha=0.33) plt.fill_between(fs, psd_low, psd_high, color='b', alpha=0.17) fs, psd = normalised_lombscargle(sample.time,", "q + 5, 'dimension mismatch' return cm.CarmaSample(data[:,0], data[:,1], data[:,2], None,", "= normalised_lombscargle(sample.time, sample.y, sample.ysig, oversampling=oversampling, nyquist_factor=nyquist_factor) bw = fs[-1] -", "np.loadtxt(datafile) times, tind = np.unique(data[:,0], return_index=True) data = data[tind, :]", "plot_psd_sample_data(sample, oversampling=5, nyquist_factor=3): psd_low, psd_high, psd_med, fs = sample.plot_power_spectrum(doShow=False) plt.clf()", "as np def csample_from_files(datafile, chainfile, p, q): data = np.loadtxt(datafile)", "ts) s2 = 1/T*np.trapz(np.square(ys-mu), ts) return fs, s2*pows/np.trapz(pows, fs) def", "ys, dys, oversampling=5, nyquist_factor=3): model = LombScargleFast().fit(ts, ys, dys) pers,", "plt.axhline(np.median(levels), color='g', alpha=0.33) plt.fill_between(fs, np.percentile(levels, 84)+0*fs, np.percentile(levels, 16)+0*fs, color='g', alpha=0.17)", "= normalised_lombscargle(sample.time, sample.y, sample.ysig, oversampling=oversampling, nyquist_factor=nyquist_factor) ys_draw = sample.predict(sample.time, bestfit='random')[0]", "5, 'dimension mismatch' return cm.CarmaSample(data[:,0], data[:,1], data[:,2], None, q=q, trace=chain[:,:-2],", "import carmcmc as cm from gatspy.periodic import LombScargleFast import matplotlib.pyplot", "84)+0*fs, np.percentile(levels, 16)+0*fs, color='g', alpha=0.17) plt.loglog(fs, psd, '-r', alpha=0.33) def", "data[tind, :] chain = np.loadtxt(chainfile) assert chain.shape[1] == p +", "loc='upper left', oversampling=5, nyquist_factor=3): fs, psd = normalised_lombscargle(sample.time, sample.y, sample.ysig,", "q): data = np.loadtxt(datafile) times, tind = np.unique(data[:,0], return_index=True) data", "normalised_lombscargle(sample.time, sample.y, sample.ysig, oversampling=oversampling, nyquist_factor=nyquist_factor) ys_draw = sample.predict(sample.time, bestfit='random')[0] fs,", "plt import numpy as np def csample_from_files(datafile, chainfile, p, q):", "times, tind = np.unique(data[:,0], return_index=True) data = data[tind, :] chain", "= data[tind, :] chain = np.loadtxt(chainfile) assert chain.shape[1] == p", "= sample.time[-1] - sample.time[0] s2 = 1/T*np.trapz(np.square(sample.ysig), sample.time) noise_level =", "s2*pows/np.trapz(pows, fs) def plot_psd_sample_data(sample, oversampling=5, nyquist_factor=3): psd_low, psd_high, psd_med, fs", "s2/bw levels = noise_level*np.sqrt(sample.get_samples('measerr_scale')) plt.axhline(np.median(levels), color='g', alpha=0.33) plt.fill_between(fs, np.percentile(levels, 84)+0*fs,", "np.percentile(levels, 16)+0*fs, color='g', alpha=0.17) plt.loglog(fs, psd, '-r', alpha=0.33) def plot_psd_sample_draw(sample,", "numpy as np def csample_from_files(datafile, chainfile, p, q): data =", "levels = noise_level*np.sqrt(sample.get_samples('measerr_scale')) plt.axhline(np.median(levels), color='g', alpha=0.33) plt.fill_between(fs, np.percentile(levels, 84)+0*fs, np.percentile(levels,", "s2 = 1/T*np.trapz(np.square(sample.ysig), sample.time) noise_level = s2/bw levels = noise_level*np.sqrt(sample.get_samples('measerr_scale'))", "= model.periodogram_auto(oversampling=oversampling, nyquist_factor=nyquist_factor) fs = 1.0/pers T = np.max(ts) -", "oversampling=5, nyquist_factor=3): psd_low, psd_high, psd_med, fs = sample.plot_power_spectrum(doShow=False) plt.clf() plt.loglog(fs,", "p, q): data = np.loadtxt(datafile) times, tind = np.unique(data[:,0], return_index=True)", "- np.min(ts) mu = 1/T*np.trapz(ys, ts) s2 = 1/T*np.trapz(np.square(ys-mu), ts)", "plt.fill_between(fs, psd_low, psd_high, color='b', alpha=0.17) fs, psd = normalised_lombscargle(sample.time, sample.y,", "gatspy.periodic import LombScargleFast import matplotlib.pyplot as plt import numpy as", "oversampling=oversampling, nyquist_factor=nyquist_factor) ys_draw = sample.predict(sample.time, bestfit='random')[0] fs, dpsd = normalised_lombscargle(sample.time,", "= 1.0/pers T = np.max(ts) - np.min(ts) mu = 1/T*np.trapz(ys,", "= np.unique(data[:,0], return_index=True) data = data[tind, :] chain = np.loadtxt(chainfile)", "as cm from gatspy.periodic import LombScargleFast import matplotlib.pyplot as plt", "as plt import numpy as np def csample_from_files(datafile, chainfile, p,", "= np.loadtxt(chainfile) assert chain.shape[1] == p + q + 5,", "psd_med, '-b', alpha=0.33) plt.fill_between(fs, psd_low, psd_high, color='b', alpha=0.17) fs, psd", "matplotlib.pyplot as plt import numpy as np def csample_from_files(datafile, chainfile,", ":] chain = np.loadtxt(chainfile) assert chain.shape[1] == p + q", "== p + q + 5, 'dimension mismatch' return cm.CarmaSample(data[:,0],", "plt.loglog(fs, psd_med, '-b', alpha=0.33) plt.fill_between(fs, psd_low, psd_high, color='b', alpha=0.17) fs,", "alpha=0.33) def plot_psd_sample_draw(sample, loc='upper left', oversampling=5, nyquist_factor=3): fs, psd =", "nyquist_factor=nyquist_factor) ys_draw = sample.predict(sample.time, bestfit='random')[0] fs, dpsd = normalised_lombscargle(sample.time, ys_draw,", "fs = sample.plot_power_spectrum(doShow=False) plt.clf() plt.loglog(fs, psd_med, '-b', alpha=0.33) plt.fill_between(fs, psd_low,", "fs) def plot_psd_sample_data(sample, oversampling=5, nyquist_factor=3): psd_low, psd_high, psd_med, fs =", "trace=chain[:,:-2], loglike=chain[:,-2], logpost=chain[:,-1]) def normalised_lombscargle(ts, ys, dys, oversampling=5, nyquist_factor=3): model", "T = sample.time[-1] - sample.time[0] s2 = 1/T*np.trapz(np.square(sample.ysig), sample.time) noise_level", "fs = 1.0/pers T = np.max(ts) - np.min(ts) mu =", "psd = normalised_lombscargle(sample.time, sample.y, sample.ysig, oversampling=oversampling, nyquist_factor=nyquist_factor) ys_draw = sample.predict(sample.time,", "psd_med, fs = sample.plot_power_spectrum(doShow=False) plt.clf() plt.loglog(fs, psd_med, '-b', alpha=0.33) plt.fill_between(fs,", "nyquist_factor=3): model = LombScargleFast().fit(ts, ys, dys) pers, pows = model.periodogram_auto(oversampling=oversampling,", "def plot_psd_sample_draw(sample, loc='upper left', oversampling=5, nyquist_factor=3): fs, psd = normalised_lombscargle(sample.time,", "logpost=chain[:,-1]) def normalised_lombscargle(ts, ys, dys, oversampling=5, nyquist_factor=3): model = LombScargleFast().fit(ts,", "alpha=0.17) plt.loglog(fs, psd, '-r', alpha=0.33) def plot_psd_sample_draw(sample, loc='upper left', oversampling=5,", "+ 5, 'dimension mismatch' return cm.CarmaSample(data[:,0], data[:,1], data[:,2], None, q=q,", "fs[-1] - fs[0] T = sample.time[-1] - sample.time[0] s2 =", "return fs, s2*pows/np.trapz(pows, fs) def plot_psd_sample_data(sample, oversampling=5, nyquist_factor=3): psd_low, psd_high,", "return_index=True) data = data[tind, :] chain = np.loadtxt(chainfile) assert chain.shape[1]", "sample.y, sample.ysig, oversampling=oversampling, nyquist_factor=nyquist_factor) bw = fs[-1] - fs[0] T", "alpha=0.33) plt.fill_between(fs, np.percentile(levels, 84)+0*fs, np.percentile(levels, 16)+0*fs, color='g', alpha=0.17) plt.loglog(fs, psd,", "plot_psd_sample_draw(sample, loc='upper left', oversampling=5, nyquist_factor=3): fs, psd = normalised_lombscargle(sample.time, sample.y,", "bw = fs[-1] - fs[0] T = sample.time[-1] - sample.time[0]", "ys, dys) pers, pows = model.periodogram_auto(oversampling=oversampling, nyquist_factor=nyquist_factor) fs = 1.0/pers", "1.0/pers T = np.max(ts) - np.min(ts) mu = 1/T*np.trapz(ys, ts)", "def plot_psd_sample_data(sample, oversampling=5, nyquist_factor=3): psd_low, psd_high, psd_med, fs = sample.plot_power_spectrum(doShow=False)", "sample.plot_power_spectrum(doShow=False) plt.clf() plt.loglog(fs, psd_med, '-b', alpha=0.33) plt.fill_between(fs, psd_low, psd_high, color='b',", "bestfit='random')[0] fs, dpsd = normalised_lombscargle(sample.time, ys_draw, sample.ysig, oversampling=oversampling, nyquist_factor=nyquist_factor) plt.loglog(fs,", "fs, psd = normalised_lombscargle(sample.time, sample.y, sample.ysig, oversampling=oversampling, nyquist_factor=nyquist_factor) bw =", "nyquist_factor=nyquist_factor) plt.loglog(fs, psd, '-k', label='Data', alpha=0.5) plt.loglog(fs, dpsd, '-b', label='Prediction',", "= noise_level*np.sqrt(sample.get_samples('measerr_scale')) plt.axhline(np.median(levels), color='g', alpha=0.33) plt.fill_between(fs, np.percentile(levels, 84)+0*fs, np.percentile(levels, 16)+0*fs,", "from gatspy.periodic import LombScargleFast import matplotlib.pyplot as plt import numpy", "sample.predict(sample.time, bestfit='random')[0] fs, dpsd = normalised_lombscargle(sample.time, ys_draw, sample.ysig, oversampling=oversampling, nyquist_factor=nyquist_factor)" ]